Невозможно загрузить файл в каталог приложения на iPhone

Я новичок в iPhone,

В настоящее время я разрабатываю приложение для iPhone и хотел бы реализовать возможность загрузки файла с URL-адреса. Я создал UIWebView, когда я нажимаю ссылку download в веб-просмотре, начинается загрузка, и я сохраняю этот файл в указанной папке в каталоге документов. но я не вижу загруженный файл.

Вот мой фрагмент кода,

//CAPTURE USER LINK-CLICK in UIwebView.

 - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

         // Create the request.
            NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:DUrl]
                                                      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 = [[NSMutableData data] retain];
            } else {
                NSLog(@"Inform the user that the connection failed."); 
            }
  return YES; 
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    DirPath=[self MyApplicationDocumentDirectory];
    [receivedData writeToFile:DirPath atomically:YES];

    UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
                                                         message:nil delegate:nil 
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
    [Alert show];
    [Alert release];


    // release the connection, and the data object
    [connection release];
    [receivedData release];
}

Любая помощь будет принята.

РЕДАКТИРОВАТЬ:

            BOOL success =[[NSFileManager defaultManager] fileExistsAtPath:MyDirPath];

            if (success) 
            {
                    UIAlertView* innerAlert = [[UIAlertView alloc] initWithTitle:@"Already downloaded."
                                                                         message:@"Do you want to Downlaod again ?" delegate:self 
                                                               cancelButtonTitle:nil
                                                               otherButtonTitles:@"Yes",@"No",nil];
                    [innerAlert show];
                    [innerAlert release];
            }

где написать это условие?


person Krunal    schedule 20.08.2012    source источник
comment
Возвращает ли метод writeToFile: атомарно ДА? На данный момент вы просто предполагаете, что это удастся. Вам, вероятно, следует проверить это специально. например if([receivedData writeToFile:DirPath atomically:YES]) { //alert success } else { //handle failure }   -  person Killian    schedule 20.08.2012
comment
да, он возвращается, я забыл добавить сюда.   -  person Krunal    schedule 20.08.2012
comment
Хорошо, вы также указываете имя файла при создании пути?   -  person Killian    schedule 20.08.2012


Ответы (1)


РЕДАКТИРОВАТЬ Перед записью (сохранением) загруженных данных убедитесь, что загруженный файл уже находится в каталоге doc:

 NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DirPath error:nil];
 BOOL fileExists = NO;
 for(NSString *fileName in dirContents)
 {
   NSString *filePath = [DirPath stringByAppendingPathComponent:fileName];
   NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    if([receivedData isEqualToData:fileData]) //your receivedData here
    {
        fileExists = YES;
    }
 }
 if(fileExists)
 {
   NSLog(@"File exists");
 }
 else
 {
   NSLog(@"File  does not exists");
  }

Вы забыли указать имя файла для записи данных:

DirPath=[self MyApplicationDocumentDirectory];
  NSString *filePath = [DirPath stringByAppendingPathComponent:@"yourFileName"];
[receivedData writeToFile:filePath atomically:YES];
person Paresh Navadiya    schedule 20.08.2012
comment
Работает, принц, ты всегда качаешься, ты много ответил на мой вопрос :) - person Krunal; 20.08.2012
comment
Как показать предупреждение о дублирующейся загрузке? означает, что если пользователь снова загрузит то же самое, я хочу отобразить предупреждение. см. мое РЕДАКТИРОВАНИЕ, где написать мое РЕДАКТИРОВАНИЕ? - person Krunal; 20.08.2012