iOS скачать файл с iCloud Drive

В моем приложении для iOS я храню какой-то файл в папке iCloud Drive для резервного копирования. Теперь я хочу получить этот файл, но я не знаю, как правильно это сделать. Я имею в виду, есть ли какой-то конкретный метод для iCloud Drive, или я могу просто получить его по URL-адресу.

Я сохраняю файл в iCLoud следующим образом (https://stackoverflow.com/a/27358392/3065901):

- (void) storeToIcloud
{
   // Let's get the root directory for storing the file on iCloud Drive
   [self rootDirectoryForICloud:^(NSURL *ubiquityURL) {

        if (ubiquityURL) {

             // We also need the 'local' URL to the file we want to store

             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
             NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
             NSString *filePath = [documentsPath stringByAppendingPathComponent:@"myFile.xml"]; //Add the file name

             NSURL *localURL = [NSURL fileURLWithPath:filePath];

             // Now, append the local filename to the ubiquityURL
             ubiquityURL = [ubiquityURL URLByAppendingPathComponent:localURL.lastPathComponent];

             // And finish up the 'store' action
             NSError *error;
             if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:localURL destinationURL:ubiquityURL error:&error]) {
                NSLog(@"Error occurred: %@", error);
             }
        }
        else {
            NSLog(@"Could not retrieve a ubiquityURL");
        }
   }];
}

- (void)rootDirectoryForICloud:(void (^)(NSURL *))completionHandler {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:@"Documents"];

        if (rootDirectory) {
             if (![[NSFileManager defaultManager] fileExistsAtPath:rootDirectory.path isDirectory:nil]) {
                  NSLog(@"Create directory");
                  [[NSFileManager defaultManager] createDirectoryAtURL:rootDirectory withIntermediateDirectories:YES attributes:nil error:nil];
             }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
             completionHandler(rootDirectory);
        });
    });
}

- (NSURL *)localPathForResource:(NSString *)resource ofType:(NSString *)type {
      NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
      NSString *resourcePath = [[documentsDirectory stringByAppendingPathComponent:resource] stringByAppendingPathExtension:type];
      return [NSURL fileURLWithPath:resourcePath];
}

Как я могу загрузить файл с диска iCloud?

Заранее спасибо.


person user3065901    schedule 15.06.2015    source источник


Ответы (1)


Вы должны использовать NSMetadataQuery, чтобы получить элемент из icloud, затем, когда вы подключите закладку к файлу, используйте NSFileCoordinate для его чтения, тот же метод можно использовать для чтения из из облака или из песочницы вашего приложения... Все подробно описано здесь: Building Приложения на основе документов, и есть даже пример кода, которому вы можете следовать. Надеюсь это поможет!

person gbdavid    schedule 24.06.2015
comment
Спасибо за ответ. Все, что я вижу, написано в стремительном. Знаете ли вы какую-либо документацию или учебник по Objective C? - person user3065901; 29.06.2015
comment
Обычно в документации Apple (и где-либо еще) очень мало информации о том, что вам нужно для ios и osx... Лучше всего начать с NSMetadataQuery здесь (есть информация как для swift, так и для target-c): developer.apple.com/library/mac/documentation/Cocoa /Reference/ и руководство по поиску файловых метаданных по программированию: developer.apple.com/library/mac/documentation/Carbon/Conceptual/ эта последняя статья написана только на Objective-C - person gbdavid; 30.06.2015