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答案,然后我决定这是最好的方法! –