通过身份验证从URL读取JSON

时间:2016-08-24 06:58:57

标签: ios json swift

我尝试从URL读取JSON,但身份验证不起作用。我在网上找到了很多例子,但每次验证都失败了......

这是我的代码:

let requestURL: NSURL! = NSURL(string: "http://example.com")!

    let request = NSMutableURLRequest(URL:requestURL!);
    let username = "USERNAME"
    let password = "PW"
    let loginString = NSString(format: "%@:%@", username, password)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
    request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        print(statusCode)
     }

    task.resume()

任何想法为什么它不起作用? :)

叔JEY

2 个答案:

答案 0 :(得分:-1)

确保请求的方法是POST

//POST Method
request.HTTPMethod = "POST"
//base64 needs the Basic keyword in the auth header
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

答案 1 :(得分:-2)

  

创建登录功能后;

您可以在clear login function下面看URLRequest

func getLogin() {
    let url:NSURL = NSURL(string: "http://example.com/login.php?username="+String(username)+"&password="+String(password)+"")!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    let task = session.downloadTaskWithRequest(request) {
        (
        let location, let response, let error) in

        guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

        guard let _:NSString = urlContents else {
            print("error")
            return
        }

        //all result is here
        //print(urlContents)
        //string to NSData conversion
        let data = urlContents.dataUsingEncoding(NSUTF8StringEncoding)
        do {
            //parse NSData to JSON
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                if let check = name["status"] as? String {

                if check == "1" {

                 print("Login SUCCESS")

                }else{

                 print("Login ERROR") 

                }


            }


            }



        } catch {
            print("error serializing JSON: \(error)")
        }


    }





    task.resume()

}

示例输出后的后端json authentication;

[{
    "status": "1" // If login true write 1 else write 0
}]
  

使用此function;

    getLogin()

此外,您可以在login successlogin error时使用您的代码,在下面您可以查看是否,

 if check == "1" {

    print("Login SUCCESS")

 }else{

    print("Login ERROR") 

 }