Swift animateWithDuration调用在长时间后写入URLSession时进行
在Swift 2.0中,我使用web API上传和下载一些数据。在调用API之前,我已经启动了一个活动指示器动画,并希望在API响应到来时停止它 但是,当我想在API响应后停止动画时,指示器会在长时间等待后停止 这是我的密码:Swift animateWithDuration调用在长时间后写入URLSession时进行,swift,nsurlsession,animatewithduration,activity-indicator,Swift,Nsurlsession,Animatewithduration,Activity Indicator,在Swift 2.0中,我使用web API上传和下载一些数据。在调用API之前,我已经启动了一个活动指示器动画,并希望在API响应到来时停止它 但是,当我想在API响应后停止动画时,指示器会在长时间等待后停止 这是我的密码: let activityIndi = UIActivityIndicatorView(activityIndicatorStyle: .White) activityIndi.startAnimating() flagBtn.addSubview
let activityIndi = UIActivityIndicatorView(activityIndicatorStyle: .White)
activityIndi.startAnimating()
flagBtn.addSubview(activityIndi)
let urlString = NSURL(string: "URL")
NSURLSession.sharedSession().dataTaskWithURL(urlString!, completionHandler: { (data: NSData?, _, _) -> Void in
if data != nil {
do {
let jsonInfoDic = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String:AnyObject]
if(jsonInfoDic["status"] as! Bool)
{
UIView.animateWithDuration(1.0, animations: {
activityIndi.stopAnimating()
}, completion:{ (finished: Bool) -> Void in
})
}
}
catch { print("Exception in parsing JSON.\n\nReason: \(error)") }
}
}).resume()
您需要在主线程上执行UI修改操作。由于
dataTaskWithURL:completionHandler:
的回调是在后台线程(NSURLSession
thread)上执行的,因此必须按如下方式分派UI代码:
dispatch_async(dispatch_get_main_queue()) {
activityIndi.stopAnimating()
}
此外,我怀疑您不需要
UIView.animateWithDuration:completion:
,因为stop animating
本身执行动画。您需要在主线程上执行UI修改操作。由于dataTaskWithURL:completionHandler:
的回调是在后台线程(NSURLSession
thread)上执行的,因此必须按如下方式分派UI代码:
dispatch_async(dispatch_get_main_queue()) {
activityIndi.stopAnimating()
}
此外,我怀疑您不需要UIView.animateWithDuration:completion:
,因为stop animating
会自动执行动画