我正在使用MBProgressHUD作为指标。并且你知道它在执行其他方法时使用单独的线程。当我想使用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
。我怎么能解决这个问题?
答案 0 :(得分:2)
您可以在主线程中启动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还有一个例子。
答案 1 :(得分:0)
NSURLConnection在另一个应该有运行循环的线程中运行。您可以尝试在线程的主方法中添加运行循环的代码:
while (!finished)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}