Skip to content

Commit

Permalink
Merge pull request #1054 from bannzai/fix/settings/local_notification
Browse files Browse the repository at this point in the history
Fill settings
  • Loading branch information
bannzai authored Nov 28, 2023
2 parents 2c84041 + 9f98a24 commit dda788f
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 28 deletions.
50 changes: 41 additions & 9 deletions ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import HealthKit
import WidgetKit
import flutter_local_notifications

private var channel: FlutterMethodChannel?
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
private var channel: FlutterMethodChannel?

override func application(
_ application: UIApplication,
Expand Down Expand Up @@ -176,12 +176,12 @@ import flutter_local_notifications
let userConfiguredFamilies = try result.get().map(\.family)
if !userConfiguredFamilies.isEmpty {
if #available(iOS 16.0, *) {
self.analytics(name: "user_configured_ios_widget", parameters: [
analytics(name: "user_configured_ios_widget", parameters: [
"systemSmall": userConfiguredFamilies.contains(.systemSmall),
"accessoryCircular": userConfiguredFamilies.contains(.accessoryCircular)
])
} else {
self.analytics(name: "user_configured_ios_widget", parameters: [
analytics(name: "user_configured_ios_widget", parameters: [
"systemSmall": userConfiguredFamilies.contains(.systemSmall),
])
}
Expand All @@ -196,18 +196,29 @@ import flutter_local_notifications
UNUserNotificationCenter.current().swizzle()
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["repeat_notification_for_taken_pill", "remind_notification_for_taken_pill"])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["repeat_notification_for_taken_pill", "remind_notification_for_taken_pill"])
UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
GeneratedPluginRegistrant.register(with: registry)
}
// NOTE: [LOCAL_NOTIFICATION] Flutter Local NotificationのExamplesではFlutterLocalNotificationsPlugin.setPluginRegistrantCallbackのあとにDelegateをセットしている
// 通知が来ない問題があり再現しないため原因は不明だがこの順番を守る
UNUserNotificationCenter.current().delegate = self

GeneratedPluginRegistrant.register(with: self)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [self] in
// NOTE: [LOCAL_NOTIFICATION] Flutter local notificationの構造体をロギングしている
if let dic = UserDefaults.standard.object(forKey: "flutter_local_notifications_presentation_options") as? [String: Any] {
analytics(name: "fln_debug", parameters: dic)
}
}

return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

private func analytics(name: String, parameters: [String: Any]? = nil, function: StaticString = #function) {
print(function, name, parameters ?? [:])
channel?.invokeMethod("analytics", arguments: ["name": name, "parameters": parameters ?? [:]])
}
}

private func analytics(name: String, parameters: [String: Any]? = nil, function: StaticString = #function) {
print(function, name, parameters ?? [:])
channel?.invokeMethod("analytics", arguments: ["name": name, "parameters": parameters ?? [:]])
}

// MARK: - Avoid bug for flutter app badger
Expand All @@ -230,7 +241,6 @@ extension UNUserNotificationCenter {
}
setNotificationCategories_methodSwizzle(categories)
}

}

// MARK: - Notification
Expand All @@ -253,6 +263,28 @@ extension AppDelegate {
UNUserNotificationCenter.current().setNotificationCategories([category])
}

// NOTE: [LOCAL_NOTIFICATION] async/await版のメソッドは使わない。
// FlutterPluginAppLifeCycleDelegateから呼び出しているのがwithCompletionHandler付きのものなので合わせる
// https://chromium.googlesource.com/external/github.com/flutter/engine/+/refs/heads/flutter-2.5-candidate.8/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm#283

// NOTE: このメソッドをoverrideすることでplugin側の処理は呼ばれないことに注意する。
// 常に一緒な結果をcompletionHandlerで実行すれば良いのでoverrideしても問題はない
override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if #available(iOS 15.0, *) {
analytics(name: "will_present", parameters: ["notification_id" : notification.request.identifier, "content_title": notification.request.content.title, "content_body": notification.request.content.body, "content_interruptionLevel": notification.request.content.interruptionLevel.rawValue])
} else {
// Fallback on earlier versions
}
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { requests in
analytics(name: "pending_notifications", parameters: ["length": requests.count])
})
if #available(iOS 14.0, *) {
completionHandler([.banner, .list, .sound, .badge])
} else {
completionHandler([.alert, .sound, .badge])
}
}

override func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
func end() {
var isCompleted: Bool = false
Expand Down
9 changes: 3 additions & 6 deletions lib/entity/reminder_notification_customization.codegen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@ part 'reminder_notification_customization.codegen.g.dart';
part 'reminder_notification_customization.codegen.freezed.dart';

@freezed
class ReminderNotificationCustomization
with _$ReminderNotificationCustomization {
class ReminderNotificationCustomization with _$ReminderNotificationCustomization {
@JsonSerializable(explicitToJson: true)
const factory ReminderNotificationCustomization({
@Default(pill) String word,
@Default(pillEmoji) String word,
@Default(false) bool isInVisibleReminderDate,
@Default(false) bool isInVisiblePillNumber,
@Default(false) bool isInVisibleDescription,
}) = _ReminderNotificationCustomization;
const ReminderNotificationCustomization._();

factory ReminderNotificationCustomization.fromJson(
Map<String, dynamic> json) =>
_$ReminderNotificationCustomizationFromJson(json);
factory ReminderNotificationCustomization.fromJson(Map<String, dynamic> json) => _$ReminderNotificationCustomizationFromJson(json);
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ class __$$ReminderNotificationCustomizationImplCopyWithImpl<$Res>
class _$ReminderNotificationCustomizationImpl
extends _ReminderNotificationCustomization {
const _$ReminderNotificationCustomizationImpl(
{this.word = pill,
{this.word = pillEmoji,
this.isInVisibleReminderDate = false,
this.isInVisiblePillNumber = false,
this.isInVisibleDescription = false})
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions lib/entrypoint.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ Future<void> entrypoint() async {
setupRemoteConfig(),
).wait;

await localNotificationService.initialize();

// MEMO: FirebaseCrashlytics#recordFlutterError called dumpErrorToConsole in function.
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(ProviderScope(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,17 @@ class ReminderNotificationCustomizeWordPage extends HookConsumerWidget {
style: TextStyle(fontFamily: FontFamily.japanese, fontSize: 12, fontWeight: FontWeight.w400, color: TextColor.darkGray),
),
const Spacer(),
Text(
"${wordState.value.characters.length}/8",
style:
const TextStyle(fontFamily: FontFamily.japanese, fontSize: 12, fontWeight: FontWeight.w400, color: TextColor.darkGray),
),
if (wordState.value.characters.isNotEmpty)
Text(
"${wordState.value.characters.length}/8",
style: const TextStyle(
fontFamily: FontFamily.japanese, fontSize: 12, fontWeight: FontWeight.w400, color: TextColor.darkGray),
),
if (wordState.value.characters.isEmpty)
const Text(
"0文字以上入力してください",
style: TextStyle(fontFamily: FontFamily.japanese, fontSize: 12, fontWeight: FontWeight.w400, color: TextColor.danger),
),
]),
),
autofocus: true,
Expand Down
2 changes: 1 addition & 1 deletion lib/utils/emoji/emoji.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const lockEmoji = "🔒";
const pill = "💊";
const pillEmoji = "💊";
28 changes: 23 additions & 5 deletions lib/utils/local_notification.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,13 @@ class LocalNotificationService {
],
),
],
defaultPresentAlert: true,
// Alertはdeprecatedなので、banner,listをtrueにしておけばよい。
// https://developer.apple.com/documentation/usernotifications/unnotificationpresentationoptions/unnotificationpresentationoptionalert
defaultPresentAlert: false,
defaultPresentBadge: true,
defaultPresentSound: true,
defaultPresentBanner: true,
defaultPresentList: true,
),
),
onDidReceiveBackgroundNotificationResponse: Platform.isAndroid
Expand Down Expand Up @@ -103,8 +107,8 @@ class LocalNotificationService {
),
iOS: DarwinNotificationDetails(
categoryIdentifier: iOSQuickRecordPillCategoryIdentifier,
presentBadge: true,
sound: "becho.caf",
presentBadge: true,
presentSound: true,
),
),
Expand Down Expand Up @@ -361,6 +365,10 @@ class RegisterReminderLocalNotification {
if (Environment.isDevelopment) {
result += " Local";
}
// NOTE: 0文字以上じゃないと通知が表示されない。フロントでバリデーションをかけていてもここだけは残す
if (result.isEmpty) {
return "通知です";
}
return result;
}();
debugPrint("title:$title");
Expand Down Expand Up @@ -390,9 +398,14 @@ class RegisterReminderLocalNotification {
),
iOS: DarwinNotificationDetails(
categoryIdentifier: iOSQuickRecordPillCategoryIdentifier,
presentBadge: true,
sound: "becho.caf",
presentBadge: true,
presentSound: true,
// Alertはdeprecatedなので、banner,listをtrueにしておけばよい。
// https://developer.apple.com/documentation/usernotifications/unnotificationpresentationoptions/unnotificationpresentationoptionalert
presentAlert: false,
presentBanner: true,
presentList: true,
badgeNumber: badgeNumber + dayOffset,
),
),
Expand Down Expand Up @@ -439,9 +452,14 @@ class RegisterReminderLocalNotification {
category: AndroidNotificationCategory.alarm,
),
iOS: DarwinNotificationDetails(
presentBadge: true,
sound: "becho.caf",
presentBadge: true,
presentSound: true,
// Alertはdeprecatedなので、banner,listをtrueにしておけばよい。
// https://developer.apple.com/documentation/usernotifications/unnotificationpresentationoptions/unnotificationpresentationoptionalert
presentAlert: false,
presentBanner: true,
presentList: true,
badgeNumber: badgeNumber + dayOffset,
),
),
Expand Down Expand Up @@ -552,4 +570,4 @@ extension ScheduleLocalNotificationService on LocalNotificationService {
}
}

var localNotificationService = LocalNotificationService()..initialize();
var localNotificationService = LocalNotificationService();

0 comments on commit dda788f

Please sign in to comment.