【问题标题】:SwiftyJSON - Returning json array from funcSwiftyJSON - 从 func 返回 json 数组
【发布时间】:2015-10-20 11:40:11
【问题描述】:

我正在开发我的本地 json api,它可以很好地使用 swiftyjson 和 alamofire 接收和解析数据,但是在返回这些数据时,我遇到了一些麻烦:

import Alamofire
import SwiftyJSON

...

func getApi() -> Array<JSON> {

    let user = "user"
    let password = "password"

    Alamofire.request(.GET, "http://localhost/api/")
        .authenticate(user: user, password: password)
        .responseString { (req, res, body, error) in

            if let data = (body)!.dataUsingEncoding(NSUTF8StringEncoding) {

                let json = JSON(data: data)

                println(json) // works fine

                return json // does not work   
            }
    }
}

所以它打印“JSON 不可转换为 Void”...

有人知道怎么处理吗?

你认为我使用 alamofire 进行“http-basic-authentification”做得对吗?

问候和感谢!

【问题讨论】:

    标签: json swift function parsing return


    【解决方案1】:

    如果你的 api 返回一个 JSON 对象,alamofire 提供一个 .responseJSON,swiftyJSON 可以包装那个响应。

    另外不要忘记这个请求是异步的,所以你可能需要在完成处理程序中获取这些结果,如下所示:

    func getApi(completionHandler: (jsonResponse: JSON) -> () {
        let user = "user"
        let password = "password"
    
        Alamofire.request(.GET, "http://localhost/api/")
            .authenticate(user: user, password: password)
            .responseJSON { (req, res, JSON, error) in
    
                    println(json) // works fine
    
                    completionHandler(json)
                }
        }
    }
    

    像这样调用方法:

    getAPI(completionHandler: { (response: JSON) -> () in
      // do something with your response. If the JSON contains an array you can iterate through it here.
    }
    

    下一件好事是检查 Alamofire 文档上的“响应序列化”部分。

    【讨论】:

      【解决方案2】:

      您正试图在没有返回类型 (Void) 的块内返回 JSON 类型的对象。

      【讨论】:

        【解决方案3】:

        根据你的变量名,你应该设置

        res = json 
        

        res.setResponse(json)
        

        或者像这样。现在无法检查,因为我现在离我的 mac 很远

        【讨论】:

          【解决方案4】:

          您的函数返回一个 JSON 数组:[JSON]

          您正在尝试返回单个 JSON 类型对象。

          更改您的 return 语句以返回一个数组:

          return [json] // should work
          

          编辑:我在发布答案时误读了代码。您正在调用异步方法 Alamofire.request。该方法会立即返回,但数据直到稍后才会真正加载。您当前的设计将无法正常工作。

          @Gwendle 的答案是正确的。您需要重构您的方法以获取完成块并将响应处理放在该完成块中。

          【讨论】:

          • 作者试图在没有返回类型的 Alamofire 块中返回 JSON 类型的对象,因此出现 Void 错误。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-13
          • 2020-05-19
          • 1970-01-01
          相关资源
          最近更新 更多