我有一个按钮的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 {
}
在调试区域中有以下详细信息
data Data? some
response URLResponse? 0x0000618000223500
error Error? nil none
我想我错过了一行,或者需要将变量设置为JSONSerialization而不是尝试!'但我不确定是什么。
答案 0 :(得分:2)
您将返回null
。试试这个
if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
return json_encode($returnValue);
}