将iOS 8文档保存到iCloud Drive

use*_*452 10 xcode ios icloud uidocument ios8

我想让我的应用程序将它创建的文档保存到iCloud Drive,但我很难跟上Apple写的内容.这是我到目前为止所做的,但我不确定从哪里开始.

UPDATE2

我的代码中有以下内容手动将文档保存到iCloud Drive:

- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.ubiquityURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
        if (self.ubiquityURL != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"iCloud available at: %@", self.ubiquityURL);
                completion(TRUE);
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"iCloud not available");
                completion(FALSE);
            });
        }
    });
}
if (buttonIndex == 4) {



     [self initializeiCloudAccessWithCompletion:^(BOOL available) {

        _iCloudAvailable = available;

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:selectedCountry];

        NSURL* url = [NSURL fileURLWithPath: pdfPath];


        [self.manager setUbiquitous:YES itemAtURL:url destinationURL:self.ubiquityURL error:nil];


    }];

       }
Run Code Online (Sandbox Code Playgroud)

我有为App ID和Xcode本身设置的权利.我点击按钮保存到iCloud Drive,没有错误弹出,应用程序没有崩溃,但在iCloud Drive中我的Mac上没有显示任何内容.在使用iOS 8.1.1时,该应用程序通过Test Flight在我的iPhone 6 Plus上运行.

如果我在模拟器上运行它(我知道由于iCloud Drive无法使用模拟器它将无法工作),我收到崩溃错误: 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[3]'

fgu*_*aar 35

好吧,你让我对这件事情感兴趣,结果我花了很多时间在这个问题上,但是现在我已经开始工作了,我希望它对你有所帮助!

在我的Mac上存档

要查看后台实际发生的情况,您可以查看~/Library/Mobile Documents/,因为这是文件最终将显示的文件夹.另一个非常酷的实用程序是brctl监视在iCloud中存储文件后Mac上发生的情况.brctl log --wait --shorten从终端窗口运行以启动日志.

在启用iCloud功能(选择了iCloud文档)后,首先要做的是为iCloud Drive支持(启用iCloud驱动器支持)提供信息.在再次运行应用程序之前,我还必须更新我的软件包版本; 我花了一些时间来弄明白这一点.将以下内容添加到您的info.plist:

<key>NSUbiquitousContainers</key>
<dict>
    <key>iCloud.YOUR_BUNDLE_IDENTIFIER</key>
    <dict>
        <key>NSUbiquitousContainerIsDocumentScopePublic</key>
        <true/>
        <key>NSUbiquitousContainerSupportedFolderLevels</key>
        <string>Any</string>
        <key>NSUbiquitousContainerName</key>
        <string>iCloudDriveDemo</string>
    </dict>
</dict>
Run Code Online (Sandbox Code Playgroud)

接下来,代码:

- (IBAction)btnStoreTapped:(id)sender {
    // Let's get the root directory for storing the file on iCloud Drive
    [self rootDirectoryForICloud:^(NSURL *ubiquityURL) {
        NSLog(@"1. ubiquityURL = %@", ubiquityURL);
        if (ubiquityURL) {

            // We also need the 'local' URL to the file we want to store
            NSURL *localURL = [self localPathForResource:@"demo" ofType:@"pdf"];
            NSLog(@"2. localURL = %@", localURL);

            // Now, append the local filename to the ubiquityURL
            ubiquityURL = [ubiquityURL URLByAppendingPathComponent:localURL.lastPathComponent];
            NSLog(@"3. ubiquityURL = %@", ubiquityURL);

            // 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];
}
Run Code Online (Sandbox Code Playgroud)

我有一个名为demo.pdf存储在Documents文件夹中的文件,我将"上传".

我将重点介绍一些部分:

URLForUbiquityContainerIdentifier: 提供存储文件的根目录,如果你想在Mac上的de iCloud Drive中显示它们,那么你需要将它们存储在Documents文件夹中,所以在这里我们将该文件夹添加到root:

NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:@"Documents"];
Run Code Online (Sandbox Code Playgroud)

您还需要将文件名添加到URL,此处我从localURL(即demo.pdf)复制文件名:

// Now, append the local filename to the ubiquityURL
ubiquityURL = [ubiquityURL URLByAppendingPathComponent:localURL.lastPathComponent];
Run Code Online (Sandbox Code Playgroud)

这基本上就是......

作为奖励,请查看如何提供NSError指针以获取潜在的错误信息:

// And finish up the 'store' action
NSError *error;
if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:localURL destinationURL:ubiquityURL error:&error]) {
    NSLog(@"Error occurred: %@", error);
}
Run Code Online (Sandbox Code Playgroud)

  • 编辑:不得不增加`CFBundleVersion`.郁闷了!http://stackoverflow.com/a/25328864/1148702 (3认同)