gpt4 book ai didi

php - 使用 swift 解析 json 数据时出错 "The data couldn’ t 被读取,因为它的格式不正确。”

转载 作者:行者123 更新时间:2023-11-28 08:33:39 27 4
gpt4 key购买 nike

任何知道从数据库中检索数据并使用它来检查用户是否退出(登录)的人请帮忙。我的脑袋坏了,不幸的是我的编码还不够好,无法解决这个问题!

 do {


if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
{


let parseJSON = json

let userID = parseJSON["userId"] as? String //dictionary object that uses a key

if(userID != nil)
{
//everything is fine and take user to main page
//instantiate the view controller
let profilePage = self.storyboard?.instantiateViewControllerWithIdentifier("ProfilePageViewController") as! ProfilePageViewController

//wrap it in nav controller

let profilePageNav = UINavigationController(rootViewController: profilePage)

//take user to this page
//window root view controller- existing is replaced and no back button

let appDelegate = UIApplication.sharedApplication().delegate
appDelegate?.window??.rootViewController = profilePageNav




}else{
//display the alert message from the php file
let errorMessage = parseJSON["message"] as? String


let myAlert = UIAlertController(
title: "Alert!",
message: errorMessage,
preferredStyle: UIAlertControllerStyle.Alert)

//create a button action -
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)

//adding ok button and presenting to a user and once ok button is pressed- dismiss the view
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion:nil)





}


}//end of if let json
}//end of do
catch let error as NSError {
print(error.localizedDescription)
}



print("success")

}//end of dispatch_async
}).resume()//end of request




}//end of action sign in

我认为问题在于 if let json = try 行,数据格式不正确。我的 php 脚本运行良好,我可以在浏览器中传递参数,一切似乎都正常。 key 是正确的 (userId)。我认为另一个问题是 let userID = parseJSON["userId"] as?字符串

如果我已将数据请求作为 NSDictionary - 我如何才能将此信息转换为 String 类型(我相信你无论如何都不能)抱歉 - 有很多问题。我需要在另一个 View Controller 中使用字符串表示。我已经尝试了很长时间,但我无法让它工作所以我真的很感激一些帮助-当我运行代码时 - 它绕过“do” block 并直接进入 .localizedDescription

感谢您花时间阅读我的长问题!

最佳答案

问题肯定出在 NSJSONSerialization.JSONObjectWithData 中,由于某种原因它不喜欢您的 JSON。

在将它提供给 NSJSONSerialization 之前尝试清理你的 JSON:

var dataString = String(data: data, encoding: NSUTF8StringEncoding)!
dataString = dataString.stringByReplacingOccurrencesOfString("\\'", withString: "'")
let cleanData: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)!

关于php - 使用 swift 解析 json 数据时出错 "The data couldn’ t 被读取,因为它的格式不正确。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38351304/

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