Search code examples
swiftfileswift3nsdata

Apple Swift 3.0 Data


I'm trying to use:

init(contentsOf: URL, options: Data.ReadingOptions)

in Swift 3.0 with xCode 8.0. The exact statement I am using is:

let jsonData = try Data.init(contentsOf: URL(file_path), options: .mappedIfSafe)

I have also tried:

let jsonData = try Data(contentsOf: URL(file_path), options: .mappedIfSafe)

I am following the documentation

This does not compile, complaining about incorrect argument labels in call.

I'm a Swift newbie, so please be gentle. file_path is a string obtained from an NSOpenPanel and stringified using stringValue.

Thanks!


Solution

  • Don't use string paths in conjunction with NSOpenPanel, get the url property – that avoids the extra step to create the URL – and wrap the Data initializer in a do - catch block.

    if let url = openPanel.url {
        do {
            let jsonData = try Data(contentsOf: url, options: .mappedIfSafe)
            // do things with jsonData
        } catch {
           print(error)
        }
    }