Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift UIActivityIndicatorView while NSURLConnection

I know how to animate the UIActivityIndicatorView I know how to make a connection with NSURLConnection.sendSynchronousRequest

But I don't know how to animate the UIActivityIndicatorView WHILE making a connection with NSURLConnection.sendSynchronousRequest

Thanks

like image 660
dams net Avatar asked Dec 21 '14 17:12

dams net


2 Answers

Don't use sendSynchronousRequest from main thread (because it will block whatever thread you run it from). You could use sendAsynchronousRequest, or, given that NSURLConnection is deprecated, you should really use NSURLSession, and then your attempt to use UIActivityIndicatorView should work fine.

For example, in Swift 3:

let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
indicator.center = view.center
view.addSubview(indicator)
indicator.startAnimating()

URLSession.shared.dataTask(with: request) { data, response, error in
    defer {
        DispatchQueue.main.async {
            indicator.stopAnimating()
        }
    }

    // use `data`, `response`, and `error` here
}

// but not here, because the above runs asynchronously

Or, in Swift 2:

let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
indicator.center = view.center
view.addSubview(indicator)
indicator.startAnimating()

NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    defer {
        dispatch_async(dispatch_get_main_queue()) {
            indicator.stopAnimating()
        }
    }

    // use `data`, `response`, and `error` here
}

// but not here, because the above runs asynchronously
like image 136
Rob Avatar answered Nov 10 '22 20:11

Rob


As pointed out by @Rob in the comment, as long as you use a SynchronousRequest it will block your UI-thread and you won't be able to animate anything. Chris does a good job at explaining the two modes of NSURLConnection in this article (though for Objective-C, but you will get the idea). Among other things he compares the two modes as

Async or Sync?

So should you perform an asynchronous request or use a synchronous one for your application? I find that in the large majority of times, I’m using the async request because otherwise the UI would be frozen while the synchronous request is doing its thing and that’s a big problem when the user is performing gestures or touches and the screen is unresponsive. Unless I’m firing off a request to do something really simple and quick like ping a server, I default to using the async pattern.

This summarizes your options better than I could state it. So you really should learn about the asynchronous variant in order to be able to do your animation.

like image 43
Patru Avatar answered Nov 10 '22 21:11

Patru