简体   繁体   English

使用Alamofire的HTTP请求

[英]Http request using Alamofire

I'm using Alamofire to send HTTP request in my App. 我正在使用Alamofire在我的应用程序中发送HTTP请求。 I'm using a TabBarViewController, In first view's ViewDidLoad, I send a request. 我正在使用TabBarViewController,在第一个视图的ViewDidLoad中,我发送了一个请求。 Also in ViewWillDisappear, I send another request. 同样在ViewWillDisappear中,我发送了另一个请求。 However, I found it behave unexpected when I changing the tabs. 但是,我发现在更改选项卡时,它的行为异常。

func sendHttpCommand(parameter: NSDictionary) {
    Alamofire.request(.GET, URL, parameters: (parameter as! [String: AnyObject]))
             .response {
                 request, response, data, error in
                 print(request)
             }
}

viewDidLoad() {
    let dict: NSDictionary = ["value": 0]
    sendHttpCommand(dict)
}

viewWillDisappear(animated: Bool) {
    let dict: NSDictionary = ["value": 1]
    sendHttpCommand(dict)
}

When I switching the tabs, in NORMAL CASE , my console will print out 当我切换选项卡时,在NORMAL CASE中 ,我的控制台将打印输出

Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})

However, when I switching the tabs fast enough , my console will print out 但是,当我足够快地切换选项卡时,控制台将打印出

Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=1})
Optional(NSMutableURLRequest {URL: xxxxx/value=0})

Any ideas? 有任何想法吗?

the alamofire requests are executed async. alamofire请求将异步执行。

Read here to understand asyncs and syncs: Difference between dispatch_async and dispatch_sync on serial queue? 阅读此处以了解异步和同步: 串行队列上的dispatch_async和dispatch_sync之间的区别?

You can cancel your alamofire request when you change the tab and the request is not finished. 当您更改标签并且请求未完成时,您可以取消alamofire请求。 For this you need an Alamofire Manager. 为此,您需要Alamofire管理器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM