0

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?

Willjay
  • 6,381
  • 4
  • 33
  • 58

1 Answers1

2

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.

Community
  • 1
  • 1
Sebi
  • 71
  • 1
  • 4
  • How can I make the request in order? I tried to use `dispatch_group`. However, i seems not working. [link](http://stackoverflow.com/questions/28100847/checking-for-multiple-asynchronous-responses-from-alamofire-and-swift) – Willjay Apr 01 '16 at 02:43
  • you have to call the next request in your response handler. Or use a delegate and fire it in your response handler to start the next request. You can also cancel your request if the user changes the tab http://stackoverflow.com/questions/26305707/how-to-pause-resume-cancel-my-download-request-in-alamofire – Sebi Apr 01 '16 at 09:36