gpt4 book ai didi

php - 从 PHP 脚本接收 'json_encode' 时 Swift JSON 出错。没有它也能正常工作

转载 作者:行者123 更新时间:2023-11-28 12:38:33 26 4
gpt4 key购买 nike

我有一个用于按钮的 Swift 函数,当按下该按钮时,它会通过 PHP 将一些详细信息写入数据库:

 @IBAction func createCommunityButtonTapped(_ sender: AnyObject) {

let communityName = communityNameTextField.text;
if (communityName!.isEmpty){
displayMyAlertMessage(userMessage: "You must name your Community");

return;
}else{

func generateRandomStringWithLength(length: Int) -> String {

var randomString = ""
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

for _ in 1...length {
let randomIndex = Int(arc4random_uniform(UInt32(letters.characters.count)))
let a = letters.index(letters.startIndex, offsetBy: randomIndex)
randomString += String(letters[a])
}

return randomString
}

let communityCode = generateRandomStringWithLength(length: 6)
passwordTextField.text = communityCode

let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php?");

var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";

let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}
}

task.resume()

}

}

除了我将此 echo json 行添加到 PHP 脚本中之外,该函数工作得很好:

if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
echo json_encode($returnValue);
return;
}

然后我在这一行收到错误 Thread 8: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subside = 0x0):

if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}

并且在调试区有以下详细信息

数据数据?一些
响应 URLResponse? 0x0000618000223500
错误错误?零 无

我想我漏掉了一行,或者需要为 JSONSerialization 设置一个变量而不是“try!”但我不确定是什么。

最佳答案

您正在返回 null。试试这个

if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
return json_encode($returnValue);
}

关于php - 从 PHP 脚本接收 'json_encode' 时 Swift JSON 出错。没有它也能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40149491/

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