当我尝试让我的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()
}问题是,数据总是为零。正如您所看到的,我已经尝试插入完整的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()发布于 2021-02-20 00:55:01
Postman生成的解决方案适用于我:
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()https://stackoverflow.com/questions/66280371
复制相似问题