我在视图控制器中的函数内部已经有了所有这些代码:
self.activityIndicator.startAnimating()
let url = NSURL(string: "http://www.google.com")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "PUT"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(["notes": self.textView.text], options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var s = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, reponse, error) -> Void in
// ------------------
// This doesn't work
// ------------------
self.activityIndicator.stopAnimating()
println(NSString(data: data, encoding: NSUTF8StringEncoding))
})
task.resume()
我希望我的活动指示器在我完成任务时停止动画,但是调用stopAnimating()没有做任何事情 - 甚至没有抛出任何错误。谁知道我做错了什么?
答案 0 :(得分:2)
您需要在主UI线程上执行此操作,如下所示:
// ------------------
// This should work :-)
// ------------------
dispatch_async(dispatch_get_main_queue(), {
// DO SOMETHING ON THE MAINTHREAD
self.activityIndicator.stopAnimating()
})
答案 1 :(得分:1)
在主线程上执行:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, reponse, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.stopAnimating()
}
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}