服务器不再接受URLSession请求

时间:2017-02-08 03:57:47

标签: json swift3 xcode8 ios10

在StackOverflow上查看并尝试其他问题和答案后,我继续遇到以下问题。

该应用程序旨在验证用户的用户名和密码,然后在服务器验证用户和密码有效的情况下,将其登录到另一个屏幕上的服务器中。

JSON响应意味着有一个键成功,如果它 1 ,那么如果 0 则可以登录其他地方用户无法登录。

使用Swift 2工作得很好,我执行了从Swift2到Swift 3的推荐更改,并且没有错误,但对以下代码有一个奇怪的响应。

            let body : String = ("username=\(tkUserName.text!)&password=\(tkPassword.text!)")
        var request = NSMutableURLRequest()
        request = NSMutableURLRequest(url: URL(string: "https://xxxxxxxxxxxx/LoginApp")!)
        request.httpMethod = "POST"
        request.httpBody = body.data(using: String.Encoding.utf8)

        URLSession.shared.dataTask(with: request as URLRequest)
        { (data, response, error) -> Void in
            DispatchQueue.main.async(execute: { () -> Void in

                    if response == nil
                    {
                        //advise user no internet or other
                    }
                    else
                    {
                        var success : Int?
                        do {
                            let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                            success = jsonResult!.object(forKey: "success") as? Int

                        }
                        catch let error as NSError
                        {
                            //action error
                        }

                        if success == 1
                        {
                            //capture all is good and go to other page                                
                            self.performSegue(withIdentifier: "unwindThenGoToTeamPage", sender: self)
                        }
                        else
                        {
                            //THIS IS WHERE IT DROPS INTO EACH TIME AS SUCCESS WAS "0"

                        }
                    }

            }.resume()

这是服务器响应

    Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 7/02/2017 10:19:31 AM
Event time (UTC): 6/02/2017 11:19:31 PM
Event ID: 1f9ff75ee64149b0994fa4a46a6ea03b
Event sequence: 5
Event occurrence: 1
Event detail code: 0

<NSHTTPURLResponse: 0x7b9ea440> { URL: https://xxxxxxxxxxxxx/teambeta/LoginApp } { status code: 200, headers {
"Cache-Control" = private;
"Content-Length" = 67;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 08 Feb 2017 03:48:09 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=ixxxxxxxxxxx; domain=xxxxx.com; path=/; HttpOnly, .ASPXAUTH=xxxxxxxxxxx; domain=xxxxx.com; expires=Fri, 10-Mar-2017 17:08:09 GMT; path=/; HttpOnly, TIsMobileDevice=True; path=/";
"X-AspNet-Version" = "4.0.30319";
"X-AspNetMvc-Version" = "5.2";
"X-Powered-By" = "ASP.NET";

}}

服务器响应的内容还有很多,但问题似乎与我正在创建的URL会话有关。 JSON序列化工作正常,但没有成功密钥,所以我没有给服务器正确的URL数据。

我检查过服务器仍然可以正常使用Swift2以及Android和Windows版本,所以我知道它是我的代码。

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码,这在我的结束时工作正常。请检查:

 var request = URLRequest(url:url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue(AUTENTICATION_KEY, forHTTPHeaderField: "AuthenticateKey")

    request.httpBody = try! JSONSerialization.data(withJSONObject: json, options: [])
    request.timeoutInterval = 30
    let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
        guard data != nil else
        {
            print("no data found: \(error)")
            return
        }

        do
        {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
            completion(json)
        }
        catch let parseError
        {
            print(parseError)
            // Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("Error could not parse JSON to load staff: '\(jsonStr)'")
        }
    }) 
    task.resume()