【问题标题】:Swift - How to return json object from an API call in Model to use in View ControllerSwift - 如何从模型中的 API 调用返回 json 对象以在视图控制器中使用
【发布时间】:2017-06-26 20:15:25
【问题描述】:

我正在使用 REST api 在我的应用程序中显示一些细节。为此,我计划有一个数据模型类将数据传递回控制器。

    import UIKit
import AlamofireObjectMapper
import Alamofire
class ContactUsModelClass {

    func getContactUsApiCall(URL: URL, callback: @escaping ((Dictionary<AnyHashable,Any>) -> ())) {
        Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseObject { (response: DataResponse<GetContactusResponse>) in
                print(response.result.value!)
                switch response.result {
                case .success:
                    // optional is NOT NULL, neither NIL nor NSNull
                    guard let end = response.result.value else {
                        return
                    }
                        //end = nullToNil(end.loginAuthenticationInfo?.accessToken)
                    callback(response.result.value)
                    break
                case .failure:
                    if let error = response.result.error as? URLError {
                        print("URLError occurred: \(error)")
                    } else {
                        print("Unknown error: \(String(describing: response.result.error))")
                    }
                    break
                }
        }
    }


}

在我的视图控制器中,我试图通过以下方式访问它:

  override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        //getContactUsApiCall(URL:contactusURL!as URL)
        getContactUsApiCall(URL:contactusURL!as URL) { dictionary in
            print(dictionary)
        }

但我收到以下错误:

【问题讨论】:

    标签: ios json swift callback


    【解决方案1】:

    尝试改用这个函数

    class func getContactUsApiCall(URL: URL, completionHandler: @escaping ((Dictionary<AnyHashable,Any>)->Void)) {
        Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseJSON{ response in
                print(response.result.value!)
                switch response.result {
                case .success(let value):
                    // optional is NOT NULL, neither NIL nor NSNull
                    guard let end = response.result.value else {
                        return
                    }
                    //end = nullToNil(end.loginAuthenticationInfo?.accessToken)
                    completionHandler(value as! Dictionary<AnyHashable, Any>)//I would be careful here to make sure you data is returned in this format
                    break
                case .failure:
                    if let error = response.result.error as? URLError {
                        print("URLError occurred: \(error)")
                    } else {
                        print("Unknown error: \(String(describing: response.result.error))")
                    }
                    break
                }
        }
    }
    

    然后这是你加载的视图

    ContactUsModelClass.getContactUsApiCall(URL:contactusURL!as URL, completionHandler: { (dictionary) -> Void in
         print(dictionary)
    })
    

    希望对您有所帮助。如果您正在使用视图中的数据确实加载,则可以将调用放在同一个 VC 中。

    【讨论】:

      【解决方案2】:

      这些错误实际上是不言自明的。 Use of unresolved id 表示你调用的方法不在当前作用域内。由于getContactUsApiCall 实际上是在ContactUsModelClass 类中声明的,因此您需要从该类的对象中调用它。或者,您可以将方法修改为class 方法并将其称为ContactUsModelClass.getContactUsApiCall(...)

      关于第二个错误,response.result.value 的类型是GetContactusResponse?。因此,您的回调签名也应该使用该类型。像这样:

      class func getContactUsApiCall(URL: URL, callback: @escaping ((GetContactusResponse) -> ())) {
          Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
              .responseObject { (response: DataResponse<GetContactusResponse>) in
                  switch response.result {
                  case .success:
                      // optional is NOT NULL, neither NIL nor NSNull
                      guard let end = response.result.value else {
                          return
                      }
                      callback(end)
                      break
                  case .failure:
                      if let error = response.result.error as? URLError {
                          print("URLError occurred: \(error)")
                      } else {
                          print("Unknown error: \(String(describing: response.result.error))")
                      }
                      break
                  }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多