在快速使用Alamofire的Json请求失败

时间:2018-06-12 06:41:44

标签: ios json swift alamofire

http://dev.alshmokh1.net/mobile/Login/?username=yasser&password=123

当我打电话给这个api从后端获取数据时

[
    {
        "UserID": "yasser",
        "Username": null,
        "sysAdmin": "True",
        "UpdatePW": "True",
        "Name": "  selem yasser",
        "Email": "a@a/com",
        "iType": "2",
        "UserPW": "123",
        "Admin": "True",
        "Id_Bank": "5",
        "msg": "Success"
    }
]

我使用alamofire来解析来自api的数据。 这是解析代码

func login()
   {

    let username = txtUserName.text!
     let password  = txtPassword.text!

    print("username\(username)  password \(password)")

    let params: [String: Any] = ["username": username, "password": password]

    let urlString = "http://dev.alshmokh1.net/mobile/Login/"
    guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: nil) else{
        //
        return
    }

    request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
    Alamofire.request(request).responseJSON { response in

        print("response",response)
     }
    }

结果

[
    {
        "UserID": null,
        "Username": null,
        "sysAdmin": null,
        "UpdatePW": null,
        "Name": null,
        "Email": null,
        "iType": null,
        "UserPW": null,
        "Admin": null,
        "Id_Bank": null,
        "msg": "failure"
    }
]

如何在我错误的情况下使用alamofire解析数据

1 个答案:

答案 0 :(得分:0)

尝试此代码,因为您需要在url

中附加param
func login()
    {

        let username = txtUserName.text!
        let password  = txtPassword.text!

        print("username\(username)  password \(password)")


        let urlString = String(format:"http://dev.alshmokh1.net/mobile/Login?username=%@&password=%@",username,password)
        guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: nil) else{
            //
            return
        }

        Alamofire.request(request).responseJSON { response in

            print("response",response)
        }
    }

响应

response SUCCESS: (
        {
        Admin = True;
        Email = "a@a/com";
        "Id_Bank" = 5;
        Name = "  selem yasser";
        UpdatePW = True;
        UserID = yasser;
        UserPW = 123;
        Username = "<null>";
        iType = 2;
        msg = Success;
        sysAdmin = True;
    }
)