1

我有結構推送通知關於保存在iOS中形成從遠程通知

{ 
    "aps": 
    { 
     "alert": "Hello, world!", 
     "sound": "default", 
     "funcId": "abc" <-- this key i add more 
    } 
} 

我想存儲的關鍵「FUNCID」價值的應用程序收到
通知後使用(在狀態backgound應用程序或殺死),如:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
{ 
    NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"]; 
    [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

我曾嘗試使用NSUserDefaults存儲該值,但是當應用程序在後臺狀態和殺害,此值不存儲。 如何從應用程序重新啓動時使用遠程通知存儲vaule?

謝謝大家的支持!

回答

1

您將不得不以2種不同的方式處理推送通知,因此您必須以2種不同的方法保存該值。在將值/對象保存到NSUserDefaults之前,您還需要確保用戶信息而不是

的代碼是一樣的東西如下: -

//Receive Push Notification when the app is active in foreground or background 
- (void)application:(UIApplication *)application 
      didReceiveRemoteNotification:(NSDictionary *)userInfo { 

    if(userInfo){ 
    //TODO: Handle the userInfo here 
    NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"]; 
    [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
    } 

} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    //Get the push notification when app is not open 
    NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]; 

    if(remoteNotif){ 
     [self handleRemoteNotification:application userInfo:remoteNotif]; 
    } 

    return YES; 
} 

-(void)handleRemoteNotification:(UIApplication*)application userInfo:(NSDictionary*)userInfo{ 

    if(userInfo){ 
    //TODO: Handle the userInfo here 
    NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"]; 
    [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
    } 
} 
+0

謝謝,但你的方式不成功,當我的應用程序在狀態背景或遇難 – dleviathan 2014-09-02 09:07:38

+1

請仔細檢查並使用** setObject **,而不是** setValue **。當應用程序被殺害或在後臺,你將不得不**,點擊通知**去應用程序,以接收通知。如果您直接點擊該應用,則不會收到通知信息。 – Ricky 2014-09-02 09:11:14

+0

非常感謝,我知道我沒有收到通知信息的原因。那麼有另一種方法可以直接從應用程序獲取通知信息嗎? – dleviathan 2014-09-02 10:32:27

1

你不能保存到NSUserDefaults,因爲你沒有權限。

使用NSFileManager創建另一個文件,並設置適當的文件權限。

然後,您將能夠在收到通知時寫入該文件。

+0

謝謝,但它的成功應用時運行應用程序時在後臺或者殺死它不 – dleviathan 2014-09-02 10:29:22

+0

經過了這一點:https://developer.apple.com/文件保護值 – meim 2014-09-02 11:10:48

+0

您應該將該文件設置爲NSFileProtectionNone,以便即使在設備上使用了文件保護值被鎖定並且通知到達,您仍然可以寫入該文件 – meim 2014-09-02 11:12:21