又是好久沒有寫東西了,前幾天去面試問到關于App Extension的問題,以前沒做過,就和大家一起學習下吧,一般常用的是Today和Share,這里就先看看這兩個吧.由于關于這方面的介紹網上已經有很多資料了,但沒有demo,我自己寫了個demo,通過這個demo,相信很快就能將App Extension用到自己的項目中。
Today
先看效果圖(系統:iOS 10, demo主要有三個功能,分別是視圖的折疊收縮、頁面跳轉和數據共享):
today_test.gif
下面來說說實現過程
視圖的折疊收縮
創建一個Extension我就不說了,UI我是通過storyboard來做的,所以不用做修改,若是用代碼布局需要修改Info.plist文件.
需要說明的幾行代碼:
[self.extensionContext widgetMaximumSizeForDisplayMode:NCWidgetDisplayModeCompact];
這行代碼是指當today視圖折疊起來的最小Size(你所設置的尺寸要比這個大)。
self.extensionContext.widgetLargestAvailableDisplayMode = NCWidgetDisplayModeExpanded;
設置成可以折疊的模式
頁面跳轉
頁面跳轉就是用通過URL Schemes來打開App,并通過URL傳過來的參數跳轉到指定的頁面,具體做法:
- 在項目的Info.plist文件中添加URL types字段
- 設置填寫URL Schemes和URL identifier如下圖:
URL Schemes.png
- AppDelegate.m文件中添加
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionarylt;UIApplicationOpenURLOptionsKey,idgt; *)options
這個方法,并在方法內實現跳轉到App后執行的代碼 -
在
TodayViewController.m
文件中使用[self.extensionContext openURL:url completionHandler:nil];
方法打開App,url就是前面填寫的URL Schemes數據共享
數據共享有兩種方法,這里只說demo中用到的UserDefault
-
打開主程序和Extension的App Group,并設置Group名稱,如下圖
App Group.png
- 通過
[[NSUserDefaults alloc] initWithSuiteName:@quot;group.steven.appquot;];
來創建NSUserDefaults,并通過KVC來進行數據存儲和讀取即可。
到這里,關于Today的demo就完成了。。。
Share
先看效果圖(系統:iOS 10, demo主要有兩個功能,分別是分享的字數限制、數據提取和數據共享,這里只做了Safari的分享):
share_test.gif
字數限制(demo限制為66個字)
- (BOOL)isContentValid { // Do validation of contentText and/or NSExtensionContext attachments here NSInteger maxLength = 66; NSInteger length = self.contentText.length; self.charactersRemaining = @(maxLength - length); if (self.charactersRemaining.integerValue gt; 0) { return YES; }else { return NO; } }
數據提取
dispatch_sync(dispatch_get_global_queue(0, 0), ^{ NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@quot;group.steven.appquot;]; [userDefaults setObject:self.contentText forKey:@quot;shareTextquot;]; NSExtensionItem * item = self.extensionContext.inputItems.firstObject; NSItemProvider * provider =item.attachments.firstObject; [provider loadPreviewImageWithOptions:nil completionHandler:^(idlt;NSSecureCodinggt; _Nullable item, NSError * _Null_unspecified error) { NSData * data = http://www.tuicool.com/articles/UIImagePNGRepresentation((UIImage *)item); [userDefaults setObject:data forKey:@quot;shareImagequot;]; }]; NSString * dataType = provider.registeredTypeIdentifiers.firstObject; [provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(idlt;NSSecureCodinggt; _Nullable item, NSError * _Null_unspecified error) { NSString * url = [NSString stringWithFormat:@quot;%@quot;,item]; [userDefaults setObject:url forKey:@quot;shareURLquot;]; }]; [userDefaults synchronize]; });
關于數據共享是和Today是一樣的,這里就不再重復了, demo點擊下載 ,歡迎大家Star.
版權聲明:本文為 Crazy Steven 原創出品,歡迎轉載,轉載時請注明出處!
Tags: iOS開發
文章來源:http://www.jianshu.com/p/c466e1a6ea90