gpt4 book ai didi

ios - NSURLConnection 的 SynchronousRequest 的 DidReceiveAuthenticationChallenge

转载 作者:行者123 更新时间:2023-11-29 02:14:18 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com