【发布时间】:2025-12-21 08:25:07
【问题描述】:
我在 swift 中遇到了我的代码问题。我通过 httpMethod POST 向网络服务器发出请求。这个要求没问题。我在数据值中得到响应和数据。数据看起来像 JSON
{"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}
然后我将加载此响应数据以根据响应数据设置按钮。但我没能写出这段代码。有人能帮助我吗? :)
错误代码
Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)'
// 我用其他选项测试过,但总是失败:-(
我在代码中注释错误....
let url = "https://URL.php"
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
let bodyData = "token=" + (dts)
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) {
(response, data, error) in
// here i get the result of
// {"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}
var str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
var names = [String]()
// here i will get each value of pushValues to add to the array names
do {
if let data = str,
// ... and here is the error code by xcode ::: ==> Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)'
// i tested with other options but i always fail :-(
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let blogs = json["pushValues"] as? [[String: Any]] {
for blog in blogs {
if let name = blog["devicePushGlobal"] as? String {
print(name)
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
// names array is empty
print(names)
}
感谢您的帮助
【问题讨论】:
-
删除
if let data = str。