我最近在使用Alamofire时遇到了问题。
这是我的代码LoginViewController.swift
class LoginViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
let baseApi = BaseApi()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginButton(_ sender: UIButton) {
let dict = ["name":name.text,"email":email.text,
"password":password.text]
print("api succeed1")
let result = baseApi.login(paras: dict as! [String : String])
print("api succeed2")
if result[0]["status"].string == "success" {
print("api succeed3")
present( UIStoryboard(name: "Main", bundle:
nil).instantiateViewController
(withIdentifier:"TabBarController")
as! TabBarController, animated: true, completion: nil)
}
}
BaseApi.swift
class BaseApi{
func login(paras : [String:String]) -> JSON {
let url = URL(string: "http://127.0.0.1:8000/api/login")
let result = baseApi(url: url!,paras: paras)
print("BaseApi3333")
return result
}
func baseApi(url : URL,paras : [String:String]) -> JSON {
var json:JSON = []
let toke = getToken()
let parameters: Parameters = [
"name": paras["name"]!,
"email": paras["email"]!,
"password": paras["password"]!
]
let headers: HTTPHeaders = [
"Authorization": "Basic "+toke,
"Accept": "application/json"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
json = JSON(value)
print("baseAp2222")
print(json)
case .failure(let error):
print(error)
}
}
print("baseApi111")
print(json)
return json
}
}
这是日志
api succeed1
baseApi111
[
]
BaseApi3333
api succeed2
baseAp2222
{
"status_code" : 200,
"status" : "success",
"data" : {
"token" : "xxxx"
}
}
我的问题是为什么print(baseApi111)在print之前出来(“baseAp2222”),我需要返回json,但看起来excute命令不对,所以返回json是nil,我应该如何解决这个问题?
你需要使用回调闭包来进行回调,你不能从api调用中返回这样的数据。
让我举个例子 - 以下方法是使用alamofire调用api -
func fetchDataFromWebService<T: Mappable>(_ parameters: Dictionary<String , AnyObject>, closure:@escaping (_ response: T) -> Void){
let url = getWebServiceUrl()
// let url = NSURL(string: getWebServiceUrl)
print("parameters = \(parameters)")
Alamofire.request(url, method: .get, parameters: parameters, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
// print(response.result.value)
var user = Mapper<T>().map(JSONObject: response.result.value)
// var user = Mapper<T>().map(response.result.value)
if self.processSingleRecord() == true {
user = Mapper<T>().map(JSONObject: (response.result.value as! NSArray).object(at: 0))
// user = Mapper<T>().map(response.result.value?.objectAtIndex(0))
}
closure(user!)
// print("user = ",user)
}
else if response.response?.statusCode == 0{
// print(self.DisplayNetworkAvailabilityMessage())
}
else {
if let _ = response.result.value as? Error {
}
}
break
case .failure(let error):
debugPrint("getEvents error: \(error)")
SVProgressHUD.dismiss()
break
}
}
}
现在这里是调用这个方法 -
let anotherWebServiceHandler = DeviceTokenDataHandler.init() anotherWebServiceHandler.fetchDataFromWebService(["":""], closure: { (response:SignUpResponse) -> Void in
})
你需要了解sequential code execution - 和Closures