苹果内购

代码经过验证,但是这里只提供了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!");
        }
    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容

  • 关于苹果内购(IAP)的一些问题以及那些坑: 最近在研究苹果内购功能,所以,在网上找了一些资料,进行学习。但是,内...
    魔芋Brace阅读 7,346评论 0 5
  • 花了快10个工作日,终于完成了内购(IAP)功能。必须写篇文章来记录一下这十天来的心得体会,更是为了避免后续的开发...
    flightlessBirdT阅读 9,474评论 16 38
  • 一.适用情况: 什么时候使用苹果内购?为什么时候苹果内购? 在苹果制定的游戏规则中,所有在App内提供的服务需要付...
    4VZhang阅读 1,748评论 6 2
  • 2016年苹果内购 http://www.jianshu.com/p/298a01961ba7 iOS应用程序内购...
    SHRookie阅读 2,839评论 0 0
  • 每次被学校深深伤害后 我就想回家 但每当我收书到一半时 脑子里就出现我在家快废了的样子 就又把书放回了原位 老爹在...
    zx七月阅读 198评论 0 0