Alamofire

1.请求链接

static func login(identification: String, password: String, handler: @escaping ((DataResponse)->Void)){
  let parameters : [String : Any] = ["identification":identification, "password":password, "remember_me":"on"]
  Alamofire.request(Url.loginUrl(), method: .post, parameters: parameters).validate().responseJSON(completionHandler: handler)
}

validate()用于检测请求是否成功。

2.处理

Request.login(identification: username, password: password) {
  (returnResult) in
  print(returnResult.description)
  switch returnResult.result.isSuccess {
    case true:
    print("login successfully!")
    if let data = returnResult.data {
    let json = JSON(data: data)
    let id = json["id"].int ?? -1
    let userName = json["username"].string ?? ""
    let email = json["email"].string ?? ""
    
    UserDefaultTool.userName = username
    UserDefaultTool.password = password
    User.sharedInstance.setUser(id: id, userName: userName, email: email, password: password)

    (UIApplication.shared.delegate as! AppDelegate).showMainView()
  }
  case false:
    print(returnResult.result.error ?? Error.self)
    showError(vc: self, error: "Incorrect username or password")
  }
}

你可能感兴趣的:(Alamofire)