2013-09-23 81 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

相關問題