2014-12-21 42 views
4

我知道如何動畫UIActivityIndi​​catorView 我知道如何使NSURLConnection.sendSynchronousRequest迅速UIActivityIndi​​catorView而NSURLConnection的

連接,但我不知道如何製作動畫的UIActivityIndi​​catorView,同時與NSURLConnection.sendSynchronousRequest

由於連接

+0

您可能對此課程感興趣:https://github.com/goktugyil/CozyLoadingActivity – Esqarrouth

回答

12

請勿在主線程中使用sendSynchronousRequest(因爲它會阻止您運行它的任何線程)。您可以使用sendAsynchronousRequest,或者,由於NSURLConnection已棄用,因此您應該使用NSURLSession,然後嘗試使用UIActivityIndicatorView應該可以正常工作。

例如,在斯威夫特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 

或者,斯威夫特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 
1

正如評論所指出的@Rob,只要您使用SynchronousRequest它會阻止你的UI線程,你將不能動畫任何東西。 Chris在解釋NSURLConnectionthis article這兩種模式方面做得很好(雖然對於Objective-C,但你會明白)。除此之外,他將兩種模式比較爲

異步或同步?

所以你應該爲你的應用程序執行異步請求還是使用同步請求?我發現在大多數情況下,我使用異步請求,因爲否則當同步請求正在做它的事情時UI會被凍結,當用戶執行手勢或觸摸並且屏幕無響應時,這是一個大問題。除非我發出一個請求,像ping一臺服務器那樣簡單快速地完成某項操作,否則我會默認使用異步模式。

這總結了你的選擇比我能說的更好。所以你應該瞭解異步變體以便能夠進行動畫製作。

相關問題