首页 > 解决方案 > Swift 5 API 调用数据变量 nil 但 API 证明有效

问题描述

我在尝试让我的 iOS 应用程序与我的快速后端通信时遇到了一些麻烦。

我刚开始使用 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()

标签: iosswiftapi

解决方案


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()

推荐阅读