Alamofire Request not getting executed

强颜欢笑 提交于 2019-12-24 11:36:33

问题


Something strange is happening. I have two ViewControllers A & B.

In both of them I have imported Alamofire using below command

import Alamofire

ISSUE: I am calling exactly the same Alamofire Request in both controller. In VC - A it executes, in VC - B --its just not executing..There is no error or anything. When I debug using breakpoints, the entire Alamofire code is getting skipped for some reason. Can't seem to figure out why.

Below is my Alamofire Code (THIS IS SAME in BOTH Controllers A & B)

override func viewDidLoad() {
    super.viewDidLoad()
print("check1") 
Alamofire.request(.GET, hubsURL).response { request, response, result, error in
        print(response)
        print("check2")
}
print("check"3)
}

The above code prints the response when ViewController A is executed but not for View Controller B. For viewcontroller B other commands are getting executed only Alamofire not getting executed.In the above code - "Check 1" & "Check 3" get printed to console but not "Check 2" (for VC - B).


回答1:


Alamofire code is asynchronous, that means while your print statements may be executed successfully and synchronously, some function in either viewDidLoad or viewDidAppear (or somewhere else) may be looping forever not allowing alamofire.request to execute its closure.

For example this code below will print: check1, check3, but because the func inside viewDidAppear is blocking, Alamofire can't execute its asynchronous code. So in this example the Alamofire request will do nothing. If you comment out the endless loop, the code will work.

override func viewDidLoad() {
    super.viewDidLoad()
    print("check1") 
    Alamofire.request(.GET, hubsURL).response { request, response, result, error in
        print(response)
        print("check2")
    }
    print("check"3)
}

override func viewDidAppear(animated: Bool) {
    while (true != nil) {
    }
    print("After While")
}

Plus I would suggest moving to Alamofire 3.0 https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md




回答2:


There can be many problems, we cannot tell if you do not provide the entire code. Maybe you just messed with other part of the code, for example

  • Is that action triggered by a button? Is the button/action properly connected in your code/storyboard?
  • Did you set correctly the UIViewController in the Storyboard? Meaning is the viewcontroller you are calling a VC - B? (Is your viewDidLoad method called?)

And many more possibilities, but if it works for VC - A there shouldn't be a problem with Alamofire. If you still cannot solve consider editing your question with additional code.



来源:https://stackoverflow.com/questions/33023046/alamofire-request-not-getting-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!