举例:游戏应用中,比如我们要获取当前的网络状态。
所采用的网络检查库:
苹果官方 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();