又是好久沒有寫東西了,前幾天去面試問到關(guān)于App Extension的問題,以前沒做過,就和大家一起學(xué)習(xí)下吧,一般常用的是Today和Share,這里就先看看這兩個吧.由于關(guān)于這方面的介紹網(wǎng)上已經(jīng)有很多資料了,但沒有demo,我自己寫了個demo,通過這個demo,相信很快就能將App Extension用到自己的項目中。
Today
先看效果圖(系統(tǒng):iOS 10, demo主要有三個功能,分別是視圖的折疊收縮、頁面跳轉(zhuǎn)和數(shù)據(jù)共享):

下面來說說實現(xiàn)過程
視圖的折疊收縮
創(chuàng)建一個Extension我就不說了,UI我是通過storyboard來做的,所以不用做修改,若是用代碼布局需要修改Info.plist文件.
需要說明的幾行代碼:
[self.extensionContext widgetMaximumSizeForDisplayMode:NCWidgetDisplayModeCompact];這行代碼是指當(dāng)today視圖折疊起來的最小Size(你所設(shè)置的尺寸要比這個大)。
self.extensionContext.widgetLargestAvailableDisplayMode = NCWidgetDisplayModeExpanded;設(shè)置成可以折疊的模式
頁面跳轉(zhuǎn)
頁面跳轉(zhuǎn)就是用通過URL Schemes來打開App,并通過URL傳過來的參數(shù)跳轉(zhuǎn)到指定的頁面,具體做法:
- 在項目的Info.plist文件中添加URL types字段
-
設(shè)置填寫URL Schemes和URL identifier如下圖:
URL Schemes.png - AppDelegate.m文件中添加
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options這個方法,并在方法內(nèi)實現(xiàn)跳轉(zhuǎn)到App后執(zhí)行的代碼 - 在
TodayViewController.m文件中使用[self.extensionContext openURL:url completionHandler:nil];方法打開App,url就是前面填寫的URL Schemes
數(shù)據(jù)共享
數(shù)據(jù)共享有兩種方法,這里只說demo中用到的UserDefault
-
打開主程序和Extension的App Group,并設(shè)置Group名稱,如下圖
App Group.png - 通過
[[NSUserDefaults alloc] initWithSuiteName:@"group.steven.app"];來創(chuàng)建NSUserDefaults,并通過KVC來進(jìn)行數(shù)據(jù)存儲和讀取即可。
到這里,關(guān)于Today的demo就完成了。。。
Share
先看效果圖(系統(tǒng):iOS 10, demo主要有兩個功能,分別是分享的字?jǐn)?shù)限制、數(shù)據(jù)提取和數(shù)據(jù)共享,這里只做了Safari的分享):

字?jǐn)?shù)限制(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 > 0) {
return YES;
}else {
return NO;
}
}
數(shù)據(jù)提取
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.steven.app"];
[userDefaults setObject:self.contentText forKey:@"shareText"];
NSExtensionItem * item = self.extensionContext.inputItems.firstObject;
NSItemProvider * provider =item.attachments.firstObject;
[provider loadPreviewImageWithOptions:nil completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
NSData * data = UIImagePNGRepresentation((UIImage *)item);
[userDefaults setObject:data forKey:@"shareImage"];
}];
NSString * dataType = provider.registeredTypeIdentifiers.firstObject;
[provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
NSString * url = [NSString stringWithFormat:@"%@",item];
[userDefaults setObject:url forKey:@"shareURL"];
}];
[userDefaults synchronize];
});
關(guān)于數(shù)據(jù)共享是和Today是一樣的,這里就不再重復(fù)了,demo點擊下載,歡迎大家Star.

