UIDocumentPickerViewController скопированные файлы исчезают при загрузке для тестирования iPad - PullRequest
0 голосов
/ 02 мая 2020

Я использую UIDocumentPickerViewController, чтобы позволить пользователю выбирать файлы, которые будут «прикреплены» и доступны в приложении. Концепция позволяет пользователю отправлять детали по электронной почте с выбранными вложенными файлами. Когда каждый файл прикреплен, я копирую файл из папки «Входящие» tmp (куда fileManager помещает импортированный файл) в каталог, который я создаю в каталоге документов приложения под названием «fileAttachments». Я перечисляю файлы в UITableView, и пользователь может выбрать каждую запись и просмотреть содержимое в представлении QLPreviewController, используя путь, сохраненный в объекте файла fileOJ.filePath. Все работает хорошо, до перезагрузки проекта до моего тестового iPad, затем все файлы исчезают. Мой список файлов все еще в порядке, но нет файла в пути. Буду очень признателен за любую помощь в том, что происходит.

    - (IBAction)selectFilesAction:(UIBarButtonItem *)sender {

        NSArray *UTIs = [NSArray arrayWithObjects:@"public.data", nil];
        [self openFilePicker:UTIs];

    }

    - (void)openFilePicker:(NSArray *)UTIs {
            UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:UTIs inMode:UIDocumentPickerModeImport];
            documentPicker.delegate = self;
            documentPicker.allowsMultipleSelection = FALSE;
            documentPicker.popoverPresentationController.barButtonItem = self.selectFilesButton;
            [self presentViewController:documentPicker animated:TRUE completion:nil];
    }

    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
        NSLog(@"picked URLs %@", urls);
        // selecting multiple documents is cool, but requires iOS 11

        for (NSURL *documentURL in urls) {
            //get file details
            NSDictionary *attr = [documentURL resourceValuesForKeys:@[NSURLFileSizeKey,NSURLCreationDateKey] error:nil];
            NSLog(@"object: %@", attr);

            NSNumber *fileSize = [attr valueForKey:NSURLFileSizeKey];
            NSDate *dateFileCreated = [attr valueForKey:NSURLCreationDateKey];

            NSDateFormatter *storageDateFormat = [[NSDateFormatter alloc] init];
            [storageDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *createdDateString = [storageDateFormat stringFromDate:dateFileCreated];

            MMfile *fileObj = [[MMfile alloc]init];
            fileObj.fileName = documentURL.lastPathComponent;
            fileObj.meetingID = _meetingID;
            fileObj.fileSize = fileSize;
            fileObj.fileCreateDate = createdDateString;

            //move file to new directory
            fileObj.filePath = [self movefile:documentURL.lastPathComponent sourceFilePath:documentURL.path directory:@"fileAttachments"];

            //save file details
            [self.meetingModel saveFile:fileObj];

            //refresh array and reload table
            self.fileArray = [self.meetingModel getFiles:self.meetingID];
            [self.tableView reloadData];
        }
    }


    - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
        NSLog(@"cancelled");
    }

    -(NSString *)movefile:(NSString *)filename sourceFilePath:(NSString *)sourcePath directory:(NSString *)directoryName{
        // Move file from tmp Inbox to the destination directory
        BOOL isDir;
        NSError *error;
        NSFileManager *fileManager= [NSFileManager defaultManager];

        //get directory path
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString* directoryPath;

        if (paths>0) {
            NSString *documentsDirectory = [paths objectAtIndex:0];
            directoryPath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,directoryName];
        }

        if(![fileManager fileExistsAtPath:directoryPath isDirectory:&isDir])
            if(![fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:NO attributes:nil error:NULL])
                NSLog(@"Error: Create folder failed %@", directoryPath);

        NSString *destinationPath = [NSString stringWithFormat:@"%@/%@",directoryPath,filename];;
        BOOL success = [fileManager moveItemAtPath:sourcePath toPath:destinationPath error:&error];
        if (success) {
            NSLog(@"moved file");

        }else{
            NSLog(@"error %@",error.description);
        }
        return destinationPath;
    }

1 Ответ

0 голосов
/ 03 мая 2020

Нашел проблему. Когда проект перестраивается и загружается на iPad, AppID изменяется, и, поскольку путь к документам включает в себя AppID, путь к документам изменяется. Ключ не для сохранения пути к файлу, а только для имени файла и перестройки пути каждого экземпляра. После того, как я нашел проблему, я теперь вижу другие подобные сообщения, которые я не нашел ранее. Также см. Изменение пути к каталогу документов при перестройке приложения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...