ios - 当我尝试快速使用外部数据库和 API 时如何修复此错误

标签 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()
}

有什么理想吗?对不起我的英语

最佳答案

针对 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()
}

关于ios - 当我尝试快速使用外部数据库和 API 时如何修复此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894704/

相关文章:

ios - 非 ARC 到 ARC : Pointer to a pointer to an object (**)

iphone - 显示启动图像直到 webView 加载

iphone - 如何设置一个tableview delegate

iphone - 创建类似于新的 iOS 6 按钮共享的自定义共享 View

ios - 支持 Apple NFC 的印度奖励通行证

ios - Swift 应用程序中的预处理

ios - Swift UIImageView 始终为空

php - 在一个有两个外键的表中插入数据(php)

MongoDB/RethinkDB 是否使用 ODM?

database - 如何构造/实现多维数据/数据立方体