iOS Widget

前言

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基本完成了。如有错误请大家多多指正。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容