在使用 RubyMotion 创建应用程序之后,这是我第一次使用 xCode 在 Swift 中开发应用程序。
我使用以下代码从 Rails API 获取所有帖子,请求成功但解析 JSON 时出错。
代码:
func loadData() {
let url = NSURL(string: "http://localhost:3000/api/posts")
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSDictionary
})
task.resume()
}
错误:
libswift_stdlib_core.dylib`swift_dynamicCastObjCClassUnconditional:
0x103dbae20: pushq %rbp
0x103dbae21: movq %rsp, %rbp
0x103dbae24: pushq %rbx
0x103dbae25: pushq %rax
0x103dbae26: movq %rsi, %rcx
0x103dbae29: movq %rdi, %rbx
0x103dbae2c: xorl %eax, %eax
0x103dbae2e: testq %rbx, %rbx
0x103dbae31: je 0x103dbae4d ; swift_dynamicCastObjCClassUnconditional + 45
0x103dbae33: movq 0x72b66(%rip), %rsi ; "isKindOfClass:"
0x103dbae3a: movq %rbx, %rdi
0x103dbae3d: movq %rcx, %rdx
0x103dbae40: callq *0x5e212(%rip) ; (void *)0x0000000105b6f000: objc_msgSend
0x103dbae46: testb %al, %al
0x103dbae48: movq %rbx, %rax
0x103dbae4b: je 0x103dbae54 ; swift_dynamicCastObjCClassUnconditional + 52
0x103dbae4d: addq $0x8, %rsp
0x103dbae51: popq %rbx
0x103dbae52: popq %rbp
0x103dbae53: retq
0x103dbae54: leaq 0xe427(%rip), %rax ; "Swift dynamic cast failed"
0x103dbae5b: movq %rax, 0x7974e(%rip) ; gCRAnnotations + 8
0x103dbae62: int3
0x103dbae63: nopw %cs:(%rax,%rax)
提前致谢!
最佳答案
从你的 URL http://localhost:3000/api/posts
我可以假设你收到了一个对象数组,所以你应该将结果转换为 NSArray。
代码应该是:
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSArray
然而,正如 Yatheesha 所提到的,您可以收到 nil,因此最好转换为可为 null 的数组并 checkin if let...
:
if let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray {
...
}
关于ios - Swift 动态转换因 HTTP GET 请求而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956956/