我只是想用我的sql获得这个json连接。 php文件工作正常。在我直接测试时写入和检索。
但是在XCode上我只能写。当我试图让json对象返回时,它总是以零返回。错误如下。知道那是什么意思吗?
NSURLSESSION错误 - 无 NSURLSESSION数据 - < 0a0a3264 36663234 37323334 37383135 65313633 33653764 30383233 34626231 34346262 61653830 3637436f 6e6e6563 74656420 746f2064 61746162 6173656c 6f63616c 686f7374 6c6f6361 6c686f73 74537769 66744170 707b2273 74617475 73223a22 34303022 2c226d65 73736167 65223a22 506c6561 73652063 686f6f73 65206469 66666572 656e7420 656d6169 6c206164 64726573 73227d>
JSON字典 - nil
json错误 - 错误 Domain = NSCocoaErrorDomain Code = 3840“操作不可能 完成。 (可可错误3840.)“(JSON文本没有以数组或 允许片段未设置的对象和选项。)UserInfo = 0x7f8e88a44d40 {NSDebugDescription = JSON文本不是以数组或对象开头的 允许片段未设置的选项。}
import UIKit
class SignupViewController: UIViewController {
@IBOutlet weak var userEmailAddressTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var userRepeatPasswordTextField: UITextField!
@IBOutlet weak var userFirstnameTextField: UITextField!
@IBOutlet weak var userLastNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func signUpButtonTapped(sender: AnyObject) {
let userEmail = userEmailAddressTextField.text
let userPassword = userPasswordTextField.text
let userPasswordRepeat = userRepeatPasswordTextField.text
let userFirstName = userFirstnameTextField.text
let userLastName = userLastNameTextField.text
// if (userPassword != userPasswordRepeat){
//
// self.displayAlertMessage("password do not match")
//
// }
//
// if (userEmail.isEmpty || userPassword.isEmpty || userFirstName.isEmpty || userLastName.isEmpty){
//
// self.displayAlertMessage("All fields required")
//
// }
let myUrl = NSURL(string: "http://localhost/SwiftAppAndMYSQL/scripts/registerUser.php")
let request = NSMutableURLRequest(URL: myUrl!)
//let postString = "userEmail=\(userEmail)&userPassword=\(userPassword)&userFirstName=\(userFirstName)&userLastName=\(userLastName)"
let postString = "userEmail=8&userPassword=90&userFirstName=890&userLastName=809"
request.HTTPMethod = "POST"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
println("NSURLSESSION error - \(error)")
println("NSURLSESSION data - \(data)")
dispatch_async(dispatch_get_main_queue())
{
if error != nil {
self.displayAlertMessage(error.localizedDescription)
return
}
var err:NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("JSON dictionary - \(json)")
println("json error - \(err!)")
println("JSON data - \(data)")
if let parseJSON = json{
var userId = parseJSON["userId"] as? String
println(userId)
if (userId != nil){
let alertController = UIAlertController(
title: "Bam!",
message: "Registration Sucessful",
preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(
title: "OK",
style: UIAlertActionStyle.Default){
(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
else{
let errorMessage = parseJSON["Message"] as? String
if (errorMessage != nil){
self.displayAlertMessage(errorMessage!)
}
}
}
}
}).resume()
}
func displayAlertMessage (message: String){
let alertController = UIAlertController(title: "Bam!", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
我正在使用的Php脚本
<?php
//use MySQLDAO;
require ("../db/MySQLDAO.php");
$config = parse_ini_file('../db/SwiftApp.ini');
$returnValue = array();
if (
empty($_REQUEST["userEmail"]) ||
empty($_REQUEST["userPassword"]) ||
empty($_REQUEST["userFirstName"]) ||
empty($_REQUEST["userLastName"])) {
$returnValue["status"] = "400";
$returnValue["message"] = "Missing required information";
echo json_encode($returnValue);
return;
}
$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);
$salt = openssl_random_pseudo_bytes(16);
$secure_password = sha1($userPassword . $salt);
//http://localhost/SwiftAppAndMYSQL/scripts/registerUser.php?userEmail=email&userPassword=123456&userFirstName=gui&userLastName=Maia
echo $secure_password;
//CONNECT USING .INI
$dbhost = trim($config["dbhost"]);
$dbuser = trim($config["dbuser"]);
$dbpassword = trim($config["dbpassword"]);
$dbname = trim($config["dbname"]);
$dao = new MySQLDAO($dbhost, $dbuser, $dbpassword, $dbname);
$dao->openConnection();
echo $dao->dbhost;
echo $dao->dbname;
$userDetails = $dao->getUserDetails($userEmail);
if(!empty($userDetails))
{
$returnValue["status"] = "400";
$returnValue["message"] = "Please choose different email address";
echo json_encode($returnValue);
return;
}
$result = $dao->registerUser($userEmail, $userFirstName, $userLastName, $secure_password, $salt);
if ($result) {
$userDetails = $dao->getUserDetails($userEmail);
$returnValue["status"] = "200";
$returnValue["message"] = "Sucessfully registered new user";
$returnValue["userId"] = $userDetails["user_id"];
$returnValue["userFirstName"] = $userDetails["first_name"];
$returnValue["userLastName"] = $userDetails["last_name"];
$returnValue["userEmail"] = $userDetails["email"];
} else {
$returnValue["status"] = "400";
$returnValue["message"] = "Could not register user with provided information";
}
$dao->closeConnection();
echo json_encode($returnValue);
?>
答案 0 :(得分:1)
字符串格式的数据是:
2d6f2472347815e1633e7d08234bb144bbae8067Connected to databaselocalhostlocalhostSwiftApp{"status":"400","message":"Please choose different email address"}
哪个不是有效的JSON结构。在将其转换为JSON字典之前,您必须只获取{}
包围的部分(包括那些{}
)。