iOS本地通知动作在后台

杰克

我正在构建一个应用程序,当用户收到本地通知时,它通过条带化和解析功能向他们的信用卡收费,这还不止于此,但这就是开始。当在应用程序内部接收到通知时,一切正常,但是在应用程序外部接收到通知时,操作未完成。

https://github.com/jackintosh7/唤醒

我希望该操作在应用程序外完成,并且在用户单击通知时显示该视图。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{


    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }

    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    if (StripePublishableKey) {
        [Stripe setDefaultPublishableKey:StripePublishableKey];
    }
    if (ParseApplicationId && ParseClientKey) {
        [Parse setApplicationId:ParseApplicationId
                      clientKey:ParseClientKey];
    }

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"Customer Created"]) {
        UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Home"];
        self.window.rootViewController = viewController;
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Customer Created"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Tutorial"];
        self.window.rootViewController = viewController;

    }

    [self.window makeKeyAndVisible];

    UILocalNotification *notification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (notification) {
        [self application:application didReceiveLocalNotification:notification];
    }


    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"1");




    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{




    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{



    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{




    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"AlarmModel" withExtension:@"mom"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"AlarmModel.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    dispatch_async(dispatch_get_main_queue(), ^{

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alertView show];

    });

    NSString *customerId = @"cus_4ot6ggKUOp6bHg";
    NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
    [self chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];
    NSLog(@"11");
}

-(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{
    NSLog(@"22");

    [PFCloud callFunctionInBackground:@"chargeCustomer"
                       withParameters:@{
                                        @"amount":amountInCents,
                                        @"customerId":customerId
                                        }
                                block:^(id object, NSError *error) {
                                    //Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
                                    handler(object,error);

                                }];

}



#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end

行动:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];

    NSString *customerId = @"cus_4ot6ggKUOp6bHg";
    NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
    [AppDelegate chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];
    NSLog(@"11");
}

+(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{
    NSLog(@"22");

    [PFCloud callFunctionInBackground:@"chargeCustomer"
                       withParameters:@{
                                        @"amount":amountInCents,
                                        @"customerId":customerId
                                        }
                                block:^(id object, NSError *error) {
                                    //Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
                                    handler(object,error);

                                }];

}

添加的nslog的结果:请参阅收费信息:(空)错误:invalid_request_error:没有这样的客户:cus_4ot6ggKUOp6bHg(代码:141,版本:1.4.1)最后一个我明白问题是什么。

奥尼克四世

当您的应用程序正在运行时application:didReceiveLocalNotification:正在调用,但是如果您的应用程序未在运行,则有关本地通知的信息将添加到launchOptions dict中;

在您的AppDelegate中的application:didFinishLaunchingWithOptions中添加以下代码:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

// Keep al exist code in your app...and at the END of this methods

UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
    [self application:application didReceiveLocalNotification:localNotification];
}

return YES;
}

在主线程中强制使用UIAlert是一件好事:

dispatch_async(dispatch_get_main_queue(),
               ^{
                   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                   [alertView show];
});

新提案:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

dispatch_async(dispatch_get_main_queue(), ^{

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];
NSString *customerId = @"cus_4ot6ggKUOp6bHg";
NSNumber *amountInCents = [NSNumber numberWithInteger: 1000];
[self chargeCustomer:customerId amount:(NSNumber *)amountInCents completion:^(id object, NSError *error) { }];

});

}

和 :

-(void)chargeCustomer:(NSString *)customerId amount:(NSNumber *)amountInCents completion:(PFIdResultBlock)handler
{


[PFCloud callFunctionInBackground:@"chargeCustomer"
                   withParameters:@{
                                    @"amount":amountInCents,
                                    @"customerId":customerId
                                    }
                            block:^(id object, NSError *error) {
                                //Object is an NSDictionary that contains the stripe charge information, you can use this as is or create, an instance of your own charge class.
                                handler(object,error);
                                NSLog(@"See the error:%@",[error localizedDescription]);
                                NSLog(@"See the charge information:%@",[object description]);

                            }];

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

后台的iOS本地通知操作

来自分类Dev

在后台运行时获取本地通知

来自分类Dev

App在后台Swift 2.0中运行时发送本地通知

来自分类Dev

在后台收到Api响应时如何使用本地通知?

来自分类Dev

在后台收到Api响应时如何使用本地通知?

来自分类Dev

iOS和本地通知

来自分类Dev

创建iOS本地通知

来自分类Dev

本地通知phonegap ios

来自分类Dev

创建iOS本地通知

来自分类Dev

iOS本地通知-点击操作

来自分类Dev

iOS Swift本地通知未“弹出”

来自分类Dev

iOS本地通知重复x次

来自分类Dev

用本地通知ios打开URL

来自分类Dev

iOS重复本地通知

来自分类Dev

iOS 中的本地通知(目标 C)

来自分类Dev

Swift中显示本地通知时如何分配动作

来自分类Dev

动作按钮未显示在本地通知中

来自分类Dev

后台获取,NSURLSession GET和本地通知

来自分类Dev

后台获取,NSURLSession GET和本地通知

来自分类Dev

本地通知未通过后台提取触发

来自分类Dev

当应用程序在后台运行时,如何通过单击ngCordova本地通知将用户引导到特定页面

来自分类Dev

在后台iOS中接收推送通知

来自分类Dev

在后台iOS中接收推送通知

来自分类Dev

静默通知后ios迅速创建本地通知

来自分类Dev

每周本地通知

来自分类Dev

本地通知

来自分类Dev

本地通知

来自分类Dev

本地通知数据

来自分类Dev

未在后台获取时创建本地用户通知