[英]How can I do an action on receiving a remote notification even when the app is in background or terminated?
I have used this function: 我已经使用了这个功能:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
but getting no result. 但没有结果。 Also I have added the required capabilities(refer screenshot for this).
另外,我还添加了必需的功能(请参阅此屏幕截图)。 How can I do it?
我该怎么做? Actually I have to send the device's location to the server when the app receives notification.
实际上,当应用收到通知时,我必须将设备的位置发送到服务器。 I am able to do it when the app is in foreground but not when the app is in background or is terminated.
我可以在应用程序处于前台时执行此操作,但在应用程序处于后台或终止时无法执行此操作。 screenshot
屏幕截图
在后台启动异步网络操作之前,需要先调用beginBackgroundTask
Objective 目的
Use this code: here type of backgroundUpdateTask variable is NSInteger 使用此代码:此处的backgroundUpdateTask变量类型为NSInteger
- (void) doUpdate
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self beginBackgroundUpdateTask];
NSURLResponse * response = nil;
NSError * error = nil;
//call your api here for location update
NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
// Do something with the result
[self endBackgroundUpdateTask];
});
}
- (void) beginBackgroundUpdateTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
Swift 迅速
func doUpdate() {
DispatchQueue.global(qos: .default).async(execute: {() -> Void in
self.beginBackgroundUpdateTask()
var response: URLResponse? = nil
var error: Error? = nil
//call your api here for location update
let responseData: Data? = try? NSURLConnection.sendSynchronousRequest(request, returning: response)
// Do something with the result
self.endBackgroundUpdateTask()
})
}
func beginBackgroundUpdateTask() {
backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {() -> Void in
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
backgroundUpdateTask = UIBackgroundTaskInvalid
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.