2015-05-07 62 views
0

我想在收到推送通知時觸發數據提取。我知道這發生在通知顯示給用戶之前。現在我有這個在我的AppDelegate.m:APN後臺刷新,設置AppDelegate.m

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

    if (application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ) 
    { 
     //restore push 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"appRestorePush" object:nil]; 

    } 

    else { 

     //push for when the app is open 
     self.pushString = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"appOpenPush" object:nil]; 

    } 


} 

這個控制程序不取決於什麼,如果接到通知上,而應用程序是在前臺或者如果應用程序是從一個推送通知開開。要添加支持後臺刷新我只是改變這個方法:

void didReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) 
{ 
    if([content-available]) { 
    // fetch content methods here 
    completionHandler (UIBackgroundFetchResult.NewData); 
    } 

if (application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ) 
     { 
      //restore push 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"appRestorePush" object:nil]; 

     } 

     else { 

      //push for when the app is open 
      self.pushString = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"appOpenPush" object:nil]; 

     } 
} 

將這項工作既顯示前推,然後處理來自一鍵打開應用程序像以前一樣或獲取的數據是有兩個單獨的方法,一個用於後臺刷新,另一個用於處理如何打開推送?任何指針將非常感激。謝謝!

回答

2

首先,你的第二個代碼塊是一個swift-Objective-C混合。所以我假設你使用Objective-C進行開發。

因此,相關的方法如下:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler { 
    if (application.applicationState == UIApplicationStateInactive) { 
     // Application is inactive, fetch new data and call the completion handler. 
     completionHandler(UIBackgroundFetchResultNewData); 

    } else if (application.applicationState == UIApplicationStateBackground) { 
     // Application is in background, fetch new data and call the completion handler. 
     completionHandler(UIBackgroundFetchResultNewData); 

    } else { 
     // Application is active, so to what you need 
     completionHandler(UIBackgroundFetchResultNewData); 

    } 
} 

如果你在你的通知對象發送content-available = 1(aps對象內),該通知將不會被顯示給用戶。該參數告訴操作系統您不希望向用戶顯示新信息,而只是從服務器獲取新數據。

如果您不會發送此參數,則操作系統會將其視爲常規通知,並且只有在用戶點擊顯示的通知後纔會調用上述方法(除非該應用程序處於活動狀態,並且不會超出通知將不會顯示,並立即調用此方法)。

+0

你可以添加推送消息到APN,但不是嗎?即您可以擁有content-available = 1,並在獲取後將「發送給您的電話」消息發送給手機? 後臺刷新後我怎麼能得到它發佈我的一個通知,即[[NSNotificationCenter defaultCenter] postNotificationName:@「appRestorePush」object:nil];? – Kex

+0

當然。但是,如果可用內容設置爲1,並且您的應用程序處於後臺/未運行狀態,則無法執行任何UI工作,但可以(未測試)顯示本地通知。 – Asaf