Search code examples
iosswiftapple-push-notificationsurlsessionios-background-mode

REST request from iOS background URLSession using APNs


Update 2018-05-25:

I replaced datatask with downloadTask after reading Rob's answer here: https://stackoverflow.com/a/44140059/4666760 . It still does not work when the app is backgrounded.


Hello

I need some help with iOS background tasks. I want to use Apple Push Notification service (APNs) to wake up my app in the background so that it can do a simple RESTful API call to my server. I am able to make it work when the app is in the foreground, but not in the background. I think I do something wrong with the configuration of the URLSession, but I don't know. The entire code for the app and the server is at my repo linked below. Please, clone it and do whatever you like - I just want your help :)

https://github.com/knutvalen/ping

In AppDelegate.swift the app listen for remote notifications:

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
    }
}

The RestController.swift handles URLSessions with background configurations:

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 = "POST"
        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 = "POST"
        request.httpBody = login.serialize()

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

Solution

  • By adding App provides Voice over IP services as Required Background Mode in info.plist and using PushKit to handle the APNs payloads I were able to do what I wanted. A SSCCE (example) is available at my repository:

    https://github.com/knutvalen/ping