我可以使用下面的代码
在Swift中发送POST请求func post() -> String{
let request = NSMutableURLRequest(URL: NSURL(string: "http://myserverip/myfile.php")!)
request.HTTPMethod = "POST"
let postString = "data=xxxxxxx"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString!)")
}
task.resume()
return "";//how would i return data here
}
我需要返回结果,但这是不可能的,因为网络请求是异步的。我想我可以使用一个监听器来等待结果,然后返回它,但我不确定这是如何工作或如何实现它 如果有人可以提供帮助,我将非常感激 我是iOS和Swift的新手
答案 0 :(得分:4)
您的帖子功能可能如下:
func post(completionHandler: (response: String) -> ()) { your code }
在回复部分:
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
completionHandler(response: responseString)
最后,你可以调用你的帖子方法,如:
post( {(response: String) -> () in
println("response = \(response)")})
答案 1 :(得分:2)
您可以使用委托或传递函数作为最后调用的帖子的参数
完成处理程序的示例:
struct RemoteCenter {
static func post(completion: (message: String?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://myserverip/myfile.php")!)
request.HTTPMethod = "POST"
let postString = "data=xxxxxxx"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
completion(message: NSString(data: data, encoding: NSUTF8StringEncoding) as? String)
}
task.resume()
}
}
class YourController: UIViewController {
override func viewDidLoad() {
RemoteCenter.post(completionHandler)
}
func completionHandler(message: String?){
println("I got \(message)")
}
}
委托示例:
protocol DelegateProtocol {
func didReceiveAMessage(message: String?)
}
struct RemoteCenter {
var delegate:DelegateProtocol?
func post() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://myserverip/myfile.php")!)
request.HTTPMethod = "POST"
let postString = "data=xxxxxxx"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
self.delegate?.didReceiveAMessage(NSString(data: data, encoding: NSUTF8StringEncoding) as? String)
}
task.resume()
}
}
class YourController: UIViewController, DelegateProtocol {
var remote = RemoteCenter()
override func viewDidLoad() {
remote.delegate = self
remote.post()
}
func didReceiveAMessage(message: String?) {
println("I got \(message)")
}
}
在这两种情况下,目标都是从UIViewController获取互联网上的一些数据,并在完成后打印消息。
你可以找到很多关于它的教程。查看http://www.raywenderlich.com