Skip to content

Comments

Fix registration lifecycle and simplify API#14

Merged
mlaucis merged 6 commits intomainfrom
fix-registration-lifecycle
Jun 17, 2025
Merged

Fix registration lifecycle and simplify API#14
mlaucis merged 6 commits intomainfrom
fix-registration-lifecycle

Conversation

@mlaucis
Copy link
Member

@mlaucis mlaucis commented Jun 17, 2025

Fix registration lifecycle for delayed registration scenarios and simplify API by using getter pattern for device token access.

  • Add permission checking without prompting for consistent registration
  • Change initialize() and registerDevice() to return Future
  • Use PntaFlutter.deviceToken getter to access token
  • Remove metadata parameter from registerDevice()
  • Update documentation and examples

mlaucis added 3 commits June 17, 2025 10:56
- Add checkNotificationPermission method to check permissions without prompting
- Initialize now always registers device when permissions are already granted
- Simplify registerDevice API to remove metadata parameter
- Ensure consistent device registration across app restarts
- Remove metadata parameter from registerDevice - uses initialize metadata
- Update README examples to show proper usage pattern
- Simplify permission checking logic with ternary operator
- Change initialize() and registerDevice() to return Future<void>
- Use PntaFlutter.deviceToken getter to access token when needed
- Update all examples and documentation to use getter pattern
- Align with existing getter pattern for projectId and currentMetadata
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added the ability to check notification permission status on both Android and iOS without prompting the user.
  • Documentation
    • Updated guides and examples to reflect changes in how device tokens are accessed and how device registration is handled.
  • Refactor
    • Changed initialization and device registration methods to no longer return the device token; the token is now accessed via a static property after completion.
  • Tests
    • Enhanced test coverage to include notification permission status checks.

Summary by CodeRabbit

  • New Features
    • Added the ability to check notification permission status on both Android and iOS without prompting the user.
  • Documentation
    • Updated guides and examples to reflect changes in how the device token is accessed after initialization and registration.
  • Refactor
    • Changed initialization and registration methods to no longer return the device token directly; the token is now accessed via a static property.

Walkthrough

This update changes the return types of the initialize and registerDevice methods in the Flutter plugin from returning a device token (Future<String?>) to returning Future<void>. Device tokens are now accessed through a static getter. Additionally, a new method for checking notification permission status without prompting the user was added to both Android and iOS implementations and exposed through the Dart API. Documentation and example code were updated to reflect these changes.

Changes

File(s) Change Summary
README.md Updated documentation and code samples to reflect new initialization, registration, and device token access APIs.
example/lib/main.dart Updated example to use new static device token getter and revised initialization logic.
lib/pnta_flutter.dart Changed initialize and registerDevice to return Future<void>, updated registration logic, removed token returns.
lib/pnta_flutter_method_channel.dart Added checkNotificationPermission method to query notification permission status via platform channel.
lib/pnta_flutter_platform_interface.dart Added abstract checkNotificationPermission method to platform interface.
android/src/main/kotlin/io/pnta/pnta_flutter/PermissionHandler.kt Added checkNotificationPermission method to check notification permission synchronously.
android/src/main/kotlin/io/pnta/pnta_flutter/PntaFlutterPlugin.kt Added method channel handler for "checkNotificationPermission".
ios/Classes/PermissionHandler.swift Added static checkNotificationPermission method for iOS notification permission status.
ios/Classes/PntaFlutterPlugin.swift Added method channel handler for "checkNotificationPermission".
test/pnta_flutter_test.dart Added mock implementation of checkNotificationPermission returning true.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant PntaFlutter (Dart)
    participant PlatformChannel
    participant Native (Android/iOS)

    App->>PntaFlutter (Dart): initialize(projectId, ...)
    PntaFlutter (Dart)->>PlatformChannel: checkNotificationPermission()
    PlatformChannel->>Native (Android/iOS): checkNotificationPermission
    Native (Android/iOS)-->>PlatformChannel: permissionGranted (bool)
    PlatformChannel-->>PntaFlutter (Dart): permissionGranted (bool)
    alt permissionGranted and registerDevice
        PntaFlutter (Dart)->>PlatformChannel: registerDevice
        PlatformChannel->>Native (Android/iOS): registerDevice
        Native (Android/iOS)-->>PlatformChannel: (no return value)
        PlatformChannel-->>PntaFlutter (Dart): (void)
    else permission not granted and registerDevice
        PntaFlutter (Dart)->>PlatformChannel: requestNotificationPermission
        PlatformChannel->>Native (Android/iOS): requestNotificationPermission
        Native (Android/iOS)-->>PlatformChannel: permissionGranted (bool)
        PlatformChannel-->>PntaFlutter (Dart): permissionGranted (bool)
        alt permissionGranted
            PntaFlutter (Dart)->>PlatformChannel: registerDevice
            PlatformChannel->>Native (Android/iOS): registerDevice
            Native (Android/iOS)-->>PlatformChannel: (void)
            PlatformChannel-->>PntaFlutter (Dart): (void)
        else permission not granted
            PntaFlutter (Dart)-->>App: (void)
        end
    end
    PntaFlutter (Dart)-->>App: (void)
    App->>PntaFlutter (Dart): access deviceToken (static getter)
Loading

Possibly related PRs

  • pnta-io/pnta-flutter-plugin#13: Refactors and renames registration and permission methods, overlapping with the current PR's method changes but retaining device token return values, indicating related API evolution.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 400b4e9 and a0c4eb0.

📒 Files selected for processing (1)
  • ios/Classes/PermissionHandler.swift (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ios/Classes/PermissionHandler.swift
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (5)
lib/pnta_flutter_platform_interface.dart (1)

31-34: Document the new API surface

checkNotificationPermission() is public surface; add a short Dart-doc that clarifies how it differs from requestNotificationPermission() (no prompt, immediate status). This avoids ambiguity for plugin integrators and keeps the interface self-describing.

-  Future<bool> checkNotificationPermission() {
+  /// Returns `true` if the user has already granted notification permission
+  /// without displaying any system prompt.  
+  ///
+  /// Use this when you merely need the current status and do **not** want to
+  /// disturb the user with a permission dialog.
+  Future<bool> checkNotificationPermission() {
lib/pnta_flutter_method_channel.dart (1)

28-34: Graceful handling of unimplemented platforms

The method currently defaults to false when the platform doesn’t implement 'checkNotificationPermission'. This is fine, but consider surfacing a warning (e.g. debugPrint) so integrators know the feature is missing on their target platform rather than silently assuming “denied”.

-    final result =
-        await methodChannel.invokeMethod<bool>('checkNotificationPermission');
-    return result ?? false;
+    final result =
+        await methodChannel.invokeMethod<bool>('checkNotificationPermission');
+    if (result == null) {
+      debugPrint('[PNTA] checkNotificationPermission not implemented on this platform.');
+    }
+    return result ?? false;
android/src/main/kotlin/io/pnta/pnta_flutter/PermissionHandler.kt (1)

32-44: Drop hard Activity requirement for a read-only permission query

For a simple permission check you only need a Context; insisting on a non-null Activity forces callers to be in the foreground and breaks use-cases such as background initialisation.

-fun checkNotificationPermission(activity: Activity?, result: Result) {
+fun checkNotificationPermission(context: Context, result: Result) {
     if (Build.VERSION.SDK_INT >= 33) {
-        if (activity == null) {
-            result.error("NO_ACTIVITY", "Activity is null", null)
-            return
-        }
-        val granted = ContextCompat.checkSelfPermission(activity,
+        val granted = ContextCompat.checkSelfPermission(context,
                 android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
         result.success(granted)

Overload a second function (or make Activity nullable) for the existing request-permission path to keep API compatibility.

README.md (1)

350-356: Out-of-date example uses removed requestPermission API

requestPermission() no longer exists. Replace the commented snippet with the new
await PntaFlutter.registerDevice(); call (or remove it entirely) to avoid confusing readers.

lib/pnta_flutter.dart (1)

131-137: Minor: avoid duplicate permission queries inside _performRegistration

When skipPrompt is true, _performRegistration calls checkNotificationPermission() a second time even though the caller already confirmed it. Pass the result in as a parameter or guard the extra call to save an unnecessary platform hop.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 05c6b93 and f3ada51.

📒 Files selected for processing (9)
  • README.md (4 hunks)
  • android/src/main/kotlin/io/pnta/pnta_flutter/PermissionHandler.kt (1 hunks)
  • android/src/main/kotlin/io/pnta/pnta_flutter/PntaFlutterPlugin.kt (1 hunks)
  • example/lib/main.dart (2 hunks)
  • ios/Classes/PermissionHandler.swift (1 hunks)
  • ios/Classes/PntaFlutterPlugin.swift (1 hunks)
  • lib/pnta_flutter.dart (4 hunks)
  • lib/pnta_flutter_method_channel.dart (1 hunks)
  • lib/pnta_flutter_platform_interface.dart (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
ios/Classes/PermissionHandler.swift (1)
android/src/main/kotlin/io/pnta/pnta_flutter/PermissionHandler.kt (1)
  • checkNotificationPermission (32-44)
ios/Classes/PntaFlutterPlugin.swift (1)
ios/Classes/PermissionHandler.swift (1)
  • checkNotificationPermission (19-31)
🔇 Additional comments (2)
ios/Classes/PntaFlutterPlugin.swift (1)

20-22: iOS branch looks good

New switch case correctly delegates to the native permission handler and returns asynchronously. No issues spotted.

example/lib/main.dart (1)

52-65: Potential race: token may still be null

PntaFlutter.deviceToken is read immediately after initialize().
On a freshly-installed app the token is usually delivered asynchronously (APNs/Firebase callback), so _deviceToken may remain null even when permission is granted.

Consider awaiting registerDevice() (if that’s still required) or listening to a dedicated token stream/callback before updating UI.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
test/pnta_flutter_test.dart (1)

13-15: Add a dedicated unit-test for the new checkNotificationPermission API

The mock correctly stubs checkNotificationPermission, but there is no test that exercises the new public-facing Dart API. Without a test, regressions in the platform channel wiring (e.g. wrong method name or return type) could slip through unnoticed.

@@ void main() {
   test('deviceToken getter', () async {
     ...
   });

+  test('checkNotificationPermission returns true', () async {
+    final fakePlatform = MockPntaFlutterPlatform();
+    PntaFlutterPlatform.instance = fakePlatform;
+
+    final hasPermission = await PntaFlutter.checkNotificationPermission();
+    expect(hasPermission, isTrue);
+  });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1572e14 and 400b4e9.

📒 Files selected for processing (1)
  • test/pnta_flutter_test.dart (1 hunks)

…states

- Add support for .provisional and .ephemeral notification statuses
- Ensure main thread dispatch consistency for pre-iOS 10 branch
- All notification-capable permission states now properly detected
@mlaucis mlaucis merged commit cb9284a into main Jun 17, 2025
2 checks passed
@mlaucis mlaucis deleted the fix-registration-lifecycle branch June 17, 2025 09:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant