UIApplicationLaunchOptionsRemoteNotificationKey没有获取userinfo

时间:2015-05-18 07:41:56

标签: ios objective-c

在我目前的项目中,我有推送通知。当我点击应用程序图标时,我想从启动选项对象获取收到的通知,但它始终返回UIDeviceBatteryStateUnknown

nil

2 个答案:

答案 0 :(得分:7)

您无法检测到该情况,因为应用程序未使用推送通知打开(已通过应用程序图标打开)。
尝试通过滑动推送通知来打开应用程序。

编辑:

如果您希望调用推送通知(通过后台提取,当您的应用程序未处于活动状态时),您需要让后端开发人员在推送通知中设置"content-available": 1

之后将调用-application:didReceiveRemoteNotification:fetchCompletionHandler:(当推送通知到达时),这样您就可以将有效负载保存到文件中,然后当应用程序打开时,您可以读取文件并采取措施。

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"#BACKGROUND FETCH CALLED: %@", userInfo);
    // When we get a push, just writing it to file
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"];

    [userInfo writeToFile:filePath atomically:YES];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Checking if application was launched by tapping icon, or push notification
    if (!launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"];

        [[NSFileManager defaultManager] removeItemAtPath:filePath
                                                   error:nil];
        NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:filePath];
        if (info) {
            // Launched by tapping icon
            // ... your handling here
        }
    } else {
        NSDictionary *info = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        // Launched with swiping
        // ... your handling here
    }
    return YES;
}

也不要忘记启用"远程通知"在"背景模式" enter image description here

答案 1 :(得分:6)

当您从PUSH NOTIFICATION ACTION启动应用程序时,[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]将返回推送通知有效负载(以字典格式)。当我说推送通知操作时,它意味着从操作中心或推送通知警告对话框中点击推送通知(根据设备设置,推送通知传送机制会有所不同)。

如果您通过点按APP ICON启动应用程序,[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]始终返回nil。因为,它还没有从任何推送通知中启动。