我有代碼工作正常,並沒有警告從我的服務器解析一些JSON。它直接運行並返回控制檯中的值,直到我嘗試導入AWSNS框架,因此它在標題中給出警告,並在運行時說出「 - [__ NSCFArray長度]:無法識別的選擇器發送到實例」。任何想法,當我導入亞馬遜的SNS框架時,這可能會失敗?Cast from'String ?!'到不相關的類型'[[String:AnyObject]]'總是失敗
這裏是我的代碼:
import UIKit
import AWSSNS
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.getEvents()
}
func getEvents(){
let requestURL: NSURL = NSURL(string: "http://www.example.com/mydirectory/JSONFile")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("File downloaded successfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let events = json["events"] as? [[String: AnyObject]] {
for event in events {
if let eventName = event["eventName"] as? String {
if let day = event["day"] as? String {
print(day,eventName)
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
該警告出現在「if let events = json [」events「] as?[[String:AnyObject]]的行上」 –
檢查選項左鍵單擊json以查看Xcode認爲該變量具有哪些類型,並且沒有導入 – Feldur