我正在尝试使用 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
我目前正在使用同步调用,但异步似乎更好,因为在我完成代码库后,我将把它实现到 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);
}
我尝试了以下方法:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];