ios - NSURLConnection 的 SynchronousRequest 的 DidReceiveAuthenticationChallenge

标签 ios objective-c nsurlconnection

我正在使用 NSURLConnection 的 sendSynchronousRequest 与服务器通信。我想处理可以使用连接委托(delegate)实现的身份验证,但不会为同步请求调用委托(delegate)。

NSData *data = [NSURLConnection sendSynchronousRequest:UrlRequest returningResponse:&response error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{

            if(!error)
            {

             // Do something
             }
            else
             {
              // Handle error
             }

         });

但是我想到了使用

异步发送所有请求
[NSURLConnection connectionWithRequest:menuRequest delegate:self];

但是我在同一个类中有多个连接,每个连接的成功和错误用于执行不同的任务。如果我使用异步请求错误并且成功被代表听到,对于该类中的所有请求都是相同的,我不能找出哪个请求失败了,哪个请求成功了。我有两个问题

  1. 如果有办法实现同步请求的https。
  2. 如何在异步请求的同一个类的多个连接中找出哪个连接失败或成功。

最佳答案

您可以通过不同的方式实现这一目标。

  1. 您可以将凭据放入 url 中,例如 https://username:password@domain.tld/api/user.json

  2. 您可以在同步连接调用之前将您的凭据添加到 NSURLCredentialStorage

  3. 您可以使用下面的代码来实现。

    - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse *__strong*)response error:(NSError *__strong*)error
    {
       _finishedLoading=NO;
       _receivedData=[NSMutableData new];
       _error=error;
       _response=response;
    
       NSURLConnection*con=[NSURLConnection initWithRequest:request
                       delegate:self
               startImmediately:NO];
       [con start];
    
       return _receivedData;
    }
    
    
    - (BOOL)connection:(NSURLConnection *)connection  canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
       return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
    {
        //handle the challenge
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
       *_response=response;
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
       [_receivedData appendData:data];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
       *_error=error;
    
    }
    
     - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    
    }
    

关于ios - NSURLConnection 的 SynchronousRequest 的 DidReceiveAuthenticationChallenge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28935667/

相关文章:

ios - 从某些 URL 添加一些图像到 ScrollView

ios - 在 iOS 中访问 RESTful Web 服务

ios - 具有向量的 3D 点的正射投影

ios - 初始化核心数据 ManagedObjectContext

ios - 如何转义 NSPredicate 格式字符串中的尾部反斜杠

iphone - 从 NSMutableData 中提取数据

macos - Mac Cocoa 应用程序中的 NSURLConnection 有连接限制吗?

xcode - 将 mimetype 转换为文件扩展名

c++ - Objective-C++ 对 UI 的绝对混淆;最佳实践

objective-c - 需要有关使用 GCD 将 block 添加到队列(objective-c)的建议