草庐IT

ios - OSX 和 iOS 之间的 iCloud 核心数据共享

coder 2023-07-28 原文

我有一个适用于 OSX 和 iOS 的应用程序,两者都使用 iCloud 在它们之间共享核心数据。当我在 iPhone 中进行更改时,我可以在 OSX 应用程序中看到它们,并且 NSPersistentStoreDidImportUbiquitousContentChangesNotification 在两个应用程序中都被调用,因此 iOS -> Mac 运行良好。但是当我在 Mac 应用程序中进行一些更改时,我无法在 iPhone 中看到它们。 iPhone 从不调用 NSPersistentStoreDidImportUbiquitousContentChangesNotification。我能够获得 Mac 更改的唯一方法是在 iPhone 上进行一些更改。然后我可以看到所有的变化。

两个项目中的 iCloud 集成是相同的。核心数据数据模型是相同的。权利也是相同的。

我所有的代码都基于这个库:http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/

为什么在我对 iPhone 进行一些更改之前,iPhone 没有获得 Mac 更改?有什么想法吗?

另一个问题

在我的应用程序中,当用户启用 iCloud 时,我会检查是否已经是 iCloud 上的文件。如果文件存在,用户可以选择从 iCloud 文件恢复核心数据或从本地存储开始新的副本。 要开始新副本,我使用以下代码:

- (void)startNewCopy
{
    [self removeICloudStore];
    [self moveStoreToIcloud];
}

- (void)removeICloudStore
{
    BOOL result;
    NSError *error;
    // Now delete the iCloud content and file
    result = [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:[self icloudStoreURL]
                                                                             options:[self icloudStoreOptions]
                                                                             error:&error];
    if (!result)
    {
        NSLog(@"Error removing store");
    }
    else
    {
        NSLog(@"Core Data store removed.");
        // Now delete the local file
        [self deleteLocalCopyOfiCloudStore];
    }

}


- (void)deleteLocalCopyOfiCloudStore {
   // We need to get the URL to the store
   NSError *error = nil;
   [[NSFileManager defaultManager] removeItemAtURL:[self localUbiquitySupportURL] error:&error];
}

- (void)moveStoreToIcloud
{
     // Open the store
     NSPersistentStore *sourceStore = [[_persistentStoreCoordinator persistentStores] firstObject];

     if (!sourceStore)
     {
         NSLog(@" failed to add old store");
     }
     else
     {
         NSLog(@" Successfully added store to migrate");
         NSError *error;
         id migrationSuccess = [_persistentStoreCoordinator migratePersistentStore:sourceStore toURL:[self icloudStoreURL] options:[self icloudStoreOptions] withType:NSSQLiteStoreType error:&error];

         if (migrationSuccess)
         {
             NSLog(@"Store migrated to iCloud");

             _persistentStoreCoordinator = nil;
             _managedObjectContext = nil;

             // Now delete the local file
             [self deleteLocalStore];

         }
         else
         {
             NSLog(@"Failed to migrate store: %@, %@", error, error.userInfo);

         }
     }

}

- (void)deleteLocalStore
{
     NSError *error = nil;
     [[NSFileManager defaultManager] removeItemAtURL:[self localStoreURL] error:&error];
}

在单个设备上执行此操作似乎一切正常,但当我在多个设备上尝试此操作时,我遇到了一些错误。

例子:

我有两个设备。第一个没有连接到 iCloud,第二个连接到 iCloud。 在第一台设备中,当我启用 iCloud 时,我选择 startNewCopy,然后在第二台设备中出现此错误:

CoreData: Ubiquity: Librarian returned a serious error for starting downloads Error Domain=BRCloudDocsErrorDomain Code=5 "The operation couldn’t be completed. (BRCloudDocsErrorDomain error 5 - No document at URL)"

NSPersistentStoreCoordinatorStoresDidChangeNotification 从未在错误发生前被调用。

这是我的通知代码:

- (void)processStoresDidChange:(NSNotification *)notification
{
      NSLog(@"processStoresDidChange");
      // Post notification to trigger UI updates

      // Check type of transition
      NSNumber *type = [notification.userInfo objectForKey:NSPersistentStoreUbiquitousTransitionTypeKey];

      //NSLog(@" userInfo is %@", notification.userInfo);
      //NSLog(@" transition type is %@", type);

      if (type.intValue == NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted) {

          NSLog(@" transition type is NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted");

      } else if (type.intValue == NSPersistentStoreUbiquitousTransitionTypeAccountAdded) {
          NSLog(@" transition type is NSPersistentStoreUbiquitousTransitionTypeAccountAdded");
      } else if (type.intValue == NSPersistentStoreUbiquitousTransitionTypeAccountRemoved) {
          NSLog(@" transition type is NSPersistentStoreUbiquitousTransitionTypeAccountRemoved");
      } else if (type.intValue == NSPersistentStoreUbiquitousTransitionTypeContentRemoved) {
          NSLog(@" transition type is NSPersistentStoreUbiquitousTransitionTypeContentRemoved");
      }

      [[NSOperationQueue mainQueue] addOperationWithBlock:^ {

          if (type.intValue == NSPersistentStoreUbiquitousTransitionTypeContentRemoved) {

              [self deleteLocalStore];
              _persistentStoreCoordinator = nil;
              _managedObjectContext = nil;

              NSLog(@" iCloud store was removed! Wait for empty store");
          }

          // Refresh user Interface
          [[NSNotificationCenter defaultCenter] postNotificationName:@"notiIcloud" object:@"storeChanged"];
      }];

}

如何检测到 iCloud 内容已被删除并避免出现上述错误?

最佳答案

在我看来,您可能没有使用适当的接口(interface)。

您可以在不使用 NSPersistentStore 方法的情况下将文件移入和移出 iCloud。 通常还必须将适当的操作包装在 NSFileCoordinator 调用中。

这是我在 iOS 上所做的。 toLocal 表示移动到本地(设备)存储或从本地(设备)存储移动:

//
/// Move file between stores (assumed no name clash).
/// Return new URL.
/// Note: cloud file moves are asynchronous.
///
- (NSURL *)moveStoreFile:(NSURL *)url toRootURL:(NSURL *)rootURL toLocal:(BOOL)toLocal
{
    NSURL *newURL = rootURL;
    if (!toLocal)
        newURL = [newURL URLByAppendingPathComponent:@"Documents"];
    newURL = [newURL URLByAppendingPathComponent:url.lastPathComponent];

    [self backupFile:url isLocal:!toLocal completionHandler:
     ^(BOOL success) {

        MRLOG(@"MOVE %s %@ to %s %@", toLocal? "icloud" : "local", [url lastPathComponent],
              toLocal? "local" : "icloud", [newURL lastPathComponent]);

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
        ^{
           NSError *error;
           // setUbiquitous does file coordination
           BOOL msuccess = [[NSFileManager defaultManager]
                           setUbiquitous:!toLocal itemAtURL:url destinationURL:newURL error:&error];

           dispatch_async(dispatch_get_main_queue(),
           ^{
              if (!msuccess)
                  MRLOG(@"move failed: %@", error);
              [self.delegate moveStoreFileCompletedWithStatus:success error:error];
           });
        });
    }];

    return newURL;
}

删除需要明确的文件协调:

///
/// Purge backup file (really delete it).
/// Note: cloud deletes are asynchronous.
///
- (void)purgeFile:(NSURL *)url isLocal:(BOOL)isLocal
{
    MRLOG(@"PURGE %s %@", isLocal? "local" : "icloud", [url lastPathComponent]);

    if (isLocal)
        [self removeFile:url];
    else
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
        ^{
            NSError *coordinationError;
            NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];

            [coordinator coordinateWritingItemAtURL:url options:NSFileCoordinatorWritingForDeleting
                                                    error:&coordinationError
                                     byAccessor:
             ^(NSURL* writingURL)
             {
                 [self removeFile:writingURL];
             }];
            if (coordinationError) {
                MRLOG(@"coordination error: %@", coordinationError);
                [(SSApplication *)[SSApplication sharedApplication] fileErrorAlert:coordinationError];
            }
        });
}

要检测文件更改,您需要使用 NSMetadataQuery 并为 NSMetadataQueryDidUpdateNotification 添加观察者。

关于ios - OSX 和 iOS 之间的 iCloud 核心数据共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32330863/

有关ios - OSX 和 iOS 之间的 iCloud 核心数据共享的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  6. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  7. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  8. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  9. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  10. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

随机推荐