我必须执行SSL固定,因此需要验证服务器端SSL证书。 所以我必须使用NSURL代表。我有一个帮助器类,我在其中创建了一个返回登录响应的方法:
- (NSData *)sendSynchronousRequest:(NSString *)strNewLoginRequest
returningResponse:(NSURLResponse **)response
error:(NSError **)error {
NSMutableURLRequest *finalRequest = nil;
NSURL *url= [NSURL URLWithString:const_url];
finalRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
NSData *requestData = [NSData dataWithBytes:[strLoginRequest UTF8String] length:[strLoginRequest length]];
self.connection = [[NSURLConnection alloc] initWithRequest:finalRequest delegate:self startImmediately:NO];
NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
[self.connection unscheduleFromRunLoop:currentRunLoop forMode:NSDefaultRunLoopMode];
[self.connection scheduleInRunLoop:currentRunLoop forMode:@"connectionRunLoopMode"];
[self.connection start];
while ([currentRunLoop runMode:@"connectionRunLoopMode" beforeDate:[NSDate distantFuture]]);
return self.mutableResponse;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
self.mutableResponse = [[NSMutableData alloc]init];
[self.mutableResponse appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
if (loadingView)
{
[loadingView removeView];
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Failure" message:@"Network Failure" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
});
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (loadingView)
{
[loadingView removeView];
}
self.resultString = [[NSString alloc] initWithData:self.mutableResponse encoding:NSASCIIStringEncoding];
}
我从另一个名为ViewController的类中使用代码
调用此方法-(void)doLogin
{
self.service = [[SyncCommunicationService alloc]init];
NSData *data = [self.service sendSynchronousRequest:strNewLoginRequest
returningResponse:&response
error:nil];
}
我试过在后台和主线程上调用这个方法,但仍然没有调用委托方法,我已经尝试了很多来自同一网站的其他答案,但仍然无法解决这个问题所以请任何人都可以我知道我做错了什么。
答案 0 :(得分:1)
我想知道为什么有人会使用异步请求同步执行任务?更不用提这种奇怪的方式来等待while语句而不是dispatch_semaphore或类似的东西。
然而,为什么你甚至打扰委托?只需使用类方法sendSynchronousRequest:returningResponse:error:。我认为,在你的情况下就足够了