访问百度的时间api获取到网页,使用CCHttpClient进行网络时间的数据请求和使用rapidjson解析Http请求得到的json数据
如果使用rapidjson解析失败则对网络数据的字符串使用正则进行截取,获取时间字符串的10个字符,atoi得到时间值;
如果使用rapidjson解析失败则对网络数据的字符串使用正则(c++11 <regex>)进行截取,获取时间字符串的10个字符,
atoi得到时间值;如果网络访问失败或者获取解析网络数据失败,则根据不同平台去获取本地时间
新建一个c++类MyTime,继承自CCNode并重写init()方法。然后引入CCHttpClient和rapidjson需要的头文件
#ifndef __MYTIME_H__
#define __MYTIME_H__
#include "cocos2d.h"
#include "cocos-ext.h"
#include "json\rapidjson.h"
#include "network\HttpClient.h"
using namespace std;
using namespace cocos2d;
using namespace extension;
using namespace rapidjson;
using namespace network;
//class MyTime;
//typedef void (Object::*SEL_MyTime)(MyTime* pSender);
//#define myTime_selector(_SELECTOR)(SEL_MyTime)(&_SELCTOR);
class MyTime : public Node
{
public :
CREATE_FUNC(MyTime);
CC_SYNTHESIZE(int, m_Year, Year);
CC_SYNTHESIZE(int, m_Month, Month);
CC_SYNTHESIZE(int, m_Day, Day);
CC_SYNTHESIZE(int, m_Hour, Hour);
CC_SYNTHESIZE(int, m_Minute, Minute);
CC_SYNTHESIZE(int, m_Second, Second);
void requestNetTime();
void requestNetTime(/*CCObject* pTarget, */const function<void()>& pSelector);
//void displayTime();
private:
virtual bool init();
function<void()> m_pSelector;
//SEL_MyTime m_pSelector;
void onHttpComplete(HttpClient* sender, HttpResponse* response);
//解析json文件,获取时间值
bool readJson(string jsonStr);
//从doucment对象获取key值失败,进行的截取字符串操作,获取时间值
bool splitString(const string content,string pattern);
//网络获取时间值失败,进行本地获取时间值,
void getLocalTime();
//设置时间对象
void setTime(time_t tm);
};
#endif</span></span>