ios - 检查http响应格式

标签 ios swift

我正在进行 http 调用并接收 JSON 响应

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary

但是当没有收到实际的 json 时,此行会失败并出现错误无法将 NSArray 的值转换为 NSDictionary

我明白为什么会发生这种情况,我的问题是如何正确检查响应的格式

最佳答案

我确实喜欢我的 api 中的这个:

typealias JSONType = (dictionary: [String:AnyObject]?, array: [AnyObject]?)

var error:NSError?
var json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
if let dict = json as? [String:AnyObject] {
    return (dict, nil) 
}
else if let arr = json as? [AnyObject] { 
    return (nil, arr)
}

因此,当我返回 JSONType 时,我可以将其更改为将其用作字典或数组:

json.array

关于ios - 检查http响应格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31132354/

相关文章:

ios - Collection View 单元格刷新未发生

ios - 如何提高渲染图像的性能?

ios - 请求非结构或联合中的成员 'subview'?

ios - 使用 2 个自定义单元格在 UITableView 上索引越界

ios - 错误 : Initializer for conditional binding must have optional type, 不是 'String'

swift - 如何从 Swift REPL 获取表达式的静态类型?

swift - 大尺寸 json 的 Realm 数据插入耗时超过 7 分钟

ios - x,y位置在使用手势识别器IOS旋转时发生变化

iphone - 是否可以覆盖/禁用 iPhone 电源按钮的功能?

swift - 创建没有 tableView 部分的 indexList?