0
我有一個UIView
作爲父母和UIActivityIndicator
作爲子視圖。每當用戶提交憑證,我開始活動動畫,並在方法名稱startLoadingAnimator()
中分配父視圖alpha = 1.0它之後它調用一個API,當API完成調用時,我設置爲通過停止它並設置在名爲stopLoadingAnimator()
的方法中父視圖的alpha = 0.0。 問題是stopLoadingAnimator()
在其時間調用完美,但屏幕上的效果顯示延遲後 它應該就像方法運行時它應該消失在那個瞬間,但它需要很長時間消失。方法更新巨大的延遲後的用戶界面
停止活動動畫。
func stopLoadingAnimator() -> Void {
UIView.animateWithDuration(0.25, animations: {
self.loadingView.alpha = 0
self.activityIndicator.stopAnimating()
})
}
啓動活動的動畫。
func startLoadingAnimator() -> Void {
UIView.animateWithDuration(0.25, animations: {
self.loadingView.alpha = 1
self.activityIndicator.startAnimating()
})
}
API方法
func connectToWebWith(username:String, password:String) -> Void {
self.startLoadingAnimator()
let params = ["email":username, "password":password]
// params.setValue(username, forKey: "email")
// params.setValue(password, forKey: "password")
let request = NSMutableURLRequest(URL: NSURL(string: "https://callvabo.com/user/signin")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
self.stopLoadingAnimator()
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
self.stopLoadingAnimator()
guard error == nil else {
return
}
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success = parseJSON["success"] as? Int
print("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
})
task.resume()
}
切勿從後臺線程更新UI。 – rmaddy
是的,更新主線程上的UI。 – Santosh
我想在完成API回調後立即更新UI。與Objective-C類似,我們更新完成塊中的UI –