2013-09-23 80 views
0

我没有看到这两个方法调用的时候,我开始我的NSURLConnectionNSURLConnection的委托方法调用仅在viewDidLoad中

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

这工作时,我在viewDidLoad创建NSURLConnection但是当我打电话从另一个函数,我没有看到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

是的,你是对的罗布 – ThananutK

回答

0

如果不出意外,不结合initWithRequest:delegate:调用start。这已经开始了请求,因此手动拨打start会尝试第二次启动,而且往往会产生相反的结果。

如果您针对该第三个参数调用initWithRequest:delegate:startImmediately:NO,则应该只能致电start

此外,如果在除主线程以外的队列中调用此连接,您也可能看不到NSURLConnectionDelegateNSURLConnectionDataDelegate方法被调用。但是,再次,你不应该在后台线程中更新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)使用另一个应用程序明确启动另一个运行循环的线程。但是,主要的一点是,您只使用startstartImmediately: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 
+0

现在我宣布NSURLConnection的*连接在全球范围内使用,并连接= [[NSURLConnection的页头] initWithRequest:要求委托:自];在viewdidload和[连接开始];准备好连接按钮。我做对了吗? – ThananutK

+0

@ThananutK号你可能不应该使用'start',除非你必须因为某种原因必须使用'startImmediately'呈现方式(例如你必须使用'scheduleInRunloop'方法,因为你是在后台队列中进行的)。否则,当你按下按钮时,执行'initWithRequest:delegate:',但根本不执行'start'。 – Rob

+0

这就是我想出来的---> connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [连接scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; < - – ThananutK

相关问题