2011-09-22 38 views
-1

我開始NSURLConnection,我需要保存從互聯網接收的數據。 在- (void)connectionDidFinishLoading:(NSURLConnection *)connection 我需要使用原始url作爲數據的名稱保存具有不同名稱的數據... 如何使用異步請求獲取此信息(url)在connectionDidFinishLoading? 如果這是不可能的,可以建議我採取一些其他方法來做我所問的? 感謝 保羅NSURLConnection。我需要幫助保存數據收到

回答

1

**答案只在iOS5之前有效。自iOS5以來,Apple推出了-originalRequest方法,可以避免爲了這個特殊目的進一步進行子類化。一般來說,Apple引入了NSURLConnection類,所以有很多改進,除非需要非平凡行爲,否則不再需要子類NSURLConnection ** 您可以通過添加一個名爲

NSURL originalURL
的額外屬性來繼承NSURLConnection,然後啓動它。當委託完成方法執行時,您可以檢索此屬性並完成剩餘的工作。 *

E.g. (我會告訴相關部門,不要複製粘貼請):

MyURLConnection.h

@interface MyURLConnection:NSURLConnection { @property (nonatomic,retain) NSURL *originalURL; } @end MyURLConnection.m

@implementation MyURLConnection @synthesize originalURL; In your calling class:

MyURLConnection *myConnection = [[MyURLConnection alloc] initWithRequest:myRequest delegate:myDelegate]; myConnection.originalURL = [request URL]; [myConnection start]; and finally in the delegate: - (void)connectionDidFinishLoading:(NSURLConnection *)connection { MyURLConnection *myConn = (MyURLConnection)connection; NSURL *myURL = myConn.originalUrl; // following code }
+0

哇!好的解決方案但是你能告訴我一個例子嗎?謝謝 –

+0

不錯!現在我明白了....我會嘗試! –

+0

它的作品...完美!非常感謝! –

1

* NOW ASIHTTPRequest庫不再受筆者因此它的好,開始採用一些其他的庫*

我會建議你使用ASIHTTP request支持。我一直在使用這個很長一段時間。下面的代碼示例用於異步下載url中的數據。

- (IBAction)grabURLInBackground:(id)sender 
{ 
    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request setDelegate:self]; 
    [request startAsynchronous]; 
} 

- (void)requestFinished:(ASIHTTPRequest *)request 
{ 
    // Use when fetching text data 
    NSString *responseString = [request responseString]; 

    // Use when fetching binary data 
    NSData *responseData = [request responseData]; 
} 

- (void)requestFailed:(ASIHTTPRequest *)request 
{ 
    NSError *error = [request error]; 
} 

UPDATE:

- (IBAction)grabURLInBackground:(id)sender 
{ 
    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request setCompletionBlock:^{ 
     // Use when fetching text data 
     NSString *responseString = [request responseString]; 

     // Use when fetching binary data 
     NSData *responseData = [request responseData]; 

     //here you have access to NSURL variable url. 
    }]; 
    [request setFailedBlock:^{ 
     NSError *error = [request error]; 
    }]; 
    [request startAsynchronous]; 
} 

嘗試在ASIHTTP使用GCD。在塊內部,您可以訪問變量url

+0

我聽說Asihttprequest ......反正它並沒有解決我的問題......我不能得到有關的URL信息! –

+0

更新了我的答案... –

+0

謝謝!我會托盤! :D和secondo答案,然後我決定這是最好的方法! –