cocos2d-x C++和IOS OC的交互

举例:游戏应用中,比如我们要获取当前的网络状态。

所采用的网络检查库:
苹果官方 Reachability https://github.com/tonymillion/Reachability.git

1.创建 IOSNetWork.h 和 IOSNetWork.mm
.mm 可以同时使用OC 、c 和c++ 代码

#ifndef IOSNetWork_h
#define IOSNetWork_h
#include <iostream>
#include <vector>
class IOSNetWorkDelegate{
public:
    virtual ~IOSNetWorkDelegate(){};
    //回调方法
    virtual void networkResult(int networkcode,std::string &identifier ) = 0;
};
class IOSNetWork {
public:
    IOSNetWork();
    IOSNetWorkDelegate * delegate;
    void getNetWorkStatus();//获取网络状态
    
};
#endif /* IOSNetWork_h */
#import <Foundation/Foundation.h>
#import "Reachability.h"
#include "IOSNetWork.h"

IOSNetWork::IOSNetWork(){
    
}

void IOSNetWork::getNetWorkStatus(){
    
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    reach.reachableBlock = ^(Reachability*reach)
    {

        NSString * type = @"";
        if (reach.isReachableViaWiFi) {
            type = @"WIFI";
        }
        else if (reach.isReachableViaWWAN){
            type = @"WWAN";
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{

              std::string identifier([type UTF8String]);
            this->delegate->networkResult(200,identifier);
        });
    };
    
    reach.unreachableBlock = ^(Reachability*reach)
    {
          NSString * type = @"";
        NSLog(@"UNREACHABLE!");
        std::string identifier([type UTF8String]);
        this->delegate->networkResult(404,identifier);
    };
    
    // Start the notifier, which will cause the reachability object to retain itself!
    [reach startNotifier];
}

2.创建bridge

//IOSNetWork_Bridge.h

#ifndef IOSNetWork_Bridge_h
#define IOSNetWork_Bridge_h
#import "IOSNetWork.h"
class IOSNetWork_Bridge: public IOSNetWorkDelegate {
public:
    IOSNetWork_Bridge();
     ~IOSNetWork_Bridge();
    IOSNetWork * network;
    void requestGetNetWorkStatus();//获取网络状态
    virtual void networkResult(int networkcode,std::string &identifier);//回调
};

#endif /* IOSNetWork_Bridge_h */

//IOSNetWork_Bridge.cpp

#include <stdio.h>
#include "IOSNetWork_Bridge.h"
IOSNetWork_Bridge::IOSNetWork_Bridge(){
    network = new IOSNetWork();
    network -> delegate = this;
}
IOSNetWork_Bridge::~IOSNetWork_Bridge(){
    delete network;
}

void IOSNetWork_Bridge::requestGetNetWorkStatus(){
    network -> getNetWorkStatus();
}

void IOSNetWork_Bridge::networkResult(int networkcode,std::string &identifier){
    log(networkcode);
}

//具体调用

  IOSNetWork_Bridge  * netBridge =  new IOSNetWork_Bridge();
    netBridge -> requestGetNetWorkStatus();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容