您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 學習筆記(32):iCloud 入門指南

編輯:iOS 程式設計技術

一、iCloud 雲服務

iCloud 是蘋果提供的雲端服務,使用者可以將通訊錄、備忘錄、郵件、照片、音樂、影片等備份到雲服務器,並在各個蘋果裝置間直接共享而無需操心資料同步;甚至即使裝置丟失後,也能在一台新裝置上透過 Apple ID 登入同步。

蘋果已將雲端存儲功能開放給開發者,可以存儲兩類資料:
  1. key-value data:
    分享小量的非關鍵配置資料到應用的多個實例,使用方式類似於 NSUserDefault。
  2. document:
    存儲使用者文件與應用資料到使用者的 iCloud 帳戶。
進行 iCloud 開發的準備工作:
  1. 在開發者中心建立 Apple ID,啟用 iCloud 服務。
  2. 生成對應的配置文件(Provisioning Profile),這裡可以使用通配的 Bundle ID。
  3. 以上 2 步是針對真機的,調試模擬器可以忽略。
  4. 打開專案的 Capabilities,找到 iCloud 服務並開啟它。
  5. 在 iCloud 服務的 Service 中勾選 Key-value storage 和 iCloud Documents。
  6. 你的專案中就會多出一個 entitlements 檔。
  7. 裡面的內容是自動生成的,就像這樣:
  8. 無論真機還是模擬器,都需要進入手機的設定中登入 iCloud 帳號。

二、Key-Value 的 iCloud 存儲

使用方式和 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

三、Document 的 iCloud 存儲

核心類 UIDocument
  • 文件存儲主要是使用 UIDocument 類來完成,這個類提供了新建、修改、查詢、打開、刪除文件的功能。
  • UIDocument 對文件的新增、修改、刪除、讀取全部基於一個雲端 URL 來完成,對於開發者而言沒有本地和雲端之分,大大簡化了開發過程。
雲端 URL 的獲取方式:
  • 呼叫 NSFileManager 的物件方法:

    -(NSURL *)URLForUbiquityContainerIdentifier:(NSString *)identifier;
  • 上面需要傳遞一個雲端存儲容器的唯一標示,這個可以去自動生成的 entitlements 檔查看 Ubiquity Container Identifiers 欄位獲得;如果傳 nil,代表第一個容器。

補充知識:

預設的第一個容器標識是 iCloud.$(CFBundleIdentifier),其中 $(CFBundleIdentifier) 代表 Bundle ID。那麼根據應用的 Bundle ID 就能得知我的第一個容器標識是 iCloud.com.liuting.icloud.iCloudTest。

UIDocument 的物件方法:
/* 將指定 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;
刪除文件使用的是 NSFileManager 的物件方法:
/* 刪除指定 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 對應類型的資料。
下面是我自訂的 Document 類,繼承於 UIDocument:
LTDocument.h 檔
#import <UIKit/UIKit.h>

@interface LTDocument : UIDocument
@property (strong, nonatomic) NSData *data; /* 文件數據 */
@end
LTDocument.m 檔
#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
  • 如果要加載 iCloud 中的文件列表,就需要使用另一個類 NSMetadataQuery。
  • 通常考慮到網路的緣故,並不會一次性加載所有資料,而是利用 NSMetadataQuery 並指定 searchScopes 為 NSMetadataQueryUbiquitousDocumentScope 來限制查找 iCloud 文件資料。
  • 使用 NSMetadataQuery 還可以透過謂詞限制搜尋關鍵字等資訊,並在搜尋完成之後透過通知的形式通知客戶端搜尋的情況。
下面是使用示例:
1. 屬性定義和宏定義:
#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
2. 獲取雲端 URL 方法:
/**
 * 取得雲端存儲文件的地址
 */
- (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;
}
3. 查詢文件列表方法
/* 從 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];
}
4. UI 點擊事件
#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 = @"";
}
5. 視圖控制器初始化和列表顯示
@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 的實例程式碼)。

如果有什麼問題請在下方評論區中提出!O(∩_∩)O 哈!
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved