2012-11-19 80 views
0

我有上傳和下載圖像和音頻文件的單一視圖。在這裏我在做什麼NSURLConnection出現問題

開始下載我用這:

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

,這觸發了delagate方法

connection:didReceiveResponse: 

connection:didReceiveData: 

connectionDidFinishLoading: 

,並在這些方法中,我計算文件的大小,顯示下載進度通過進度條並保存我的設備中的文件。

對於上傳我這樣做

[NSURLConnection connectionWithRequest:request delegate:self]; 

,並使用該connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:

此委託方法工作正常上傳文件,也講述了bytesWritten,totalBytesWritten,totalBytesExpectedToWrite但它也要求

connection:didReceiveResponse: 

connection:didReceiveData: 

connectionDidFinishLoading: 

及其有效,因爲都是委託方法。

但問題是我使用這三個來處理下載。

使用NSURLConection有關上傳和下載數據的正確方法是什麼?

參考Apple Doc

+0

我稍後會給你更詳細的答案。 – Peres

+0

好吧......謝謝。 –

回答

-1

您可以爲任務使用AFNetworking

AFNetworking是一個愉快的網絡庫iOSMac OS X。它建立在NSURLConnection,NSOperation和其他熟悉的Foundation technologies之上。它有一個modular architecture,它具有精心設計的功能豐富的API,使用起來很愉快。

找到SDK here

+0

這不是問什麼。 – Peres

+0

@JackyBoy,我只是引導他一個替代方式,這可能對他有幫助,這是不正確的? –

+0

這個人並不是要求另一種做X或Y的方法,而是要求解釋如何做X和Y.「AFNetworking」抽象了很多任務,在這種情況下,它並不能幫助回答問題。 – Peres

2

最好的辦法,我將實現專用類(例如DownloadingDelegate和UploadingDelegate)的代表和爲每個連接實例不同的代表。下載和上傳過程可以完全獨立處理。

或者,如果下載和上傳不是併發的,可以更簡單地使用布爾值作爲標誌並在代理函數中對其進行測試。

例如,假設您使用名爲downloading的布爾實例變量。

您將有下載:

downloading = true; 
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

而且上傳:

downloading = false; 
[NSURLConnection connectionWithRequest:request delegate:self]; 

然後在您的委託:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    if(downloading) 
    { 
     // handle the response when downloading ... 
    } 
    else 
    { 
     // when uploading 
    } 
} 
1

保存指針指向NSURLConnections和內代表確定使用哪一個。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    if(connection==downloaderConn) { 
     //handle download 
    } 
    else { 
     //handle upoad 
    } 
} 
+0

感謝您的回覆,這是我的想法,但這是一個正確的方法? –

+1

更簡單的情況下,它不需要專門的類它是有意義的。蘋果在那裏使用它廣泛的樣品。請記住,雖然這種方法對於2或3個類是很好的,但它會因N個連接對象而變得混亂 –