方法在巨大延迟后更新UI



我有一个UIView作为父和UIActivityIndicator作为子视图。每当一个用户提交凭据,我开始活动动画和分配的parentViews alpha = 1.0在一个方法名称startLoadingAnimator()之后,它调用了一个API,当API完成调用我设置通过停止它,并设置父视图的alpha = 0.0在一个名为stopLoadingAnimator()的方法中恢复活动动画。问题是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()
    }

更新你的开始和停止动画方法,使它们总是在主线程上执行,像这样:

停止活动动画。

 func stopLoadingAnimator() -> Void {
   dispatch_async(dispatch_get_main_queue(), ^(){
        //Add method, task you want perform on mainQueue
        //Control UIView, IBOutlet all here
        UIView.animateWithDuration(0.25, animations: {
            self.loadingView.alpha = 0
            self.activityIndicator.stopAnimating()
        })
    })
 }

启动活动动画。

func startLoadingAnimator() -> Void {
  dispatch_async(dispatch_get_main_queue(), ^(){
       //Add method, task you want perform on mainQueue
       //Control UIView, IBOutlet all here
        UIView.animateWithDuration(0.25, animations: {
            self.loadingView.alpha = 1
            self.activityIndicator.startAnimating()
        })
     })
  }

最新更新