问题描述
我正在为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"