Advanced

Retrieving and Presenting a Paywall Yourself

Control what happens around a paywall in Flutter with a PaywallPresentationHandler on registerPlacement, since Flutter has no getPaywall.

If you want complete control over the paywall presentation process, you can use getPaywall(forPlacement:params:paywallOverrides:delegate:). This returns the UIViewController subclass PaywallViewController, which you can then present however you like. Or, you can use a SwiftUI View via PaywallView. The following is code is how you'd mimic register:

final class MyViewController: UIViewController {
  private func presentPaywall() async {
    do {
      // 1
  	  let paywallVc = try await Superwall.shared.getPaywall(
        forPlacement: "campaign_trigger",
        delegate: self
      )
   	  self.present(paywallVc, animated: true)
    } catch let skippedReason as PaywallSkippedReason {
      // 2
      switch skippedReason {
       case .holdout,
       .noAudienceMatch,
       .placementNotFound:
         break
       }
    } catch {
      // 3
      print(error)
    }
  }

  private func launchFeature() {
    // Insert code to launch a feature that's behind your paywall.
  }
}

// 4
extension MyViewController: PaywallViewControllerDelegate {
  func paywall(
    _ paywall: PaywallViewController,
    didFinishWith result: PaywallResult,
    shouldDismiss: Bool
  ) {
    if shouldDismiss {
      paywall.dismiss(animated: true)
    }

    switch result {
    case .purchased,
      .restored:
      launchFeature()
    case .declined:
      let closeReason = paywall.info.closeReason
      let featureGating = paywall.info.featureGatingBehavior
      if closeReason != .forNextPaywall && featureGating == .nonGated {
        launchFeature()
      }
    }
  }
}
@interface MyViewController : UIViewController

- (void)presentPaywall;

@end

@interface MyViewController () <SWKPaywallViewControllerDelegate>

@end

@implementation MyViewController

- (void)presentPaywall {
  // 1
  [[Superwall sharedInstance] getPaywallForEvent:@"campaign_trigger" params:nil paywallOverrides:nil delegate:self completion:^(SWKGetPaywallResult * _Nonnull result) {
    if (result.paywall != nil) {
      [self presentViewController:result.paywall animated:YES completion:nil];
    } else if (result.skippedReason != SWKPaywallSkippedReasonNone) {
      switch (result.skippedReason) {
      // 2
        case SWKPaywallSkippedReasonHoldout:
        case SWKPaywallSkippedReasonUserIsSubscribed:
        case SWKPaywallSkippedReasonEventNotFound:
        case SWKPaywallSkippedReasonNoRuleMatch:
        case SWKPaywallSkippedReasonNone:
          break;
      };
    } else if (result.error) {
      // 3
      NSLog(@"%@", result.error);
    }
  }];
}

-(void)launchFeature {
  // Insert code to launch a feature that's behind your paywall.
}

// 4
- (void)paywall:(SWKPaywallViewController *)paywall didFinishWithResult:(enum SWKPaywallResult)result shouldDismiss:(BOOL)shouldDismiss {
  if (shouldDismiss) {
    [paywall dismissViewControllerAnimated:true completion:nil];
  }

  SWKPaywallCloseReason closeReason;
  SWKFeatureGatingBehavior featureGating;

  switch (result) {
  case SWKPaywallResultPurchased:
  case SWKPaywallResultRestored:
    [self launchFeature];
    break;
  case SWKPaywallResultDeclined:
    closeReason = paywall.info.closeReason;
    featureGating = paywall.info.featureGatingBehavior;

    if (closeReason != SWKPaywallCloseReasonForNextPaywall && featureGating == SWKFeatureGatingBehaviorNonGated) {
        [self launchFeature];
    }
    break;
  }
}

@end
import SuperwallKit

struct MyAwesomeApp: App {
  @State var store: AppStore = .init()

  init() {
    Superwall.configure(apiKey: "MyAPIKey")
  }

  var body: some Scene {
    WindowGroup {
      ContentView()
        .fullScreenCover(isPresented: $store.showPaywall) {
          // You can just use 'placement' at a minimum. The 'feature'
          // Closure fires if they convert
          PaywallView(placement: "a_placement", onSkippedView: { skip in
            switch skip {
            case .userIsSubscribed,
              .holdout(_),
              .noRuleMatch,
              .eventNotFound:
                MySkipView()
            }
          }, onErrorView: { error in
            MyErrorView()
          }, feature: {
            // User is subscribed as a result of the paywall purchase
            // Or they already were (which would happen in `onSkippedView`)
          })
        }
    }
  }
}
import androidx.compose.runtime.Composable
import com.superwall.sdk.compose.PaywallComposable
import com.superwall.sdk.paywall.view.delegate.PaywallViewCallback

@Composable
fun EmbeddedPaywall(placement: String, delegate: PaywallViewCallback) {
    PaywallComposable(
        placement = placement,
        delegate = delegate,
    )
}

This does the following:

  1. Gets the paywall view controller.
  2. Handles the cases where the paywall was skipped.
  3. Catches any presentation errors.
  4. Implements the delegate. This is called when the user is finished with the paywall. First, it checks shouldDismiss. If this is true then is dismissed the paywall from view before launching any features. This may depend on the result depending on how you first presented your view. Then, it switches over the result. If the result is purchased or restored the feature can be launched. However, if the result is declined, it checks that the the featureGating property of paywall.info is nonGated and that the closeReason isn't .forNextPaywall.

Use the SDK's PaywallComposable from the com.superwall.sdk:superwall-compose artifact, with the same version as superwall-android. In 2.10.0+, changing placement loads a new paywall and releases the previous view. Host it in an Activity; if none is available, it calls errorComposable rather than crashing. Its default error message is localized. Embedded paywalls can request notification permission and schedule trial reminders through the host Activity.

Best practices

  1. Make sure to prevent a paywall from being accessed after a purchase has occurred.

If a user purchases from a paywall, it is your responsibility to make sure that the user can't access that paywall again. For example, if after successful purchase you decide to push a new view on to the navigation stack, you should make sure that the user can't go back to access the paywall.

  1. Make sure the paywall view controller deallocates before presenting it elsewhere.

If you have a paywall view controller presented somewhere and you try to present the same view controller elsewhere, you will get a crash. For example, you may have a paywall in a tab bar controller, and then you also try to present it modally. We plan on improving this, but currently it's your responsibility to ensure this doesn't happen.

  1. Listening for Loading State Changes.

If you have logic that depends on the progress of the paywall's loading state, you can use the delegate function paywall(_:loadingStateDidChange:). Or, if you have an instance of a PaywallViewController, you can use the published property:

let stateSub = paywall.$loadingState.sink { state in
  print(state)
}

The Expo SDK doesn't have getPaywall. To get a paywall and show it yourself, render the <PaywallView /> component. It retrieves the paywall for a placement and shows it inside your own layout: inline in a screen, as an overlay, or in your own React Native Modal. See PaywallView for all of its props.

The following code shows a paywall in a Modal and mimics register:

import { useState } from "react";
import { Button, Modal, StyleSheet } from "react-native";
import { PaywallView } from "expo-superwall";

export function MyScreen() {
  const [showPaywall, setShowPaywall] = useState(false);

  const launchFeature = () => {
    // Insert code to launch a feature that's behind your paywall.
  };

  return (
    <>
      <Button title="Unlock" onPress={() => setShowPaywall(true)} />

      <Modal
        visible={showPaywall}
        animationType="slide"
        onRequestClose={() => setShowPaywall(false)}
      >
        <PaywallView
          // 1
          placement="campaign_trigger"
          style={styles.paywall}
          // 2
          onSkip={(reason) => {
            switch (reason.type) {
              case "Holdout":
              case "NoAudienceMatch":
              case "PlacementNotFound":
                setShowPaywall(false);
                break;
            }
          }}
          // 3
          onError={(error) => {
            console.log(error);
            setShowPaywall(false);
          }}
          // 4
          onDismiss={(paywallInfo, result, shouldDismiss) => {
            if (shouldDismiss) {
              setShowPaywall(false);
            }

            switch (result.type) {
              case "purchased":
              case "restored":
                launchFeature();
                break;
              case "declined":
                if (
                  paywallInfo.closeReason !== "forNextPaywall" &&
                  paywallInfo.featureGatingBehavior === "nonGated"
                ) {
                  launchFeature();
                }
                break;
            }
          }}
        />
      </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  paywall: { flex: 1 },
});

This does the following:

  1. Retrieves the paywall for the campaign_trigger placement and shows it in the Modal. PaywallView needs a size, so the style gives it flex: 1.
  2. Handles the cases where the paywall was skipped by closing the Modal.
  3. Catches any errors while retrieving or showing the paywall.
  4. Handles the end of the paywall. First, it checks shouldDismiss. If this is true, it closes the Modal before launching any features. Then, it switches over the result. If the result is purchased or restored the feature can be launched. However, if the result is declined, it checks that the featureGatingBehavior of paywallInfo is nonGated and that the closeReason isn't forNextPaywall.

Best practices

  1. Make sure to prevent a paywall from being accessed after a purchase has occurred.

If a user purchases from a paywall, it is your responsibility to make sure that the user can't access that paywall again. For example, if after successful purchase you navigate to a new screen, you should make sure that the user can't go back to the paywall.

  1. Use a different placement for each paywall that's mounted at the same time.

Each mounted PaywallView owns its own native paywall, so unmount it when you no longer need it. If two PaywallView components are on screen at once, such as an inline paywall and a full-screen one, give them different placements.

  1. Show your own UI while the paywall loads.

To show a spinner while the paywall loads, or a message if it fails, pass a renderFallback function. It receives the current state: loading, skipped, error or dismissed. See PaywallView for an example.

The Flutter SDK doesn't have getPaywall or a paywall widget, so you can't retrieve a paywall and show it in your own layout. Superwall always presents the paywall itself when you register a placement.

To control what happens around the paywall, pass a PaywallPresentationHandler to registerPlacement. Its callbacks tell you when the paywall is presented, skipped, dismissed or fails. The following code mimics register with a handler:

Future<void> presentPaywall() async {
  final handler = PaywallPresentationHandler();

  // 1
  handler.onPresent((paywallInfo) {
    print('Presented ${paywallInfo.name}');
  });

  // 2
  handler.onSkip((reason) {
    switch (reason) {
      case PaywallSkippedReasonHoldout():
      case PaywallSkippedReasonNoAudienceMatch():
      case PaywallSkippedReasonPlacementNotFound():
        break;
    }
  });

  // 3
  handler.onError((error) {
    print(error);
  });

  // 4
  handler.onDismiss((paywallInfo, result) {
    switch (result) {
      case PurchasedPaywallResult():
      case RestoredPaywallResult():
        launchFeature();
      case DeclinedPaywallResult():
        if (paywallInfo.closeReason != PaywallCloseReason.forNextPaywall &&
            paywallInfo.featureGatingBehavior == FeatureGatingBehavior.nonGated) {
          launchFeature();
        }
    }
  });

  await Superwall.shared.registerPlacement(
    'campaign_trigger',
    handler: handler,
  );
}

void launchFeature() {
  // Insert code to launch a feature that's behind your paywall.
}

This does the following:

  1. Runs when Superwall presents the paywall.
  2. Handles the cases where the paywall was skipped.
  3. Catches any presentation errors.
  4. Runs when the paywall is dismissed. It switches over the result. If the result is PurchasedPaywallResult or RestoredPaywallResult the feature can be launched. However, if the result is DeclinedPaywallResult, it checks that the featureGatingBehavior of paywallInfo is nonGated and that the closeReason isn't forNextPaywall.

If you only need the feature to run, pass a feature callback to registerPlacement instead. Superwall then runs it based on the paywall's gating mode.

To find out whether a placement would show a paywall without presenting it, use getPresentationResult.

How is this guide?

On this page