• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 来自 iOS 后台 URLSession 的 REST 请求使用 APNs

[复制链接]
菜鸟教程小白 发表于 2022-12-11 20:11:44 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

2018 年 5 月 25 日更新:

在阅读 Rob 的回答后,我将 datatask 替换为 downloadTask : https://stackoverflow.com/a/44140059/4666760 。当应用程序在后台运行时,它仍然不起作用。


你好

我需要一些有关 iOS 后台任务的帮助。我想使用 Apple 推送通知服务 (APNs) 在后台唤醒我的应用程序,以便它可以对我的服务器进行简单的 RESTful API 调用。当应用程序在前台而不是在后台时,我可以让它工作。我想我对 URLSession 的配置做错了,但我不知道。应用程序和服务器的完整代码位于下面链接的我的仓库中。请克隆它并做任何你喜欢的事情 - 我只是想要你的帮助

https://github.com/knutvalen/ping

AppDelegate.swift 中应用监听远程通知:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    // MARK: - Properties

    var window: UIWindow?

    // MARK: - Private functions

    private func registerForPushNotifications() {
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            guard granted else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    // MARK: - Delegate functions

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        Login.shared.username = "foo"
        registerForPushNotifications()
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        os_log("AppDelegate application(_:didRegisterForRemoteNotificationsWithDeviceToken token: %@", token)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        os_log("AppDelegate application(_:didFailToRegisterForRemoteNotificationsWithError error: %@", error.localizedDescription)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        os_log("AppDelegate application(_:didReceiveRemoteNotification:fetchCompletionHandler")
            if let aps = userInfo["aps"] as? [String: AnyObject] {
            if aps["content-available"] as? Int == 1 {
                RestController.shared.onPing = { () in
                    RestController.shared.onPing = nil
                    completionHandler(.newData)
                    os_log("AppDelegate onPing")
                }

                RestController.shared.pingBackground(login: Login.shared)
//                RestController.shared.pingForeground(login: Login.shared)
            }
        }
    }

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        RestController.shared.backgroundSessionCompletionHandler = completionHandler
    }
}

RestController.swift 处理带有后台配置的 URLSession:

class RestController: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate {

    // MARK: - Properties

    static let shared = RestController()
    let identifier = "no.qassql.ping.background"
    let ip = "http://123.456.7.89:3000"
    var backgroundUrlSession: URLSession?
    var backgroundSessionCompletionHandler: (() -> Void)?
    var onPing: (() -> ())?

    // MARK: - Initialization

    override init() {
        super.init()
        let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
        configuration.isDiscretionary = false
        configuration.sessionSendsLaunchEvents = true
        backgroundUrlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }

    // MARK: - Delegate functions

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        DispatchQueue.main.async {
            if let completionHandler = self.backgroundSessionCompletionHandler {
                self.backgroundSessionCompletionHandler = nil
                completionHandler()
            }
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            os_log("RestController urlSession(_:task:didCompleteWithError error: %@", error.localizedDescription)
        }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        do {
            let data = try Data(contentsOf: location)
            let respopnse = downloadTask.response
            let error = downloadTask.error

            self.completionHandler(data: data, response: respopnse, error: error)
        } catch {
            os_log("RestController urlSession(_:downloadTask:didFinishDownloadingTo error: %@", error.localizedDescription)
        }
    }

    // MARK: - Private functions

    private func completionHandler(data: Data?, response: URLResponse?, error: Error?) {
        guard let data = data else { return }

        if let okResponse = OkResponse.deSerialize(data: data) {
            if okResponse.message == ("ping_" + Login.shared.username) {
                RestController.shared.onPing?()
            }
        }
    }

    // MARK: - Public functions

    func pingBackground(login: Login) {
        guard let url = URL(string: ip + "/ping") else { return }
        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "OST"
        request.httpBody = login.serialize()

        if let backgroundUrlSession = backgroundUrlSession {
            backgroundUrlSession.downloadTask(with: request).resume()
        }
    }

    func pingForeground(login: Login) {
        guard let url = URL(string: ip + "/ping") else { return }
        var request = URLRequest(url: url)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "OST"
        request.httpBody = login.serialize()

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            return self.completionHandler(data: data, response: response, error: error)
        }.resume()
    }
}



Best Answer-推荐答案


通过在 info.plist 中添加 App 提供 IP 语音服务 作为所需的后台模式,并使用 PushKit 处理 APNs 负载,我能够做我想做的事。我的存储库中提供了 SSCCE(示例):

https://github.com/knutvalen/ping

关于ios - 来自 iOS 后台 URLSession 的 REST 请求使用 APNs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50497207/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap