当我开始NSURLConnection
:
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
当我在NSURLConnection
中创建viewDidLoad
时,这很有用,但是当我从另一个函数调用它时,我没有看到canAuthenticateAgainstProtectionSpace
被调用。这就是我创建NSURLConnection
:
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:video_link1]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
答案 0 :(得分:0)
如果不出意外,请勿与start
一起致电initWithRequest:delegate:
。这已经启动了请求,因此对start
的手动调用会尝试再次启动它,通常会产生适得其反的结果。
如果您使用start
为第三个参数调用initWithRequest:delegate:startImmediately:
,则只能致电NO
。
此外,如果在主线程以外的队列中调用此连接,您也可能看不到调用NSURLConnectionDelegate
和NSURLConnectionDataDelegate
方法。但是,再说一次,你不应该在后台线程中更新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
。
如果已经从主队列执行此操作,则只需:
[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