My app is configured to support silent push (content-available), and also supports background fetch. Want I need to achieve is upon receiving a silent push, I need to send an ajax request to the server, get back the data and save it (persist it with CoreData).
Of course all this happens without the user ever opening the app. When he do opens up the app, a fresh data will be waiting. This is the silent push call back:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Use Alamofire to make an ajax call:
//...
let mutableURLRequest = NSMutableURLRequest(URL: URL)
let requestBodyData : NSMutableData = NSMutableData()
mutableURLRequest.HTTPBody = body
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
request(mutableURLRequest)
.responseJSON { (req, res, data, error) in
//We do not reach this code block !
// Save the incoming data to CoreData
completionHandler(UIBackgroundFetchResult.NewData)
}
}
Now, the problem is that when a notification arrives and the delegate is called, the ajax code executes, make the call to the server, and then exits. The code inside the ajax callback will not run. But, when I open the app and brings it to the foreground, suddenly this code section wakes up and continues to run.
This is not the desirable behaviour because when I open the app I still need to wait 1-2 seconds for the those operations to run (updating the UI etc)
What am I doing wrong here? Should I open a new background thread for this operation?
UPDATE:
I moved completionHandler(UIBackgroundFetchResult.NewData) into the ajax callback, but still this dose not fix the original problem, which is that this ajax callback code block won't execute.
UPDATE 2:
It seems like it's an issue with Alamofire, and that I will have to use NSURLSession to make this ajax call. Trying to put some code together.