ios - 在 iCloud 中收到有关文件更改的通知

标签 ios icloud icloud-documents

我在两个不同的设备上创建了一个名为 File - 1.jpg 的文件,并将其放入 iCloud 容器中。

我不使用 UIDocument,即使我尝试使用它,也不会产生冲突。相反,我看到的是 iCloud 自动重命名和移动文档。

所以在上传一个文件或另一个文件后变成File - 2.jpg。所有这一切都很好,但现在我没有对文件的引用,所以我不知道哪个是哪个...

有什么方法可以在应用端通知文件在 iCloud 中被重命名/移动/删除了吗?

最佳答案

最终,我不得不创建一个实现 NSFilePresenter 的类,并将其指向 iCloud 容器文件夹。

来自 iCloud 的实时更新可能会很晚,并且只有在 iCloud 提取元数据时才会发生。

此外,我必须将每个创建的文件与每个设备和 iCloud 帐户关联起来,并保存这些数据,在我的例子中是在 CoreData 中。这就是 ubiquityIdentityToken 发挥作用的地方。

iCloud 容器中的所有文件操作当然应该使用 NSFileCoordinator 进行。

对于添加/删除事件,最好使用 NSMetadataQueryNSFileCoordinator 根本不报告这些事件,但对于检测文件何时被移动仍然有用,这就是元数据查询报告作为更新。

这是一个非常基本的样板文件,可以用作起点:

@interface iCloudFileCoordinator () <NSFilePresenter>

@property (nonatomic) NSString *containerID;
@property (nonatomic) NSURL *containerURL;

@property (nonatomic) NSOperationQueue *operationQueue;

@end

@implementation iCloudFileCoordinator

- (instancetype)initWithContainerID:(NSString *)containerID {
    self = [super init];
    if(!self) {
        return nil;
    }

    self.containerID = containerID;
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.qualityOfService = NSQualityOfServiceBackground;

    [self addFilePresenter];

    return self;
}

- (void)dealloc {
    [self removeFilePresenter];
}

- (void)addFilePresenter {
    [NSFileCoordinator addFilePresenter:self];
}

- (void)removeFilePresenter {
    [NSFileCoordinator removeFilePresenter:self];
}

#pragma mark - NSFilePresenter
#pragma mark - 

- (NSURL *)presentedItemURL {
    NSURL *containerURL = self.containerURL;

    if(containerURL) {
        return containerURL;
    }

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    containerURL = [fileManager URLForUbiquityContainerIdentifier:self.containerID];

    self.containerURL = containerURL;

    return containerURL;
}

- (NSOperationQueue *)presentedItemOperationQueue {
    return self.operationQueue;
}

- (void)presentedSubitemAtURL:(NSURL *)oldURL didMoveToURL:(NSURL *)newURL {
    NSLog(@"Moved file from %@ to %@", oldURL, newURL);
}

/*
 ... and other bunch of methods that report on sub item changes ...
 */

@end

关于ios - 在 iCloud 中收到有关文件更改的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423110/

相关文章:

ios - MPMoviePlayerController initialPlaybackTime 属性在 iOS 8.4 中不起作用

ios - 这个 Int32 初始化器能返回 nil 吗?

ios - AVMutableComposition - 连接的视频 Assets 在第一个 Assets 后停止

oauth-2.0 - 是否有 iCloud 网络 API?

ios - 我没有写入 iCloud 文件夹的权限

ios - 如何在 Swift 中创建一个圆形按钮?

xcode - 如何按添加日期组织 icloud 数据?

ios - CloudKit 中私有(private)存储的数据是否存储在用户的 iCloud 帐户中?

ios - 为 iCloud 冲突合并 UIDocument 更改

iOS iCloud 文档 : can I prevent documents from being purged?