0
在Xcode 7(和Swift 2)上,以下代碼工作正常。它的功能是獲取當前觀察值的天氣API json字符串,然後解析字符串並找到UV值。 (我知道它很混亂,但我無法讓JSON解析我的頭)。不要介意我將字符串拆分成越來越小的數組。什麼是錯的是在代碼段的底部:遷移到Swift 3 - 在URL會話期間獲取以下錯誤
class weatherGetter {
fileprivate let weatherMapBaseURL = "https://api.wunderground.com/api/"
fileprivate let weatherAPIKey = "************"
func getWeather(city: String) {
// This is a pretty simple networking task, so the shared session will do.
let session = URLSession.shared
let weatherRequestURL = URL(string: "\(weatherMapBaseURL)\(weatherAPIKey)/conditions/q/FL/\(city).json")!
let dataTask = session.dataTask(with: weatherRequestURL, completionHandler: {
(data: Data?, response: URLResponse?, error: NSError?) in
if let error = error {
// Case 1: Error
// We got some kind of error while trying to get data from the server.
print("Error:\n\(error)")
}
else {
do {
// Try to convert that data into a Swift dictionary
let dataString = String(data: data!, encoding: String.Encoding.utf8)
print("Human-readable data:\n\(dataString!)")
let fullArr = dataString!.characters.split{$0 == "\n"}.map(String.init)
let smallArr = String(fullArr[79]).characters.split{$0 == ":"}.map(String.init)
let smallerArr = String(smallArr[1]).characters.split{$0 == ","}.map(String.init)
//let smallerArr2 = String(smallArr[1]).characters.split{$0 == ","}.map(String.init)
//let characters = Array(smallerArr)
//print(smallerArr[0])
let final = String(smallerArr[0])
//print(final)
let charArr = Array(final!.characters)
//print(charArr)
let subarray = charArr[1...charArr.count-2]
let finalNum = String(subarray)
let myDouble = Double(finalNum)
var myDouble2: Double = myDouble!
print(myDouble2)
Calculator_Calculations.sharedInstance.uvIndex = myDouble2
print(Calculator_Calculations.sharedInstance.uvIndex)
//print(String(subarray))
//print(finalNum)
//print(myDouble)
}
// Case 2: Success
// We got a response from the server!
//let dataString = String(data: data!, encoding: NSUTF8StringEncoding)
//print("Human-readable data:\n\(dataString!)")
}
} as! (Data?, URLResponse?, Error?) -> Void)
// The data task is set up...launch it!
dataTask.resume()
}
}
當我遷移到斯威夫特3,我得到了這行代碼
}as! (Data?, URLResponse?, Error?) -> Void)
exc_bad_instruction(代碼= exc_i386_invop子碼下面的錯誤= 0x0)
我知道這與零值等有關,但我是新的enugh Swift,並且自從我遷移到Swift 3以來我遇到了很多問題我的代碼出來了。
感謝分享,這樣簡單的修復減輕了很多壓力=) – DG7