我的應用從互聯網下載視頻並將其保存在iPhone中。瞭解更新UIprogressView的下載進度
我使用這個代碼
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];
我能做些什麼? 謝謝
好的,泰克!有用!但現在我有一個問題:使用我的舊方法,我可以使用「文檔文件夾」獲得視頻,這很容易...現在,我下載的視頻在哪裏?我怎麼知道路徑(也用於檢查,如果已經存在等...)?謝謝! – JAA
對不起,我可以使用[nameFile writeToFile:Path自動:否]寫入,'fileExists'檢查是否可用!謝謝! – JAA
你能否更新鏈接?它不可達。謝謝 – Vinh