2015-08-15 2 views
2

В течение длительного времени я получаю странную ошибку, но только при работе на устройстве. В симуляторе все в порядке. То, что я делаю, - это перемещать образцы файлов из каталога приложений в каталог Documents на устройстве. я пытался все эти методы NSFileManager:iOS9 NSFileManager запрашивает разрешение на сохранение файлов в каталоге Documents

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error 
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error 
- (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error 

И каждый бросает ошибки, как следующее:

2015-08-15 23:14:15.152 app[1010:339938] Error: Error Domain=NSCocoaErrorDomain Code=513 "“file.txt” couldn’t be linked because you don’t have permission to access “Documents”." UserInfo={NSSourceFilePathErrorKey=/var/mobile/Containers/Bundle/Application/verylongid/fastdict.app/Dictionaries/file.txt, NSUserStringVariant=( Link ), NSDestinationFilePath=/var/mobile/Containers/Data/Application/verylongid/Documents/file.txt, NSFilePath=/var/mobile/Containers/Bundle/Application/verylongid/fastdict.app/Dictionaries/file.txt, NSUnderlyingError=0x13666d5a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}} in -[AppDelegate fillDirectoryWithSamplesIfEmpty]

Как я могу решить эту проблему?

Обновление: solution найденный здесь действительно работает! Удачи!

+0

Возможный дубликат [iPhone - копирование файла из ресурсов в документы дает ошибку] ​​(http://stackoverflow.com/questions/1132005/iphone-copying-a-file- from-resources-to-documents-give-an-error) –

ответ

5

Вы не можете переместить файл пакета в каталог документов, так как у вас нет разрешения на выполнение. Попробуйте copyItemAtPath Также убедитесь, что вы получаете каталог документа правильно

NSString *fileName = @"LICENSE.txt"; 
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName]; 
    NSData *mainBundleFile = [NSData dataWithContentsOfFile:sourcePath]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectoryPath = [paths objectAtIndex:0]; 

    [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectoryPath,fileName] 
              contents:mainBundleFile 
              attributes:nil]; 
    NSString* content = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", documentsDirectoryPath,fileName] encoding:NSUTF8StringEncoding 
                error:NULL]; 
    self.label.text = content; 
    NSLog(@"file content = %@",content); 

Приведенный выше код работает отлично в iPhone5 устройства iOS9.0. Все еще проблема существует, вставьте фрагмент кода

+0

Я написал, что я уже пробовал это ... –

+1

вставить фрагмент кода –

+0

Его единственная строка кода. Точно так же, как вы писали. Вы можете увидеть описание ошибки в моем сообщении вопроса. –

Смежные вопросы