3

新しくアップグレードされた Swift 2.0 プロジェクトで、次の 2 つの呼び出しを次々と実行します。

let session = NSURLSession.sharedSession()
   authRequest.HTTPMethod = "POST"
   authRequest.HTTPBody = authData
   authRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
   authRequest.addValue("close", forHTTPHeaderField: "Connection")
   authRequest.addValue("application/json", forHTTPHeaderField: "Accept")
   let authTask = session.dataTaskWithRequest(authRequest, completionHandler: { (data : NSData?, response : NSURLResponse? , error : NSError?) -> Void in
       print("Response: \(response)")
       print("Error: \(error)")
       let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
       print("Body: \(strData)")
       if let httpResponse = response as? NSHTTPURLResponse
       {
           if 200 ... 299 ~= httpResponse.statusCode
           {
               do
               {
               result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! Dictionary
               credentials.ClientId = (result["client_id"] as String?)!
               credentials.ClientSecret = (result["client_secret"] as String?)!
               credentials.Username = userDetail.Username
               credentials.Password = userDetail.Password
                   completionHandler(result: true)
                                }
               catch {

               }
           }
           else
           {
               self.RemoveInvalidUserCredentials()
               completionHandler(result: false)
           }

       }

       })
       authTask.resume()

に続く:

let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
   session.configuration.URLCache = nil
   session.configuration.HTTPMaximumConnectionsPerHost = 1
   tokenRequest.HTTPBody = tokenData
   tokenRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
   tokenRequest.addValue("close", forHTTPHeaderField: "Connection")
   tokenRequest.addValue("Basic " + (credentials.encodedClientIdAndSecret() as String), forHTTPHeaderField: "Authorization")
   let tokenTask = session.dataTaskWithRequest(tokenRequest, completionHandler: {(data : NSData?, response : NSURLResponse? , error : NSError?) -> Void in
       print("Response: \(response)")
       print("Error: \(error)")
       let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
       print("Body: \(strData)")
       if let httpResponse = response as? NSHTTPURLResponse {
           if 200 ... 299 ~= httpResponse.statusCode
           {
               do
               {
               result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! Dictionary
               credentials.TokenType = (result["token_type"] as! String?)!
               credentials.Token = (result["access_token"] as! String?)!
               completionHandler(result: true)
               }
               catch{}
           }
       }
   })
   tokenTask.resume()

最初のコード ブロックが正しく実行され、次のものが返されます。

Response: Optional(<NSHTTPURLResponse: 0x14ffe3e60> { URL: <URL>/authorize } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 115;
"Content-Type" = "application/json; charset=utf-8";
Date = "Tue, 29 Sep 2015 14:17:52 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = ".AspNet.ApplicationCookie=E98BMJ5l56psnnJZRy2fyhRTWVYqw4aJsFqPeV1ktkJGi5_frTJ9-8pbp28TcDAn9ISFj_LqwFwOV7WhP1mfTVPktTGTs2Dr5-hvmnISxFVRc1Rg9CcYf3p-Cbn1w6qOEyuXco9PCmCnlsf54KPuSY6Z7FEcUgOyg2nq5oDyamfB_Y4b1dI-7cIZ3LB6ehoI50rIbc2ca7L7f73H1rhbsmuLRarBYsYehSRHRuKs9ec5-XuN0P1W6yqiQ3OOJMayPmmbi6y4uIhBUu0zoRC2v3k9usmRjubxGy2hqf6n0baTOIDokav0wQq_smR9qDA6nNh09YTS1Mzvf0iQPS2YJa7QrnERlNSixDROhkQVLC8hc3GV8jc9_7iGUhJzLgeVzhnjnVeB7Z311QLcXxGonEzzcWAzPu29tm2LkZgdte4J0kQHc-iTiNjSbgBqV2zVH9v_0JHtZCFGdSxSGptXGfsPr5O9M-EyVX2UNXxIsVI-hfv3p8-_igV96phbWsvWyqyYhVMQ8v61vHxfO2CFIQ; path=/; secure; HttpOnly";
"X-Powered-By" = "ASP.NET";

ただし、2番目には次のエラーがあります。

エラー Domain=NSURLErrorDomain Code=-1005 「ネットワーク接続が失われました。」UserInfo={NSUnderlyingError=0x14ffe3cc0 {エラー ドメイン=kCFErrorDomainCFNetwork コード=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey= https://test.acumentive.com/tagmanager/api/ v1/tokens , NSErrorFailingURLKey= https://test.acumentive.com/tagmanager/api/v1/tokens , _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=ネットワーク接続が失われました。}

サーバーにアクセスできず、別のセッションと同じ共有セッションを試してリクエストを送信しました。

何か案は?

4

2 に答える 2

4

NSURLSession の代わりに NSURLConnection を使用して問題を解決しました。セッションが以前の接続をキャッシュしているために発生しているようです。

于 2015-09-30T10:59:42.327 に答える
1

これがエラー 1005 の要点です。サーバーにアクセスできません。サーバーにリクエストを送信すると、サーバーにアクセスしてステータスコードが返されるか、デバイスがサーバーと通信できず、サーバーがステータスコードを提供できないかのいずれかが発生します。代わりに、通常は #1000 前後のエラーが発生します。

これは非常にまれです。デバイスがサーバーとの通信を開始した後、接続が失われたことを意味します (数メガバイトのファイルをダウンロードする場合により一般的です)。サーバーへのリクエストの最中に誰かがあなたの Mac からネットワーク ケーブルを引き抜いたり、あなたが iPad を持って WiFi 範囲外に出たりすることを想像してみてください。

携帯電話を「機内」モードに変更して、何が起こるかを確認することをお勧めします。すべてのリクエストで同様のエラーが発生するため、アプリがこれに十分耐えることをテストする必要があります。また、「機内」モードをオフにすると、完全な機能に回復するはずです。

于 2015-09-29T15:04:16.700 に答える