2

我有一個使用本地通知的iOS應用程序。當應用程序在後臺運行或處於活動狀態時,我使用application didReceiveLocalNotification方法,這很好。但是當應用程序關閉時(不在後臺運行),我使用application didFinishLaunchingWithOptions方法來控制通知處理時發生的情況。UIApplicationLaunchOptionsLocalNotificationKey始終爲空 - iOS

但是,我的問題是didFinishLaunchingWithOptions方法中的通知總是(null)

這裏是我的代碼:

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

    // Override point for customization after application launch. 

    // Register the app for local notifcations. 

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

    // Setup the local notification check. 
    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 

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

    // Check if a notifcation has been received. 

    if (notification) { 

     // Run the notifcation. 
     [self.myViewController run_notifcation:[notification.userInfo valueForKey:@"notification_id"]]; 
    } 

    // Ensure the notifcation badge number is hidden. 
    application.applicationIconBadgeNumber = 0; 

    return YES; 
} 

我在這裏失去了一些東西?我先要求用戶獲得許可,並獲得正確的代碼以獲取通知對象。我的應用程序僅適用於iOS 9和更高版本。

謝謝你的時間,丹。

+0

你是怎麼知道通知總是'空'的?你是否在調試模式下從Xcode運行應用程序?默認情況下,沒有通知以 – Azat

+0

開始@Azat我試圖在uialertview中顯示通知對象。 – Supertecnoboff

+0

當應用程序沒有在後臺運行,並且用戶點擊通知時,該應用程序將啓動並且通知將具有價值。確保用戶點擊通知 – user1046037

回答

3

在警報視圖中顯示值launchOptions以查看是否有任何值。

如果該值不是零,那麼可能你的UI代碼會在後臺線程中執行。

確保所有UI代碼是在主線程中執行的,如下圖所示:

dispatch_async(dispatch_get_main_queue(), ^{ 
//self doSomething (UI Code) 
}); 

當您使用您的應用程序的異步調用這是非常重要的。

+0

非常感謝:) – Supertecnoboff

+0

非常感謝您的幫助。 –

-1

applicationWillTerminate而不是didFinishLaunchingWithOptions中實現您的代碼。因爲當應用程序終止時,然後執行applicationWillTerminate方法。

func applicationWillTerminate(application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 
+0

我不明白這將如何解決這個問題,我試圖調用一個方法,當時應用程序已被打開。我真的不認爲這會解決我的問題。 – Supertecnoboff