【问题标题】:AFNetworking and Swift - Save json responseAFNetworking 和 Swift - 保存 json 响应
【发布时间】:2014-07-03 09:14:35
【问题描述】:

我想快速发出 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 ""
}

你能帮帮我吗?

【问题讨论】:

    标签: json swift afnetworking afnetworking-2


    【解决方案1】:

    由于您想在 web 服务请求完成后返回值,您必须通过委托或块传递数据(在 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 :])

    【讨论】:

      【解决方案2】:

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

      1. 你拨打makeGet

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

      3. makeGet 执行完毕,返回一个空字符串

      4. (一段时间后)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】:
        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。 这是一个获取响应对象的简单示例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-28
          • 2013-12-08
          • 1970-01-01
          • 2014-03-24
          • 1970-01-01
          相关资源
          最近更新 更多