【问题标题】:JSON NSBundle Error - Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)JSON NSBundle 错误 - 线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)
【发布时间】:2016-04-07 09:48:49
【问题描述】:

我在解析 JSON 时遇到问题。

这是 JSON 的结构:

[{"id":33,"name":"5","sort":2},{"id":34,"name":"6","sort":3},{"id":35,"name":"7","sortOrder":4}]

运行后我遇到了致命错误:

Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)” with code "fatalError("error")"

问题在于 NSBundle。我想是因为我添加了代码:

guard let path = NSBundle.mainBundle().pathForResource("sections", ofType: "json"),
        let jsonData = NSData(contentsOfFile: path) else {
            fatalError("error")
    }
    do {
        if let sections = try NSJSONSerialization.JSONObjectWithData(jsonData,
            options: .MutableContainers) as? [String: AnyObject] {
                // work with sections
                let addr = Address(dict: sections)
                print("sections")
        }
    } catch let error as NSError {
        print(error)
    } 

但是没有“部分”。事实上,与 JSON 的链接没有路径——只有对象(id、name、sort 等)。那么我应该如何更改 guard let path = NSBundle 来解决这个问题呢?

【问题讨论】:

  • 您的应用中是否有文件sections.json?如果没有,你在用NSBundle做什么?
  • 不,JSON 是从 URL 中获取的字符串。那么我应该使用什么来代替 NSBundle 呢?
  • 如何获取字符串?获取它,并将其转换为 NSData(有一个方法)。
  • 让 urlAsString = "xxx.xxx" 让 url = NSURL(string: urlAsString)!让 urlSession = NSURLSession.sharedSession() 让用户名 = "xxx" 让密码 = "xxx"
  • 然后保存该字符串!不要打电话给NSBundle

标签: json swift swift2 nsbundle


【解决方案1】:

您需要在“DocumentDirectory and UserDomainMask”中检查您的文件,为此需要检查文件是否可用,

   let resourcePath = (bundle as! NSBundle).pathForResource("sections", ofType: "Json")

如果文件可用,上述代码将在您的目录中找到文件。

let resourcePath = self.bundle.pathForResource("sections", ofType: "Json");

P.S 请检查您的文件是否在 copyBundleResources 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2017-04-20
    • 2019-12-09
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多