swift - 需要调整 NSJSONSerialization 到 iOS10

标签 swift ios10

升级到 iOS10 后,用户开始提示我的应用程序崩溃。 我正在模拟器上使用 iOS10 对其进行测试,实际上应用程序崩溃并显示一条消息“无法将‘__NSArrayI’类型的值转换为‘NSMutableArray’”。这是我的代码,请帮忙:

import Foundation

protocol getAllListsModel: class {
    func listsDownloadingComplete(downloadedLists: [ContactsList])
}

class ListsDownloader: NSObject, NSURLSessionDataDelegate{

    //properties

    weak var delegate: getAllListsModel!

    var data : NSMutableData = NSMutableData()

    func downloadLists() {

        let urlPath: String = "http://..."
        let url: NSURL = NSURL(string: urlPath)!
        var session: NSURLSession!
        let configuration =     NSURLSessionConfiguration.ephemeralSessionConfiguration()     //defaultSessionConfiguration()


    session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let task = session.dataTaskWithURL(url)

    task.resume()

}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
    self.data.appendData(data);
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    if error != nil {
        print("Failed to download data")
    }else {
        self.parseJSON()
        print("Lists downloaded")
    }

}
func parseJSON() {

    var jsonResult: NSMutableArray = NSMutableArray()

    do{
        try jsonResult =  NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

        } catch let error as NSError {
        print(error)
        }

        var jsonElement: NSDictionary = NSDictionary()
        var downloadedLists: [ContactsList] = []

        for i in 0...jsonResult.count-1 {

            jsonElement = jsonResult[i] as! NSDictionary

            let tempContactsList = ContactsList()

            //the following insures none of the JsonElement values are nil through optional binding
            let id = jsonElement["id"] as? String
            let name = jsonElement["name"] as? String
            let pin = jsonElement["pin"] as? String
            let lastUpdated = jsonElement["created"] as? String
            let listAdminDeviceID = jsonElement["admin"] as? String

            tempContactsList.id = id
            tempContactsList.name = name
            tempContactsList.pin = pin
            tempContactsList.lastUpdated = lastUpdated
            tempContactsList.listAdmin = listAdminDeviceID

            downloadedLists.append(tempContactsList)

        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            self.delegate.listsDownloadingComplete(downloadedLists)

        })
    }
}

最佳答案

即使在 iOS 9 中,也无法保证 NSJSONSerialization.JSONObjectWithData(_:options:) 会返回可变对象。您应该指定 NSJSONReadingOptions.MutableContainers

并且在您的代码中,您没有修改jsonResult,这意味着您无需将其声明为NSMutableArray。只需将 NSMutableArray 替换为 NSArray,然后就无需指定 NSJSONReadingOptions.MutableContainers

但是正如 vadian 所建议的,您最好使用 Swift 类型而不是 NSArrayNSDictionary。此代码应适用于 iOS 9 和 10。

func parseJSON() {

    var jsonResult: [[String: AnyObject]] = [] //<- use Swift type

    do{
        try jsonResult =  NSJSONSerialization.JSONObjectWithData(self.data, options: []) as! [[String: AnyObject]] //<- convert to Swift type, no need to specify options

    } catch let error as NSError {
        print(error)
    }

    var downloadedLists: [ContactsList] = []

    for jsonElement in jsonResult { //<- your for-in usage can be simplified

        let tempContactsList = ContactsList()

        //the following insures none of the JsonElement values are nil through optional binding
        let id = jsonElement["id"] as? String
        let name = jsonElement["name"] as? String
        let pin = jsonElement["pin"] as? String
        let lastUpdated = jsonElement["created"] as? String
        let listAdminDeviceID = jsonElement["admin"] as? String

        tempContactsList.id = id
        tempContactsList.name = name
        tempContactsList.pin = pin
        tempContactsList.lastUpdated = lastUpdated
        tempContactsList.listAdmin = listAdminDeviceID

        downloadedLists.append(tempContactsList)

    }

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        self.delegate.listsDownloadingComplete(downloadedLists)

    })
}

试试这个并在 iOS 10 设备上检查它。

(当您的服务器发生故障时,as! 转换会导致一些奇怪的崩溃,但那将是另一个问题,所以我保留它。)

关于swift - 需要调整 NSJSONSerialization 到 iOS10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39680555/

相关文章:

swift - 无法强制将类型 'UIViewController' 的值转换为类型 'TableView'

ios - Swift - 由于某种原因,Realm 在主线程上

ios - Firebase 实时数据库不保存注册页面的数据

swift - swift 从文件路径读取数据时如何处理符号链接(symbolic link)

jquery - 无法加载资源: Preflight response is not successful

swift3 - swift 3.0 : Ambiguous reference to member 'Subscript' issue

swift - 截断 NSTextField 的最后一个可见行

ios - 由于 "Elaborated type refers to a typedef"错误,Project-Swift.h 文件编译失败

ios - 为什么我的对象位置随机但不显示?

swift - Firebase 身份验证注销错误 - Swift