8

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?

Matt
  • 2,576
  • 6
  • 34
  • 52
  • 3
    It's expecting a `NSData`: `try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as NSData)`. Looks like something just slipped through the cracks in the API. – Rob Sep 15 '16 at 21:46
  • Unrelated, but you could simplify this a bit: https://gist.github.com/robertmryan/73c19aaed3792723ba3e8c28960d94e2 – Rob Sep 15 '16 at 21:53
  • @Rob, that should be an answer not a comment :) – Fawkes Dec 13 '16 at 10:00

1 Answers1

11

The NSKeyedUnarchiver is still expecting a NSData:

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

This has been remedied in Swift 4

Rob
  • 415,655
  • 72
  • 787
  • 1,044