来自' String?!'到不相关的类型' [[String:AnyObject]]'总是失败

时间:2016-07-02 00:00:15

标签: ios swift amazon-web-services amazon-sns

我的代码工作正常,并没有警告从我的服务器解析一些JSON。它运行并在控制台中返回值而没有问题,直到我尝试导入AWSNS框架,然后它在标题中给出警告并在运行时崩溃说" - [__ NSCFArray length]:无法识别的选择器发送到实例&# 34 ;.当我导入亚马逊的SNS框架时,为什么这可能会失败?

这是我的代码:

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()
}

2 个答案:

答案 0 :(得分:0)

if let events = json["events"] as? [[String: AnyObject]] {

你可能在JSON中有一个字符串,而你正试图将它转换为字典,这将无效。

在此处设置断点并检查以查看要验证的JSON的内容。

答案 1 :(得分:0)

"-[__NSCFArray length]: unrecognized selector sent to instance"

我认为你的问题不是来自JSON。如果你可以解析JSON,那就意味着JSON没有问题。检查selector