I perform a REST call whenever the application the application becomes inactive. I make the call within the AppDelegate's
applicationWillResignActive
method. The call works perfectly if the user clicks the home button on the device, but if a user locks the screen while the application is still in the foreground, the call appears to send, but never completes and I don't receive the call on the server side.
I even attempted what was mentioned in the Creating a Manager with Background Configuration
section, but the result has been the same. When using the background configuration, I do receive the error Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service"
. This is the code I currently have:
var deviceId:String
// Check if deviceId has been stored
if let device: String = NSUserDefaults.standardUserDefaults().stringForKey(Globals.KEY_DEVICE_ID) {
// deviceId is stored, use it
deviceId = device
} else {
// deviceId not stored, create a new one and store it
deviceId = NSUUID().UUIDString
NSUserDefaults.standardUserDefaults().setObject(deviceId, forKey: Globals.KEY_DEVICE_ID)
}
let params = ["statusId": "2"]
let url = "client/device/" + deviceId
// Create the URL Request
let URLRequest = NSMutableURLRequest(URL: NSURL(string: Globals.BASE_URL + url)!)
// set header fields
if let key = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_SESSION) {
URLRequest.setValue(key, forHTTPHeaderField: "X-XX-API")
}
// Add user agent
if let userAgent = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_USER_AGENT) {
URLRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent")
}
// Set the HTTP method
URLRequest.HTTPMethod = Alamofire.Method.PUT.rawValue
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.myapp.background")
manager = Alamofire.Manager(configuration: configuration)
let encodeMethod: Alamofire.ParameterEncoding = Alamofire.ParameterEncoding.URL
manager.startRequestsImmediately = true
manager.request(encodeMethod.encode(URLRequest, parameters: params).0).validate().responseJSON() {
(response) in
print("response from call: \(response)")
self.manager = nil
}
I am using XCode 7.1 with deployment target 9.1 and Alamofire version 3.1.2.