草庐IT

exception - EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)与 dataTaskWithUrl

coder 2023-09-12 原文

我正在使用 google places api 来搜索附近的地点。但是,我只想要特定类型的地方。当我只指定一种类型时,代码(如下所示)有效,但是当我添加第二个类型时,我的代码运行并立即在这一行给我一个 EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 错误:

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

我知道网址有效。我可以将它插入浏览器并看到 json,所以我不明白是什么问题。

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
}

最佳答案

I know the url is valid

URL 无效。你知道你认为你知道的。听听运行时。它比你知道的更多。

只需单独尝试此代码(例如,在 Playground 上):

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 为零。那是你的问题。您不能强制展开 nil;如果你这样做,你会崩溃。

一旦您确认了这一点,您就可以开始考虑 为什么 URL 无效。 (原因很明显。)学会相信编译器和运行时是成功编程的关键

提示:像这样形成您的 URL,一切都很好:

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")

为什么会这样?查看文档,看看这个初始化程序为您做了什么......

关于exception - EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)与 dataTaskWithUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054030/

有关exception - EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)与 dataTaskWithUrl的更多相关文章

  1. ruby-on-rails - Ruby 流量控制 : throw an exception, 返回 nil 还是让它失败? - 2

    我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id

  2. ruby-on-rails -/usr/local/lib/libz.1.dylib,文件是为 i386 构建的,它不是被链接的体系结构 (x86_64) - 2

    在我的mac上安装几个东西时遇到这个问题,我认为这个问题来自将我的豹子升级到雪豹。我认为这个问题也与macports有关。/usr/local/lib/libz.1.dylib,filewasbuiltfori386whichisnotthearchitecturebeinglinked(x86_64)有什么想法吗?更新更具体地说,这发生在安装nokogirigem时日志看起来像:xslt_stylesheet.c:127:warning:passingargument1of‘Nokogiri_wrap_xml_document’withdifferentwidthduetoproto

  3. Ruby 1.9.2-p-180 失败,返回 'illegal instruction' 或 'stack level too deep (SystemStackError)' - 2

    行为:Ruby1.9.2p180因“非法指令”而失败,没有其他详细信息。Ruby1.9.1p378运行完全没有问题。失败发生在pin=fronto.index(k)行中,仅在某些迭代中发生。from和into都是对象数组,by是该对象的属性(x或y)。代码:defadd_from_to_byfrom,into,bynto=into.sort_by{|k|k.send(by)}fronto=(from+nto).sort_by{|k|k.send(by)}dict={}nto.each{|k|dict[k]=[]}nto.eachdo|k|pin=fronto.index(k)up=pi

  4. c - Ruby c 扩展 : How can I catch all exceptions, 包括不是 StandardErrors 的东西? - 2

    在ruby中,begin#...rescue#...end不会捕获不是StandardError子类的异常。在C中,rb_rescue(x,Qnil,y,Qnil);VALUEx(void){/*...*/returnQnil;}VALUEy(void){/*...*/returnQnil;}会做同样的事情。我如何从ruby​​C扩展中rescueException=>e(而不仅仅是rescue=>e)? 最佳答案 Ruby需要更多文档。我不得不进入ruby​​源代码,这是我发现的:VALUErb_rescue(VALUE(*b_p

  5. ruby-on-rails - 发生异常时发送电子邮件不起作用,使用 exception_notification - 2

    我正在从rails2.3迁移到rails3.1,我试图在生成异常时发送电子邮件。我正在使用exception_notificationgem。我的其余电子邮件都在工作。但是异常邮件不会被解雇。以下是我的staging.rb文件中的设置。config.action_mailer.perform_deliveries=trueconfig.action_mailer.raise_delivery_errors=true下面是application.rb中的代码C::Application.config.middleware.useExceptionNotification::Rack,:e

  6. ruby-on-rails - 有可能 CanCan can :manage, :all except one or more method? - 2

    我在做:can:manage,:allifuser.role=='admin'can:approve,Anunciodo|anuncio|anuncio.try(:aprovado)==falseend我的第二种方法不起作用,因为:manage:all覆盖了它。有一种方法可以声明可以管理除批准之外的所有内容吗?在里面批准我只是做can:approve,Anunciodo|anuncio|user.role=='admin'&&anuncio.try(:aprovado)==falseend什么是更好的解决方案? 最佳答案 尝试换一种

  7. ruby-on-rails - Rails 和 attr_accessible : is there a way to raise an exception if a non-mass-assignable attribute is mass-assigned? - 2

    如果尝试批量分配attr_accessible不允许的属性,是否有办法让Rails引发错误?这在开发中会很方便,可以提醒我为什么我Shiny的新模型不起作用,也有助于登录生产环境以检测恶意事件。我正在使用Rails2.3.8,但可能很快就会迁移到3。 最佳答案 从Rails3.2开始,这不再需要monkeypatching——rails现在提供了这种行为。将其放入development.rb和test.rb:config.active_record.mass_assignment_sanitizer=:strict

  8. ruby-on-rails - Ruby无一异常(exception)地获得回溯 - 2

    我有一个RubyonRails应用程序,其中一个模型的验证失败。对于此验证可能失败的地方,代码库有不同的入口点。我有兴趣弄清楚它是从哪里来的。由于这是一个简单的验证方法,因此不涉及任何异常,我只是从方法中返回false并且保存失败。目前是否还可以记录回溯以查明此验证源自哪个服务/路由,以便我可以查看是什么导致此对象的状态发生更改以使其验证失败? 最佳答案 你可以试试caller():deffoo2putscallerenddeffoofoo2#line5endfoo#line7结果:test.rb:5:in`foo'test.rb:

  9. ruby - Rspec any_instance.stub 为 nil :NilClass exception 引发未定义的方法 `any_instance_recorder_for' - 2

    这是我正在测试的包含在Foo.rb中的类:classFoodefbarreturn2endend这是Foo_spec.rb中包含的我的测试:require"./Foo.rb"describe"Foo"dobefore(:all)doputs"#{Foo==nil}"Foo.any_instance.stub(:bar).and_return(1)endit"shouldpassthis"dof=Foo.newf.bar.shouldeq1endend我得到以下输出:falseFFailures:1)FooShouldpassthisFailure/Error:Foo.any_insta

  10. ruby - 公寓 ruby gem : Want to Catch an exception - 2

    我正在使用这个apartmentruby。我在application.rb文件中添加了这个:config.middleware.use'Apartment::Elevators::Subdomain'当我尝试在PostgreSQL中不存在子域“test”模式的浏览器url“test.domain.local:3000”中点击这个时,我看到了这个错误Apartment::SchemaNotFound(Oneofthefollowingschema(s)isinvalid:test,"public")我知道这是gem的正常行为,但想捕获此异常并将用户重定向到其他页面,我该怎么做?

随机推荐