Swift 对本地服务器的 NSURLSession 请求 - 没有发送或接收数据
Swift NSURLSession Request to local server - no data sent or received
我正在尝试在 Swift 2.2 中使用 NSURLSession
为服务器编写一个简单的 API 客户端,我在本地端口 3000 运行ning。服务器只提供 JSON.
的静态字符串
这很好用:
$ curl http://localhost:3000
{"data":"value"}
我的 Swift 命中 API 的代码是:
// api_client.swift
let url = NSURL(string: "http://localhost:3000/api")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print("The response was:")
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
print("Running the request...")
task.resume()
我正在尝试从命令行运行它
$ swift api_client.swift
Running the request...
但仅此而已。我没有看到打印的 "The response was" 行,也没有看到服务器的响应。当我检查服务器日志时,它显示根本没有请求进来。
我做错了什么?我是 Swift 的新手,无法弄清楚这一点。我在 Swift 2.2 和 XCode 7.3
跟进pbush25所说的内容。您可以尝试在代码中创建回调吗?
func GET(path : String, callback: (result: NSData?, response: NSHTTPURLResponse?, error: NSError?) -> Void) {
let session = NSURLSession.sharedSession()
let url = NSURL(string: path)
let task = session.dataTaskWithURL(url!){
(data, response, error) -> Void in
if (error != nil) {
// return the NSData as nil (since you have an error)
callback(result: nil, response: response as? NSHTTPURLResponse, error: error!)
} else {
// return the NSData
callback(result: data, response: response as? NSHTTPURLResponse, error: nil)
}
}
task.resume()
}
然后调用您的函数:
GET("http://localhost:3000/api") {
(data, response, error) -> Void in
print(data)
}
感谢 pbush25,我发现我的请求没有执行,因为运行时在异步请求开始之前到达了文件末尾。
使用信号量解决了它,但是证明这是问题所在的一种快速而肮脏的方法是在代码底部添加 sleep(1)
。如果我这样做,我会在日志中看到请求并返回数据!
我正在尝试在 Swift 2.2 中使用 NSURLSession
为服务器编写一个简单的 API 客户端,我在本地端口 3000 运行ning。服务器只提供 JSON.
这很好用:
$ curl http://localhost:3000
{"data":"value"}
我的 Swift 命中 API 的代码是:
// api_client.swift
let url = NSURL(string: "http://localhost:3000/api")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print("The response was:")
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
print("Running the request...")
task.resume()
我正在尝试从命令行运行它
$ swift api_client.swift
Running the request...
但仅此而已。我没有看到打印的 "The response was" 行,也没有看到服务器的响应。当我检查服务器日志时,它显示根本没有请求进来。
我做错了什么?我是 Swift 的新手,无法弄清楚这一点。我在 Swift 2.2 和 XCode 7.3
跟进pbush25所说的内容。您可以尝试在代码中创建回调吗?
func GET(path : String, callback: (result: NSData?, response: NSHTTPURLResponse?, error: NSError?) -> Void) {
let session = NSURLSession.sharedSession()
let url = NSURL(string: path)
let task = session.dataTaskWithURL(url!){
(data, response, error) -> Void in
if (error != nil) {
// return the NSData as nil (since you have an error)
callback(result: nil, response: response as? NSHTTPURLResponse, error: error!)
} else {
// return the NSData
callback(result: data, response: response as? NSHTTPURLResponse, error: nil)
}
}
task.resume()
}
然后调用您的函数:
GET("http://localhost:3000/api") {
(data, response, error) -> Void in
print(data)
}
感谢 pbush25,我发现我的请求没有执行,因为运行时在异步请求开始之前到达了文件末尾。
sleep(1)
。如果我这样做,我会在日志中看到请求并返回数据!