简体   繁体   中英

How do I spot a custom location in Swift 3?

I've been working for a while to try and spot a custom location on a map...basic stuff (with google maps sdk).

But I still get a fatal error at runtime.

Maybe I'm not doing the conversion from the JSON format to a dictionary object correctly?

        geocodeURLString = geocodeURLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!


                dictionary = try JSONSerialization.jsonObject(with: geocodingResultsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<NSObject, AnyObject>

                //ERROR HERE: fatal error: unexpectedly found nil while unwrapping an Optional value


                // Get the response status.

                let status = dictionary["status" as NSObject] as! String

                if status == "OK" {

                    let allResults = dictionary["results" as NSObject] as! Array<Dictionary<NSObject, AnyObject>>


}

I am not completely sure if that is your error. Because if your json parsing doesn't work it will simply return []. But since you asked that specifically, you may try this.

I think you need an API key for your application from google for this JSON parsing which you can create here - https://console.developers.google.com

Also, " https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY " -- This is the right format of url string for your parsing.

You may refer Google Docs here for your reference - https://developers.google.com/maps/documentation/geocoding/intro

You can also verify whether your url string works by passing it to your browser. That will return your JSON page. It will also return the error if it doesn't work.

I hope this helps... All the Best!

At first, I'd recommend to create the required URL using URL components if you're unsure whether the URL constructed from pasting string values together gives you a properly encoded string. You try to encode the whole string via URL host rules which is not the adequate way for the other parts of URL string. Composing via URL components along with URL Query items gives you the option to use raw data as the components can be converted to properly encoded string automatically using the available getters.

Secondly, if you force-unwrap an optional, you do that intentionally and you should be prepared it may break down, in other words you still need to handle the situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM