微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JSON URLComponents URLQueryItem失败

如何解决JSON URLComponents URLQueryItem失败

我正在为json数据的http调用而苦苦挣扎。如果我将整个网址用作字符串, json提取有效。如果我将呼叫分为URLComponents,则无法 使它起作用。

我的Web服务:

final class Webservice {

      var components: URLComponents {
          var components = URLComponents()
          components.scheme = "https"
          components.host = "weather.visualcrossing.com"

          components.queryItems =
              [
              URLQueryItem(name: "aggregateHours",value: "24"),URLQueryItem(name: "combinationMethod",value: "aggregate"),URLQueryItem(name: "startDateTime",value: "2020-08-03T00:00:00"),URLQueryItem(name: "endDateTime",value: "2020-08-10T00:00:00"),URLQueryItem(name: "collectStationContributions",value: "false"),URLQueryItem(name: "maxStations",value: "-1"),URLQueryItem(name: "maxdistance",URLQueryItem(name: "includenormals",URLQueryItem(name: "contentType",value: "json"),URLQueryItem(name: "unitGroup",value: "us"),URLQueryItem(name: "locationMode",value: "single"),URLQueryItem(name: "key",value: "myPersonalKeyHere"),URLQueryItem(name: "locations",value: "Findlay,OH"),]
          return components
      }

    let myURL = URL(string: "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?aggregateHours=24&combinationMethod=aggregate&startDateTime=2020-08-03T00%3A00%3A00&endDateTime=2020-08-10T00%3A00%3A00&collectStationContributions=false&maxStations=-1&maxdistance=-1&includenormals=false&contentType=json&unitGroup=us&locationMode=single&key=myPersonalKeyHere&locations=Findlay%2C%20oh")

    func fetchItems() -> AnyPublisher<ItemDataContainer,Error> {
    
        //fix this - do not force unwrap
        
        //Using myURL - it works
        //return URLSession.shared.dataTaskPublisher(for: myURL!)
        
        //using the components url it fails
        return URLSession.shared.dataTaskPublisher(for: components.url!)
            .map { $0.data }
            .decode(type: ItemDataContainer.self,decoder: JSONDecoder())
            .receive(on: dispatchQueue.main)
            .erasetoAnyPublisher()
    }//fetch

}//class

这是错误

收到错误:,dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。”,底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840“字符周围的无效值0.“ UserInfo = {NSDebugDescription =字符0周围的值无效。})))

任何指导将不胜感激。 Xcode 11.6,iOS 13.6

解决方法

您缺少组件中的路径

components.path = "/VisualCrossingWebServices/rest/services/weatherdata/history"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。