无法使用NSURLRequest下载文件

时间:2012-12-18 05:47:08

标签: ios nsurlconnection nsurlrequest nsmutabledata

我是IOS开发的新手。我一直在努力想象苹果文件。所以我读了这页:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

这就是我所做的:

NSMutableData *testFileType;
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    testFileType = [[NSMutableData data] retain];
    NSLog(@"the connection is successful");
} else {
    // Inform the user that the connection failed.
    NSLog(@"the connection is unsuccessful");
}

[testFileType setLength:0];
[testFileType appendData:[NSMutableData data]];

谁能告诉我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

仅创建NSURLConnection是不够的。您还需要实现didReceiveResponse和didFinishLoading委托方法。如果没有这些,连接会下载文件,但你永远不会看到它。

NSURLConnection在收到标头时为每次重定向发送didReceiveResponse。然后它发送带有文件的一些字节的didReceiveData。那些你需要附加到你的可变数据。最后你会得到一个didFinishLoading,你知道你已经获得了所有数据。如果出现错误,您将获得didFailWithError。

查看NSURLConnectionDelegate协议文档:https://developer.apple.com/library/mac/ipad/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html

答案 1 :(得分:0)

您应该实现以下委托方法:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error: %d %@", [error code], [error localizedDescription]);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    responseData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [responseData writeToFile:savePath atomically:YES]; 
}

这里的responseData和savePath是用:

声明的实例变量
NSMutableData *responseData;
NSString *savePath;

并且您的班级必须符合NSURLConnectionDataDelegateNSURLConnectionDelegate协议。

要使代码生效,您可能希望将savePath设置为这样的工作路径

NSString *savePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"testfile.txt"];

下载完成后,您可以根据需要对savePath的文件执行任何操作。