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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41683099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:03:32  来源:igfitidea点击:

How to convert NSData to Data in Swift 3?

iosjsonswiftxcode

提问by Eric Phillips

I'm trying to create a simple weather app that grabs the user's location and shows simple weather data using the Google Maps api. Everything is working, except for this part where I take the JSON and get the address.

我正在尝试创建一个简单的天气应用程序,它可以使用 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)"
        }
    }
}

On the line:

在线上:

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

I get this error:

我收到此错误:

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

What am I doing wrong?

我究竟做错了什么?

回答by Caleb Kleveter

You need to change a couple things. First, you are using NSData. You should be using the Swift type Data. To convert from NSData?to Data?, just add as Data?to the end of the variable declaration.

你需要改变一些事情。首先,您正在使用NSData. 您应该使用 Swift 类型Data。要转换NSData?Data?,只需添加as Data?变量声明的结尾。

Also, Your type is optional, but you can't pass in an optional type, so you need to unwrap it (using, in this example, if let data = data { /* stuff here */}):

此外,您的类型是可选的,但您不能传入可选类型,因此您需要解开它(在本例中使用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)"
            }
        }
    }
}

Update:

更新:

Another thing you need to change is:

你需要改变的另一件事是:

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

When you cast to the type Dictionary, the compiler does not know what you are talking about because Dictionaryis a generic type. So you need to cast to Dictionary<String, AnyObject>or [String: AnyObject](They are the same).

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