Iphone NSURL连接。我需要帮助保存收到的数据
我正在启动一个Iphone NSURL连接。我需要帮助保存收到的数据,iphone,objective-c,nsurlconnection,nsoperationqueue,Iphone,Objective C,Nsurlconnection,Nsoperationqueue,我正在启动一个NSURLConnection,我需要保存从internet接收的数据。 在-(void)connectionIDFinishLoading:(NSURLConnection*)连接中 我需要用不同的名称保存数据,使用原始url作为数据的名称。。。 如何使用异步请求在connectiondFinishLoading中获取此信息(url)? 如果不可能的话,你能给我建议一些其他的方法来完成我的要求吗? 谢谢 Paolo*现在作者不再支持ASIHTTPRequest库,因此最好开始采用
NSURLConnection
,我需要保存从internet接收的数据。
在-(void)connectionIDFinishLoading:(NSURLConnection*)连接中
我需要用不同的名称保存数据,使用原始url作为数据的名称。。。
如何使用异步请求在connectiondFinishLoading
中获取此信息(url)?
如果不可能的话,你能给我建议一些其他的方法来完成我的要求吗?
谢谢
Paolo*现在作者不再支持ASIHTTPRequest库,因此最好开始采用其他库*
我建议你使用。我已经用这个很久了。下面的代码示例用于从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];
}
更新:
- (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];
}
尝试在HTTP中使用GCD。在块内部,您可以访问变量
url
**答案仅在iOS5之前有效。自iOS5以来,Apple引入了-originalRequest方法,该方法允许避免为了这个特殊目的而进行任何进一步的子类化。一般来说,Apple在NSURLConnection类中引入了如此多的改进,以至于它不再需要子类NSURLConnection,除非需要非平凡的行为**
您可以通过添加一个名为“我听说过Asihttprequest”的额外属性来对NSURLConnection进行子类化。。。无论如何,这并不能解决我的问题。。。我无法获取有关url的信息!谢谢我要用托盘装它D和第二个答案,然后我决定这是最好的方法!顺便说一句,您不需要使用ASIHTTP库来执行此操作。您可以使用async GCD iOS块来实现同样的功能,使用
NSURLConnection
itselfNSURLConnection已经有了一个实例方法-originalRequest,因此完全不需要子类化来添加originalURL。myConnection.originalRequest.URL是一种方法。是的,这种方法是在ios5中引入的,答案可能是在从ios4到ios5的过渡阶段。我已在答覆中作出澄清。
NSURL originalURL
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
}