123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495 |
- //
- // HTTPDataProcession.m
- // Unity-iPhone
- //
- // Created by leon on 2021/2/2.
- //
- #import "HTTPDataProcession.h"
- @interface HTTPDataProcession ()<NSURLSessionDataDelegate>
- @end
- @implementation HTTPDataProcession
- #pragma mark - 网络请求数据
- + (void)getHTTPDataProcession:(NSString*)urlString token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
-
- // 1.创建url
- // 请求一个网页
- // NSString *urlString = @"http://test-shoes-api.hiyd.com/forum/friends?limit=1000";
- // 一些特殊字符编码
- urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- NSURL *url = [NSURL URLWithString:urlString];
-
- // 2.创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
- NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
- //2.创建一个 NSMutableURLRequest 添加 header
- NSMutableURLRequest *mutableRequest = [request mutableCopy];
- [mutableRequest addValue:token forHTTPHeaderField:@"token"];
- [mutableRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
- //3.把值覆给request
- request = [mutableRequest copy];
-
- // 3.采用苹果提供的共享session
- NSURLSession *sharedSession = [NSURLSession sharedSession];
- // 4.由系统直接返回一个dataTask任务
- NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
- if (data && (error == nil)){
-
- // 网络请求完成之后就会执行,NSURLSession自动实现多线程
- successBlock(data);
-
- } else {//
- // 网络访问失败
- for (NSString * key in error.userInfo){
-
- if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
-
- id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
-
- NSLog(@"错误信息 ERROR =========== >>> %@",error);
- failBlock(errorObject);
- }
-
- }
- }
-
- }];
- // 5.每一个任务默认都是挂起的,需要调用 resume 方法
- [dataTask resume];
-
- }
- + (void)postHTTPDataProcession:(NSString *)urlString withParams:(NSDictionary *)params token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
-
- NSURL *url = [NSURL URLWithString:urlString];
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
- request.HTTPMethod = @"POST";
- request.timeoutInterval = 10.0f;
-
- NSString *keyValueBody = [self getKeyValueStringWithDictionary:params];
- request.HTTPBody = [keyValueBody dataUsingEncoding:NSUTF8StringEncoding];
-
- NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
- sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=utf-8",@"token":token};
-
- NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
-
- NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
-
- if (data && (error == nil)){
-
- // 网络请求完成之后就会执行,NSURLSession自动实现多线程
- successBlock(data);
-
- }else{
-
- // 网络访问失败
- for (NSString * key in error.userInfo){
-
- if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
-
- id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
-
- failBlock(errorObject);
- }
-
- }
- }
-
- }];
-
- //发送请求
- [dataTask resume];
-
- }
- //字典转json字符串
- +(NSString*)getKeyValueStringWithDictionary:(NSDictionary*)dic{
-
- if (!dic||dic.count==0){
- return @"";
- }
-
- NSString *result = @"";
- NSArray *theAllKeys = [dic allKeys];
- for (int i=0; i<theAllKeys.count; i++){
- NSString *theKey = [theAllKeys objectAtIndex:i];
- NSString *theValue = [dic objectForKey:theKey];
- if (i==0){
- NSString *temp = [NSString stringWithFormat:@"%@=%@", theKey, theValue];
- result = [result stringByAppendingString:temp];
- }else {
- NSString *temp = [NSString stringWithFormat:@"&%@=%@", theKey, theValue];
- result = [result stringByAppendingString:temp];
- }
- }
- NSLog(@"json = %@",result);
- return result;
-
- }
- #pragma mark --------- request
- +(void)getFriendsList:(UserFriendsDataBlock)userFriendsDataBlock{
-
- NSString *urlString = [NSString stringWithFormat:@"%@&limit=%@&v=%@&os=%@",GAME_FRIENDS,@"1000",CFBundleVersion,OS];
- NSLog(@"urlString = %@",urlString);
- [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
- // 网络访问成功
- // NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
- NSError * error;
- NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
-
- // NSLog(@"gameFriends dictionary === %@ ",dictionary);
- if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
-
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
-
- NSDictionary * dict = dictionary[@"data"];
- NSArray * arr = dict[@"list"];
- if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
- return;
- }
-
- NSMutableArray * jsonArr = [NSMutableArray new];//存储数据
- for (NSDictionary * object in arr){
-
- NSDictionary * socialInfo = object[@"socialInfo"];
- UserFriendsModel * model = [UserFriendsModel new];
- model.code = 0;
- [model setValuesForKeysWithDictionary:socialInfo];
-
- // NSLog(@"model =========== >>> %d %@ %@ %d %@ %@",model.trans_id,model.nickname,model.city,model.gender,model.status,model.avatar);
-
- NSMutableDictionary * gameFriends = [NSMutableDictionary new];
-
- NSMutableDictionary * userInfo = [NSMutableDictionary new];
- [userInfo setObject:[NSNumber numberWithInt:model.trans_id] forKey:@"id"];
- [userInfo setValue:model.nickname forKey:@"nickname"];
- [userInfo setObject:[NSNumber numberWithInt:model.gender] forKey:@"gender"];
- [userInfo setValue:model.city forKey:@"city"];
- [userInfo setValue:model.avatar forKey:@"avatar"];
-
- [gameFriends setValue:model.status forKey:@"status"];
- [gameFriends setValue:userInfo forKey:@"user"];
- [jsonArr addObject:gameFriends];
- // NSLog(@"gameFriends =========== >>>%@",gameFriends);
- }
-
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArr options:NSJSONWritingPrettyPrinted error:nil];
-
- NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
-
- // NSLog(@"GetUserFriends ==>> unity 请求好友列表 %@ ",jsonString);
-
- const char * cusChar =[jsonString UTF8String];
-
- userFriendsDataBlock(code,cusChar,jsonArr);
-
- }
-
- }
-
- }fail:^(id errorDes){
-
- }];
-
- }
- //邀请好友
- + (void)inviteFriends:(int)friendid inviteInfo:(NSString*)inviteInfo inviteDataBlock:(InviteDataBlock)inviteDataBlock{
-
- NSString * invite_user_id = [NSString stringWithFormat:@"%d",friendid];
- NSString *urlString = [NSString stringWithFormat:@"%@&invite_user_id=%@&invite=%@&game_id=%@",GAME_INVITE,invite_user_id,inviteInfo,[CacheTool getGameId]];
- NSLog(@"InviteFriend urlString ===>> %@",urlString);
- [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
-
- NSError * error;
- NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
- // NSLog(@"gameFriends dictionary === %@ ",dictionary);
- if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
-
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
-
- inviteDataBlock(@"邀请成功");
-
- }
-
- }
-
- }fail:^(id errorDes){
-
- }];
-
- }
- //获取排行榜
- + (void)GetRank:(int)type rankDataBlock:(RankDataBlock)rankDataBlock{
- NSString * scoreType;
- if (type ==0){
- scoreType = @"world";
- }else{
- scoreType = @"friend";
- }
-
- NSString *urlString = [NSString stringWithFormat:@"%@&game_id=%@&scope=%@",GAME_RANK,[CacheTool getGameId],scoreType];
- NSLog(@"urlString == %@",urlString);
-
- [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
- NSError * error;
- NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
-
- // NSLog(@"GetRank dictionary === %@ ",dictionary);
-
- if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
- // NSLog(@"榜单数据 ====>> %@",dictionary);
-
- if (dictionary!=nil){
-
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
-
- NSDictionary * dict = dictionary[@"data"];
- NSArray * arr = dict[@"records"];
- if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
- return;
- }
- NSMutableArray * userArr = [NSMutableArray new];//存储数据
-
- NSMutableDictionary * list = [NSMutableDictionary new];
- int rank_i = 0;
-
- for (NSDictionary * object in arr){
-
- rank_i++;
-
- RankModel * model = [RankModel new];
- // model.code = 0;
- [model setValuesForKeysWithDictionary:object];
-
- NSMutableDictionary * rank = [NSMutableDictionary new];
- // [gameFriends setValue:model.status forKey:@"status"];
- NSMutableDictionary * user = [NSMutableDictionary new];
- [user setObject:[NSNumber numberWithInt:model.user_id] forKey:@"id"];
- [user setValue:model.user_name forKey:@"nickname"];
- [user setObject:[NSNumber numberWithInt:model.user_gender] forKey:@"gender"];
- [user setValue:@"" forKey:@"address"];
- [user setValue:model.user_avatar forKey:@"avatar"];
-
- [rank setObject:user forKey:@"user"];
- [rank setObject:[NSNumber numberWithInt:model.score] forKey:@"score"];
- [rank setObject:[NSNumber numberWithInt:rank_i] forKey:@"rank"];
-
- [userArr addObject:rank];
-
- [list setObject:userArr forKey:@"list"];
- }
-
- // NSLog(@"榜单数据 list ====>> %@",list);
-
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:list options:NSJSONWritingPrettyPrinted error:nil];
-
- NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
-
- // NSLog(@"HTTPDataProcession 请求榜单列表 GetRank 异步回调 ==>> %@ ",jsonString);
-
- const char * cusChar =[jsonString UTF8String];
-
- rankDataBlock(cusChar);
- }
- }
- }
- }
-
- }fail:^(id errorDes){
- NSLog(@"HTTPDataProcession 获取榜单数据 错误 ====>> %@",errorDes);
- }];
-
- }
- /**
- 开始游戏
- */
- +(void)gameStart{
- NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_START,[CacheTool getGameId]];
- [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
-
- NSError * error;
- NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
- // NSLog(@"gameFriends dictionary === %@ ",dictionary);
- if (!error && dictionary!=nil && ![dictionary isKindOfClass:[NSNull class]]){
-
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
-
- NSLog(@"gameStart 上传成功 ==>> %@",dictionary[@"message"]);
-
- }
-
- }
-
- }fail:^(id errorDes){
-
- NSLog(@"gameStart 上传失败 ==>> %@",errorDes);
- }];
-
- }
- /**
- 结束游戏
- */
- +(void)gameEnd{
-
- NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_END,[CacheTool getGameId]];
- [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
-
- NSError * error;
- NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
- // NSLog(@"gameFriends dictionary === %@ ",dictionary);
- if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
-
- int code = [dictionary[@"code"] intValue];
- if (code==0){//
-
- NSLog(@"gameEnd 上传成功 ==>> %@",dictionary[@"message"]);
-
- }
-
- }
-
- }fail:^(id errorDes){
-
- NSLog(@"gameEnd 上传失败 ==>> %@",errorDes);
- }];
-
- }
- /**
- 上传运动数据
- */
- +(void)postGameRecord:(int)level
- score:(double)score
- record:(int)record
- mode:(int)mode
- opponentId:(int)opponentId
- gameEndDataBlock:(GameEndDataBlock)gameEndDataBlock{
-
- NSMutableDictionary * gameRecord = [NSMutableDictionary new];
- //缓存的token、game_id
- NSString * game_id = [CacheTool getGameId];
- [gameRecord setObject:game_id forKey:@"game_id"];//游戏类型
- //预留字段:默认
- [gameRecord setObject:@0 forKey:@"distance"];//废弃
- [gameRecord setObject:@0 forKey:@"is_cancel"];//是否正常停止游戏 正常0 不正常1
- //unity回调数据
- [gameRecord setObject:[NSNumber numberWithDouble:score] forKey:@"score"];
- [gameRecord setObject:[NSNumber numberWithInt:mode] forKey:@"mode"];
-
- //缓存的动作数据和持续时间
- NSDictionary * movements = [IOS_NSUSERDEFAULT objectForKey:IOSSDK_MOTIONCOUNT];
- if (movements!=nil){
- NSDictionary * sub = movements[@"movements"];
- NSData * jsonData = [NSJSONSerialization dataWithJSONObject:sub options:NSJSONWritingPrettyPrinted error:nil];
- NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
- [gameRecord setObject:jsonString forKey:@"movements"];
- [gameRecord setObject:movements[@"duration"] forKey:@"duration"];
- [gameRecord setObject:movements[@"play_group"] forKey:@"play_group"];
- }
-
- // NSLog(@"gameRecord = %@",gameRecord);
- [HTTPDataProcession postHTTPDataProcession:GAME_RECORD withParams:gameRecord token:[CacheTool getToken] success:^(id data){
- NSError * error;
- NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
- if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
- int code = [dictionary[@"code"] intValue];
- if (code==0){
-
- NSDictionary * data = dictionary[@"data"];
- if (data!=nil) {
- NSDictionary * record = data[@"record"];
- if (record!=nil) {
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:record options:NSJSONWritingPrettyPrinted error:nil];
- NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
- const char * cusChar =[jsonString UTF8String];
- gameEndDataBlock(cusChar);
- NSLog(@"gameRecord 上传成功 %@",record);
- }
- }
-
- }else{
- NSLog(@"gameRecord 请求错误 =========== >>> %@",dictionary[@"msg"]);
- }
-
- }
-
- }fail:^(id errorDes){
-
- NSLog(@"gameRecord 请求失败 =========== >>> %@",errorDes);
- }];
-
-
- }
- //
- +(NSString*)getBaseUrl{
- NSString * baseUrl;
- int isdebug = [[CacheTool getGameDebug] intValue];
- if (isdebug == 1){//测试环境
- baseUrl = @"https://test-shoes-api.funfet.com";
- }else{
- baseUrl = @"https://shoes-api.funfet.com";
- }
- return baseUrl;
- }
- @end
|