Fast UIActivityIndicatorView with NSURLConnection

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

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

thank

+4
source share
2 answers

Do not use sendSynchronousRequestfrom the main thread (because it will block any thread from which you start it). You can use, sendAsynchronousRequestor given that it's NSURLConnectionout of date, you really should use NSURLSession, and then your attempt to use UIActivityIndicatorViewshould 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
+12
source

@Rob , SynchronousRequest, UI-, . NSURLConnection ( Objective-C, ),

Async Sync?

, ? , Im async, , , , , . Im, - , ping-, async.

, . , .

+1

Source: https://habr.com/ru/post/1568536/


All Articles