繁体   English   中英

即使应用程序处于后台或终止状态,我该如何采取措施接收远程通知?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM