iCloud 是蘋果提供的雲端服務,使用者可以將通訊錄、備忘錄、郵件、照片、音樂、影片等備份到雲服務器,並在各個蘋果裝置間直接共享而無需操心資料同步;甚至即使裝置丟失後,也能在一台新裝置上透過 Apple ID 登入同步。
key-value data:NSUserDefault。document:Provisioning Profile),這裡可以使用通配的 Bundle ID。Capabilities,找到 iCloud 服務並開啟它。Service 中勾選 Key-value storage 和 iCloud Documents。
entitlements 檔。


使用方式和 NSUserDefault 差不多,都是以鍵值對的形式存儲。
#import "iCloudKeysViewController.h"
@interface iCloudKeysViewController ()
@property (strong, nonatomic) NSUbiquitousKeyValueStore *keyStore;
@property (strong, nonatomic) IBOutlet UILabel *textLabel;
@end
@implementation iCloudKeysViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textLabel.text = @"Ready Go";
// 獲取 iCloud 配置首選項
self.keyStore = [NSUbiquitousKeyValueStore defaultStore];
// 註冊通知中心,當配置發生改變時發出通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(ubiquitousKeyValueStoreDidChange:) name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification object:keyStore];
}
/* UI 點擊,點擊改變按鈕 */
- (IBAction)changeKey {
[self.keyStore setString:@"Hello World" forKey:@"MyString"];
[self.keyStore synchronize];
NSLog(@"Save key");
}
/* 監聽通知,當配置發生改變時會調用 */
- (void)ubiquitousKeyValueStoreDidChange:(NSNotification *)notification {
NSLog(@"External Change detected");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Change detected" message:@"Change detected" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
// 顯示改變的信息
self.textLabel.text = [self.keyStore stringForKey:@"MyString"];
}
@end
UIDocument 類來完成,這個類提供了新建、修改、查詢、打開、刪除文件的功能。UIDocument 對文件的新增、修改、刪除、讀取全部基於一個雲端 URL 來完成,對於開發者而言沒有本地和雲端之分,大大簡化了開發過程。呼叫 NSFileManager 的物件方法:
-(NSURL *)URLForUbiquityContainerIdentifier:(NSString *)identifier;上面需要傳遞一個雲端存儲容器的唯一標示,這個可以去自動生成的 entitlements 檔查看 Ubiquity Container Identifiers 欄位獲得;如果傳 nil,代表第一個容器。
預設的第一個容器標識是
iCloud.$(CFBundleIdentifier),其中$(CFBundleIdentifier)代表Bundle ID。那麼根據應用的Bundle ID就能得知我的第一個容器標識是iCloud.com.liuting.icloud.iCloudTest。
/* 將指定 URL 的文件保存到 iCloud(可以是新增或覆蓋,透過 saveOperation 參數設定)*/
- (void)saveToURL:(NSURL *)url forSaveOperation:(UIDocumentSaveOperation)saveOperation completionHandler:(void (^)(BOOL success))completionHandler;
/* 保存操作 option */
typedef NS_ENUM(NSInteger, UIDocumentSaveOperation) {
UIDocumentSaveForCreating, /* 創建 */
UIDocumentSaveForOverwriting /* 覆蓋寫入 */
};
/* 打開文件,參數是打開文件成功回呼 */
- (void)openWithCompletionHandler:(void (^)(BOOL success))completionHandler;
/* 刪除指定 URL 下的文件 */
- (BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error;
UIDocument 在設計時沒有提供統一的存儲方式來存儲資料,需要我們去繼承它,重寫 2 個物件方法自己操作資料:
/* 保存文件時調用 */
-(id)contentsForType:(NSString *)typeName error:(NSError **)outError;
/* 讀取數據時調用 */
-(BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError;UIDocument 保存資料的本質:將 A 對應類型的資料轉化為雲端存儲的 NSData 或 NSFileWrapper 資料。UIDocument 讀取資料的本質:將雲端下載的 NSData 或 NSFileWrapper 資料轉化為 A 對應類型的資料。#import <UIKit/UIKit.h>
@interface LTDocument : UIDocument
@property (strong, nonatomic) NSData *data; /* 文件數據 */
@end
#import "LTDocument.h"
@implementation LTDocument
#pragma mark - 重寫父類方法
/**
* 保存時調用
*/
- (id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
if (!self.data) {
self.data = [NSData data];
}
return self.data;
}
/**
* 讀取數據時調用
*/
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
self.data = [contents copy];
return true;
}
@end
NSMetadataQuery。NSMetadataQuery 並指定 searchScopes 為 NSMetadataQueryUbiquitousDocumentScope 來限制查找 iCloud 文件資料。NSMetadataQuery 還可以透過謂詞限制搜尋關鍵字等資訊,並在搜尋完成之後透過通知的形式通知客戶端搜尋的情況。#import "ViewController.h"
#import "LTDocument.h"
#define kContainerIdentifier @"iCloud.com.liuting.icloud.iCloudTest"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *documentField; /* 輸入框 */
@property (weak, nonatomic) IBOutlet UILabel *documentShowLable; /* 顯示欄 */
@property (weak, nonatomic) IBOutlet UITableView *documentTableView; /* 文件列表 */
/* 文件文件信息,鍵為文件名,值為創建日期 */
@property (strong, nonatomic) NSMutableDictionary *files;
@property (strong, nonatomic) NSMetadataQuery *query; /* 查詢文件物件 */
@property (strong, nonatomic) LTDocument *document; /* 當前選中文檔 */
@end
/**
* 取得雲端存儲文件的地址
*/
- (NSURL *)getUbiquityFileURL:(NSString *)fileName {
// 取得雲端 URL 基地址(傳入 nil 則默認獲取第一個容器)
NSFileManager *manager = [NSFileManager defaultManager];
NSURL *url = [manager URLForUbiquityContainerIdentifier:kContainerIdentifier];
// 取得 Documents 目錄
url = [url URLByAppendingPathComponent:@"Documents"];
// 取得最終地址
url = [url URLByAppendingPathComponent:fileName];
return url;
}
/* 從 iCloud 上加載所有文件信息 */
- (void)loadDocuments {
if (!self.query) {
self.query = [[NSMetadataQuery alloc] init];
self.query.searchScopes = @[NSMetadataQueryUbiquitousDocumentsScope];
// 注意查詢狀態是透過通知的形式告訴監聽物件的
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(metadataQueryFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query]; // 數據獲取完成通知
[center addObserver:self selector:@selector(metadataQueryFinish:) name:NSMetadataQueryDidUpdateNotification object:self.query]; // 查詢更新通知
}
// 開始查詢
[self.query startQuery];
}
/* 查詢更新或者數據獲取完成的通知調用 */
- (void)metadataQueryFinish:(NSNotification *)notification {
NSLog(@"數據獲取成功!");
NSArray *items = self.query.results; // 查詢結果集
self.files = [NSMutableDictionary dictionary];
// 遍歷結果集,存儲文件名稱、創建日期
[items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSMetadataItem *item = obj;
NSString *fileName = [item valueForAttribute:NSMetadataItemFSNameKey];
NSDate *date = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
NSDateFormatter *dateformate = [[NSDateFormatter alloc] init];
dateformate.dateFormat = @"YY-MM-dd HH:mm";
NSString *dateString = [dateformate stringFromDate:date];
[self.files setObject:dateString forKey:fileName];
}];
// 表格刷新
self.documentShowLable.text = @"";
[self.documentTableView reloadData];
}
#pragma mark - UI 點擊事件
/* 點擊添加文件 */
- (IBAction)addDocument:(id)sender {
if (self.documentField.text.length <= 0) {
self.documentField.placeholder = @"請輸入要創建的文件名";
return;
}
NSString *text = self.documentField.text;
NSString *fileName = [NSString stringWithFormat:@"%@.txt", text];
NSURL *url = [self getUbiquityFileURL:fileName];
LTDocument *document = [[LTDocument alloc] initWithFileURL:url];
NSString *dataString = @"hallo World";
document.data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
self.documentField.text = @"";
[self loadDocuments];
}
}];
}
/* 點擊修改文件 */
- (IBAction)saveDocument:(UIButton *)sender {
if ([sender.titleLabel.text isEqualToString:@"修改文檔"]) {
self.documentField.text = self.documentShowLable.text;
[sender setTitle:@"保存文檔" forState:UIControlStateNormal];
} else if ([sender.titleLabel.text isEqualToString:@"保存文檔"]) {
[sender setTitle:@"修改文檔" forState:UIControlStateNormal];
self.documentField.placeholder = @"請輸入修改的文件內容";
NSString *dataText = self.documentField.text;
self.document.data = [dataText dataUsingEncoding:NSUTF8StringEncoding];
[self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
self.documentShowLable.text = self.documentField.text;
self.documentField.text = @"";
}];
}
}
/* 點擊刪除文件 */
- (IBAction)removeDocument:(id)sender {
if (self.documentField.text.length <= 0) {
self.documentField.placeholder = @"請輸入要刪除的文件名";
return;
}
NSString *fileName = [NSString stringWithFormat:@"%@.txt", self.documentField.text];
NSArray *fileNames = [self.files allKeys];
if (![fileNames containsObject:fileName]) {
return;
}
NSURL *url = [self getUbiquityFileURL:fileName];
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtURL:url error:&error];
if (error) {
return;
}
[self.files removeObjectForKey:fileName];
self.documentField.text = @"";
}
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.documentTableView.delegate = self;
self.documentTableView.dataSource = self;
[self loadDocuments];
}
#pragma mark - UITableView 數據源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.files.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identtityKey = @"myTableViewCellIdentityKey1";
UITableViewCell *cell = [self.documentTableView dequeueReusableCellWithIdentifier:identtityKey];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identtityKey];
}
NSArray *fileNames = self.files.allKeys;
NSString *fileName = fileNames[indexPath.row];
cell.textLabel.text = fileName;
cell.detailTextLabel.text = [self.files valueForKey:fileName];
return cell;
}
#pragma mark - UITableView 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.documentTableView cellForRowAtIndexPath:indexPath];
NSURL *url = [self getUbiquityFileURL:cell.textLabel.text];
LTDocument *document = [[LTDocument alloc] initWithFileURL:url];
self.document = document;
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
NSString *dataText = [[NSString alloc] initWithData:document.data encoding:NSUTF8StringEncoding];
self.documentShowLable.text = dataText;
}
}];
}
@end


上面的程式碼 Demo 點這裡:LearnDemo 裡面的 iCloudDemo(僅含 Document 的實例程式碼)。