问题获取NSData请求在Swift 2.0中工作

时间:2015-08-20 19:58:17

标签: nsdata nsurl swift2

我希望有人能够帮助我弄清楚我正在尝试用Swift 2.0编写(或学习写作)的应用程序。这在以前的Swift 1.2中有效,但经过必要的转换后,我不断面对错误;

无法使用类型为'(contenOfURL:NSURL,options:NSDataReadingOptions,error:nil)'的参数列表调用'NSData'类型的初始化程序

这是我的代码,略有截断,我正在使用;

...

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
}

...

请注意,我计划在下载后使用SwiftyJSON库进一步解析数据。我在网上无休止地搜索,但我似乎无法弄清楚这一点!谢谢!

2 个答案:

答案 0 :(得分:10)

如果您正在使用Swift 2,则不应传递最后一个参数" error"。而是尝试围绕NSData初始化。如果需要在外部访问数据,请将init结果转换为var并转换为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
  }

答案 1 :(得分:0)

Dictionary的示例代码:) Swift 2.0 https://github.com/DaRkD0G/LoadExtension/edit/master/LoadExtensionDictionary.swift

enum EHError: ErrorType {
    case Nil(String)
    case NSData(String)
    case JSON(String) 
}
extension Dictionary {

        /**
        Loads a JSON file from the app bundle into a new dictionary

        - parameter filename: File name

        - throws: PathForResource / NSData / JSON

        - returns: Dictionary<String, AnyObject>
        */
        static func loadJSONFromBundle(filename: String) throws ->  Dictionary<String, AnyObject> {

            guard let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")  else {
                throw EHError.Nil("[EasyHelper][loadJSONFromBundle][->pathForResource] The file could not be located\nFile : '\(filename).json'")
            }

            guard let data = try? NSData(contentsOfFile: path, options:NSDataReadingOptions())   else {
               throw EHError.NSData("[EasyHelper][loadJSONFromBundle][->NSData] The absolute path of the file not find\nFile : '\(filename)'")
            }

            guard let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? Dictionary<String, AnyObject> else {
                throw EHError.JSON("[EasyHelper][loadJSONFromBundle][->NSJSONSerialization]Error.InvalidJSON Level file '\(filename)' is not valid JSON")


            }

            return jsonDict

        }
}

如果我没有犯错,那就是你

/**
Loads a JSON file from the app bundle into a new dictionary

- parameter filename: File name

- throws: EHError : PathForResource / NSData / JSON

- returns: [String : AnyObject] 
*/
static func loadJSONFromBundle(filename: String, nameJson:String) throws ->  [String : AnyObject] {

    guard let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")  else {
        throw EHError.Nil("[EasyHelper][loadJSONFromBundle][->pathForResource] The file could not be located\nFile : '\(filename).json'")
    }

    guard let data = try? NSData(contentsOfFile: path, options:NSDataReadingOptions())   else {
        throw EHError.NSData("[EasyHelper][loadJSONFromBundle][->NSData] The absolute path of the file not find\nFile : '\(filename)'")
    }

    guard let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] else {
        throw EHError.JSON("[EasyHelper][loadJSONFromBundle][->NSJSONSerialization] Invalid JSON\n nameJson '\(nameJson)'\nFile '\(filename)'")
    }



    return jsonDict

}