[英]How can I do an action on receiving a remote notification even when the app is in background or terminated?
我已經使用了這個功能:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
但沒有結果。 另外,我還添加了必需的功能(請參閱此屏幕截圖)。 我該怎么做? 實際上,當應用收到通知時,我必須將設備的位置發送到服務器。 我可以在應用程序處於前台時執行此操作,但在應用程序處於后台或終止時無法執行此操作。 屏幕截圖
在后台啟動異步網絡操作之前,需要先調用beginBackgroundTask
目的
使用此代碼:此處的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;
}
迅速
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.