在执行AFNetwork请求之前执行UI更改

时间:2015-04-28 05:13:53

标签: ios swift asynchronous afnetworking

我在登录视图控制器中有一个fromLonLat,按下后,从UIButton获取值并通过UITextField向服务器发出POST请求。我想隐藏文本字段并在按下按钮后立即显示AFNetwork,以便用户看到正在发生的事情。

问题是,请求是异步的,在我甚至可以更新UI之前发生。所以请帮我找到实现理想行为的方法

UIActivityIndicatorView

2 个答案:

答案 0 :(得分:1)

您还可以使用以下方法在单个方法中启动和停止主线程上的活动指示器,同时也提供异步执行代码 -

- (void) buttonTapped:(UIButton *)button
{
    // hide your text field or do any code just before performing request
    // start the activity indicator (you are now on the main queue)
    [activityIndicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // do your background code here
        // perform request here
        dispatch_sync(dispatch_get_main_queue(), ^{
            // stop the activity indicator (you are now on the main queue again)  
        [activityIndicator stopAnimating];
        });
    });
}

注意:上面的示例代码只是骨架,您可以根据自己的要求填充/自定义。

答案 1 :(得分:1)

remove waitUntilFinished()..它阻止当前线程的执行,直到操作对象完成其任务..

manager.POST(requestURL, parameters: [ "code" : token ], success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
   NSLog("Success! Response is \(responseObject.description)")
 }, 
 failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
   println("Failure! Error is: \(error.localizedDescription)")
   self.displayLoginAttempErrorAlert()
 })