Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

move more to store manager

rorycleardc661c0f6852
diff --git a/ios/clearcam/SettingsViewController.m b/ios/clearcam/SettingsViewController.m
index 7a6df48..f80cbbf 100644
--- a/ios/clearcam/SettingsViewController.m
+++ b/ios/clearcam/SettingsViewController.m
@@ -252,7 +252,7 @@
self.liveStreamInternetEnabled = NO;
[defaults setBool:NO forKey:@"live_stream_internet_enabled"];
[defaults synchronize];
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
}
}
@@ -830,14 +830,14 @@
[self showThresholdInputDialog];
} else if (indexPath.row == 5 + offset) {
if (!isPremium) {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
}
} else if (indexPath.row == 6 + offset) {
if (isPremium) {
[self promptForPasswordWithCompletion:^(BOOL success) {
}];
} else {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
}
} else if (indexPath.row == 7 + offset) {
ScheduleManagementViewController *scheduleVC = [[ScheduleManagementViewController alloc] init];
@@ -855,19 +855,19 @@
} else if (indexPath.section == 1) { // Live Stream Settings
if (indexPath.row == 0) {
if (!isPremium) {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
} // Switch handles toggle when premium
} else if (indexPath.row == 1) {
if (isPremium) {
[self showDeviceNameInputDialog];
} else {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
}
}
} else if (indexPath.section == 2) { // Viewer Settings
if (indexPath.row == 0) {
if (!isPremium) {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
} // Switch handles toggle when premium
}
} else if (indexPath.section == 3) { // Advanced Settings
@@ -875,14 +875,16 @@
} else if (indexPath.section == 4) { // Upgrade to Premium / Subscription
BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];
if (!isSubscribed && indexPath.row == 0) {
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
} else if ((isSubscribed && indexPath.row == 0) || (!isSubscribed && indexPath.row == 1)) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"restoring_purchases_title", @"Title for restoring purchases alert")
message:NSLocalizedString(@"restoring_purchases_message", @"Message for restoring purchases alert")
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
- [[StoreManager sharedInstance] restorePurchases];
+ [[StoreManager sharedInstance] restorePurchasesWithCompletion:^(BOOL success) {
+ [self.tableView reloadData];
+ }];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:nil];
@@ -922,154 +924,6 @@
}
}
-- (void)showUpgradePopup {
- [[StoreManager sharedInstance] getPremiumProductInfo:^(SKProduct * _Nullable product, NSError * _Nullable error) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (!product) {
- NSLog(@"Error fetching product info: %@", error.localizedDescription);
- return;
- }
-
- // Format price
- NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
- [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
- [formatter setLocale:product.priceLocale];
- NSString *localizedPrice = [formatter stringFromNumber:product.price] ?: NSLocalizedString(@"price_unknown", @"Fallback for unknown price");
-
- // Detect dark mode
- BOOL isDarkMode = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
- UIColor *cardBackground = isDarkMode ? [UIColor colorWithWhite:0.1 alpha:1.0] : [UIColor colorWithWhite:1.0 alpha:1.0];
- UIColor *textColor = isDarkMode ? UIColor.whiteColor : UIColor.blackColor;
-
- // Overlay
- UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
- overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
- overlay.tag = 999;
- [self.view addSubview:overlay];
-
- // Card
- UIView *card = [[UIView alloc] init];
- card.translatesAutoresizingMaskIntoConstraints = NO;
- card.backgroundColor = cardBackground;
- card.layer.cornerRadius = 20;
- card.clipsToBounds = YES;
- [overlay addSubview:card];
-
- // Title
- UILabel *title = [[UILabel alloc] init];
- title.translatesAutoresizingMaskIntoConstraints = NO;
- title.text = NSLocalizedString(@"get_premium_title", @"Title for premium upgrade popup");
- title.textColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0]; // gold
- title.font = [UIFont boldSystemFontOfSize:24];
- title.textAlignment = NSTextAlignmentCenter;
-
- // Features
- UIStackView *featureStack = [[UIStackView alloc] init];
- featureStack.translatesAutoresizingMaskIntoConstraints = NO;
- featureStack.axis = UILayoutConstraintAxisVertical;
- featureStack.spacing = 8;
-
- NSArray *features = @[
- NSLocalizedString(@"premium_feature_1", @"Feature 1 description for premium"),
- NSLocalizedString(@"premium_feature_2", @"Feature 2 description for premium"),
- NSLocalizedString(@"premium_feature_3", @"Feature 3 description for premium"),
- NSLocalizedString(@"premium_feature_4", @"Feature 4 description for premium")
- ];
-
- for (NSString *item in features) {
- UILabel *label = [[UILabel alloc] init];
- label.text = [NSString stringWithFormat:@"• %@", item];
- label.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
- label.textColor = textColor;
- label.numberOfLines = 0;
- [featureStack addArrangedSubview:label];
- }
-
- // Upgrade button
- UIButton *upgradeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
- upgradeBtn.translatesAutoresizingMaskIntoConstraints = NO;
-
- NSString *line1 = NSLocalizedString(@"1 week free trial", @"Free trial label");
- NSString *line2 = [NSString stringWithFormat:NSLocalizedString(@"upgrade_button", @"Subscription price after trial"), localizedPrice];
- NSString *fullText = [NSString stringWithFormat:@"%@\n%@", line1, line2];
-
- NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
- paragraphStyle.alignment = NSTextAlignmentCenter;
-
- NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:fullText attributes:@{
- NSParagraphStyleAttributeName: paragraphStyle,
- NSForegroundColorAttributeName: UIColor.blackColor
- }];
-
- NSRange line1Range = [fullText rangeOfString:line1];
- [attributedTitle addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:line1Range];
-
- NSRange line2Range = [fullText rangeOfString:line2];
- [attributedTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:line2Range];
-
- [upgradeBtn setAttributedTitle:attributedTitle forState:UIControlStateNormal];
- upgradeBtn.titleLabel.numberOfLines = 2;
- upgradeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
- upgradeBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0];
- upgradeBtn.layer.cornerRadius = 12;
- [upgradeBtn addTarget:self action:@selector(handleUpgradeTap) forControlEvents:UIControlEventTouchUpInside];
-
-
- // Cancel button
- UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
- cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
- [cancelBtn setTitle:NSLocalizedString(@"not_now", @"Not now button") forState:UIControlStateNormal];
- [cancelBtn setTitleColor:textColor forState:UIControlStateNormal];
- cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
- [cancelBtn addTarget:self action:@selector(dismissUpgradePopup) forControlEvents:UIControlEventTouchUpInside];
-
- // Disclaimer label
- UILabel *disclaimer = [[UILabel alloc] init];
- disclaimer.translatesAutoresizingMaskIntoConstraints = NO;
- disclaimer.text = NSLocalizedString(@"premium_disclaimer", @"Disclaimer for premium subscription limits");
- disclaimer.font = [UIFont systemFontOfSize:13];
- disclaimer.textColor = [textColor colorWithAlphaComponent:0.6];
- disclaimer.numberOfLines = 0;
- disclaimer.textAlignment = NSTextAlignmentCenter;
-
- // Add all to card
- [card addSubview:title];
- [card addSubview:featureStack];
- [card addSubview:upgradeBtn];
- [card addSubview:cancelBtn];
- [card addSubview:disclaimer];
-
- // Constraints
- [NSLayoutConstraint activateConstraints:@[
- [card.centerXAnchor constraintEqualToAnchor:overlay.centerXAnchor],
- [card.centerYAnchor constraintEqualToAnchor:overlay.centerYAnchor],
- [card.widthAnchor constraintEqualToConstant:320],
-
- [title.topAnchor constraintEqualToAnchor:card.topAnchor constant:24],
- [title.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
- [title.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
-
- [featureStack.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:20],
- [featureStack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
- [featureStack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
-
- [upgradeBtn.topAnchor constraintEqualToAnchor:featureStack.bottomAnchor constant:24],
- [upgradeBtn.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
- [upgradeBtn.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
- [upgradeBtn.heightAnchor constraintEqualToConstant:48],
-
- [cancelBtn.topAnchor constraintEqualToAnchor:upgradeBtn.bottomAnchor constant:16],
- [cancelBtn.centerXAnchor constraintEqualToAnchor:card.centerXAnchor],
-
- [disclaimer.topAnchor constraintEqualToAnchor:cancelBtn.bottomAnchor constant:14],
- [disclaimer.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
- [disclaimer.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
- [disclaimer.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-20]
- ]];
- });
- }];
-}
-
- (void)handleUpgradeTap {
// Create and show a loading spinner
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
@@ -1225,7 +1079,7 @@
self.sendNotifEnabled = NO;
[defaults setBool:NO forKey:@"send_notif_enabled"];
[defaults synchronize];
- [self showUpgradePopup];
+ [[StoreManager sharedInstance] showUpgradePopupInViewController:self];
}
}
diff --git a/ios/clearcam/StoreManager.h b/ios/clearcam/StoreManager.h
index 173f144..9a14310 100644
--- a/ios/clearcam/StoreManager.h
+++ b/ios/clearcam/StoreManager.h
@@ -1,4 +1,5 @@
#import <StoreKit/StoreKit.h>
+#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@@ -7,17 +8,22 @@ extern NSString *const StoreManagerSubscriptionStatusDidChangeNotification;
@interface StoreManager : NSObject <SKProductsRequestDelegate, SKPaymentTransactionObserver>
@property (nonatomic, assign) NSTimeInterval last_check_time;
+@property (nonatomic, strong) SKProduct *premiumProduct;
+ (instancetype)sharedInstance;
-
-- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion;
+- (BOOL)isUserSubscribed;
- (void)verifySubscriptionWithCompletion:(void (^)(BOOL isActive, NSDate * _Nullable expiryDate))completion;
- (void)verifySubscriptionWithCompletionIfSubbed:(void (^)(BOOL isActive, NSDate * _Nullable expiryDate))completion;
-- (NSString *)retrieveSessionTokenFromKeychain;
+- (void)showUpgradePopupInViewController:(UIViewController *)presentingVC
+ darkMode:(BOOL)isDarkMode
+ completion:(void (^)(BOOL success))completion;
+- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion;
+- (void)restorePurchasesWithCompletion:(void (^)(BOOL success))completion;
- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion;
-- (void)restorePurchases;
+- (NSString *)retrieveSessionTokenFromKeychain;
- (void)storeSessionTokenInKeychain:(NSString *)sessionToken;
- (void)clearSessionTokenFromKeychain;
+- (void)showUpgradePopupInViewController:(UIViewController *)presentingVC;
@end
diff --git a/ios/clearcam/StoreManager.m b/ios/clearcam/StoreManager.m
index eaacb65..b2aa757 100644
--- a/ios/clearcam/StoreManager.m
+++ b/ios/clearcam/StoreManager.m
@@ -1,26 +1,21 @@
#import "StoreManager.h"
#import "FileServer.h"
#import <StoreKit/StoreKit.h>
+#import <objc/runtime.h>
// Define the notification name
NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreManagerSubscriptionStatusDidChangeNotification";
@interface StoreManager ()
@property (nonatomic, strong) SKProductsRequest *productsRequest;
-@property (nonatomic, strong) SKProduct *premiumProduct;
-@property (nonatomic, strong) void (^productInfoCompletionHandler)(SKProduct * _Nullable product, NSError * _Nullable error); // Store completion handler for fetching info
+@property (nonatomic, strong) void (^productInfoCompletionHandler)(SKProduct * _Nullable product, NSError * _Nullable error);
@property (nonatomic, copy) void (^purchaseCompletionHandler)(BOOL success, NSError * _Nullable error);
-// Implement SKPaymentTransactionObserver method to handle transaction updates
-- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion;
+@property (nonatomic, copy) void (^restoreCompletionHandler)(BOOL success);
@end
@implementation StoreManager
-- (void)restorePurchases {
- [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
-}
-
-+ (StoreManager *)sharedInstance {
++ (instancetype)sharedInstance {
static StoreManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
@@ -30,95 +25,240 @@ NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreMan
return sharedInstance;
}
-- (instancetype)init {
- self = [super init];
- if (self) {
- [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
- }
- return self;
+- (BOOL)isUserSubscribed {
+ return [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];
}
-- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion {
+#pragma mark - Upgrade Popup
+
+- (void)showUpgradePopupInViewController:(UIViewController *)presentingVC
+ darkMode:(BOOL)isDarkMode
+ completion:(void (^)(BOOL success))completion {
+
[self getPremiumProductInfo:^(SKProduct * _Nullable product, NSError * _Nullable error) {
- if (!product) {
- if (completion) {
- completion(NO, error ?: [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Failed to fetch product information"}]);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (!product) {
+ NSLog(@"Error fetching product info: %@", error.localizedDescription);
+ if (completion) completion(NO);
+ return;
}
- return;
- }
-
- // Initiate the purchase
- SKPayment *payment = [SKPayment paymentWithProduct:product];
- [[SKPaymentQueue defaultQueue] addPayment:payment];
-
- // Store the completion handler to call it when the transaction finishes
- self.purchaseCompletionHandler = completion;
- }];
-}
-- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion {
- if (self.premiumProduct) {
- if (completion) {
- completion(self.premiumProduct, nil);
- }
- return;
- }
-
- // Store the completion handler
- self.productInfoCompletionHandler = completion;
-
- // Fetch product info from App Store
- NSSet *productIdentifiers = [NSSet setWithObject:@"monthly.premium"]; // Your product ID
- self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
- self.productsRequest.delegate = self; // Delegate methods will handle the response
- [self.productsRequest start];
-}
+ // Format price
+ NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
+ [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
+ [formatter setLocale:product.priceLocale];
+ NSString *localizedPrice = [formatter stringFromNumber:product.price] ?: NSLocalizedString(@"price_unknown", @"Fallback for unknown price");
+
+ // Colors
+ UIColor *cardBackground = isDarkMode ? [UIColor colorWithWhite:0.1 alpha:1.0] : [UIColor colorWithWhite:1.0 alpha:1.0];
+ UIColor *textColor = isDarkMode ? UIColor.whiteColor : UIColor.blackColor;
+
+ // Overlay
+ UIView *overlay = [[UIView alloc] initWithFrame:presentingVC.view.bounds];
+ overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
+ overlay.tag = 999;
+ [presentingVC.view addSubview:overlay];
+
+ // Card
+ UIView *card = [[UIView alloc] init];
+ card.translatesAutoresizingMaskIntoConstraints = NO;
+ card.backgroundColor = cardBackground;
+ card.layer.cornerRadius = 20;
+ card.clipsToBounds = YES;
+ [overlay addSubview:card];
+
+ // Title
+ UILabel *title = [[UILabel alloc] init];
+ title.translatesAutoresizingMaskIntoConstraints = NO;
+ title.text = NSLocalizedString(@"get_premium_title", @"Title for premium upgrade popup");
+ title.textColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0]; // gold
+ title.font = [UIFont boldSystemFontOfSize:24];
+ title.textAlignment = NSTextAlignmentCenter;
+
+ // Features
+ UIStackView *featureStack = [[UIStackView alloc] init];
+ featureStack.translatesAutoresizingMaskIntoConstraints = NO;
+ featureStack.axis = UILayoutConstraintAxisVertical;
+ featureStack.spacing = 8;
+
+ NSArray *features = @[
+ NSLocalizedString(@"premium_feature_1", @"Feature 1 description for premium"),
+ NSLocalizedString(@"premium_feature_2", @"Feature 2 description for premium"),
+ NSLocalizedString(@"premium_feature_3", @"Feature 3 description for premium"),
+ NSLocalizedString(@"premium_feature_4", @"Feature 4 description for premium")
+ ];
+
+ for (NSString *item in features) {
+ UILabel *label = [[UILabel alloc] init];
+ label.text = [NSString stringWithFormat:@"• %@", item];
+ label.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
+ label.textColor = textColor;
+ label.numberOfLines = 0;
+ [featureStack addArrangedSubview:label];
+ }
-#pragma mark - SKProductsRequestDelegate
+ // Upgrade button
+ UIButton *upgradeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
+ upgradeBtn.translatesAutoresizingMaskIntoConstraints = NO;
+
+ NSString *line1 = NSLocalizedString(@"1 week free trial", @"Free trial label");
+ NSString *line2 = [NSString stringWithFormat:NSLocalizedString(@"upgrade_button", @"Subscription price after trial"), localizedPrice];
+ NSString *fullText = [NSString stringWithFormat:@"%@\n%@", line1, line2];
+
+ NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
+ paragraphStyle.alignment = NSTextAlignmentCenter;
+
+ NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:fullText attributes:@{
+ NSParagraphStyleAttributeName: paragraphStyle,
+ NSForegroundColorAttributeName: UIColor.blackColor
+ }];
+
+ NSRange line1Range = [fullText rangeOfString:line1];
+ [attributedTitle addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:line1Range];
+
+ NSRange line2Range = [fullText rangeOfString:line2];
+ [attributedTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:line2Range];
+
+ [upgradeBtn setAttributedTitle:attributedTitle forState:UIControlStateNormal];
+ upgradeBtn.titleLabel.numberOfLines = 2;
+ upgradeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
+ upgradeBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0];
+ upgradeBtn.layer.cornerRadius = 12;
+
+ // Handle upgrade tap
+ __weak typeof(self) weakSelf = self;
+ [upgradeBtn addTarget:weakSelf action:@selector(handleUpgradeTap:) forControlEvents:UIControlEventTouchUpInside];
+ objc_setAssociatedObject(upgradeBtn, @"completionBlock", completion, OBJC_ASSOCIATION_COPY_NONATOMIC);
+ objc_setAssociatedObject(upgradeBtn, @"presentingVC", presentingVC, OBJC_ASSOCIATION_ASSIGN);
+ objc_setAssociatedObject(upgradeBtn, @"overlayView", overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+
+ // Cancel button
+ UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
+ cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
+ [cancelBtn setTitle:NSLocalizedString(@"not_now", @"Not now button") forState:UIControlStateNormal];
+ [cancelBtn setTitleColor:textColor forState:UIControlStateNormal];
+ cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
+ [cancelBtn addTarget:self action:@selector(dismissUpgradePopup:) forControlEvents:UIControlEventTouchUpInside];
+ objc_setAssociatedObject(cancelBtn, @"overlayView", overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+
+ // Disclaimer label
+ UILabel *disclaimer = [[UILabel alloc] init];
+ disclaimer.translatesAutoresizingMaskIntoConstraints = NO;
+ disclaimer.text = NSLocalizedString(@"premium_disclaimer", @"Disclaimer for premium subscription limits");
+ disclaimer.font = [UIFont systemFontOfSize:13];
+ disclaimer.textColor = [textColor colorWithAlphaComponent:0.6];
+ disclaimer.numberOfLines = 0;
+ disclaimer.textAlignment = NSTextAlignmentCenter;
+
+ // Add all to card
+ [card addSubview:title];
+ [card addSubview:featureStack];
+ [card addSubview:upgradeBtn];
+ [card addSubview:cancelBtn];
+ [card addSubview:disclaimer];
+
+ // Constraints
+ [NSLayoutConstraint activateConstraints:@[
+ [card.centerXAnchor constraintEqualToAnchor:overlay.centerXAnchor],
+ [card.centerYAnchor constraintEqualToAnchor:overlay.centerYAnchor],
+ [card.widthAnchor constraintEqualToConstant:320],
+
+ [title.topAnchor constraintEqualToAnchor:card.topAnchor constant:24],
+ [title.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
+ [title.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
+
+ [featureStack.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:20],
+ [featureStack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
+ [featureStack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
+
+ [upgradeBtn.topAnchor constraintEqualToAnchor:featureStack.bottomAnchor constant:24],
+ [upgradeBtn.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
+ [upgradeBtn.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
+ [upgradeBtn.heightAnchor constraintEqualToConstant:48],
+
+ [cancelBtn.topAnchor constraintEqualToAnchor:upgradeBtn.bottomAnchor constant:16],
+ [cancelBtn.centerXAnchor constraintEqualToAnchor:card.centerXAnchor],
+
+ [disclaimer.topAnchor constraintEqualToAnchor:cancelBtn.bottomAnchor constant:14],
+ [disclaimer.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],
+ [disclaimer.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],
+ [disclaimer.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-20]
+ ]];
+ });
+ }];
+}
-- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
- NSLog(@"Received product response.");
- if (response.products.count > 0) {
- self.premiumProduct = response.products.firstObject;
- if (self.productInfoCompletionHandler) {
- dispatch_async(dispatch_get_main_queue(), ^{
- self.productInfoCompletionHandler(self.premiumProduct, nil);
- self.productInfoCompletionHandler = nil;
- });
- }
- } else {
- NSError *error = [NSError errorWithDomain:@"StoreManagerError" code:101 userInfo:@{NSLocalizedDescriptionKey: @"No products found."}];
- if (self.productInfoCompletionHandler) {
- dispatch_async(dispatch_get_main_queue(), ^{
- self.productInfoCompletionHandler(nil, error);
- self.productInfoCompletionHandler = nil;
- });
- }
- }
- self.productsRequest.delegate = nil;
- self.productsRequest = nil;
+- (void)showUpgradePopupInViewController:(UIViewController *)presentingVC {
+ [self showUpgradePopupInViewController:presentingVC
+ darkMode:(presentingVC.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark)
+ completion:^(BOOL success) {
+ }];
}
-- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
- if (self.productInfoCompletionHandler) {
+- (void)handleUpgradeTap:(UIButton *)sender {
+ void (^completion)(BOOL) = objc_getAssociatedObject(sender, @"completionBlock");
+ UIViewController *presentingVC = objc_getAssociatedObject(sender, @"presentingVC");
+ UIView *overlay = objc_getAssociatedObject(sender, @"overlayView");
+
+ // Create and show a loading spinner
+ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
+ spinner.translatesAutoresizingMaskIntoConstraints = NO;
+ spinner.color = UIColor.whiteColor;
+ [overlay addSubview:spinner];
+
+ // Center the spinner in the overlay
+ [NSLayoutConstraint activateConstraints:@[
+ [spinner.centerXAnchor constraintEqualToAnchor:overlay.centerXAnchor],
+ [spinner.centerYAnchor constraintEqualToAnchor:overlay.centerYAnchor]
+ ]];
+
+ [spinner startAnimating];
+
+ // Disable user interaction on the overlay to prevent multiple taps
+ overlay.userInteractionEnabled = NO;
+
+ // Fetch and initiate the purchase
+ [self fetchAndPurchaseProductWithCompletion:^(BOOL success, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
- self.productInfoCompletionHandler(nil, error);
- self.productInfoCompletionHandler = nil; // Clear the handler
+ // Stop the spinner and re-enable interaction
+ [spinner stopAnimating];
+ [spinner removeFromSuperview];
+ overlay.userInteractionEnabled = YES;
+
+ // Dismiss the upgrade popup
+ [overlay removeFromSuperview];
+
+ if (!success && error) {
+ // Show error alert if purchase failed
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"purchase_failed", @"Title for purchase failed alert")
+ message:error.localizedDescription
+ preferredStyle:UIAlertControllerStyleAlert];
+ [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button") style:UIAlertActionStyleDefault handler:nil]];
+ [presentingVC presentViewController:alert animated:YES completion:nil];
+ }
+
+ if (completion) {
+ completion(success);
+ }
});
- }
- self.productsRequest.delegate = nil;
- self.productsRequest = nil;
+ }];
}
-#pragma mark - Purchase Product
-
-- (void)purchaseProduct:(SKProduct *)product {
- if ([SKPaymentQueue canMakePayments] && product) {
- SKPayment *payment = [SKPayment paymentWithProduct:product];
- [[SKPaymentQueue defaultQueue] addPayment:payment];
+- (void)dismissUpgradePopup:(UIButton *)sender {
+ UIView *overlay = objc_getAssociatedObject(sender, @"overlayView");
+ [overlay removeFromSuperview];
+
+ void (^completion)(BOOL) = objc_getAssociatedObject(sender, @"completionBlock");
+ if (completion) {
+ completion(NO);
}
}
+- (void)restorePurchasesWithCompletion:(void (^)(BOOL success))completion {
+ self.restoreCompletionHandler = completion;
+ [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
+}
+
#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
@@ -176,9 +316,9 @@ NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreMan
topController = topController.presentedViewController;
}
[topController presentViewController:alert animated:YES completion:nil];
- if (self.purchaseCompletionHandler) {
- self.purchaseCompletionHandler(YES, nil);
- self.purchaseCompletionHandler = nil;
+ if (self.restoreCompletionHandler) {
+ self.restoreCompletionHandler(YES);
+ self.restoreCompletionHandler = nil;
}
} else {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"No Purchases Found"
@@ -190,9 +330,9 @@ NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreMan
topController = topController.presentedViewController;
}
[topController presentViewController:alert animated:YES completion:nil];
- if (self.purchaseCompletionHandler) {
- self.purchaseCompletionHandler(NO, [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"No valid subscriptions found"}]);
- self.purchaseCompletionHandler = nil;
+ if (self.restoreCompletionHandler) {
+ self.restoreCompletionHandler(NO);
+ self.restoreCompletionHandler = nil;
}
}
});
@@ -208,6 +348,102 @@ NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreMan
}
}
+
+- (void)restorePurchases {
+ [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
+}
+
+- (instancetype)init {
+ self = [super init];
+ if (self) {
+ [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
+ }
+ return self;
+}
+
+- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion {
+ [self getPremiumProductInfo:^(SKProduct * _Nullable product, NSError * _Nullable error) {
+ if (!product) {
+ if (completion) {
+ completion(NO, error ?: [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Failed to fetch product information"}]);
+ }
+ return;
+ }
+
+ // Initiate the purchase
+ SKPayment *payment = [SKPayment paymentWithProduct:product];
+ [[SKPaymentQueue defaultQueue] addPayment:payment];
+
+ // Store the completion handler to call it when the transaction finishes
+ self.purchaseCompletionHandler = completion;
+ }];
+}
+
+- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion {
+ if (self.premiumProduct) {
+ if (completion) {
+ completion(self.premiumProduct, nil);
+ }
+ return;
+ }
+
+ // Store the completion handler
+ self.productInfoCompletionHandler = completion;
+
+ // Fetch product info from App Store
+ NSSet *productIdentifiers = [NSSet setWithObject:@"monthly.premium"]; // Your product ID
+ self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
+ self.productsRequest.delegate = self; // Delegate methods will handle the response
+ [self.productsRequest start];
+}
+
+#pragma mark - SKProductsRequestDelegate
+
+- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
+ NSLog(@"Received product response.");
+ if (response.products.count > 0) {
+ self.premiumProduct = response.products.firstObject;
+ if (self.productInfoCompletionHandler) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ self.productInfoCompletionHandler(self.premiumProduct, nil);
+ self.productInfoCompletionHandler = nil;
+ });
+ }
+ } else {
+ NSError *error = [NSError errorWithDomain:@"StoreManagerError" code:101 userInfo:@{NSLocalizedDescriptionKey: @"No products found."}];
+ if (self.productInfoCompletionHandler) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ self.productInfoCompletionHandler(nil, error);
+ self.productInfoCompletionHandler = nil;
+ });
+ }
+ }
+ self.productsRequest.delegate = nil;
+ self.productsRequest = nil;
+}
+
+- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
+ if (self.productInfoCompletionHandler) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ self.productInfoCompletionHandler(nil, error);
+ self.productInfoCompletionHandler = nil; // Clear the handler
+ });
+ }
+ self.productsRequest.delegate = nil;
+ self.productsRequest = nil;
+}
+
+#pragma mark - Purchase Product
+
+- (void)purchaseProduct:(SKProduct *)product {
+ if ([SKPaymentQueue canMakePayments] && product) {
+ SKPayment *payment = [SKPayment paymentWithProduct:product];
+ [[SKPaymentQueue defaultQueue] addPayment:payment];
+ }
+}
+
+#pragma mark - SKPaymentTransactionObserver
+
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
NSLog(@"Restore completed transactions finished.");
}