返回从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); 

?> 
+0

问题是您的答案是可选的? 'readvalue!' – AgRizzo

+0

但是,如果我删除!我有一个错误:@AgRizzo – riki

+0

@AgRizzo所以,你需要收到“[email protected]”没有可选? –

我认为它可以做类似:wihtout可选

+0

我试过没有改变任何东西 – riki

+0

它开始感谢 – riki

只是做这在操场和它的作品如预期..

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是:世界你好”

该代码不是非常安全...

+0

您能否让我看看如何修改上面的代码来删除可选项? – riki

+0

readvalue = jsonData.value(forKey:“message”)as!字符串 – aofs

+0

我试过没有改变什么 – riki

你需要无凝聚,使你的价值非可选使用

if let readvalue = jsonData.value(forKey: "message") as? String { 
    print(readvalue) 
} 

必须打印。例如print(readvalue ?? "nil")。更好的做法是重新设计响应处理,以正确返回键入的值或特定的错误。