objective-c - 如何在 iCloud 中保存 NSData

标签 objective-c cocoa icloud

我的应用程序中有 NSData,我想将该数据保存在 iCloud 中。 我不想将我的 NSUserDefaults 与 iCloud 同步,所以它不是“Can I use iCloud to sync the NSUserDefaults plist file”的克隆。 那可能吗?我怎样才能做到这一点?我怎样才能检索保存的数据?

最佳答案

是的,这是可能的。我以前做过,我的答案是 syncing zip with iCloud ,我在其中创建 zip 并将其转换为 NSData 并与 iCloud 同步,稍后我收到 NSData 并再次将其转换回 zip 并解压缩内容。在这里,您的主要需求是 NSData 的同步,因此您需要为 NSData 工作。

1) 创建UIDocument的子类

#import <UIKit/UIKit.h>

@interface MyDocument : UIDocument
    @property (strong) NSData *dataContent;
@end

2) MyDocument.m

#import "MyDocument.h"

@implementation MyDocument
@synthesize dataContent;

// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
    self.dataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"noteModified" object:self];
    return YES;     
}

// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError 
{
    return self.dataContent;
}

@end

3)与iCloud同步(你可以根据需要做)

-(IBAction) iCloudSyncing:(id)sender
{

    NSURL* ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
    NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"]  URLByAppendingPathComponent:@"iCloudPictures.zip"];

    MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
    NSData *data = << YOUR NSDATA >>;
    mydoc.dataContent = data;

    [mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
     {
         if (success)
         {
             NSLog(@"Synced with icloud");
         }
         else
             NSLog(@"Syncing FAILED with icloud");

     }];
}

希望这有帮助..

关于objective-c - 如何在 iCloud 中保存 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198492/

相关文章:

ios - 在 iPhone 4/4S 和 iPad 2 上生成 54 兆像素图像

cocoa - tvOS applicationDidBecomeActive 在电视关闭时重复调用

c++ - RootViewController 在其委托(delegate)外部访问时不会添加 subview

ios - iOS5 中 icloud 的核心数据

iphone - iOS 6 外观 API UIBarButtonSystemItemAdd 不工作?

ios - FB 用户 emailID 未获取

xcode - 使用 applescript cocoa objc 设置音量在 xcode 中不起作用

ios - 'iCloud' 功能仅适用于注册 Apple Developer Program 的用户。请访问 https ://developer. apple.com/programs/报名

ios - 如何在 iOS 应用程序上处理管理员控制的帐户

c++ - 在 Objective-C 中使用外部 C++ 头文件