Shemil Hashan Shemil Hashan - 1 year ago 94
Swift Question

IOS SWIFT - Return response data when service call finish fetching

I have a web service which returns response in json.
I created a separate class for data access in xcode(swift) for iphone.
What I want to do is call a function in the data access layer, which returns the response dictionary, WHEN FETCHING IS COMPLETE.
Problem: How return ONLY WHEN fetching from service is complete.
Ex: Student Table->Click a student->Fetch data of student->Return data when fetching completes

func getUser(userID:String)->NSDictionary{

let manager = AFHTTPRequestOperationManager()
let parameters = ["uid":userID]
manager.POST(urlStudentInfo, parameters: parameters,
success: {(operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
print("JSON success: " + responseObject.description)
if let responseDic = responseObject as? NSDictionary{
let isUser = responseDic["status"] as! Bool

if isUser{




failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in


return response


This is my function structure. Problem is fetching happens after the return is done. So the return is always nil.

Anyone have a suggestion to return only after fetching is complete?

Answer Source

What does your {callService} actually look like? does it have a completion handler? but in general, asynchronous functions like webservices cant be thought of in the same way as a normal function, you need to launch the ws call in one function, then call another function to let something know its finished from the completion handler, or whatever lets the ws function know its completed. So in short, you shouldnt be trying to return anything from that function, and instead return the value from the completion handler


I would advise not to use NSNotifications, but rather delegate callbacks, or simply just use the data inside the completion handler directly. but whatever is trying to use that returned NSDictionary should instead be a delegate of the class this function is in (look up tutorials on protocols if you dont know how it works), then you can pass the dictionary back through the delegates callbacks inside the completion handler (think of how UITableviews make you implement all those functions to make it work, you need to make something similar for your webservice call)

this answer might help you understand what i mean