NSURLConnection委托方法未被调用

err*_*ran 2 ssl https objective-c ios

我正在尝试使用NSURLConnection的委托方法.目前尚未调用以下方法:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
//I also want to be able to use self-signed https urls

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
//I also want to be able to use self-signed https urls
Run Code Online (Sandbox Code Playgroud)

我目前正在使用同步调用,但异步似乎更好,因为在我完成代码库后,我将把它实现到iPhone应用程序中,我不能让我的ui冻结.

用以下方法responseData = [NSMutableData dataWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]];

我得到了我需要的数据但是使用异步我似乎必须使用委托方法来获取数据.我尝试使用添加委托@interface myClass : NSObject<NSURLConnectionDelegate>

我正在调用我的方法如下:

-(void)grabData{
    NSArray* array = [NSArray arrayWithObjects:@"auth.login",@"user",@"pass", nil];
    NSData* packed_array = [array messagePack];

    NSURL* url = [NSURL URLWithString:@"https://192.168.1.115:3790/"];
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc]initWithURL:url]retain];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"RPC Server" forHTTPHeaderField:@"Host"];
    [request setValue:@"binary/message-pack" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d",[packed_array length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:packed_array];

    //NSHTTPURLResponse *response = nil;
    NSError *error = nil;

    NSLog(@"connecting");
    NSURLConnection* connection = [[[NSURLConnection alloc]initWithRequest:request delegate:self]retain];
    if (connection) {
        NSLog(@"connection exists");
        self.responseData = [[NSMutableData data]retain];
    }
    else {
        NSLog(@"Connection doesn't exist?");
    }
    NSLog(@"response data: %@",[responseData messagePackParse]);
    NSLog(@"error: %@",error);
}
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Run Code Online (Sandbox Code Playgroud)

err*_*ran 9

我继续搜索相关问题,发现这个答案最有帮助.它引导我使用以下方法.首先,我在我的界面中声明了一个名为finished的BOOL属性,并在我的实现中添加了以下方法,这导致我的委托方法被调用.

while(!finished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
Run Code Online (Sandbox Code Playgroud)