JSON 응답을 가져 와서 결과를 변수에 저장하려고합니다. Xcode 8의 GM 버전이 출시 될 때까지는 이전 버전의 Swift에서이 코드의 버전을 사용할 수있었습니다. StackOverflow에서 유사한 게시물 몇 개를 보았습니다 : Swift 2 Parsing JSON - Cannot subscript a value of type 'AnyObject' 및 JSON Parsing in Swift 3.Swift에서 JSON을 올바르게 구문 분석 3
그러나 여기에 전달 된 아이디어가이 시나리오에 적용되지 않는 것 같습니다.
Swift 3에서 JSON 응답을 올바르게 구문 분석하려면 어떻게해야합니까? Swift 3에서 JSON이 읽히는 방식이 변경 되었습니까?
import Cocoa
let url = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
if let url = NSURL(string: url) {
if let data = try? Data(contentsOf: url as URL) {
do {
let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
//Store response in NSDictionary for easy access
let dict = parsedData as? NSDictionary
let currentConditions = "\(dict!["currently"]!)"
//This produces an error, Type 'Any' has no subscript members
let currentTemperatureF = ("\(dict!["currently"]!["temperature"]!!)" as NSString).doubleValue
//Display all current conditions from API
print(currentConditions)
//Output the current temperature in Fahrenheit
print(currentTemperatureF)
}
//else throw an error detailing what went wrong
catch let error as NSError {
print("Details of JSON parsing error:\n \(error)")
}
}
}
편집 : 아래
은 (는 놀이터에서 실행할 수 있습니다) 문제의 코드 여기는 API 호출의 결과의 샘플입니다 후print(currentConditions)
["icon": partly-cloudy-night, "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precipIntensity": 0, "windSpeed": 6.04, "summary": Partly Cloudy, "ozone": 321.13, "temperature": 49.45, "dewPoint": 41.75, "apparentTemperature": 47, "windBearing": 332, "cloudCover": 0.28, "time": 1480846460]
API 호출에서 반환 된 샘플 데이터를 넣을 수 있습니까? – User
예, 방금 print (currentConditions) 후에 인쇄 된 결과 샘플을 추가했습니다. 희망이 도움이됩니다. – user2563039