閱讀896 返回首頁    go 阿裏雲 go 技術社區[雲棲]


iOS網絡編程-iCloud鍵值數據存儲編程實例

iCloud鍵值數據存儲設計

iCloud鍵值數據存儲編程實例,畫麵中有兩個開關控件,左圖是設備1點擊“設置iCloud數據”按鈕,將控件狀態保存到iCloud服務器。右圖是設備2畫麵,過幾秒鍾後設備2收到變更通知。

 10

 

配置Xcode工程

使用Xcode創建一個iOS工程,工程創建好之後,選擇TAGETS→MyNotes→Summary→Entitlements,我們可以在這裏配置授權信息。

11

然後我們還需要應用設置代碼簽名標識,代碼簽名標識需要選擇這個配置概要文件的。選擇TAGETS→MyNotes→Code Signing Identity

12

設置完成之後可以開始編碼工作了。

代碼實現

首先是需要注冊NSUbiquitousKeyValueStoreDidChangeExternallyNotification通知,並同步數據,代碼參考ViewController.m的viewDidLoad方法:

- (void)viewDidLoad

{

[super viewDidLoad];

NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore]; ①

[[NSNotificationCenter defaultCenter]  ②

addObserverForName:

NSUbiquitousKeyValueStoreDidChangeExternallyNotification

object:store

queue:nil

usingBlock:^(NSNotification *note) { ③

//更新控件狀態

[_switchSound setOn:[store boolForKey:UbiquitousSoundKey]]; ④

[_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]];  ⑤

UIAlertView *alert = [[UIAlertView alloc]

initWithTitle:@”iCloud變更通知”

message:@”你的iCloud存儲數據已經變更”

delegate:nil

cancelButtonTitle:@”Ok”

otherButtonTitles:nil, nil];

[alert show];

}];

[store synchronize];  ⑥

//初始化控件狀態

[_switchSound setOn:[store boolForKey:UbiquitousSoundKey]];  ⑦

[_switchMusic setOn:[store boolForKey:UbiquitousMusicKey]];  ⑧

 

}


保存數據到iCloud存儲,代碼ViewController.m的setData:方法:

- (IBAction)setData:(id)sender {

NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];

//存儲到iCloud

[store setBool:_switchSound.isOn forKey:UbiquitousSoundKey];

[store setBool:_switchMusic.isOn forKey:UbiquitousMusicKey];

[store synchronize];

}

因為是BOOL值所以存儲使用的方法是setBool:forKey:。最後不要忘記解除注冊的通知,在視圖控製器中解除通知可以在didReceiveMemoryWarning方法中完成:

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

[[NSNotificationCenter defaultCenter] removeObserver:self];

}


由於本應用中隻有一個通知,因此可以使用[[NSNotificationCenter defaultCenter] removeObserver:self]語句解除全部通知,而不影響其它的通知,如果還有其它的通知我們要慎用這個語句。

編程完成代碼我們可以測試一下,這個應用的測試很麻煩,需要兩個真實設備而不能在模擬器上進行。運行兩個設備,點擊其中一個設備的“設置iCloud數據”按鈕,過幾秒鍾後另外一個設備收到變更通知。

13

出自《iOS網絡編程與雲端應用最佳實踐》作者:關東升 新浪微博@tony_關東升

最後更新:2017-04-03 19:06:48

  上一篇:go 一個有問題的驅動程序
  下一篇:go 雲計算領域10大最重要的科技公司