简体   繁体   中英

Http request using Alamofire

I'm using Alamofire to send HTTP request in my App. I'm using a TabBarViewController, In first view's ViewDidLoad, I send a request. Also in ViewWillDisappear, I send another request. 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

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.

Read here to understand asyncs and syncs: Difference between dispatch_async and dispatch_sync on serial queue?

You can cancel your alamofire request when you change the tab and the request is not finished. For this you need an Alamofire Manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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