将 iOS 8 文档保存到 iCloud Drive

2024-02-16

我想让我的应用程序将其创建的文档保存到 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];


    }];

       }

我已经为 App ID 和 Xcode 本身设置了权利。我单击按钮保存到 iCloud Drive,没有弹出任何错误,应用程序也没有崩溃,但我的 Mac 上的 iCloud Drive 上没有显示任何内容。该应用程序在使用 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]'


好吧,你让我自己对这个问题感兴趣,因此我在这个问题上花了很多时间,但现在我已经成功了,我希望它也对你有帮助!

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

启用 iCloud 功能(选择 iCloud 文档)后要做的第一件事是提供 iCloud Drive 支持信息(启用 iCloud 驱动器支持 https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/EnablingiCloudDriveSupport/EnablingiCloudDriveSupport.html#//apple_ref/doc/uid/TP40014451-CH4-SW1). 在再次运行该应用程序之前,我还必须更改捆绑版本;我花了一些时间才弄清楚这一点。将以下内容添加到您的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>

接下来,代码:

- (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];
}

我有一个名为demo.pdf存储在“文档”文件夹中,我将“上传”该文件夹。

我将重点介绍一些部分:

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

NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:@"Documents"];

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

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

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

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

// And finish up the 'store' action
NSError *error;
if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:localURL destinationURL:ubiquityURL error:&error]) {
    NSLog(@"Error occurred: %@", error);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 iOS 8 文档保存到 iCloud Drive 的相关文章

  • Xcode 中定义的宏 CURRENT_PROJECT_VERSION 在哪里?

    这个帖子如何在 xcode 8 中设置 CURRENT PROJECT VERSION https stackoverflow com questions 39673280 how to set current project versio
  • CF 类型的带有 __attribute__((NSObject)) 的强 @property 不会保留

    更新 自 Xcode 4 6 起 此问题已得到修复 现在 这项技术再次按预期发挥作用 但是 在代码中使用之前 请务必阅读 Rob Napier 出色答案顶部的注释 原帖 ARC Xcode 4 3 1 iOS 5 1 我有一个 CF 类型
  • 将 Objective-C 框架 (CocoaPod) 导入 Swift?

    我正在尝试导入libjingle peerconnection框架到我的 Xcode 项目中 但由于某种原因 我无法使用以下命令导入 Objective C 标头import RTCICEServer在 Swift 源文件中 我尝试使用头文
  • iOS:启动图像多语言

    我有一个多语言应用程序 我的问题是启动图像 根据设备的语言使用启动图像的方法是什么 有什么东西在info plist file 解决方案是像项目中的任何其他资源一样本地化 Default png 从 Xcode 的项目列表中选择 Defau
  • 既然 Gradle 和 Maven 都弃用了 http,如何使用 Liferay Mobile SDK 6.2.18 生成 jar 库?

    在我当前的项目中 我们正在维护 开发使用客户网站 liferay 6 2 服务的移动 android iOS 应用程序 每当后端的人员生成新服务 或者只是将现有服务更新为具有新功能的新版本 时 我们需要使用 Liferay Mobile S
  • pdf文件文本阅读和搜索

    我想从 pdf 文件中读取文本并将文本搜索到 pdf 文件中 这是我知道的链接 这些都帮不了我 使用 Quartz 2D 解析 pdf 时获取文本位置 https stackoverflow com questions 3627745 ge
  • 如何在 swift 3 中的表视图单元格中实现集合视图的分页?

    在这里 我有一个布局 其中我的表视图单元格之一由集合视图组成 在这个布局中我需要实现分页 但我无法使用func collectionView collectionView UICollectionView willDisplay cell
  • 以编程方式显示 UIView

    我试图 通过动画 显示 UIView 具体来说 我想显示视图的中心部分 然后慢慢地显示它的外边缘 有点像拉开窗帘 我的第一次尝试是简单地将边界矩形设置得更小 并将其动画化为视图框架的完整大小 但这没有达到预期的效果 因为通过更改边界 我也更
  • 更新到 SDK 1.3.1 后未捕获 GMSMapView 上的拖动/平移手势

    我在通过手势识别器捕获 GMSMapView 上的拖动 平移手势时遇到了一个奇怪的问题 此问题仅在从 GMS 1 2 更新到 1 3 1 后才出现 其中 引用文档 https developers google com maps docum
  • MKPolylineView initWithPolyLine:在 iOS 7 中已弃用

    我收到以下错误 initWithPolyline 已弃用 首先在 iOS 7 0 中弃用 MKPolylineView lineView MKPolylineView alloc initWithPolyline overlay 代替这个的
  • MacTypes.h 中 UInt32 的 Typedef 重新定义,来自 CFBase.h 中的定义

    我在 MacTypes h 的以下代码块中的两行中收到 typedef 重新定义错误 if LP64 typedef unsigned int UInt32 typedef signed int SInt32 else typedef un
  • iOS 8 UITableView 分隔符插入 0 不起作用

    我有一个应用程序 其中UITableView的分隔符插入设置为自定义值 右0 Left 0 这完美地适用于iOS 7 x 但是在iOS 8 0我看到分隔符插入设置为默认值15在右侧 即使在 xib 文件中它设置为0 它仍然显示不正确 我该如
  • 为什么我的matchedGeometryEffect根据右下点移动?

    我只是尝试使用matchedGeometryEffect 制作一些动画 但是 存在一个错误 即该对象是根据右下点而不是中心进行动画处理的 我使用的代码在这里 import SwiftUI struct Test View Namespace
  • 移动文件并覆盖[重复]

    这个问题在这里已经有答案了 即使同名文件已存在 我也尝试移动文件 NSFileManager moveItemAtURL location1 toURL location2 Does NSFileManager的方法moveItemAtUR
  • 在 Objective-C iPad 开发中发布

    我正在尝试发出 POST 请求 但我似乎无法弄清楚出了什么问题 我从服务器收到响应 但我的电子邮件 密码对似乎没有正确发送 读取 由服务器 它告诉我不存在这样的帐户 这是我的代码 它包含在一个函数中 当用户按下我创建的 登录 按钮时调用该函
  • 无法转换“String”类型的值?预期参数类型“URL”

    我正在尝试从主包中的文件加载数据 当我使用这段代码时 let path Bundle main path forResource abc ofType txt let dataTwo try Data contentsOf path err
  • 在模拟器上卸载应用程序后,NSUserDefaults 未清除

    这听起来可能很菜鸟 我想检查用户是否第二次进入我的应用程序 以便保留我正在使用的运行计数NSUserDefaults 我已经在我的中实现了以下代码rootViewController s viewDidLoad method NSUserD
  • 动态框架中未定义的架构符号

    我正在开发一个 iOS 框架 该框架包含多个第三方框架并使用 UnitySendMessage C 方法与 Unity 进行通信 我想创建一个动态框架 支持 iOS8 但我偶然发现以下编译错误 Undefined symbols for a
  • 如何在没有 Xcode 的情况下提交 iOS 应用程序?

    我是一名合同开发商 我已经为客户编写了一个应用程序 是的 使用 Xcode 现在我们准备发货了 我想向他发送一份应用程序副本 他可以签署该副本并将其提交到 iTunes 应用程序商店 但是他没有或没有使用 Xcode 虽然这是一个备份计划
  • 将对象映射到 TableView 部分的 Swift 二维数组

    我想不出更好的方法来做到这一点 我将学生对象的所有属性映射到二维数组中 所以我的电视有几个部分 我也不能使用静态表视图 如果是这样 这个问题就不会存在 所以我在 TVC 中的代码 let currentUser PFUser current

随机推荐