The code between the {}
is the equivalent of block in objective-C : this is a chunk of code that gets executed asynchronously.
The error you made is where you put your return statement : when you launch your request, the code in {}
is not executed until the framework received a response, so when the return
statement is reached, chances are, there is still no response. You could simply move the line :
return responsePackage
inside the closure, so the func
return only when it has received a response. This is a simple way, but it’s not really optimal : your code will get stuck at waiting for the answers. The best way you can do this is by using closure, too. This would look something like :
func get(apiEndPoint: NSString, completion: (response: ResponsePackage) -> ()) -> Bool {
let responsePackage = ResponsePackage()
Alamofire
.request(.GET, apiEndPoint)
.responseJSON {(request, response, JSON, error) in
responsePackage.response = JSON
responsePackage.success = true
responsePackage.error = error
completion(response: responsePackage)
}
}