gpt4 book ai didi

ios - swift iOS 从异步中获取值(value)(发布数据)

转载 作者:可可西里 更新时间:2023-11-01 00:24:00 24 4
gpt4 key购买 nike

我在异步过程中获取值时遇到问题。

我的类(class)是:

public class PostService: NSObject {

var result : String = String()

//this is my function


func request(var dataPost : String, var destination : String)->String{

let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
println("error=\(error)")
return
}

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

self.result = responseString as String!

}

task.resume()

//problem is here that result will fill after async

return self.result
}

}

//我在这里使用这个函数

override func viewDidLoad() {
super.viewDidLoad()
var dataPost :String="Name=Ali"
var dest : String = "http://example.com/api/getUserName"
var result = Post.request(dataPost, destination: dest)
lbltext.text = result as String!
}

最佳答案

func request(var dataPost : String, var destination : String, successHandler: (response: String) -> Void)->String{
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
println("error=\(error)")
return
}

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

//self.result = responseString as String!
successHandler(responseString as String!);

}

task.resume()
}

override func viewDidLoad() {
super.viewDidLoad()
var dataPost :String="Name=Ali"
var dest : String = "http://example.com/api/getUserName"
Post.request(dataPost, destination: dest, successHandler: {
(response) in
lbltext.text = response;
});

}

类似下面的内容。基本上,您传递成功处理程序的回调并在回调函数内执行您的操作。

异步操作意味着,它们独立于代码的字节序列发生。这就是为什么当你进行异步调用时,你不能返回一个值。代码的原始序列在异步调用在后台(或另一个线程)运行时运行。这就是存在成功和错误处理程序的原因。它们允许您在异步请求完成时运行一段代码。

P.S 请重新格式化您的问题并确保所有代码都正确缩进。

关于ios - swift iOS 从异步中获取值(value)(发布数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025152/

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