使用alamofire处理Json响应

时间:2018-12-24 10:23:32

标签: swift alamofire swifty-json

我正在使用IOS登录应用程序,但是我不知道如何处理服务器的Json响应,我想编写一个依赖于服务器响应的布尔函数: 如果用户名和密码正确,这是服务器的响应:

SUCCESS: {
    users =     (
                {
            email = test;
            id = 1;
            money = 200;
            password = test;
            username = test;
        }
    );
}

如果用户名和密码错误:

SUCCESS: {
    users =     (
    );
}

这是我用NodeJs编写的后端代码:

app.get('/login/:username/:password',(req,res)=>{
    let user = req.params;
    var sql = "SELECT * FROM  users WHERE username = ? And password = ? ";
    mysqlConnection.query(sql,[user.username,user.password],
    function(err, rows){
        if(!err){    

       res.send(JSON.stringify({"users" : rows}));
}
 else {
console.log(err)
         }
    }

这是我的快捷功能:

   class func login(username : String , password : String, _ completion: @escaping (Bool) -> ()) {
        let url = "http://127.0.0.1:3000/login/"+username+"/"+password
        Alamofire.request(url).responseJSON{response in
            switch response.result
            {
            case .failure:
    print(response)
    completion(false)
            case .success:
                //I want to handle the response here
                //return true if the username and password are right
                //return wrong if not
    print(response)
    completion(true)

            }
        }
}

2 个答案:

答案 0 :(得分:0)

在两种情况下,您都获得SUCCESS,因此可以将users作为密钥并检查天气是否包含任何元素,就像用户名和密码正确一样,您将获得

(
            {
        email = test;
        id = 1;
        money = 200;
        password = test;
        username = test;
    }
)

但是如果用户名和密码错误,您将获得users键的空值,因此在这种情况下,您可以使用

if usersDict.count == 0 {

    //username and password are wrong 
} else {

    //username and the password are right
}

答案 1 :(得分:-1)

使用上面的代码:-

func CallAPI(){

    let parameters: [String: Any] = [
        "Username": "Admin",
        "Password": "123456",
        "Language_Code": "EN"]


    Alamofire.request("Your API Url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in

            if((response.result.value) != nil) {

                let ResultJson = JSON(response.result.value!)

                print("ResultJson==",ResultJson)

                let UserCount = ResultJson["users"].count

                if UserCount > 0 {

                    // Do with your above code

                    let Email =  ResultJson["users"]["email"].stringValue
                    let id =  ResultJson["users"]["id"].intValue
                    let money =  ResultJson["users"]["money"].intValue
                    let password =  ResultJson["users"]["password"].stringValue
                    let username =  ResultJson["users"]["username"].stringValue
                }
            }
    }
}