gpt4 book ai didi

objective-c - NSURLConnection 委托(delegate)方法未被调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:36 26 4
gpt4 key购买 nike

我正在尝试使用 NSURLConnection 的委托(delegate)方法。当前未调用以下方法:

- (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

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

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

我取回了我需要的数据,但是使用异步我似乎必须使用委托(delegate)方法来取回数据。我尝试使用 @interface myClass : NSObject<NSURLConnectionDelegate> 添加委托(delegate)

我按如下方式调用我的方法:

-(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);
}

我尝试了以下操作:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

最佳答案

我继续搜索相关问题,找到this answer most helpful .它引导我使用以下方法。首先,我在我的接口(interface)中声明了一个名为 finished 的 BOOL 属性,并在我的实现中添加了以下方法,这导致我的委托(delegate)方法被调用。

while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

关于objective-c - NSURLConnection 委托(delegate)方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126595/

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