我正在尝试删除表格视图中的帖子,但在执行JSON序列化时遇到错误,在此行中
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
如果我通过浏览器访问url,数据会在数据库中成功删除,如果从浏览器访问它,它也会像这样返回json响应
{"消息":"已成功删除","结果":1,"状态":"图片已被删除 已从驱动器中删除"}
但我得到一个错误,说json文本不是以数组或对象(代码= 3840)开头,但正如你在上面看到的那样,它是一个json字典
错误域= NSCocoaErrorDomain代码= 3840" JSON文本不是以数组或对象开头,而是选项允许未设置片段。" UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}
这是我使用的完整代码。这里出了什么问题?谢谢
func deletePost(_ indexPath: IndexPath) {
let tweet = tweetsArray[indexPath.row]
let uuid = tweet["uuid"] as! String
let imagePath = tweet["imagePath"] as! String
let url = URL(string: "http://localhost/Twitter/post.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "uuid=\(uuid)&path=\(imagePath)"
request.httpBody = body.data(using: String.Encoding.utf8)
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
guard let parsedJSON = json else {
print("error while parsing JSON")
return
}
let jsonMessage = parsedJSON["message"]
if jsonMessage != nil {
// hilangkan data di array
self.tweetsArray.remove(at: indexPath.row)
self.imagesArray.remove(at: indexPath.row)
// hilangkan rownya pada table view
self.tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.reloadData()
}
}
catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error)"
self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
})
return
}
}
else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error!.localizedDescription)"
self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
})
return
}
}
task.resume()
}
答案 0 :(得分:1)
您可以尝试打印服务器响应。请更改catch块中的代码。并识别服务器端的错误。
您的服务器数据是正确的json formate然后打印出您的服务器数据并检查服务器数据是否有效。
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let jsonData = data {
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
if let area = parsedData["AREA"] as? [[String: AnyObject]] {
for a in area {
print(a["area_name"])
print(a["price"])
}
}
}
catch let err{
print("\n\n===========Error===========")
print("Error Code: \(error!._code)")
print("Error Messsage: \(error!.localizedDescription)")
if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
print("Server Error: " + str)
}
debugPrint(error)
print("===========================\n\n")
debugPrint(err)
}
}
else {
debugPrint(error as Any)
}
}.resume()