Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSData to Data in Swift 3?

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.

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?

like image 754
Eric Phillips Avatar asked Jan 16 '17 18:01

Eric Phillips


3 Answers

let nsdata = NSData()    
let data = Data(referencing: nsdata)

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

like image 120
agandi Avatar answered Oct 23 '22 13:10

agandi


Just cast: let newData = nsData as Data

like image 38
Bitcoin Cash - ADA enthusiast Avatar answered Oct 23 '22 11:10

Bitcoin Cash - ADA enthusiast


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.

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 */}):

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 Dictionary is a generic type. So you need to cast to Dictionary<String, AnyObject> or [String: AnyObject] (They are the same).

like image 23
Caleb Kleveter Avatar answered Oct 23 '22 13:10

Caleb Kleveter