我的应用程序从 Internet 下载视频并将其保存在 iPhone 中。
我正在使用此代码
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:@"GET"];
NSError *error;
NSURLResponse *response;
NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *videosFolderPath = [documentFolderPath stringByAppendingPathComponent:@"videos"];
//Check if the videos folder already exists, if not, create it!!!
BOOL isDir;
if (([fileManager fileExistsAtPath:videosFolderPath isDirectory:&isDir] && isDir) == FALSE) {
[[NSFileManager defaultManager] createDirectoryAtPath:videosFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *filePath = [videosFolderPath stringByAppendingPathComponent:@"name.mp4"];
if ([fileManager fileExistsAtPath:filePath ] == YES) {
NSLog (@"File exists");
}
else {
NSLog (@"File not found");
NSData *urlData;
NSString *downloadPath = @"http://www.mywebsite.com/name.mp4";
[request setURL:[NSURL URLWithString:downloadPath]];
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
BOOL written = [urlData writeToFile:filePath atomically:NO];
if (written)
NSLog(@"Saved to file: %@", filePath);
else {NSLog(@"problem");}
}
一切正常,但我想添加一个进度视图,以指示下载状态。
问题(我认为但我不确定)是我的 NSURLConnection 本身并没有作为委托,所以像这样的方法
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
或者
-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{
永远不会被调用。
我试着用
urlData = [[NSURLConnection alloc] initWithRequest:request delegate:self];
但是当我尝试写入文件时应用程序崩溃
[urlData writeToFile:filePath atomically:NO];
我能做些什么?谢谢