Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

exception - EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) with dataTaskWithUrl

I'm using the google places api to search for nearby places. However, I only want places of specific types. The code (seen below) works when I specify just one type, but when I add a second my code runs and promptly give me a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) error on this line:

session.dataTaskWithURL(url!, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in

I know the url is valid. I can plug it into the browser and see the json, so I don't understand what the problem is.

func search(location : CLLocationCoordinate2D, radius : Int, callback : (items : [Attraction]?, errorDescription : String?) -> Void) {
    var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7873589,-122.408227&radius=4000&types=aquarium|art_gallery&key=YOURKEY"
    var url = NSURL(string: urlString)
    var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

    session.dataTaskWithURL(url!, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in

        if error != nil {
            callback(items: nil, errorDescription: error.localizedDescription)
        }

        if let statusCode = response as? NSHTTPURLResponse {
            if statusCode.statusCode != 200 {
                callback(items: nil, errorDescription: "Could not continue.  HTTP Status Code was (statusCode)")
            }
        }

        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            callback(items: GooglePlaces.parseFromData(data), errorDescription: nil)
        })

    }).resume()
}


class func parseFromData(data : NSData) -> [Attraction] {
    var attractions = [Attraction]()

    var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    var results = json["results"] as? [NSDictionary]

    for result in results! {

        var placeId = result["place_id"] as String
        var image = result["icon"] as String
        var name = result["name"] as String
        var ratingString = ""
        var types = result["types"] as [String]
        println(types)

        if result["rating"] != nil {
            var rating = result["rating"] as Double
            ratingString = "(rating)"
        }

        var coordinate : CLLocationCoordinate2D!

        if let geometry = result["geometry"] as? NSDictionary {
            if let location = geometry["location"] as? NSDictionary {
                var lat = location["lat"] as CLLocationDegrees
                var long = location["lng"] as CLLocationDegrees
                coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

                var placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
                var attraction = Attraction(id: placeId, imageUrl: "image url", locationName: name, ratingAvg: "(ratingString)", types: types, placemarker: placemark)

                attractions.append(attraction)
            }
        }
    }
    return attractions
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know the url is valid

The URL is not valid. You do not know what you think you know. Listen to the runtime. It knows more than you do.

Just try this code alone (in a playground, for instance):

var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7873589,-122.408227&radius=4000&types=aquarium|art_gallery&key=YOURKEY"
let url = NSURL(string:urlString)

url is nil. And that's your problem. You cannot force-unwrap nil; you will crash if you do.

Once you acknowledge this, you can start to think about why the URL is not valid. (It's pretty obvious why that might be.) Learning to believe the compiler and the runtime is key to successful programming.

HINT: Form your URL like this and all is well:

let url2 = NSURL(scheme: "https", host: "maps.googleapis.com", path: "/maps/api/place/nearbysearch/json?location=37.7873589,-122.408227&radius=4000&types=aquarium|art_gallery&key=YOURKEY")

Why do you suppose that is? Look at the docs and see what this initializer does for you...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...