gpt4 book ai didi

ios - Swift - 无法从 NSData 创建 JSON 对象

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:22 27 4
gpt4 key购买 nike

我正在向服务器发出post 请求 以验证登录尝试。如果尝试成功,则会在 NSdata block 中从服务器返回一些信息。我希望能够将其分解为 json 对象,以便我可以轻松地解析它。

func connectToServerAndGetCookie(username: String, password: String) -> NSString {
var url = "********"
var request = HTTPTask()
var parameters = ["username": username, "password": password]
var cookies = ""
request.requestSerializer = JSONRequestSerializer()
request.POST(url, parameters: parameters, success: {(response: HTTPResponse) in
if response.responseObject != nil {
let data = response.responseObject as NSData
var jsonError: NSError?
let str = NSString(data: data, encoding: NSUTF8StringEncoding)

////////////////// here is where it fails on the nsjsonserialization. the error:
//////////////////Cannot convert the expression's type 'NSDictionary?' to type 'NilLiteralConvertible'
// but when i remove the ? on the as, I get the error: expression does not conform to type '$T5'

let json2 : NSDictionary = NSJSONSerialization.JSONObjectWithData(str, options: nil, error:&jsonError ) as? NSDictionary

println(json2)
// parse cookies here
}
},failure: {(error: NSError) in
println(" error \(error)")
})
return cookies
}

我只是想将 NSData block 分解为 json 对象

最佳答案

无需将 NSData 转换为字符串,您可以按原样使用 NSData。

import Foundation

var error: NSError?
let jsonData: NSData = response.responseObject

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

关于ios - Swift - 无法从 NSData 创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com