Search code examples
iosvoipnsurlsessionnsurlsessiondatatasknsurlsessionuploadtask

ios - NSURLSession with dataTaskWithRequest fires only when app launch, not while the app is not running


As described in the title, I can reply as a text when remote notification comes. My http request works well if I tap the home button one time, but does not work when the app is not running, it waits. When the app is launched it works too.

// Please work
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
    print(userInfo["personB"])
    if identifier == "comment-reply" {
        if let response = responseInfo[UIUserNotificationActionResponseTypedTextKey],
            responseText = response as? String {
            let request = NSMutableURLRequest(URL: NSURL(string: "https://example.com/post-ios.php")!)
            request.HTTPMethod = "POST"
            let p = "a=123&b=\(responseText)"
            request.HTTPBody = p.dataUsingEncoding(NSUTF8StringEncoding)
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
            task.resume()
        }
    }
    completionHandler()
}

now, am i need: -VoIP certificate, -background session configuration, -dispatch something, or -upload task?

Can anyone help me?

UPDATE for upload task

func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
    let id = userInfo["personB"]!
    if identifier == "comment-reply" {
        if let response = responseInfo[UIUserNotificationActionResponseTypedTextKey],
            responseText = response as? String {
            let conf = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("replyPost")
            let requ = NSMutableURLRequest(URL: NSURL(string: "https://example.com/post-ios.php")!)
                requ.HTTPMethod = "POST"
            let data = "a=123&b=\(responseText)".dataUsingEncoding(NSUTF8StringEncoding)
            let task = NSURLSession(configuration: conf, delegate: self, delegateQueue: NSOperationQueue.mainQueue()).uploadTaskWithRequest(requ, fromData: data!)
            task.resume()
        }
    }
    completionHandler()
}

It does not works too. Am i add additional handler?


Solution

  • When you call completionHandler() your application will be suspended again. This will happen before your task completes.

    Instead of uploadTask(with:from:) you should call uploadTask(with:from:completionHandler:) and put completionHandler() in the completion handler block.