当前位置:  开发笔记 > 编程语言 > 正文

如何在Swift 3中将NSData转换为数据?

如何解决《如何在Swift3中将NSData转换为数据?》经验,为你挑选了2个好方法。

我正在尝试创建一个简单的天气应用程序来抓取用户的位置,并使用Google Maps api显示简单的天气数据.一切正常,除了这部分我拿JSON并获取地址.

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL)
    let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
    if let result = json["results"] as? Dictionary {
        if let address = result[0]["address_components"] as? Array {
            let number = address[0]["short_name"] as! String
            let street = address[1]["short_name"] as! String
            let city = address[2]["short_name"] as! String
            let state = address[4]["short_name"] as! String
            let zip = address[6]["short_name"] as! String
            weatherDisplay.text = "\(city),\(state)"
        }
    }
}

在线上:

let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary 

我收到此错误:

Cannot invoke 'jsonObject' with an argument list of type '(with: NSData?, options: JSONSerialization.ReadingOptions)'

我究竟做错了什么?



1> agandi..:
let nsdata = NSData()    
let data = Data(referencing: nsdata)

https://developer.apple.com/documentation/foundation/data/2224197-init



2> Caleb Klevet..:

您需要更改几件事。首先,您正在使用NSData。您应该使用Swift类型Data。要从转换NSData?Data?,只需将其添加as Data?到变量声明的末尾。

另外,您的类型是可选的,但是您不能传递可选的类型,因此您需要解开它(在此示例中,使用if let data = data { /* stuff here */}):

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL) as Data? // <==== Added 'as Data?'
    if let data = data { // <====== Added 'if let'
        let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
        if let result = json["results"] as? Dictionary {
            if let address = result[0]["address_components"] as? Array {
                let number = address[0]["short_name"] as! String
                let street = address[1]["short_name"] as! String
                let city = address[2]["short_name"] as! String
                let state = address[4]["short_name"] as! String
                let zip = address[6]["short_name"] as! String
                weatherDisplay.text = "\(city),\(state)"
            }
        }
    }
}

更新:

您需要更改的另一件事是:

let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary

转换为类型时Dictionary,编译器不知道您在说什么,因为Dictionary它是泛型类型。因此,您需要强制转换为Dictionary[String: AnyObject](它们相同)。

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有