当我尝试使用外部数据库和API与swift时,我该如何解决此错误

时间:2016-01-20 08:13:16

标签: ios iphone database swift macos

我尝试使用外部数据库和api。所以我在youtube上关注这个视频 https://www.youtube.com/watch?v=Ixk93yx-v28

我看到了这个错误

"可选类型的价值' NSURL?'没有打开; "在那条线上

    func request(url:String,callback:(NSDictionary)->()) {
    var nsURL = NSURL(string: url)
    ///////////////////////////on this line/////////////////////////////////
    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
    /////////////////////////////////////////////////////////////////
        (data,response,error) in
        var error:NSError?
        var response = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
        callback(response)
    }
    task.resume()
}

当我尝试修复时,将!放在nsURL中就像这样 xCode返回此错误"额外参数'错误'在电话"

func request(url:String,callback:(NSDictionary)->()) {
    var nsURL = NSURL(string: url)

    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
        (data,response,error) in
        var error:NSError?
////////////////////////////Error Here/////////////////////////////////////
            var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
/////////////////////////////////////////////////////////////////////////////////
        callback(response)
    }
    task.resume()
}
有任何理想吗?对不起我的英文

1 个答案:

答案 0 :(得分:1)

更新您的功能,如下图所示为swift 2.0:

func request(url:String,callback:(NSDictionary)->()) {
    guard let nsURL = NSURL(string: url) else { return }
    ///////////////////////////on this line/////////////////////////////////
    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
        /////////////////////////////////////////////////////////////////
        (data, response, error) in
        guard let data = data where error == nil else { return }
        do {
            if let response = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                callback(response) 
            }
        } catch let error as NSError {
            print("json error: \(error.localizedDescription)")
        }


    }
    task.resume()
}