我想在我的应用程序中使用静默推送通知。我在应用程序和手机上启用了后台模式。
当静默通知到达时didReceiveRemoteNotification
委托方法正在调用。但是我不能在这种方法中执行任何 http 请求。我使用以下代码:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("step 1")
let request = NSMutableURLRequest(URL: NSURL(string: "url")!)
request.HTTPMethod = "POST"
let postString = "search=(username)&me=(anonId)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
print("step 2")
if error == nil {
let jsonResult: Dictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! Dictionary<String, AnyObject>
let results = jsonResult["result"] as! [[String: AnyObject]]
print(results)
for item in results {
}
completionHandler(UIBackgroundFetchResult.NewData)
}
}
}
收到通知后,我在控制台上看到step 1
文本。但我看不到step 2
文字。
如何解决此问题?
您需要设置一个支持后台下载的 URL 会话并使用该会话。在NSURLSession
类参考中搜索"背景"以获取有关如何执行此操作的信息。
我认为您不必要求后台时间才能启动后台下载。你应该有足够的时间去做这件事。