2012-04-19 3 views

ответ

9

Чтобы удалить документ из ICloud, сначала вы должны получить имя файла, который вы хотите удалить. а затем вы можете удалить его с помощью NSFileManager.

NSString *saveFileName = @"Report.pdf"; 
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]; 
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:saveFileName]; 
NSFileManager *filemgr = [NSFileManager defaultManager]; 
[filemgr removeItemAtURL:ubiquitousPackage error:nil]; 

Это способ, которым я удалял документ, Check it out. Это отлично подходит для меня. Благодаря

+3

В соответствии с документами вы должны удалить асинхронный файл в фоновом режиме. http://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/DocumentBasedAppPGiOS/ManageDocumentLifeCycle/ManageDocumentLifeCycle. html # // apple_ref/doc/uid/TP40011149-CH4-SW4 – Jonny

+0

Где это работает, он не использует реализацию 'UIDocument'' NSF Ответ ileCoordinator''Adrian Sarli лучше. – Joseph

+1

Для справки обратите внимание, что 'removeItemAtURL:' не удалит документ, если он еще не был загружен с iCloud на устройство. – Mark

0

См Яблоко документации "Управление Life-Cyle Документа" в разделе «Удаление документа. "

13

Скопировано из "Deleting a Document" секции Document-Based App Programming Guide for iOS

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { 
    NSFileCoordinator* fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; 
    [fileCoordinator coordinateWritingItemAtURL:fileURL options:NSFileCoordinatorWritingForDeleting 
     error:nil byAccessor:^(NSURL* writingURL) { 
     NSFileManager* fileManager = [[NSFileManager alloc] init]; 
     [fileManager removeItemAtURL:writingURL error:nil]; 
    }]; 
}); 

NB:." Когда вы удаляете документ из хранилища, ваш код должен приближать то, что UIDocument делает для операций чтения и записи. Он должен выполнить удаление асинхронно на фоне очереди, и он должен использовать координацию файла.»

+1

Если вы используете 'UIDocument', вам не нужно реализовывать собственный NSFileCoordinator, он уже запечен в' UIDocument'. Использование метода - это дорогостоящие результаты в нескольких экземплярах 'NSFileCoordinator'. См. Https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileCoordinators/FileCoordinators.html – Joseph

+0

@Joseph. Мне интересно, из вашего ответа выше, почему я также не могу удалить объект, который является объектом UIDocument, из iCloud или приложение зависает при попытке сделать это? Мой родственный вопрос [здесь] (http://stackoverflow.com/questions/43821141/app-hangs-deleting-icloud-document-when-following-guideline-using-nsfilecoordi) – yohannes

1

СВИФТ 3 приходят от ответа @AlexChaffee«s

func deleteZipFile(with filePath: String) { 
    DispatchQueue.global(qos: .default).async { 
     let fileCoordinator = NSFileCoordinator(filePresenter: nil) 
     fileCoordinator.coordinate(writingItemAt: URL(fileURLWithPath: filePath), options: NSFileCoordinator.WritingOptions.forDeleting, error: nil) { 
      writingURL in 
      do { 
       try FileManager.default.removeItem(at: writingURL) 
      } catch { 
       DLog("error: \(error.localizedDescription)") 
      } 
     } 
    } 
} 
Смежные вопросы