返回从Php到Swift Alamofire的Json
问题描述:
嗨,大家好我在一个swift 3 iphone程序上使用alamofire,我的问题是我需要从php页面返回一个值我的问题是,返回给我的值是this 。我如何确保我返回值是:没有[email protected]返回从Php到Swift Alamofire的Json
我希望我已经解释
返回值(不正确):
SUCCESS: {
message = "no Optional(\"[email protected]\")";
} 没有可选( “[email protected]”)
SWIFT CODE:
import Foundation
import Alamofire
class User{
//URL to our web service
var email=""
var password=""
func PrintValue(){
// print(username);
//print(password);
}
func Login() -> String{
//var ris="";
var readvalue=""
let URLString = "http://localhost/test/login_mobile.php"
let parameters_value: Parameters = [
"email": email,
"password": password
]
//Sending http post request
Alamofire.request(URLString, method: .post, parameters: parameters_value).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
//displaying the message in label
readvalue = (jsonData.value(forKey: "message") as! String?)!
print(readvalue)
}
}
return readvalue
}
}
PHP代码:
<?php
include 'user.php';
header('Content-Type: application/json');
$email= $_POST['email'];
$password = $_POST['password'];
$ris['message']="";
$user = new User();
//procedo con il login
if($user->login($email,$password,"MOBILE")==true){
$ris['message']="yes";
}
else{
$ris['message']="no $email";
}
echo json_encode($ris);
?>
答
只是做这在操场和它的作品如预期..
import UIKit
let response: [AnyHashable: Any] = [
"message": "hello world"
]
class MyCoolClass {
func login() {
var readvalue = ""
let jsonData = response as NSDictionary
readvalue = jsonData.value(forKey: "message") as! String
debugPrint("the readvalue is: \(readvalue)")
}
}
let instance = MyCoolClass()
instance.login()
这将打印: “在readvalue是:世界你好”
该代码不是非常安全...
答
你需要无凝聚,使你的价值非可选使用
if let readvalue = jsonData.value(forKey: "message") as? String {
print(readvalue)
}
必须打印。例如print(readvalue ?? "nil")
。更好的做法是重新设计响应处理,以正确返回键入的值或特定的错误。
问题是您的答案是可选的? 'readvalue!' – AgRizzo
但是,如果我删除!我有一个错误:@AgRizzo – riki
@AgRizzo所以,你需要收到“[email protected]”没有可选? –