【问题标题】:swift alamofire request json asynchronousswift alamofire请求json异步
【发布时间】:2019-07-18 01:58:15
【问题描述】:

我尝试通过 Alamofire 发送请求以从 Amazon 获取 JSON,但它是异步的。在得到亚马逊的响应之前,它会返回调用者函数。

public func getJSON(fileName: String) -> JSON?{
    let url = "http://s3.eu-west-3.amazonaws.com" + fileName
    print(self.json)

    if self.json == nil {
        Alamofire.request(url)
            .responseJSON { response in
                if let result = response.result.value {
                    self.json = JSON(result)
                }

        }
       return self.json
    }
    else{
        return nil
    }
}

public func initTableView(){
    let myJson = AmazonFiles.shared.getJSON(fileName: "/jsonsBucket/myJson.json")
    print(myJson["id"])
}

initTableView 函数中的对象myJson 始终为零。

我该如何解决这个问题?

【问题讨论】:

    标签: ios swift asynchronous alamofire


    【解决方案1】:

    您需要实现一个完成处理程序, 看看这个article

    完成处理程序是我们提供的代码,以便在它返回这些项目时被调用。这是我们可以处理调用结果的地方:错误检查、本地保存数据、更新 UI 等等。

    typealias completionHandler = (JSON?) -> Void // this is your completion handler
    
    public func getJSON(fileName: String, completionHandler: @escaping completionHandler) -> JSON?{
        let url = "http://s3.eu-west-3.amazonaws.com" + fileName
        if self.json == nil {
            Alamofire.request(url)
                .responseJSON { response in
                    if let result = response.result.value {
                      completionHandler(json) // this will fire up your completion handler,
                    }
            }
        }
        else{
            completionHandler(nil)
        }
    }
    

    你可以像这样使用它。

    getJSON(fileName: "fileName") { (json) in
        // this will fire up when completionhandler clousre in the function get triggered
        //then you can use the result you passed whether its JSON or nil
        guard let result = json  else { return } // unwrap your result and use it
        print(result)
    }
    

    【讨论】:

      【解决方案2】:

      而不是返回 JSON?在方法签名中,使用这样的完成闭包:

      public func getJSON(fileName: String, completion: ((JSON?) -> Void)?) {
          let url = "http://s3.eu-west-3.amazonaws.com" + fileName
          Alamofire.request(url).responseJSON { response in
              if let result = response.result.value {
                  completion?(JSON(result))
              } else {
                  completion?(nil)
              }
          }
      }
      

      然后像这样调用方法:

      getJSON(fileName: "/jsonsBucket/myJson.json") { json in
          print(json)
      }
      

      或者:

      getJSON(fileName: "/jsonsBucket/myJson.json", completion: { json in
          print(json)
      })
      

      【讨论】:

        猜你喜欢
        • 2016-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-03
        • 1970-01-01
        相关资源
        最近更新 更多