gpt4 book ai didi

带有返回字符串的iOS swift post方法

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

如何使用返回获取的字符串编写post方法

func post(link:String,passedPostString:String) {
let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
request.httpMethod = "POST"


request.httpBody = passedPostString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
print("error=\(String(describing: error))")
print("******Error*****")
return

}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

print(responseString!)




}
task.resume()
}

然后我把它叫做类似的东西

var link  = "link"
var passedPostString = "passedPostString"
print(post(link: link , passedPostString: passedPostString ))

返回获取的值

最佳答案

dataTask 方法是异步的,因此无法立即返回值,因为您不知道何时调用它。

最好的办法是传入一个完成处理程序,它将从您的主代码中异步调用:

func post(link:String, passedPostString:String, completionHandler: @escaping (NSString) -> ()) {
let request = NSMutableURLRequest(url: NSURL(string: link)! as URL)
request.httpMethod = "POST"


request.httpBody = passedPostString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
print("error=\(String(describing: error))")
print("******Error*****")
return

}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

completionHandler (responseString!);
}
task.resume()
}


var link = "link"
var passedPostString = "passedPostString"
let completion = { (result: NSString) in print(result) }
post(link: link, passedPostString: passedPostString, completionHandler: completion)

关于带有返回字符串的iOS swift post方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060905/

24 4 0
文章推荐: ios - 使用 UserNotifications didReceive 响应呈现 ViewController
文章推荐: ios - (SocketIO.Swift) .connect 回调被调用但未连接到服务器
文章推荐: CSS:触发 标签中每个
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com