0

当我开始我的时,我没有看到这两种方法被调用NSURLConnection

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

这在我创建时有效NSURLConnectionviewDidLoad但是当我从另一个函数调用它时,我没有看到canAuthenticateAgainstProtectionSpace被调用。这就是我创建我的方式NSURLConnection

[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:video_link1]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
4

1 回答 1

0

如果不出意外,请不要start与 一起调用initWithRequest:delegate:。这已经启动了请求,因此手动调用start尝试再次启动它,通常会适得其反。

start仅当您为第三个参数调用initWithRequest:delegate:startImmediately:with时才应调用。NO

此外,如果在主线程以外的队列中调用此连接,您也可能看不到NSURLConnectionDelegateandNSURLConnectionDataDelegate方法被调用。但是,话又说回来,您也不应该在后台线程中更新 UI,所以我假设您没有尝试在某个后台线程中执行此操作。

因此,如果从后台线程执行此操作,您可能会这样做:

// dispatch this because UI updates always take place on the main queue

dispatch_async(dispatch_get_main_queue(), ^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
});

// now create and start the connection (making sure to start the connection on a queue with a run loop)

NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:video_link1]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; 
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[connection start];

我在[NSRunLoop mainRunLoop]上面使用。一些实现(如 AFNetworking)使用另一个线程,应用程序在该线程上显式启动了另一个运行循环。但是,要点是您只能start与 结合使用startImmediately:NO,并且仅startImmediately:NO在当前线程的运行循环以外的其他东西上使用 if 。

如果已经从主队列执行此操作,则只需:

[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:video_link1]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
// [connection start]; // don't use this unless using startImmediately:NO for above line
于 2013-09-23T04:53:26.307 回答