@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];