swift UIActivityIndicatorView while NSURLConnection

dams net picture dams net · Dec 21, 2014 · Viewed 7k times · Source

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

Answer

Rob picture Rob · Dec 21, 2014

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