AFNetworking and Swift - keep json response

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

I tried with return, but did it before 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 ""
}

Could you help me?

+4
source share
3 answers

You are not receiving a response from this function because the GET operation occurs asynchronously. That is, the execution order is as follows:

  • You call makeGet

  • makeGetcreates managerthat launches a get request

  • makeGet completes execution and returns an empty string

  • ( ) manager success, failure.

, , JSON, , 4, , . - , , :

class MyClass {

    func jsonLoaded(json: String) {
        println("JSON: \(json)")
    }

    func jsonFailed(error: NSError) {
        println("Error: \(error.localizedDescription)")
    }

    func makeGet(place: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
                self.jsonLoaded(responseObject.description)
            },
            failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
                self.jsonFailed(error)
            }
        )
    }

}
+3

webservice, ( )

.

//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
}

, ,

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

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

FYI: AFNetworking Networking swift Alamofire (AF AFNetworking - Alamofire:])

+4
let manager = AFHTTPSessionManager()
    manager.GET("http://api.androidhive.info/json/movies.json", parameters: nil, success: { (operation, responseObject) -> Void in
        print(responseObject)
        }, failure: nil)

AFHTTPRequestOperationManager is not available in the latest AFnetworking library, it is replaced by AFHTTPSessionManager. This is a simple example of getting a response object.

+2
source

Source: https://habr.com/ru/post/1546975/


All Articles