带有独立线程的NSURLConnection委托
问题描述:
我使用MBProgressHUD作为指标。而且你知道它在执行其他方法时使用了单独的线程。当我想使用NSURLConnection
时,其代表团没有正确呼叫。带有独立线程的NSURLConnection委托
在这里我有什么(@implementation文件):
- (void)viewDidLoad {
[super viewDidLoad];
[self hudShowWithLabel];
}
-(void)hudShowWithLabel {
HUD = [[MBProgressHUD alloc] initWithView: self.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Loading";
[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}
-(void)myTask {
responseData = [NSMutableData data];
NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));
NSString *requestURL = @"http://someurl";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate: self];
}
在运行时,我可以看到,myTask
不MainThread
。我怎么能解决这个问题?
答
您可以在主线程揭开序幕NSURLConnection的:
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
而且选择的开端是:
- (void)start
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
self.connection =[[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
[self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self.connection start];
}
还有上github一个例子。
答
NSURLConnection在另一个应该有运行循环的线程中运行。您可以尝试在您的线程的主要方法中为此运行循环添加代码:
while (!finished)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}