iOS APP内部打开苹果商店的下载页面封装

本文介绍了一种在iOS应用中实现应用内购买的方法。通过使用StoreKit框架,创建了一个单例管理器来处理产品展示流程。实现了从展示产品到完成购买的整个过程,并提供了错误处理机制。
@interface StoreTool : NSObject
+ (instancetype)shareManager;
@end
#import <StoreKit/StoreKit.h>
@interface StoreTool ()
<
SKStoreProductViewControllerDelegate
>
@end

@implementation StoreTool

+ (instancetype)shareManager
{
    static StoreTool * manager =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil)
        {
            manager = [[self alloc]init];
            [manager showStoreFeromIDstr:@"苹果商店链接里的ID"];
        }
    });
    return manager;
}

-(void)showStoreFeromIDstr:(NSString *)str
{
    SKStoreProductViewController *vc = [[SKStoreProductViewController alloc] init];
    vc.delegate = self;
    NSDictionary *dic = [NSDictionary dictionaryWithObject:str forKey:SKStoreProductParameterITunesItemIdentifier];
    [vc loadProductWithParameters:dic completionBlock:^(BOOL result, NSError * _Nullable error) {
        if (!error)
        {
            [[self currentViewController] presentViewController:vc animated:YES completion:nil];
        }
        else
        {
            NSLog(@"ERROR:%@", error);
        }
    }];
}

- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
{
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

//获取Window当前显示的ViewController
- (UIViewController*)currentViewController
{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式,逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

@end
// 调用
 [StoreTool shareManager];

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值