gpt4 book ai didi

Swift 使用 Alamofire 发出 http 请求

转载 作者:行者123 更新时间:2023-11-28 15:09:04 26 4
gpt4 key购买 nike

我最近在使用 Alamofire 时遇到了问题。

这是我的代码登录 View Controller .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)
}
}

基础API.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,但是好像执行命令不对,所以返回的json是nil,我应该怎么解决这个问题?

最佳答案

您需要使用回调闭包来进行返回调用,您不能从 api 调用中返回这样的数据。

让我举个例子 - 下面的方法是使用 almofire 调用 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

关于Swift 使用 Alamofire 发出 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47953714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com