舉例:游戲應(yīng)用中,比如我們要獲取當(dāng)前的網(wǎng)絡(luò)狀態(tài)。
所采用的網(wǎng)絡(luò)檢查庫:
蘋果官方 Reachability https://github.com/tonymillion/Reachability.git
1.創(chuàng)建 IOSNetWork.h 和 IOSNetWork.mm
.mm 可以同時(shí)使用OC 、c 和c++ 代碼
#ifndef IOSNetWork_h
#define IOSNetWork_h
#include <iostream>
#include <vector>
class IOSNetWorkDelegate{
public:
virtual ~IOSNetWorkDelegate(){};
//回調(diào)方法
virtual void networkResult(int networkcode,std::string &identifier ) = 0;
};
class IOSNetWork {
public:
IOSNetWork();
IOSNetWorkDelegate * delegate;
void getNetWorkStatus();//獲取網(wǎng)絡(luò)狀態(tài)
};
#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.創(chuàng)建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();//獲取網(wǎng)絡(luò)狀態(tài)
virtual void networkResult(int networkcode,std::string &identifier);//回調(diào)
};
#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);
}
//具體調(diào)用
IOSNetWork_Bridge * netBridge = new IOSNetWork_Bridge();
netBridge -> requestGetNetWorkStatus();