如果参数值对于http POST请求是正确的,则为PerformSegueWithIdentifier

时间:2016-07-04 11:28:51

标签: swift login http-post nsurlsession

当参数(params)值不正确时,它仍然会登录到另一个视图。在控制台中,响应正文和响应标头在打印时返回值。我哪里出错了?

func login() {
    let request = NSMutableURLRequest(URL: NSURL(string: "http://someurl/verify/")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    let params =
        [
          "username":username.text!,
          "password":password.text!,
          "deviceid":"r49rvnjff",
          "method":"method",
          "payload":"payload"
        ]
            as Dictionary<String,String>

    print(params)

    do {
       request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
    }
    catch {
        print(error)
        return
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        if error == nil {}

        let json: NSDictionary?
        do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        }
        catch let dataError {
            print(dataError)
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
            return
        }

        if let parseJSON = json {

            let authenticated = parseJSON["authenticated"] as? String
            print("authenticated:\(authenticated)")
            if authenticated  != "False" {
            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("segue", sender: self)
                }
            }
        }
        else {
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: \(jsonStr)")
        }
    })
    task.resume()
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

您的无效回复是什么样的?可能是它返回“false”而不是“False”(这是你要检查的),无论如何我建议你从服务器验证你的响应,以便你可以进行身份验证参数是一个布尔值,因此你可以打开你的可选项:

if let authenticated = json["authenticated"] as? Bool {
    if (authenticated) 
    { 
       // ...
    }
}

另外,我发现你的 json 属性被解包后,你的else块永远不会被击中。您的序列化是成功的,因此 json 不是nil,因此如果让parseJSON = json 将始终有效。

我建议采用以下方法:

if let authenticated = json["authenticated"] as? Bool
{
    if (authenticated)
    {
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("segue", sender: self)
        }
     }
     else 
     {
         let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
         print("Error could not parse JSON: \(jsonStr)")
     }
 }
祝你好运!