【发布时间】:2021-02-19 15:26:54
【问题描述】:
我在尝试让我的 iOS 应用与我的 express 后端通信时遇到了一些麻烦。
我刚开始使用 swift 和 iOS 开发,但我认为这应该可行:
func fetchLoc() {
var currentLoc: CLLocation!
currentLoc = locationManager.location
let latitude = String(currentLoc.coordinate.latitude)
let longitude = String(currentLoc.coordinate.longitude)
//let url = URL(string: "a542cd3116ed.ngrok.io/api/v1/public/location/66.68994/10.249066/50")!
let url = URL(string: "http://a542cd3116ed.ngrok.io/api/v1/public/" + "location/" + latitude + "/" + longitude + "/100")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
if((data) != nil) {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
}
} catch {
print("error")
}
})
task.resume()
}
问题是,Data 总是为零。如您所见,我已经尝试插入完整的 URL 进行测试。但这没有任何区别。我的代码一定有问题,因为我可以很好地从 Insomnia 调用 API。答案看起来像这样,所以它是正确的 JSON:
[
{
"location": {
"type": "Point",
"coordinates": [
66.68994,
10.249066
]
},
"type": "shop",
"name": "Laden weg 60",
"description": null,
"status": "active",
"taxRates": [
0.19,
0.07
],
"currency": "EUR",
"_id": "602e390b7c760032c0cc74d7",
"address": {
"street": "abc1",
"number": null,
"city": null,
"zip": null,
"country": "DE",
"_id": "602e390b7c760032c0cc74d8"
},
"__v": 0
}
]
我希望我只是在这里监督一些明显的事情。提前谢谢!
邮递员生成了这段代码:
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)
var request = URLRequest(url: URL(string: "http://a542cd3116ed.ngrok.io/api/v1/public/location/66.68994/10.249066/50")!,timeoutInterval: Double.infinity)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
【问题讨论】:
-
它只是不进入 if 因为数据总是 nil。
-
print("error")=>print("Error while deserializing: \(error)"),以后可能会有所帮助。但是,首先在顶部打印error,以防data为零。不相关,但 ` if((data) != nil) {` 应该是if let data = data { },软展开。 -
感谢您的提示,但到目前为止还没有运气。我在调试器中查看了数据,反正肯定是 nil。
-
你可以让它与 POSTMAN 一起工作吗?我知道 POSTMAN 可以生成 Swift 代码(不是 Swifty 代码,但仍然可以工作),看看它是否可以工作。它可能有助于发现差异和错误。 blog.postman.com/…
-
对 Insomnia 没问题,但让我试试 Postman。立即安装。