我是IOS开发的新手。我一直在努力想象苹果文件。所以我读了这页:
这就是我所做的:
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]];
谁能告诉我在这里缺少什么?
答案 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;
并且您的班级必须符合NSURLConnectionDataDelegate
和NSURLConnectionDelegate
协议。
要使代码生效,您可能希望将savePath设置为这样的工作路径
NSString *savePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"testfile.txt"];
下载完成后,您可以根据需要对savePath
的文件执行任何操作。