Search code examples
swiftxcodeurlalamofirebackground-process

Alamofire background working on simulator but not on device


As the title mentions I've set up a backgroundURL with Alamofire. It works like a charm in simulator but on my device doesn't. I'm sure I'm missing something here since I'm not that experienced with URL. Here's the code I have so far:

class NetworkManager {

static let shared = NetworkManager()

private lazy var backgroundManager: Alamofire.SessionManager = {
    let bundleIdentifier = MyStruct.identifier
    return Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: bundleIdentifier))
}()

var backgroundCompletionHandler: (() -> Void)? {
    get{
        return backgroundManager.backgroundCompletionHandler
    }
    set{
        backgroundManager.backgroundCompletionHandler = newValue
    }
}

}

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

In my ViewController:

 func populateArrays(){  
 Alamofire.request("http://www.aps.anl.gov/Accelerator_Systems_Division/Accelerator_Operations_Physics/sddsStatus/mainStatus.sdds.gz").responseData { response in
        switch response.result{
        case .success:
            print("Validation Successful")
        case .failure(let error):
            print(error.localizedDescription)
        }
        if let data = response.result.value{

Solution

  • Solved it. For anyone else that has this problem you need to add the following code to your appDelegate.

        func applicationDidEnterBackground(_ application: UIApplication) {
        var bgTask = 0
        var app = UIApplication.shared
        bgTask = app.beginBackgroundTask(expirationHandler: {() -> Void in
            app.endBackgroundTask(bgTask)
    })