My app initiates uploading content to a server while in the foreground. Since this process could take some time, the user could very well transition the app to the background.
I'm using AFHTTPSessionManager to submit the upload:
let sessionManager = AFHTTPSessionManager()
sessionManager.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type")
sessionManager.POST(urlStr, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
formData.appendPartWithFileData(dataObject, name: "object", fileName: mimeType == "image/jpg" ? "pic.jpg" : "pic.mp4", mimeType: mimeType)
}, progress: { (progress) -> Void in
}, success: { (task, responseObject) -> Void in
print(responseObject)
success(responseObject: responseObject)
}, failure: { (task, error) -> Void in
print(error)
if let errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
do {
let json = try NSJSONSerialization.JSONObjectWithData(errorData, options: NSJSONReadingOptions.MutableContainers)
failure(error: error, responseObject: json)
} catch let error {
print(error)
}
}
})
I need this process to continue while the app is in the background state until completion. There's an excellent SO answer here which has gotten me on the right track, but I'm still in the dark in some places. I've tried using the "BackgroundSessionManager" class from the linked answer to change my upload call to this:
BackgroundSessionManager.sharedManager().POST(NetworkManager.kBaseURLString + "fulfill_request", parameters: params, constructingBodyWithBlock: { (formData) -> Void in
formData.appendPartWithFileData(dataObject, name: "object", fileName: mimeType == "image/jpg" ? "pic.jpg" : "pic.mp4", mimeType: mimeType)
}, progress: nil, success: nil, failure: nil)?.resume()
And added this to my AppDelegate:
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
BackgroundSessionManager.sharedManager().savedCompletionHandler = completionHandler
}
But I'm getting an EXC_BAD_ACCESS crash on some background thread with little to no information. Am I even approaching this correctly?