咱們能夠在iPhone和Apple Watch間經過app groups來共享數據。方法以下:app
首先要在dev center添加一個新的 app group:ide
接下來建立一個新的single view application,名字就叫SharingDataDemo:ui
添加三個控件到主界面:TextField、Button和Label。spa
在Button的點擊事件中使用NSUserDefaults將用戶輸入的內容進行保存:blog
注意suiteName必須和dev center中定義的app group的identifier ID一致。事件
接下來添加Watch:選擇File - New - Target - WatchKit App:get
添加兩個控件到watch的main界面:Label和Button。it
在Button的點擊事件中使用NSUserDefaults將上一步保存的數據讀取出來,顯示到Label上:io
最後一步,也是關鍵的一步,設置iPhone App和Watch App到同一個group中,缺失這一步,數據是沒法共享的。
注意iPhone App和Watch App分別要如此設置一次,不要漏了Watch App的設置。方法
效果: