正在尝试使用 Swift 中的 Json 令牌从服务器获取身份验证

Attempting to get authentication from server using Json token in Swift

我正在我的 Swift 应用程序中添加一个登录过程,并添加了以下代码来处理 Json 令牌身份验证

 class func getValidationFromServer(success: ((svrData: NSData!) -> Void)) {
    var usrName = ViewController.gVariables.gUser
    var pwd = ViewController.gVariables.gPwd
    var postData = NSMutableData(data: "username=\(usrName)".dataUsingEncoding(NSUTF8StringEncoding)!)
    postData.appendData("&password=\(pwd)".dataUsingEncoding(NSUTF8StringEncoding)!)
    postData.appendData("&grant_type=password".dataUsingEncoding(NSUTF8StringEncoding)!)

    var request = NSMutableURLRequest(URL: NSURL(string: "http://api.mip.local/oauth/token")!,
        cachePolicy: .UseProtocolCachePolicy,
        timeoutInterval: 10.0)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData

    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            ViewController.gVariables.gUser = "Error - \(error) "
        } else {
            let httpResponse = response as? NSHTTPURLResponse
            ViewController.gVariables.gUser = response.description
        }
    })
}

当应用程序运行时,它到达 let dataTask.. 行并直接越过它,因此没有响应。我被告知我有正确的 url,我在登录时通过模拟器 运行 应用程序,所以一定是我做错了什么。

我想这里你需要一个异步POST下面的请求代码

    let urlPath: String = "http://api.mip.local/oauth/token"
    var url: NSURL = NSURL(string: urlPath)!
    var postData = NSMutableData(data: "username=\(usrName)".dataUsingEncoding(NSUTF8StringEncoding)!)
    postData.appendData("&password=\(pwd)".dataUsingEncoding(NSUTF8StringEncoding)!)
    postData.appendData("&grant_type=password".dataUsingEncoding(NSUTF8StringEncoding)!)
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request1.HTTPMethod = "POST"
    request1.timeoutInterval = 60
    request1.HTTPBody=postData
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")
    })