Skip to content

Toast Plugin: toast doesn't always appear on topmost window. #2538

@rayanuki

Description

@rayanuki

Bug Report

On iOS, Toast notification appears under a new window if you dynamically create a new one

Plugin(s)

Toast

Capacitor Version

💊   Capacitor Doctor  💊 

Latest Dependencies:

  @capacitor/cli: 8.3.4
  @capacitor/core: 8.3.4
  @capacitor/android: 8.3.4
  @capacitor/ios: 8.3.4

Installed Dependencies:

  @capacitor/cli: 8.3.4
  @capacitor/core: 8.3.4
  @capacitor/android: 8.3.4
  @capacitor/ios: 8.3.4

[success] iOS looking great! 👌
[success] Android looking great! 👌

Platform(s)

iOS

Current Behavior

  1. Load root page.
  2. Show Toast
  3. Toast Appears. (GOOD)
  4. Load InAppBrowser plugin
  5. Show Toast.
  6. Toast does not appear (BUG)

Expected Behavior

  1. Load root page.
  2. Show Toast
  3. Toast Appears.
  4. Load InAppBrowser webpage
  5. Show Toast.
  6. Toast SHOULD also appear.

Code Reproduction

  1. Load root page.
  2. Show Toast
  3. Toast Appears. (GOOD)
  4. Load InAppBrowser plugin OR any custom plugin that occupies the entire screen.
  5. Show Toast.
  6. Toast does not appear (BUG)

Other Technical Details

It seems that the bug was caused by this line of code:

viewController.view.addSubview(label)

I maneged to fix it by adding extension UIApplication on Toast.swift:

extension UIApplication {
    var topWindow: UIWindow? {
        if #available(iOS 15.0, *){
            return connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .flatMap{ $0.windows }
                .first{ $0.isKeyWindow }
        }else{
            return keyWindow
        }
    }
}

and editing @objc public class Toast: NSObject

...
DispatchQueue.main.async {
    // define the extension I created
    guard let window = UIApplication.shared.topWindow else { return }
    ...
    // replace: viewController.view.addSubview(label)
    window.addSubview(label);
   ....
}

Code above fixed my issue. Haven't generally tested on all other scenario.

Additional Context

Bug only happens on iOS, unable to replicate on Android or Web

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions