我被困在Swift项目中。我打电话给#34; SendPost"从按钮IBAction我需要它返回Alamofire.request的数据,但我不知道如何达到这个。我无法进入" utf8Text"来自Alamofire.request的变量。我怎样才能获得数据?
谢谢。 :)
import Foundation
import Alamofire
func SendPost(parameters: Parameters) -> String {
Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
return "I don't know. :(";
}
答案 0 :(得分:1)
适用于Swift 3
使用完成来返回从Request:
获得的de数据首先创建一个typealias
,用作闭包:
typealias SendPostCompletion = (_ data: String) -> Void
然后:
@IBAction func yourAction(_ sender: UIButton) {
SendPost(parameters: ...) { (data) in
print(data)
}
}
func SendPost(parameters: Parameters, completion: @escaping SendPostCompletion) -> String {
Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
var data = ("Data: \(utf8Text)")
completion(data)
}
}
completion("I don't know. :(")
}
希望它可以帮到你!
答案 1 :(得分:0)
尝试使用以下代码
func SendPost(parameters: Parameters) -> [String,AnyObject] {
let urlstring= "https://hovnocuc.com/main.php"
Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
return JSON
}
}
return "I don't know "
}