Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking and Swift - Save json response

I want to make a GET request in swift to get some Json data. I tried to use AFNetworking and it works, but I don't know how to return the Json I get.

I tried with a return but it's made before the GET so I get nothing...

func makeGet(place:String) -> String
{
    var str:String = ""
    let manager = AFHTTPRequestOperationManager()
    manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
    manager.GET("http://something.com/api/\(place)",
        parameters: nil,
        success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
            str = "JSON:  \(responseObject.description)"
            println(str) //print the good thing
        },
        failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
            str = "Error: \(error.localizedDescription)"
        })
    return str //return ""
}

Can you help me ?

like image 621
1L30 Avatar asked Dec 26 '22 07:12

1L30


1 Answers

Since you want to return the value after the webservice request is completed you have to pass the data via a delegate or a block(In swift it is called closures)

I see blocks useful here

//Above your class file create a handler alias 
typealias SomeHandler = (String! , Bool!) -> Void

func makeGet(place:String , completionHandler: SomeHandler!)
{
    var str:String = ""
    let manager = AFHTTPRequestOperationManager()
    manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
    manager.GET("http://something.com/api/\(place)",
        parameters: nil,
        success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
            str = "JSON:  \(responseObject.description)"
            println(str) //print the good thing
            completionHandler(str,false)   //str as response json, false as error value

        },
        failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
            str = "Error: \(error.localizedDescription)"
            completionHandler("Error",true)   
        })
    //return str //return ""    You don't want to return anything here
}

When you want to call the method get the values like this

makeGet(){
   yourJSONString , errorValue in   //Here the value will be passed after you get the response

     if !errorValue { 
         println("The End."
     }
}

More about swift closures

FYI: AFNetworking owner has created a new Networking layer for swift and it is called Alamofire (AF from AFNetworking is Alamofire :])

like image 172
ipraba Avatar answered Jan 07 '23 23:01

ipraba