代码经过验证,但是这里只提供了iap相关的代码,有依赖其他的代码自行删减
直接上代码
//
// PurchaseSDK.h
// Unity-iPhone
//
// Created by wang guo qing on 2017/3/24.
//
//
#import <Foundation/Foundation.h>
#import "StoreKit/StoreKit.h"
@protocol IAPPayResult <NSObject>
-(void)OnPayResult:(NSString*)res;
@end
@interface PurchaseSDK : NSObject <SKProductsRequestDelegate, SKPaymentTransactionObserver>
+(instancetype) Instance;
@property double SystemVersion;
@property (retain)id<IAPPayResult> PayResultObj;
@property (nonatomic, retain)NSMutableDictionary* TransactionDict;
-(void)Init:(id<IAPPayResult>)obj;
-(void)BuyProduct:(NSString * )productId Quantity:(NSInteger)quantity SignId:(NSString * )signId;
-(void)FinishTransaction:(NSString*)transactionIdentifier;
-(void)BuyProductBySKProductsRequest:(NSString * )productId;
- (void)provideContentWithTransaction:(SKPaymentTransaction *)transaction;
@end
//
// PurchaseSDK.m
// Unity-iPhone
//
// Created by wang guo qing on 2017/3/24.
//
//
#import <Foundation/Foundation.h>
#import "PurchaseSDK.h"
@implementation PurchaseSDK
static PurchaseSDK*instance=nil;
+(instancetype) Instance{
static dispatch_once_t onceToken=0;
dispatch_once(&onceToken,^{
instance=[[PurchaseSDK alloc] init];
NSLog(@"PurchaseSDK Instance alloc!!!!");
});
return instance;
}
-(void)Init:(id<IAPPayResult>)obj{
self.PayResultObj=obj;
self.TransactionDict=[[NSMutableDictionary alloc] init];
NSString *version=[UIDevice currentDevice].systemVersion;
NSLog(@"系统版本号:%@",version);
_SystemVersion=[[UIDevice currentDevice] systemVersion].floatValue;
//NSLog(@"系统版本号:%f",_SystemVersion);
//注册观察者
// NSLog(@"Purchase obj::%@",self);
[[SKPaymentQueue defaultQueue]addTransactionObserver:self];
//获取购买过所有的非消耗商品
//[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
//使用商品查询会有bug,当查询时断网,回调方法productsRequest始终不会被调用,网络恢复后也不会被调用;在上一种情况操作的基础上网络恢复后再次查询商品也不会有回调,大约5-10分钟后再次查询商品才有回调
-(void)BuyProductBySKProductsRequest:(NSString * )productId
{
if([SKPaymentQueue canMakePayments])
{
NSLog(@"---------查询商品请求------------");
//请求商品信息
NSSet* dataSet = [[NSSet alloc] initWithObjects:productId, nil];
SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:dataSet];
request.delegate = self;
[request start];
}
else
{
NSLog(@"应用内不允许购买!");
}
}
// 请求商品信息回调,商品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSLog(@"productsRequest=======");
NSArray * products = response.products;
NSLog(@"产品Product count:%d",(int)response.invalidProductIdentifiers.count);
NSLog(@"产品付费数量: %d", (int)[products count]);
for(SKProduct *product in products){
NSLog(@"SKProduct 描述信息%@", [product description]);
NSLog(@"产品标题 %@" , product.localizedTitle);
NSLog(@"产品描述信息: %@" , product.localizedDescription);
NSLog(@"价格: %@" , product.price);
NSLog(@"Product id: %@" , product.productIdentifier);
}
if(products.count>0)
{
SKPayment *payment = [SKPayment paymentWithProduct:products[0]];
NSLog(@"Purchase obj::%@",self);
//payment.applicationUsername=;
//NSLog(@"buyProduct::updatedTransactions,applicationUsername:%@",payment.applicationUsername);
NSLog(@"---------发送商品信息请求------------");
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
}
else
{
NSLog(@"获取商品信息失败,连接AppStore失败,请稍后再试,或则商品不存在!");
}
}
-(void)BuyProduct:(NSString * )productId Quantity:(NSInteger)quantity SignId:(NSString * )signId
{
if([SKPaymentQueue canMakePayments])
{
// NSLog(@"Purchase obj::%@",self);
NSLog(@"---------发送购买请求------------");
//请求商品信息
SKMutablePayment *payment = [[SKMutablePayment alloc] init];
payment.productIdentifier=productId;
payment.quantity=quantity;
payment.applicationUsername=signId;
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
}
else
{
NSLog(@"游戏内不允许购买!");
//self.PayCallBack(@"-10");
//UnitySendMessage([_ObjName UTF8String],[_FailCall UTF8String],[@"游戏内不允许购买!" UTF8String]);
}
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchasing:
NSLog(@"paymentQueue::updatedTransactions,SKPaymentTransactionStatePurchasing");
break;
case SKPaymentTransactionStatePurchased:
NSLog(@"paymentQueue::updatedTransactions,SKPaymentTransactionStatePurchased");
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
NSLog(@"paymentQueue::updatedTransactions,SKPaymentTransactionStateFailed");
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
NSLog(@"paymentQueue::updatedTransactions,SKPaymentTransactionStateRestored");
[self restoreTransaction:transaction];
//case SKPaymentTransactionStateDeferred:
// NSLog(@"paymentQueue::updatedTransactions,SKPaymentTransactionStateDeferred");
default:
NSLog(@"paymentQueue::updatedTransactions,default null error");
//UnitySendMessage([_ObjName UTF8String],[_FailCall UTF8String],[@"购买失败!" UTF8String]);
//_PayCallBack(@"-9");
break;
}
}
}
//购买成功
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
//获取receipt
//NSString* receipt=@"";
NSString*base64Receipt=@"";
//NSLog(@"completeTransaction productId::%@",transaction.payment.productIdentifier);
//% if(_SystemVersion>=8.0)
//% {
// % //NSURLRequest*request=[NSURLRequest requestWithURL:[[NSBundle mainBundle]appStoreReceiptURL]];
// % //NSError*error=nil;
// % //NSData * receiptData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error ];
//
//
// % // appStoreReceiptURL iOS7.0增加的,购买交易完成后,会将凭据存放在该地址
// % NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
// % // 从沙盒中获取到购买凭据
// % NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
// % //receipt=[[NSString alloc] initWithData:receiptData encoding:NSASCIIStringEncoding];
// % base64Receipt=[[NSString alloc] initWithData:[receiptData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSUTF8StringEncoding];
//% }
//% else
//% {
// % //receipt=[[NSString alloc] initWithData:[transaction transactionReceipt] encoding:NSUTF8StringEncoding];
// % base64Receipt=[[NSString alloc] initWithData:[[transaction transactionReceipt] base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSUTF8StringEncoding];
//% }
NSString *temptransactionReceipt = [[NSString alloc] initWithData:[transaction transactionReceipt] encoding:NSUTF8StringEncoding];
temptransactionReceipt = [temptransactionReceipt stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSLog(@"temptransactionReceipt =%@",temptransactionReceipt);
NSString *receipt = [transaction.transactionReceipt base64Encoding];
//NSLog(@"completeTransaction Receipt::%@",receipt);
NSLog(@"购买成功::transactionIdentifier:%@,applicationUsername:%@, quantity::%d",transaction.transactionIdentifier,transaction.payment.applicationUsername,(int)transaction.payment.quantity);
//缓存当前订单数据,直到业务层将订单处理完成才通知appstore该订单已经成功处理;不通知则认为该订单未完成,在下次打开应用的时候appstore重新下发未完成的订单
NSString* identifier=transaction.transactionIdentifier;
NSLog(@"%@",identifier);
[self.TransactionDict setObject:transaction forKey:identifier];
//回调unity
NSString* userName=transaction.payment.applicationUsername;
if(userName==nil)
{
userName=@"";
}
NSString* res=@"";
//res=[res stringByAppendingFormat:@"%@,%@,%d,%@,%@", transaction.transactionIdentifier,transaction.payment.productIdentifier,(int)transaction.payment.quantity,userName,base64Receipt];
//UnitySendMessage([_ObjName UTF8String],[_SuccCall UTF8String],[res UTF8String]);
res=[res stringByAppendingFormat:@"0|%@|%@|%@", transaction.transactionIdentifier,receipt,userName];
[self.PayResultObj OnPayResult:res];
}
//通知appstore该订单已经成功处理,不通知则appstore认为该订单未完成,在下次打开应用的时候appstore重新下发未完成的订单
-(void)FinishTransaction:(NSString*)transactionIdentifier
{
SKPaymentTransaction* transaction=[_TransactionDict objectForKey:transactionIdentifier];
if(transaction!=nil)
{
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
[_TransactionDict removeObjectForKey:transactionIdentifier];
}
}
//购买失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
NSString* errStr=@"";
NSString* err=@"-1";
if (transaction.error.code == SKErrorPaymentCancelled) {
NSLog(@"SKErrorPaymentCancelled");
errStr=@"SKErrorPaymentCancelled";
err=@"-2";
}else if (transaction.error.code == SKErrorClientInvalid) {
NSLog(@"SKErrorClientInvalid");
errStr=@"SKErrorClientInvalid";
err=@"-3";
}else if (transaction.error.code == SKErrorPaymentInvalid) {
NSLog(@"SKErrorPaymentInvalid");
errStr=@"SKErrorPaymentInvalid";
err=@"-4";
}else if (transaction.error.code == SKErrorPaymentNotAllowed) {
NSLog(@"SKErrorPaymentNotAllowed");
errStr=@"SKErrorPaymentNotAllowed";
err=@"-5";
}else if (transaction.error.code == SKErrorStoreProductNotAvailable) {
NSLog(@"SKErrorStoreProductNotAvailable");
errStr=@"SKErrorStoreProductNotAvailable";
err=@"-6";
}else{
//商品不存在,支付中断网,支付中应用被切到后台自动终止支付
errStr=@"支付失败!!!";
}
NSLog(@"SKPaymentTransactionStateFailed:%@",transaction.error.description);
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
NSString*res=@"";
res=[res stringByAppendingFormat:@"%@|%@", err,errStr];
[self.PayResultObj OnPayResult:res];
//UnitySendMessage([_ObjName UTF8String],[_FailCall UTF8String],[errStr UTF8String]);
}
//恢复购买
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
NSLog(@"------恢复购买-----------");
//[self provideContentWithTransaction:transaction];
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
}
- (void)provideContentWithTransaction:(SKPaymentTransaction *)transaction {
NSString* productIdentifier = @"";
if (transaction.originalTransaction) {
productIdentifier = transaction.originalTransaction.payment.productIdentifier;
}
else {
productIdentifier = transaction.payment.productIdentifier;
}
//check productIdentifier exist or not
//it can be possible nil
if (productIdentifier) {
//[SFHFKeychainUtils storeUsername:productIdentifier andPassword:@"YES" forServiceName:@"IAPHelper" updateExisting:YES error:nil];
//[_purchasedProducts addObject:productIdentifier];
}
}
// Sent when transactions are removed from the queue (via finishTransaction:).
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions
{
}
// Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
NSLog(@"支付失败:%d,%@",(int)error.code,error.localizedDescription);
}
// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
NSLog(@"已购买商品数量:%i",(int)queue.transactions.count);
for (SKPaymentTransaction*transaction in queue.transactions) {
NSString*productId=transaction.payment.productIdentifier;
NSString*transactionId=transaction.transactionIdentifier;
NSLog(@"已购买商品,id:%@,productId:%@",transactionId,productId);
}
}
// Sent when the download state has changed.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray<SKDownload *> *)downloads
{
}
- (void)dealloc
{
// NSLog(@"PurchaseSDK dealloc!!!!");
// [super dealloc];
if ([SKPaymentQueue defaultQueue]) {
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
}
@end
//IosTools .h
#import <Foundation/Foundation.h>
#import "PurchaseSDK.h"
#import "UnityAppController.h"
@interface IosTools : NSObject<IAPPayResult>
+ (instancetype)Instance;
-(void)IAPInit;
-(void) BuyProduct:(NSString*) productId userId:(NSString*)userId;
-(void) FinishTransaction:(NSString*) transactionIdentifier;
- (BOOL) isWiFiEnabled;
- (int)getWifiSignalStrength;
- (NSString *)getNetworkType;
- (NSString*)GetDeviceModelName;
- (bool) IsIphoneX;
@end
#import "IosTools.h"
#import <ifaddrs.h>
#import <net/if.h>
#import <sys/utsname.h>
//#define KIsiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
//#define kSCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
//#define kSCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
////iPhone X
//#define iPhoneX (kSCREEN_WIDTH == 375.f && kSCREEN_HEIGHT == 812.f)
#if defined (__cplusplus)
extern "C" {
#endif
//char*分配内存
char* StringCopy (const char* string)
{
if (string == NULL)
return NULL;
char* res = (char*)malloc(strlen(string) + 1);
strcpy(res, string);
return res;
}
char* GetImei ()
{
NSLog(@"GetImei");
NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
char* id=[uuid UTF8String];
return StringCopy(id);
}
//获取设备自定义名称
char* GetDeviceName()
{
NSString *deviceName = [[UIDevice currentDevice] name];
NSLog(@"GetDeviceName:::::::::::::::::::::::::::::::%@",deviceName);
return StringCopy([deviceName UTF8String]);
}
float GetBatteryLevel ()
{
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
return batteryLevel;
}
// show toast
void ShowToastE(char*str)
{
NSString* content = [[NSString alloc] initWithUTF8String:str];
[[[ZFToast alloc] init] popUpToastWithMessage:content];
}
//复制到剪贴板
void SetClipboardE(char* str)
{
NSString* content = [[NSString alloc] initWithUTF8String:str];
UIPasteboard*pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string=content;
ShowToastE("复制成功");
}
//open url
void OpenWebViewE(char*_url)
{
NSString* url = [[NSString alloc] initWithUTF8String:_url];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}
//获取wifi信号强度
int GetWifiSignalStrength(){
if (![[IosTools Instance] isWiFiEnabled]) {
return 1;
}
NSLog(@"GetDeviceName:::::::::::::::::::::::::::::::%@",[[IosTools Instance] GetDeviceModelName]);
// NSString *deviceName = [[UIDevice currentDevice] systemName];
// NSLog(@"GetDeviceName:::::::::::::::::::::::::::::::%@",deviceName);
// NSLog(@"phone height:%f",[[UIScreen mainScreen] fixedCoordinateSpace].bounds.size.height);
// return [[IosTools Instance] getWifiSignalStrength];
UIApplication *app = [UIApplication sharedApplication];
NSLog(@"app::::%@",app);
if(app==NULL)
{
return 0;
}
// NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
NSArray *subviews = nil;
id statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
if ([statusBar isKindOfClass:NSClassFromString(@"UIStatusBar_Modern")]) {
subviews = [[[statusBar valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
} else {
subviews = [[statusBar valueForKey:@"foregroundView"] subviews];
}
NSString *dataNetworkItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
int signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];
NSLog(@"signal %d", signalStrength);
return signalStrength;
}
//获取网络类型
int GetNetworkType()
{
UIApplication *app = [UIApplication sharedApplication];
NSArray *subviews = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
for (id subview in subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
switch (networkType) {
case 0:
NSLog(@"NONE");
break;
case 1:
NSLog(@"2G");
break;
case 2:
NSLog(@"3G");
break;
case 3:
NSLog(@"4G");
break;
case 5:
{
NSLog(@"WIFI");
}
break;
default:
break;
}
return networkType;
}
}
return 0;
}
//get start applink
char* GetStartApplinkUrlE()
{
NSString* url=[UnityAppController GetStartApplink];
char* _url="";
if(url)
{
_url=[url UTF8String];
}
NSLog(@"GetStartApplinkUrlE:::%@",url);
return StringCopy(_url);
}
//ios pay
void IAPInit()
{
[[IosTools Instance] IAPInit];
}
void BuyProduct(char* _productId,char* _userId)
{
NSString* productId = [[NSString alloc] initWithUTF8String:_productId];
NSString* userId = [[NSString alloc] initWithUTF8String:_userId];
[[IosTools Instance] BuyProduct:productId userId:userId];
}
void FinishTransaction(char* _transactionIdentifier)
{
NSString* transactionIdentifier = [[NSString alloc] initWithUTF8String:_transactionIdentifier];
[[IosTools Instance] FinishTransaction:transactionIdentifier];
}
#if defined (__cplusplus)
}
#endif
@implementation IosTools
+(instancetype)Instance {
static dispatch_once_t onceToken;
static IosTools *instance;
dispatch_once(&onceToken, ^{
instance = [[IosTools alloc] init];
});
return instance;
}
//苹果支付
-(void)IAPInit
{
[PurchaseSDK.Instance Init:self];
}
-(void)OnPayResult:(NSString*)res{
char* result=[res UTF8String];
UnitySendMessage("Service", "OnPayResult", result);
}
-(void) BuyProduct:(NSString*) productId userId:(NSString*)userId
{
[[PurchaseSDK Instance] BuyProduct:productId Quantity:1 SignId:userId];
}
-(void) FinishTransaction:(NSString*) transactionIdentifier
{
[[PurchaseSDK Instance] FinishTransaction:transactionIdentifier];
}
- (BOOL) isWiFiEnabled {
NSCountedSet * cset = [NSCountedSet new];
struct ifaddrs *interfaces;
if( ! getifaddrs(&interfaces) ) {
for( struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
if ( (interface->ifa_flags & IFF_UP) == IFF_UP ) {
[cset addObject:[NSString stringWithUTF8String:interface->ifa_name]];
}
}
}
return [cset countForObject:@"awdl0"] > 1 ? YES : NO;
}
- (NSString *)getNetworkType
{
UIApplication *app = [UIApplication sharedApplication];
id statusBar = [app valueForKeyPath:@"statusBar"];
NSString *network = @"";
NSArray *children;
NSString *state = [[NSString alloc] init];
if ([self IsIphoneX]) {
// iPhone X
// NSLog(@"IsIphoneX:::type:::::::");
// id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
// UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
// NSLog(@"foregroundView:::type:::::::%@",foregroundView);
// NSArray *subviews = [[foregroundView subviews][2] subviews];
// NSLog(@"subviews:::type:::::::%@",subviews);
// for (id subview in subviews) {
// NSLog(@"subview:::type:::::::%@",subview);
// if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
// network = @"WIFI";
// }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
// network = [subview valueForKeyPath:@"originalText"];
// }
// }
children = [[[[app valueForKeyPath:@"_statusBar"] valueForKeyPath:@"_statusBar"] valueForKeyPath:@"foregroundView"] subviews];
for (UIView *view in children) {
NSLog(@"UIVIEW::::::%@",view);
for (id child in view.subviews) {
//wifi
if ([child isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
state = @"WIFI";
}
//2G 3G 4G
if ([child isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
if ([[child valueForKey:@"_originalText"] containsString:@"G"]) {
state = [child valueForKey:@"_originalText"];
}
}
}
}
NSLog(@"iphone x net type::::::::%@",state);
// if (![state isStringValid]) {
// state = @"无网络";
// }
network=state;
}else {
// 非 iPhone X
UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
NSArray *subviews = [foregroundView subviews];
for (id subview in subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
switch (networkType) {
case 0:
network = @"NONE";
break;
case 1:
network = @"2G";
break;
case 2:
network = @"3G";
break;
case 3:
network = @"4G";
break;
case 5:
network = @"WIFI";
break;
default:
break;
}
}
}
}
if ([network isEqualToString:@""]) {
network = @"NO DISPLAY";
}
NSLog(@"getNetworkType;::::::::%@",network);
return network;
}
#pragma mark 获取Wifi信号强度
- (int)getWifiSignalStrength{
int signalStrength = 0;
// 判断类型是否为WIFI
if ([[self getNetworkType]isEqualToString:@"WIFI"]) {
UIApplication *app = [UIApplication sharedApplication];
id statusBar = [app valueForKey:@"statusBar"];
if ([self IsIphoneX]) {
// iPhone X
id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
NSArray *subviews = [[foregroundView subviews][2] subviews];
for (id subview in subviews) {
NSLog(@"subview::::::::%@",subview);
if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
signalStrength = [[subview valueForKey:@"_numberOfActiveBars"] intValue];
}
}
}else {
// 非 iPhone X
UIView *foregroundView = [statusBar valueForKey:@"foregroundView"];
NSArray *subviews = [foregroundView subviews];
NSString *dataNetworkItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];
}
}
NSLog(@"signal %d", signalStrength);
return signalStrength;
}
// 需要#import <sys/utsname.h>
- (NSString*)GetDeviceModelName
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
NSLog(@"deviceString:::::::::::::::::::::::::: %@", deviceString);
if ([deviceString isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
if ([deviceString isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([deviceString isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([deviceString isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([deviceString isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([deviceString isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([deviceString isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([deviceString isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([deviceString isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([deviceString isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
// 日行两款手机型号均为日本独占,可能使用索尼FeliCa支付方案而不是苹果支付
if ([deviceString isEqualToString:@"iPhone9,1"]) return @"国行、日版、港行iPhone 7";
if ([deviceString isEqualToString:@"iPhone9,2"]) return @"港行、国行iPhone 7 Plus";
if ([deviceString isEqualToString:@"iPhone9,3"]) return @"美版、台版iPhone 7";
if ([deviceString isEqualToString:@"iPhone9,4"]) return @"美版、台版iPhone 7 Plus";
if ([deviceString isEqualToString:@"iPhone10,1"]) return @"国行(A1863)、日行(A1906)iPhone 8";
if ([deviceString isEqualToString:@"iPhone10,4"]) return @"美版(Global/A1905)iPhone 8";
if ([deviceString isEqualToString:@"iPhone10,2"]) return @"国行(A1864)、日行(A1898)iPhone 8 Plus";
if ([deviceString isEqualToString:@"iPhone10,5"]) return @"美版(Global/A1897)iPhone 8 Plus";
if ([deviceString isEqualToString:@"iPhone10,3"]) return @"国行(A1865)、日行(A1902)iPhone X";
if ([deviceString isEqualToString:@"iPhone10,6"]) return @"美版(Global/A1901)iPhone X";
if ([deviceString isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([deviceString isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([deviceString isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([deviceString isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([deviceString isEqualToString:@"iPod5,1"]) return @"iPod Touch (5 Gen)";
if ([deviceString isEqualToString:@"iPad1,1"]) return @"iPad";
if ([deviceString isEqualToString:@"iPad1,2"]) return @"iPad 3G";
if ([deviceString isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([deviceString isEqualToString:@"iPad2,2"]) return @"iPad 2";
if ([deviceString isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([deviceString isEqualToString:@"iPad2,4"]) return @"iPad 2";
if ([deviceString isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([deviceString isEqualToString:@"iPad2,6"]) return @"iPad Mini";
if ([deviceString isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([deviceString isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad3,3"]) return @"iPad 3";
if ([deviceString isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([deviceString isEqualToString:@"iPad3,5"]) return @"iPad 4";
if ([deviceString isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
if ([deviceString isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([deviceString isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
if ([deviceString isEqualToString:@"iPad4,4"]) return @"iPad Mini 2 (WiFi)";
if ([deviceString isEqualToString:@"iPad4,5"]) return @"iPad Mini 2 (Cellular)";
if ([deviceString isEqualToString:@"iPad4,6"]) return @"iPad Mini 2";
if ([deviceString isEqualToString:@"iPad4,7"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad4,8"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad4,9"]) return @"iPad Mini 3";
if ([deviceString isEqualToString:@"iPad5,1"]) return @"iPad Mini 4 (WiFi)";
if ([deviceString isEqualToString:@"iPad5,2"]) return @"iPad Mini 4 (LTE)";
if ([deviceString isEqualToString:@"iPad5,3"]) return @"iPad Air 2";
if ([deviceString isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
if ([deviceString isEqualToString:@"iPad6,3"]) return @"iPad Pro 9.7";
if ([deviceString isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7";
if ([deviceString isEqualToString:@"iPad6,7"]) return @"iPad Pro 12.9";
if ([deviceString isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9";
if ([deviceString isEqualToString:@"iPad6,11"]) return @"iPad 5 (WiFi)";
if ([deviceString isEqualToString:@"iPad6,12"]) return @"iPad 5 (Cellular)";
if ([deviceString isEqualToString:@"iPad7,1"]) return @"iPad Pro 12.9 inch 2nd gen (WiFi)";
if ([deviceString isEqualToString:@"iPad7,2"]) return @"iPad Pro 12.9 inch 2nd gen (Cellular)";
if ([deviceString isEqualToString:@"iPad7,3"]) return @"iPad Pro 10.5 inch (WiFi)";
if ([deviceString isEqualToString:@"iPad7,4"]) return @"iPad Pro 10.5 inch (Cellular)";
if ([deviceString isEqualToString:@"AppleTV2,1"]) return @"Apple TV 2";
if ([deviceString isEqualToString:@"AppleTV3,1"]) return @"Apple TV 3";
if ([deviceString isEqualToString:@"AppleTV3,2"]) return @"Apple TV 3";
if ([deviceString isEqualToString:@"AppleTV5,3"]) return @"Apple TV 4";
if ([deviceString isEqualToString:@"i386"]) return @"Simulator";
if ([deviceString isEqualToString:@"x86_64"]) return @"Simulator";
return deviceString;
}
- (bool) IsIphoneX
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
NSLog(@"deviceString:::::::::::::::::::::::::: %@", deviceString);
if ([deviceString isEqualToString:@"iPhone10,3"]) return true;
if ([deviceString isEqualToString:@"iPhone10,6"]) return true;
return false;
}
- (void)dealloc {
}
@end
//=====================================================
// - FileName: ProviderService
// - Description:
// - Author: wangguoqing
// - Email: wangguoqing@hehemj.com
// - Created: 2017/12/13 17:12:17
// - CLR version: 4.0.30319.42000
// - UserName: Wang
// - (C) Copyright 2008 - 2015, hehehuyu,Inc.
// - All Rights Reserved.
//======================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using UnityEngine;
using Random = UnityEngine.Random;
/// <summary>
/// 和平台层交互必须通过unity主线程调用
/// </summary>
public class ProviderService : MonoBehaviour
{
public static ProviderService Instance;
private XLua.LuaFunction iosPayCallback = null;
#if UNITY_IOS
//ios pay
[DllImport("__Internal")]
private static extern void IAPInit();
[DllImport("__Internal")]
private static extern void BuyProduct(string productId,string userId);
[DllImport("__Internal")]
private static extern void FinishTransaction(string transactionIdentifier);
//open url
[DllImport("__Internal")]
private static extern void OpenWebViewE(string url);
#endif
/// <summary>
/// ios pay init
/// </summary>
public void IAPInitE(XLua.LuaFunction callback)
{
this.iosPayCallback = callback;
#if UNITY_IOS&&!UNITY_EDITOR
IAPInit();
#endif
}
/// <summary>
/// ios pay buy
/// </summary>
/// <param name="productId">商品id</param>
/// <param name="userId"></param>
public void BuyProductE(string productId, string userId, XLua.LuaFunction callback)
{
this.iosPayCallback = callback;
Dg.Log("ProviderService::BuyProductE:productId:", productId, " userId:", userId);
#if UNITY_IOS&&!UNITY_EDITOR
BuyProduct(productId,userId);
#endif
}
/// <summary>
/// ios pay finish
/// </summary>
/// <param name="transactionIdentifier">订单号</param>
public void FinishTransactionE(string transactionIdentifier)
{
Dg.Log("ProviderService::FinishTransactionE,transactionIdentifier:", transactionIdentifier);
#if UNITY_IOS&&!UNITY_EDITOR
FinishTransaction(transactionIdentifier);
#endif
}
/// <summary>
/// ios支付结果
/// ios pay
/// </summary>
/// <param name="res"></param>
public void OnPayResult(string res)
{
Dg.Log("ProviderService::OnPayResult::::", res);
if (this.iosPayCallback != null)
{
this.iosPayCallback.Call(res);
//this.iosPayCallback.Dispose();
this.iosPayCallback = null;
}
else
{
Dg.Log("ProviderService::OnPayResult:::: iosPayCallback is null!");
}
}