AFNetworking和Swift - 保存json响应

时间:2014-07-03 09:14:36

标签: json swift afnetworking afnetworking-2

我想在swift中发出一个GET请求来获取一些Json数据。 我尝试使用AFNetworking并且它可以工作,但我不知道如何返回我得到的Json。

我尝试使用return,但它是在GET之前制作的,所以我什么都没得到......

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 ""
}
你能帮帮我吗?

3 个答案:

答案 0 :(得分:4)

由于你想在webservice请求完成后返回值,你必须通过委托或块传递数据(在swift中称为闭包)

我看到这里有用的块

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

有关swift closures

的更多信息

仅供参考:AFNetworking所有者为swift创建了一个新的网络层,它被称为Alamofire(来自AFNetworking的AF是Alamofire:])

答案 1 :(得分:3)

您没有从该函数获得响应,因为GET操作是异步发生的。也就是说,执行顺序如下:

  1. 您致电makeGet

  2. makeGet创建manager,会触发GET请求

  3. makeGet完成执行并返回空字符串

  4. (一段时间之后) manager从服务器收回一个值,然后执行successfailure阻止。

  5. 因此,您可以访问从服务器返回的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)
                }
            )
        }
    
    }
    

答案 2 :(得分:2)

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

AFHTTPRequestOperationManager在最新的AFnetworking库中不可用,它已替换为AFHTTPSessionManager。 这是获取响应对象的简单示例。