2016-08-31 188 views
1

好的,當應用程序在前臺運行時,我的推送通知就像魅力一樣工作。但是,當我進入後臺時,應用程序永遠不會收到推送通知。就像通知聽不進去一樣。 所以這是發生了什麼。當應用程序首次啓動時,我可以收到通知。當我關閉並重新打開應用程序時,我可以收到通知。但是當應用程序在後臺關閉時,我無法收到通知。當應用程序進入後臺並且應用程序變爲活動狀態時我會打印出來,所以我知道它不會關閉。因爲它的打印,它將進入後臺,所以它應該運行。 原來這就是我對應用deligate類:IOS應用程序在後臺不顯示推送通知。 Swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

//OTHER THINGS 
    //Open the Push note page 
    if launchOptions != nil 
    { 
     print(launchOptions) 
     let storyboard = UIStoryboard(name: "Main", bundle: nil) 
     let vc = storyboard.instantiateViewControllerWithIdentifier(myPage) 
     self.window?.rootViewController = vc 
    } 

    //handel push note if app is closed 
    //Sends it to the regular handler for push notifcaiton 
    //didrecivepushnotificaiton 
    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary 
    { 
     print("Got A Push Note when I was closed") 
     self.application(application, didReceiveRemoteNotification: remoteNotification as [NSObject : AnyObject]) 
    } 

} 

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken 
    deviceToken: NSData) { 
    print("DEVICE TOKEN = \(deviceToken)") 

    //convert the device token into a string 
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) 
    var token = "" 

    for i in 0..<deviceToken.length { 
     token += String(format: "%02.2hhx", arguments: [tokenChars[i]]) 
    } 
    print("token: " + token) 
    //store the user device token for apns push notification 
    loginInformation.setObject(token, forKey: "token") 
    self.loginInformation.synchronize() 

} 

// [START ack_message_reception] 
func application(application: UIApplication, 
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 

    print("Recived Push Notificaion") 

    var myMess :String = "" 
    var url : String = "" 
    var myTitle : String = "" 

    if var alertDict = userInfo["aps"] as? Dictionary<String, String> { 

     print("Alert Dict") 
     print(alertDict) 

     url = alertDict["url"]! 
     myMess = alertDict["alert"]! 
     myTitle = alertDict["mytitle"]! 
     //store the url for the push control view 
     loginInformation.setObject(url, forKey: "URL") 
     loginInformation.setObject(myMess, forKey: "Message") 
     loginInformation.setObject(myTitle, forKey: "Title") 
     self.loginInformation.synchronize() 


    }else{print("No go")} 
    application.applicationIconBadgeNumber = 0 
    //post notification. 
    NSNotificationCenter.defaultCenter().postNotificationName("PushReceived", object: nil, userInfo: userInfo) 


    if myTitle == "" 
    { 
     myTitle = 「New Title「 
    } 
    if myMess == "" 
    { 
     myMess = 「All Hail Gus「 
    } 

    let alert = UIAlertController(title: myTitle, message: myMess, preferredStyle: UIAlertControllerStyle.Alert) 
    //Close Button 
    alert.addAction(UIAlertAction(title: "次回", style: UIAlertActionStyle.Default, handler: nil)) 
    self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil) 


} 

func registrationHandler(registrationToken: String!, error: NSError!) { 

} 

// [START receive_apns_token_error] 
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError 
    error: NSError) { 
    print(error) 
} 

我想我對這個太所有正確的設置。但我現在不太確定。推送通知確實有效,但我做了很多更改,並且沒有在一段時間內對它們進行測試。

enter image description here enter image description here enter image description here

而這正是有效載荷的例子

{"aps":{"alert":"Gus Message.","badge":"1", "url":"https://www.gus.com","mytitle":"Gus Title"}} 
+0

你想顯示警告,如果應用程序在後臺並收到推送? – iphonic

+0

我想要小橫幅thingy彈出並告訴他們,這裏有一些有趣的東西:) – MNM

+0

我不知道靜默推送通知是什麼。我剛剛離開https://www.raywenderlich.com/123862/push-notifications-tutorial這個教程,並添加了我需要的信息,以獲取信息 – MNM

回答

2

要全面落實APNS役,u必須處理三種情況:

  1. 不活躍
  2. 前景
  3. 背景

無效的模式應該didFinishLaunchingWithOptions方法處理

//receive apns when app in inactive mode, remaining message hint display task could be sum up by the code in applicationwillenterforeground 
    if let options = launchOptions { 
     if options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil { 
      let userInfo: NSDictionary = options[UIApplicationLaunchOptionsRemoteNotificationKey] as! NSDictionary 
      let apsInfo: NSDictionary = userInfo["aps"] as! NSDictionary 
      //parse notification body message ... 

        NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_REMOTE_NOTIF, object: userInfo) 
        APService.handleRemoteNotification(userInfo as! [NSObject : AnyObject]) 

        //Update badge number 

        let badgeIndex = apsInfo["badge"] as! Int 
        UIApplication.sharedApplication().applicationIconBadgeNumber = badgeIndex 
       } 
      } 
     } else if options[UIApplicationLaunchOptionsURLKey] != nil { 
      if let url = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL { 
       print(url) 
      } 
     } 
    } 

剩下的兩個病例應在didReceiveRemoteNotification方法處理

//receive apns when app in background mode 
    let apsInfo: NSDictionary = userInfo["aps"] as! NSDictionary 
    if UIApplication.sharedApplication().applicationState != UIApplicationState.Active{ 

     //TODO: temporary method, need further update 
     //judge notification type 
     if let _ = userInfo["inviterName"] as? String { 
      //notification for group invite 
     }else{ 
      //Update badge number 
      if let badgeInt = apsInfo["badge"] as? Int { 
       UIApplication.sharedApplication().applicationIconBadgeNumber = badgeInt > 0 ? badgeInt: 1 
      }else{ 
       UIApplication.sharedApplication().applicationIconBadgeNumber = 1 
      } 
      //turn on trigger to enable message hint btn on recorder vc when it appear 
      NSUserDefaults.standardUserDefaults().setBool(true, forKey: REMOTE_NOTIF_REMAINING) 
     } 
    } 
    //receive apns when app in forground mode 
    else{ 
     //TODO: temporary method, need further update 
     //judge notification type 
     if let _ = userInfo["inviterName"] as? String { 
      //notification for group invite 
      NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_GROUP_NOTIF, object:nil) 
     }else{ 
      //notificate recorder vc to display message hint directly 
      NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_REMOTE_NOTIF, object: userInfo) 
     } 
    } 
    APService.handleRemoteNotification(userInfo) 
    completionHandler(UIBackgroundFetchResult.NewData) 
+0

我認爲我已經這樣做了。我有didRecieveRemoteNotification方法,它爲用戶創建一個警報。有沒有更好的做法比我做得更好? – MNM

+0

似乎缺少背景案例處理程序。在'didReceiveRemoteNotification'方法中,你必須首先通過'UIApplication.sharedApplication()。applicationState'屬性來檢查應用程序狀態。在'UIApplicationState.Active'情況下,它的前景。如果沒有,它的背景(在代碼中缺少)。 –

+0

@陳偉。我怎麼能識別這個userInfo [「aps」]! NSDictionary –

相關問題