gpt4 book ai didi

具有单独线程的 NSURLConnection 委托(delegate)

转载 作者:行者123 更新时间:2023-12-01 13:36:05 25 4
gpt4 key购买 nike

我正在使用 MBProgressHUD作为指标。你知道它在执行其他方法时使用了一个单独的线程。当我想使用 NSURLConnection 时,它的委托(delegate)没有正确调用。

这是我的(@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 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608214/

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