【问题标题】:How to get Freddy working with AlamoFire in Swift?如何让 Freddy 在 Swift 中使用 AlamoFire?
【发布时间】:2024-01-14 17:04:01
【问题描述】:

我正在尝试使用 Alamofire POST 请求对我的用户进行身份验证。我得到一个响应对象作为字典。我希望我能从该字典中得到一个Freddy LoginResponse 对象。斯威夫特对我来说是新的。

import UIKit
import Alamofire
import Freddy


public struct LoginResponse {
    public let Response: String
    public let Success: Int
    public let Time: String
}

extension LoginResponse: JSONDecodable {
    public init(json value: JSON) throws {
        Response = try value.string("Response")
        Success = try value.int("Success")
        Time = try value.string("Time")
    }
}


class LoginViewController: UIViewController {


    @IBOutlet weak var emailOutlet: UITextField!
    @IBOutlet weak var passwordOutlet: UITextField!
    @IBAction func LoginAction(sender: AnyObject){
        var parameters = [String: AnyObject]()
        parameters["email"] = self.emailOutlet.text
        parameters["password"] = self.passwordOutlet.text
        Alamofire.request(.POST, "https://cool.api/iot/users/login", parameters: parameters, encoding: .JSON)
            .responseJSON
            { response in switch response.result {
            case .Success(let JSON):
                print("Success with JSON: \(JSON)")

                let response = JSON as! NSDictionary
                print(response["Response"]!)


         // What I am trying !!
         //   do {
         //       let response = JSON as! NSDictionary
         //       // Assuming `json` has the JSON data
         //       let attrs = try JSON.array("SUCCESS")
         //       let theLoginResponseObject = try attrs.map(LoginResponse.init)    
         //   } catch {
         //     
         //   }


            case .Failure(let error):
                print("Request failed with error: \(error)")
                }
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.emailOutlet.text = "myemail@gmail.com"
        self.passwordOutlet.text = "passwd"
    }

}

控制台输出

Success with JSON: {
    Response = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXZpY2VzIjpbImM5NGYyZjY0MDkwZmU4MWFmZjk5MGNkNTU0OTZhZjhkIiwiZjdmOGYzNWI0NDRiYmM3NzcxNzYxNjhlNTcxZjgzNjUiXSwiZW1haWwiOiJmcmFuY2VzY29hZmVycmFyb0BnbWFpbC5jb20iLCJleHAiOjE0NjU3MzcyOTUsImlkIjoiNTc0Y2E0NDkzMTcyODUwMDAxNjkzOGQ2Iiwicm9sZSI6Im1hc3RlciJ9.P-QxGCUTi1YWq46HJQlR2K-4S_DBKFxOLiyzqvE-r7S96XSxx02dpT8jOlZm4gx2qVrcj5wFyowJzy8HtU-y030I6OmftGe_dn2AgMJCD8dLXrRiRWfnWK5nhN6BvDJqCLyN_BopKGM2stEf7stavoPogy4HxBfg_hWIFJEwdHs";
    Success = 200;
    Time = "2016-06-12T13:04:55.426208276Z";
}
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXZpY2VzIjpbImM5NGYyZjY0MDkwZmU4MWFmZjk5MGNkNTU0OTZhZjhkIiwiZjdmOGYzNWI0NDRiYmM3NzcxNzYxNjhlNTcxZjgzNjUiXSwiZW1haWwiOiJmcmFuY2VzY29hZmVycmFyb0BnbWFpbC5jb20iLCJleHAiOjE0NjU3MzcyOTUsImlkIjoiNTc0Y2E0NDkzMTcyODUwMDAxNjkzOGQ2Iiwicm9sZSI6Im1hc3RlciJ9.P-QxGCUTi1YWq46HJQlR2K-4S_DBKFxOLiyzqvE-r7S96XSxx02dpT8jOlZm4gx2qVrcj5wFyowJzy8HtU-y030I6OmftGe_dn2AgMJCD8dLXrRiRWfnWK5nhN6BvDJqCLyN_BopKGM2stEf7stavoPogy4HxBfg_hWIFJEwdHs

错误

/Users/cesco/code/iot/iot/LoginViewController.swift:50:37: Value of type 'NSDictionary' has no member 'array'

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

    您可以使用以下 GET 调用来检索 JSON 数据以用于 Freddy。

    Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/weather?APPID=<123456>").responseJSON { (response) -> Void in
          if response.result.isSuccess {
              do {
                  let json = try JSON(data: response.data!)
                  let description = try json.array("weather")[0]["description"]
                  print(description)
              } catch {
                  print("There is an error")
              }
          }
    }
    

    或者,如果您使用的是 2016 年 8 月最新的 AlamoFire:

    Alamofire.request( "http://api.openweathermap.org/data/2.5/weather?APPID=<123456>", withMethod: .get).responseJSON { (response) -> Void in
          if response.result.isSuccess {
              do {
                  let json = try JSON(data: response.data!)
                  let description = try json.array("weather")[0]["description"]
                  print(description)
              } catch {
                  print("There is an error")
              }
          }
    }
    

    【讨论】: