Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSKeyedUnarchiver not working with Swift 3

I have the following code that I use to unarchive a file in my Mac application:

func tryOpen(_ filePath: String) throws -> NSArray {
    if #available(OSX 10.11, *) {
        do {
            if let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) {
                let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! NSArray
                return array
            } else {
                throw NSError(domain: NSExceptionName.invalidUnarchiveOperationException.rawValue, code: 0, userInfo: nil)
            }
        } catch let ex {
            throw ex
        }
    } else {
        // Fallback on earlier versions
        let dat = try? Data(contentsOf: URL(fileURLWithPath: filePath))
        let unarchiver = NSKeyedUnarchiver(forReadingWith: dat!)
        if let array = unarchiver.decodeObject(forKey: "root") as? NSArray {
            return array
        } else {
            throw NSException(name: NSExceptionName.invalidArgumentException, reason: "Unable to unarchive file", userInfo: nil) as! Error
        }
    }
}

However, ever since I upgraded to Swift 3 in Xcode 8.0, I have the following error message: 'unarchiveTopLevelObjectWithData' is unavailable in Swift: Use 'unarchiveTopLevelObjectWithData(_:) throws' instead, which is pretty much the same thing, right? So I'm seriously confused as to how to fix this. Is this a bug in Xcode?

like image 994
Matt Avatar asked Sep 15 '16 21:09

Matt


Video Answer


1 Answers

The NSKeyedUnarchiver is still expecting a NSData:

let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as NSData) as! NSArray

This has been remedied in Swift 4

like image 68
Rob Avatar answered Oct 21 '22 16:10

Rob