前言
Widget 是苹果针对手机负一屏的而设定的插件, 手机负一屏的天气插件应该都用过,这个就是最常见的widget。手机负一屏插件可以让用户在不开启APP的情况下,查看一些APP内的信息,快捷方便。但是不能展示太多,毕竟这里不是真正的APP。
这里是一些苹果对Widget的介绍
准备
Extension point | Typical app extension functionality |
---|---|
Action (iOS and macOS; UI and non-UI variants) | Manipulate or view content originating in a host app. |
Audio Unit (iOS and macOS; UI and non-UI variants) | Generates an audio stream to send to a host app, or modifies an audio stream from a host app and sends it back to the host app. |
Broadcast UI (iOS and tvOS) | . |
Broadcast Upload (iOS and tvOS) | . |
Call Directory (iOS) | Identify and block incoming callers by their phone number. To learn more, see CallKit Framework Reference. |
Content Blocker (iOS and macOS) | Indicate to WebKit that your content-blocking app has updated its rules.(This app extension has no user interface.) |
Custom Keyboard (iOS) | Replace the iOS system keyboard with a custom keyboard for use in all apps. |
Document Provider (iOS; UI and non-UI variants) | Provide access to and manage a repository of files. |
Finder Sync (macOS) | Present information about file sync state directly in Finder.(This app extension has no user interface.) |
Game App (watchOS) | Provide a game app for Apple Watch, as described in App Programming Guide for watchOS.(The Game App template is a version of the WatchKit App template, configured for game content.) |
iMessage (iOS) | Interact with the Messages app. To learn more, see Messages. |
Intents (iOS) | Handle tasks related to supporting Siri integration with your app. To learn more, see SiriKit Programming Guide. |
Intents UI (iOS) | Customize the Siri or Maps interface after handling a task related to supporting Siri integration with your app. To learn more, see SiriKit Programming Guide. |
Notification Content (iOS) | . |
Notification Service (iOS) | . |
Photo Editing (iOS and macOS) | Edit a photo or video within the Photos app. |
Share (iOS and macOS) | Post to a sharing website or share content with others. |
Smart Card Token (macOS) | . |
Spotlight Index (iOS) | Index content within your app while it isn’t running. To learn more, see Index App Content. |
Sticker Pack (iOS) | Provide a set of stickers that users can use within the Messages app. To learn more, see Messages. |
Today (iOS and macOS) | Get a quick update or perform a quick task in the Today view of Notification Center.(A Today extension is called a widget.) |
TV Services (tvOS) | . |
VPN (iOS and macOS) | Create clients for your business’s custom, remote-access VPN servers using the Packet Tunnel Provider or App Proxy Provider extension points.Create content filtering for managed devices, such as for school environments, using the Filter Control Provider and Filter Data Provider extension points. |
WatchKit App (watchOS) | Provide an app or a notification UI for Apple Watch, as described in App Programming Guide for watchOS. |
上面这个表罗列了,目前所有的 APP Extension 类型,其实我们正常的开发中 一个 Today 类型的 widget 就够用了,下面介绍一个简单的 Widget 的从无到有
App Extension 是不支持键盘输入的
创建项目
APP Extension 可以通过两种方式来创建
方式一 方式二
两种创建方式都会打开下面的窗口
选择 Today Extension 然后跟新建一个项目类似,填写 product Name 之类的
finsh之后会在项目的targets下看到你新建的 extension
项目文件夹下会新增这三个文件
一个 storyboard 一个 TodayViewController 一个 info.plist
接下来可以对 storyboard 进行编辑显示你想要的界面
注意:不习惯使用 storyboard 的同学,可以直接在这里删除storyboard然后在target里面指定VC.个人不太建议这样操作,可以直接在storyboard里指定VC就行了,不用删除,这个TodayViewController就是在storyboard里指定的。
代码
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
lazy var showLabel = {()->UILabel in
let label = UILabel(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 110))
label.text = "Hello World"
label.textAlignment = .center
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
func setUI(){
view.addSubview(showLabel)
}
/*
官方注释:Perform any setup necessary in order to update the view.
个人理解:这个相当于 viewcontroller 的 viewwillappear
因为用户可能会不断的切换负一屏到正常屏,所以可以在这里进行数据的更新
这里需要对 completionHandler 进行 回调
public enum NCUpdateResult : UInt {
case newData 有新数据更新
case noData 没有数据更新
case failed 数据更新失败、出错
}
*/
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
completionHandler(NCUpdateResult.newData)
}
/*
展开收起时会调用,初始化默认调用一次 在 viewdidload 之后 widgetPerformUpdate 之前
*/
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .expanded{//展开 show more
self.preferredContentSize = CGSize.init(width: UIScreen.main.bounds.size.width, height: 200)
}else{//show less
self.preferredContentSize = maxSize
}
}
}
}
运行效果
与主程序的数据通信
这是官方关于APP Extension 与主程序之间的通信流程图,由此图我们可以看到,widget 和 host app 共享一个独立的存储空间,他们之间可以通过
UserDefaults(suiteName: "group.name")
来共享信息 ,也可以通过
if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.name"){
url.appendPathComponent("Library/Caches/widget")
"data".write(to: url, atomically: true, encoding: .utf8)
}
来共享信息,两种方式各有优劣
通过 UserDefaults 方便传输一些碎片型数据,类似于 用户头像地址之类的
通过 Filemanager 更倾向于 文件的读写传输
值得注意的是 ,这里的 group.name 需要开发者在 xcode 中自行配置。
开发者需要在两个target 的 capabilities中App Groups 按照上图操作 像苹果申请相关通信权限
与主程序的资源文件共享
有时候一些功能我们在 主程序中已经开发完成,想在 widget 中使用,这时候你只需要
选中该文件,勾选右边的 membership 就可以了
注意:一些关联第三方的东西 也需要类似操作,从逻辑上来讲,它们是两个程序,并不相同。勾选membership之后xcode会自动编译两份到两个target里
关于 Cocoapods
如果需要,可以利用pod 导入三方库到 Widget 。 修改你的 Podfile
platform :ios, '10.0'
def sharePods
pod 'SDWebImage'
end
target 'xxx' do //xxx为target 名
use_frameworks!
sharePods
end
target 'xxx' do //xxx为target 名
use_frameworks!
sharePods
pod 'MJRefresh'
end
个人不太建议导入太多的三方库,这只是一个插件,导入太多的三方库会导致安装包体积过大
总结
到这里一个widget基本完成了。如有错误请大家多多指正。
网友评论