方法1: UIPasteboardを使う方法
一番おすすめなのがこちらです。UIPasteboardというのは要するにコピペ用のクリップボードみたいなものなのですが、こちらシステムが用意している共通のもの以外にも自分のTeam IDでコードサインされたアプリ間すべてで共用できるPasteboardを作成する機能があります。この機能を使用すると非常に簡単にデータをやりとりすることができます。面倒な設定も不要ですし、persistentプロパティを設定することでディスクへの永続化も面倒を見てくれます。
以下にサンプルコードを掲載します。本体アプリのUIApplicationDelegate内でクリップボードを作成してデータを突っ込み、App ExtensionのWidgetViewController内でその値を使用するサンプルです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions | |
{ | |
// Create a pasteboard, and pass some data to it | |
// the created pasteboard can be specified as persistent as well | |
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"Widget" create:YES]; | |
pasteboard.persistent = YES; | |
pasteboard.string = @"やっほー!"; | |
return YES; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)viewWillAppear:(BOOL)animated | |
{ | |
[super viewWillAppear:animated]; | |
// Get some data from the created pasteboard | |
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"Widget" create:NO]; | |
if (pasteboard) { | |
self.titleLabel.text = pasteboard.string; | |
} | |
} |
注意点として、UIPasteboardのnameはあなたの作成したアプリ全体(同じTeam IDでコードサインされたアプリ全体)で共有になります。ですのでWidgetですとかTestのような単純な名前ではなく、com.akisute.MyApp.Widgetのような一意になる名前をつけることをおすすめします。
UIPasteboardについての詳しい使い方については、以下の記事をご覧ください。
方法2: Keychainを使う方法(未確認)
未確認なので確定情報ではありませんが、Keychainには複数のアプリ間で値を共有する機能がありますので、そちらを使えばおそらくアプリ本体とApp Extensionの間で値を共有する事が可能になります。詳しくは以下の記事をご覧ください。