Share
Embed
CLでのウィジェット開発から得た知見集
こちらのイベントで発表した資料になります。
CA.swift #19 〜新規開発の技術選定〜
https://cyberagent.connpass.com/event/307949/
【プロフィール】
下村 一将 | CL
GitHub : s2mr X : @_kzumu
2019年にサイバーエージェント新卒入社してからずっとCLのiOSエンジニアをしています。 現在はiOSチームのリーダーとして開発基盤の刷新から施策の実装まで幅広く担当しています。 趣味は個人開発です。
Kazumasa Shimomura
April 15, 2024
Transcript
43 slides
-
簡単に自己紹介 下村一将 (Kazumasa Shimomura / かず) CyberAgent 2019年新卒入社 入社時からCL事業部に所属 4月からCL
iOSチームリーダーに SNS X: _kzumu GitHub: s2mr 2 -
ウィジェットの定義例 @available(iOSApplicationExtension 17.0, *) struct SmallWidget: Widget { let kind:
String = "SmallWidget" init() { UIFont.loadCLSansBoldFont() } var body: some WidgetConfiguration { AppIntentConfiguration( kind: kind, provider: WidgetTimelineProvider<SmallWidgetConfigIntent>(dependency: .default()) ) { entry in WidgetRootView( entry: entry, widgetURLResolver: WidgetURLResolver(baseURL: URL.service), imageDownloader: nil ) } .configurationDisplayName(Text(L10n.Widget.displayName)) .description(Text(L10n.Widget.Description.small)) .supportedFamilies([.systemSmall]) } } 今回は仕様の都合上サイズごとにWidgetを定義していますが、機能ごとにWidgetを宣言して まとめてサイズを定義することも可能です。 12 -
ウィジェット実装上の制約 リロード回数の制約 ユーザーが頻繁に確認するウィジェットの場合、通常、1日単位のバジェットに40〜70 回の更新が含まれます。この割合は、概算で15〜60分おきにウィジェットが再読み込み されることを意味しますが、一般的に、関連する多くの要因によってこの間隔は変化し ます。 https://developer.apple.com/jp/documentation/widgetkit/keeping-a-widget-up-to-date 30MBのメモリ制限 重い画像やデータの扱いには注意する。 重い処理でも制限に達することも。
CLでもこの問題に当たったので後述。 ウィジェット実装上の制約 13 -
異なるBundleID間でのデータの共有 Widget側からアプリ側のデータは参照できないので、AppGroup, Keychain Sharingを使用し てデータにアクセスする必要がある。 ファイルの共有に関してはAppGroupを使用する UserDefaults, CoreData FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "yourAppGroupIdentifier")
Keychainの共有に関してはKeychain Sharingの方式を選択 // KeychainAccess の場合 Keychain(service: "ServiceName") ウィジェット実装上の制約 14 -
状態別の出し分け実装例(Data) public enum WidgetTimelineData: Equatable, Sendable { /// 使い方紹介 case
usage(UsageWidgetView.Mode) /// 日付 case date(DateWidgetDataSet) /// コミュニティ case community(CommunityWidgetDataSet) /// 読み込み中 case placeholder /// エラー case error(ErrorMessagePattern) } 実装のアプローチ 17 -
状態別の出し分け実装例(View) public struct WidgetRootView: View { public var entry: WidgetTimelineEntry
public var widgetURLResolver: WidgetURLResolverProtocol public var imageDownloader: ImageDownloadable? public init(...) { ... } public var body: some View { switchWidgetView() .environment(\.colorScheme, entry.selectedColorScheme) } @ViewBuilder private func switchWidgetView() -> some View { switch entry.data { case .usage(let mode): UsageWidgetView(mode: mode) case .date(let dataSet): DateWidgetView(dataSet: dataSet, imageDownloader: imageDownloader) case .community(let dataSet): CommunityWidgetView(dataSet: dataSet, imageDownloader: imageDownloader) } } } 実装のアプローチ 18 -
再掲 WidgetTimelineProvider内で表示したいデータを含むentryを返却さえすれば、任意のViewが 簡単に表示できる @available(iOSApplicationExtension 17.0, *) struct SmallWidget: Widget {
let kind: String = "SmallWidget" init() { UIFont.loadCLSansBoldFont() } var body: some WidgetConfiguration { AppIntentConfiguration( kind: kind, provider: WidgetTimelineProvider<SmallWidgetConfigIntent>(dependency: .default()) ) { entry in WidgetRootView( entry: entry, widgetURLResolver: WidgetURLResolver(baseURL: URL.service), imageDownloader: nil ) } .configurationDisplayName(Text(L10n.Widget.displayName)) .description(Text(L10n.Widget.Description.small)) .supportedFamilies([.systemSmall]) } } 実装のアプローチ 19 -
@available(iOSApplicationExtension 17.0, *) struct WidgetTimelineProvider<I: WidgetIntentProtocol>: AppIntentTimelineProvider { struct Dependency
{ var timelineProviderSwitcher: TimelineProviderSwitcher var dateGenerator: DateGenerator static func `default`() -> Dependency { Dependency( timelineProviderSwitcher: TimelineProviderSwitcher(...), dateGenerator: CurrentDateGenerator() ) } } private let dependency: Dependency func placeholder(in _: Context) -> WidgetTimelineEntry { dependency.timelineProviderSwitcher.placeholder() } func timeline(for configuration: Intent, in context: Context) async -> Timeline<WidgetTimelineEntry> { ... } func snapshot(for configuration: Intent, in context: Context) async -> WidgetTimelineEntry { guard let userWidget = configuration.widgetSelection?.userWidget else { return WidgetTimelineEntry( date: dependency.dateGenerator.date, data: .usage(context.isPreview ? .gallery : .home), selectedColorScheme: .light ) } return await dependency.timelineProviderSwitcher.snapshot(for: userWidget, context: context) } } 実装のアプローチ 21 -
public struct TimelineProviderSwitcher { // Widget の種類ごとのデータ読み込みを行うstruct private let dateTimelineProvider:
DateTimelineProvider private let communityTimelineProvider: CommunityTimelineProvider private let batteryTimelineProvider: BatteryTimelineProvider public init( ... ) { ... } public func placeholder() -> WidgetTimelineEntry { ... } public func getTimeline(for userWidget: UserWidget, context: TimelineProviderContextProtocol) async -> Timeline<WidgetTimelineEntry> { ... } public func snapshot(for userWidget: UserWidget, context: TimelineProviderContextProtocol) async -> WidgetTimelineEntry { switch userWidget.widgetType { case .date: return await dateTimelineProvider.getSnapshot(for: userWidget, context: context) case .community: return await communityTimelineProvider.getSnapshot(for: userWidget, context: context) case .battery: return await batteryTimelineProvider.getSnapshot(for: userWidget, context: context) case .unknown: return WidgetTimelineEntry(date: Date(), data: .placeholder, selectedColorScheme: .dark) } } } 実装のアプローチ 22 -
プラクティス2:メモリの30MB制限と、ピクセル総数によるバリデー ション ユーザーが画像を設定できるタイプのウィジェットで遭遇 シミュレータに入っているデフォの画像だと発生せず、物理端末で撮影した画像だと発 生。 問題発生までのフロー 1. ユーザーがウィジェット作成時に画像を設定して、画像を1MBのjpegに圧縮したものを AppGroup内のディレクトリに保存。 2.
ウィジェットを配置しても、読み込み中のままでしばらく待っても何も表示されない 3. クラッシュしていた 技術的知見とプラクティス 25 -
問題の解決まで 1. Console.appでデバッグ 2. エラーを見つける Widget archival failed due to
image being too large [9] - (2848, 2846), totalArea: 8105408 > max[5193849.600000] Request ended for SmallWidget:systemSmall:148558229597663593 - error: WidgetKit.WidgetArchiver.ArchivingError.imageTooLarge(size: (2848.0, 2846.0), maximumSize: (1548.0, 3355.2)) 設定された画像がピクセル総数、ピクセル数のシステム制限に引っかかっている。 (おそらくundocumented) 3. maximumSizeの記載があるので引っかからないようにすれば良さそう 技術的知見とプラクティス 26 -
4. 表示前に、WidgetTimelineProviderの中でリサイズしてみる。 CLだとNukeを使用して画像読み込みをしているので、Nukeで用意された ImageProcessors.Resize を使用してみる。 5. クラッシュ kernel EXC_RESOURCE ->
CyberLDHWidget[77604] exceeded mem limit: InactiveHard 30 MB (fatal) 今度はメモリ制限30MBに達してしまった。 確かに十分大きい元画像がメモリに乗った状態で、新たな小さい画像を作ろうとし ても画像2枚分のメモリを食うし、画像処理にもメモリを食いそう。 技術的知見とプラクティス 27 -
6. 別のアプローチとして、省メモリな画像リサイズの方法を試してみる。 https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/ このサイトによると... Memory Usage ≠ File Size Memory
use is related to the dimensions of the image, not the file size. Typically, 1 pixel of a decoded image will take up 4 bytes of memory — 1 byte for red, 1 byte for green, 1 byte for blue, and 1 byte for the alpha component. (3648 * 5472) * 4 bytes ≈ 80MB CLの例だと、正方形にトリミングして保存していたため (2848 * 2846) * 4 bytes ≈ 30.9MB 惜しい!だから成功する場合としない場合があったのか... 技術的知見とプラクティス 28 -
func downloadWidgetImage( with url: URL?, size: ImageSize? = nil, context:
TimelineProviderContextProtocol ) async -> UIImage? { guard let url else { return await downloadImage(with: url, size: size) } let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, imageSourceOptions) else { return nil } let displayScale = context.displayScale ?? 1 let maxDimensionInPixels = min(context.displaySize.width, context.displaySize.height) * displayScale * 0.7 let downsampleOptions = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels ] as CFDictionary guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil } return UIImage(cgImage: downsampledImage) } 技術的知見とプラクティス 30 -
// WidgetEditorContent.swift private func makeFormSection() -> some View { VStack(alignment:
.leading, spacing: 32) { WidgetNameForm(widgetName: .init( get: { dataModel.editorParameter.widgetName }, set: { event(.setWidgetName($0)) } )) if let parameter = dataModel.editorParameter as? HasWidgetArtistDestination { ArtistDestinationForm( selectedArtist: dataModel.cachedArtists[parameter.destinationArtistID], changeButtonSelected: { event(.selectChangeArtistDestination) } ) } if let parameter = dataModel.editorParameter as? HasWidgetBackgroundStyle { BackgroundStyleSelectionForm( selectedBackgroundStyle: parameter.backgroundStyle ) { style in event(.selectWidgetBackgroundStyle(style)) } } ... } } 実装上の挑戦と解決策 38 -
public protocol HasWidgetBackgroundStyle { var backgroundStyle: WidgetBackgroundStyle { get set
} } public extension HasWidgetBackgroundStyle { func isBackgroundStyleValid() -> Bool { backgroundStyle != .unknown } } 実装上の挑戦と解決策 39 -
public struct WidgetEditorCastParameter: WidgetEditorParameterProtocol & HasWidgetBackgroundStyle { public static let
widgetType = WidgetType.cast public static func makeForCreate() -> Self { Self(widgetName: "", backgroundStyle: .dark) } public static func makeForEdit(userWidget: UserWidget) -> Self? { guard let castWidget = userWidget.castWidget else { return nil } return Self( widgetName: userWidget.name, backgroundStyle: castWidget.backgroundStyle ) } public var widgetName: String public var backgroundStyle: WidgetBackgroundStyle public init(...) { ... } public func isParameterValid() -> Bool { isWidgetNameValid() && isBackgroundStyleValid() } } 実装上の挑戦と解決策 40 -
インスタンスとファイルのライフサイクルの一致で状態不整合を減らせる public final class TemporaryFile { public let url: URL
private let fileManager: FileManagerProtocol public init(url: URL, fileManager: FileManagerProtocol) { self.url = url self.fileManager = fileManager } deinit { do { guard fileManager.fileExists(atPath: url.path) else { return Log.info("Already file deleted. at: " + url.path) } try fileManager.removeItem(at: url) Log.info("Temporary file deleted. at: " + url.path) } catch { Log.error(error) } } } 実装上の挑戦と解決策 42