gpt4 book ai didi

php - 将 json 对象检索到 xCode 中始终带有 nil 值

转载 作者:行者123 更新时间:2023-11-30 10:13:33 25 4
gpt4 key购买 nike

我只是想用我的 sql 获取这个 json 连接。 php 文件工作正常。当我直接测试它时,它是写入和检索的。

但是在XCode上我只能写。当我尝试取回 json 对象时,它总是以 nil 的形式返回。错误如下。知道那会是什么吗?

NSURLSESSION error - nil NSURLSESSION data - <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 dictionary - nil

json error - Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7f8e88a44d40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

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);


?>

最佳答案

字符串格式的数据为:

2d6f2472347815e1633e7d08234bb144bbae8067Connected to databaselocalhostlocalhostSwiftApp{"status":"400","message":"Please choose different email address"}

这不是有效的 JSON 结构。您必须仅获取 {} 包围的部分(包括那些 {}),然后才能将其转换为 JSON 字典。

关于php - 将 json 对象检索到 xCode 中始终带有 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com