任何知道从数据库检索数据并使用它来检查用户是否退出(登录)的人都可以提供帮助。我的头被破坏了,不幸的是我的编码不足以解决问题!
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脚本运行良好,我可以在浏览器中传递参数,一切似乎都可以。密钥是正确的(userId)。 我认为另一个问题是让userID = parseJSON [" userId"]为?串
如果我作为NSDictionary请求数据 - 如何将此信息转换为String类型(我确定你无论如何都可以)抱歉 - 很多问题。我需要在另一个视图控制器中使用String表示。我已经尝试了很多年,我无法让它工作,所以我真的很感激一些帮助 - 当我运行代码时 - 它会绕过" do"阻止并直接进入.localizedDescription
感谢您抽出时间阅读我的v问题!
答案 0 :(得分:0)
问题肯定出在NSJSONSerialization.JSONObjectWithData中,由于某种原因,它并不像你的JSON。
尝试清理JSON,然后再将其提供给NSJSONSerialization:
var dataString = String(data: data, encoding: NSUTF8StringEncoding)!
dataString = dataString.stringByReplacingOccurrencesOfString("\\'", withString: "'")
let cleanData: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)!
答案 1 :(得分:0)
while sending a request "request.setValue("application/json", forHTTPHeaderField: "Accept")" resolved my error.