Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue Getting NSData Request To Work In Swift 2.0

I'm hoping someone may be able to help me figure out a snafu I'm having with an app I am trying to write (or learn to write) in Swift 2.0. This previously worked in Swift 1.2, but after the necessary conversions, I am continunally facing the error;

Cannot invoke initializer of type 'NSData' with an argument list of type '(contenOfURL: NSURL, options: NSDataReadingOptions, error:nil)'

Here is my code, slightly truncated, that I am using;

...

class func fetchMinionData() -> [Minion] {
    let myURL = "https://myurl/test.json"

    let dataURL = NSURL(string: myURL)

    let data = NSData(contentsOfURL: dataURL!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
    //THIS IS THE LINE THAT THROWS THE ERROR

    let minionJSON = JSON(data)

    var minions = [Minion]()

    for (_ , minionDictionary) in minionJSON {
        minions.append(Minion(minionDetails: minionDictionary))
    }

    return minions
}

...

Note that I plan to use the SwiftyJSON library to further parse the data once it is downloaded. I am searching endlessly online, but I just can't seem to figure this out! Thank you!

like image 628
ZbadhabitZ Avatar asked Dec 24 '22 15:12

ZbadhabitZ


1 Answers

If you are working with Swift 2, you should not pass the last argument "error". Instead put a try around the NSData initialization. If data needs to be accessed outside take the init result in a var and convert to let Modified code

var optData:NSData? = nil
  do {
    optData = try NSData(contentsOfURL: dataURL!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
  }
  catch {
    print("Handle \(error) here")
  }

  if let data = optData {
    // Convert data to JSON here
  }
like image 179
Kedar Avatar answered Jan 04 '23 01:01

Kedar