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

Perform UI changes before performing AFNetwork request

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

问题是,请求是异步的,甚至在我更新 UI 之前就发生了。所以请帮我找到一种方法来实现所需的行为

pwdTextField.hidden = true

// Start the activity indicator
activityIndicator.startAnimating()    

// How can I make this happen before the actual request?    

let token = pwdTextField.text.trim()
let requestURL = "https://myapi.com/authenticate/"

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()
}).waitUntilFinished()

您还可以使用以下方法在主线程中以单一方法启动和停止 activity 指标,还可以让您异步执行代码 -

- (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];
        });
    });
}

注意:以上示例代码只是框架,您可以根据需要填充/自定义它。

删除 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()
 })