good4pc
good4pc

Reputation: 711

Completing webservice in background state iOS

Is there any possible way to complete a webservice task when ios application goes to background state using URLSession ? I am not trying to upload a huge sized file to the server , instead i am trying to upload a 4 digit key. i have tried the below method for background task.

var bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {})

For testing purpose , i am calling webservice in a loop and logged. when i go to background mode the webservice calls are getting stuck.

Upvotes: 2

Views: 1227

Answers (2)

ELKA
ELKA

Reputation: 735

Big upload/download files

Introduced in iOS 7.

It really depends on how much the task will take time. If it's a big download or upload task (for example downloading a video) you should execute the task using NSURLSession with background configuration. The iOS system will handle the upload/download task. Once the download completes, the downloaded file will be save into a temporary file (so you might need to copy it to another place later on). Downloading in background and waking app when finished

Normal WebServices (I think that this is what you want)

Introduced in iOS 6

For finite length operation, you can use beginBackgroundTaskWithExpirationHandler.

var task = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(){}
//do your job (call the service)
//on completion you shouldcall the bellow two lines
UIApplication.sharedApplication().endBackgroundTask(task)
task = UIBackgroundTaskInvalid

No need to have configure an NSURLSession with a background configuration.

Upvotes: 1

dirtrider
dirtrider

Reputation: 282

class func generalPost(url: String, postCompleted : (response: String) -> ()) {
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"
        let dataString = "" 
        request.HTTPBody = dataString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
             let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)                    

             postCompleted(response: strData)                  
        })
        task.resume()
    }

And you can use

 generalPost(url: "http://stackoverflow.com/") { (response) in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                UIAlertView(title: "Message", message: response, delegate: nil, cancelButtonTitle: "Ok").show()                
            })
        }

Upvotes: 0

Related Questions