IOS 10 objectForKey ("key") 兼容性

标签 ios swift ios10

我正在研究我的应用程序与 IOS10 的兼容性,但在执行此代码时遇到问题:

if let results = NSJSONSerialization.TryJSONObjectWithData(data, options: []) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["results"] as? NSMutableArray {
        print(" here");

                for i in 0 ..< networkPosts.count {
                    let post:Post = Post(postDictionary: networkPosts[i] as! NSDictionary, context: (UIApplication.sharedApplication().delegate as! 

AppDelegate).coreDataHelper.managedObjectContext);
}
        }
    }

我可以看到结果,所以 JSON 没问题,但是在我看不到字典的结果键之后。 “这里”从未打印在我的控制台上。我已经尝试制作一个断点并且同样它不会通过那里。 我也尝试过 .objectForKey("key") 但结果相同:/

有人可以帮帮我吗?

如果我将 results["results"] 用作? [[字符串:任意]]

然后

networkPosts[i] as! NSDictionary always fails

最佳答案

在使用 TryJSONObjectWithData 使数组和字典可变时,您应该使用 NSJSONReadingMutableContainers 选项

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/c/tdef/NSJSONReadingOptions

使用 Playground for Swift 3 测试的示例:

let jsonString = "{\"name\":\"Mattia\",\"iosDevices\":[\"iPhone6\",\"iPad Air 2\",\"iPhone6+\"]} 
let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false)!

if let results = try JSONSerialization.jsonObject(with: jsonData, options: [.mutableContainers]) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["iosDevices"] as? NSMutableArray {
        print(" here");
    }
}

关于IOS 10 objectForKey ("key") 兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395132/

相关文章:

ios - 如何从 iOS 缓存中正确移动 In App Purchase 下载文件?

iphone - 当应用程序进入前台时如何呈现模态视图 Controller ?

ios - MFMailComposeViewController 仅在 iOS 9 中抛出错误

iOS - 将点击手势添加到 UITextField

swift - 尝试加载 skspritenode 两次后应用程序崩溃?

从 iOS 10 开始,当 AVAssetExportSession 处于事件状态时,AVPlayer 播放失败

push-notification - xcode 8 beta ios 10 推送通知停止工作

ios - iOS 7 中的 UIActivityViewController 奇怪行为

arrays - 离开 DispatchGroup 导致我的代码崩溃

ios - 应用因缺少使用说明而被拒绝 (Xcode8)