HTTPDataProcession.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //
  2. // HTTPDataProcession.m
  3. // Unity-iPhone
  4. //
  5. // Created by leon on 2021/2/2.
  6. //
  7. #import "HTTPDataProcession.h"
  8. @interface HTTPDataProcession ()<NSURLSessionDataDelegate>
  9. @end
  10. @implementation HTTPDataProcession
  11. #pragma mark - 网络请求数据
  12. + (void)getHTTPDataProcession:(NSString*)urlString token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
  13. // 1.创建url
  14. // 请求一个网页
  15. // NSString *urlString = @"http://test-shoes-api.hiyd.com/forum/friends?limit=1000";
  16. // 一些特殊字符编码
  17. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  18. NSURL *url = [NSURL URLWithString:urlString];
  19. // 2.创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
  20. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
  21. //2.创建一个 NSMutableURLRequest 添加 header
  22. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  23. [mutableRequest addValue:token forHTTPHeaderField:@"token"];
  24. [mutableRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  25. //3.把值覆给request
  26. request = [mutableRequest copy];
  27. // 3.采用苹果提供的共享session
  28. NSURLSession *sharedSession = [NSURLSession sharedSession];
  29. // 4.由系统直接返回一个dataTask任务
  30. NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
  31. if (data && (error == nil)){
  32. // 网络请求完成之后就会执行,NSURLSession自动实现多线程
  33. successBlock(data);
  34. } else {//
  35. // 网络访问失败
  36. for (NSString * key in error.userInfo){
  37. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  38. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  39. NSLog(@"错误信息 ERROR =========== >>> %@",error);
  40. failBlock(errorObject);
  41. }
  42. }
  43. }
  44. }];
  45. // 5.每一个任务默认都是挂起的,需要调用 resume 方法
  46. [dataTask resume];
  47. }
  48. + (void)postHTTPDataProcession:(NSString *)urlString withParams:(NSDictionary *)params token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
  49. NSURL *url = [NSURL URLWithString:urlString];
  50. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  51. request.HTTPMethod = @"POST";
  52. request.timeoutInterval = 10.0f;
  53. NSString *keyValueBody = [self getKeyValueStringWithDictionary:params];
  54. request.HTTPBody = [keyValueBody dataUsingEncoding:NSUTF8StringEncoding];
  55. NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
  56. sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=utf-8",@"token":token};
  57. NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
  58. NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
  59. if (data && (error == nil)){
  60. // 网络请求完成之后就会执行,NSURLSession自动实现多线程
  61. successBlock(data);
  62. }else{
  63. // 网络访问失败
  64. for (NSString * key in error.userInfo){
  65. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  66. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  67. failBlock(errorObject);
  68. }
  69. }
  70. }
  71. }];
  72. //发送请求
  73. [dataTask resume];
  74. }
  75. //字典转json字符串
  76. +(NSString*)getKeyValueStringWithDictionary:(NSDictionary*)dic{
  77. if (!dic||dic.count==0){
  78. return @"";
  79. }
  80. NSString *result = @"";
  81. NSArray *theAllKeys = [dic allKeys];
  82. for (int i=0; i<theAllKeys.count; i++){
  83. NSString *theKey = [theAllKeys objectAtIndex:i];
  84. NSString *theValue = [dic objectForKey:theKey];
  85. if (i==0){
  86. NSString *temp = [NSString stringWithFormat:@"%@=%@", theKey, theValue];
  87. result = [result stringByAppendingString:temp];
  88. }else {
  89. NSString *temp = [NSString stringWithFormat:@"&%@=%@", theKey, theValue];
  90. result = [result stringByAppendingString:temp];
  91. }
  92. }
  93. NSLog(@"json = %@",result);
  94. return result;
  95. }
  96. #pragma mark --------- request
  97. +(void)getFriendsList:(UserFriendsDataBlock)userFriendsDataBlock{
  98. NSString *urlString = [NSString stringWithFormat:@"%@&limit=%@&v=%@&os=%@",GAME_FRIENDS,@"1000",CFBundleVersion,OS];
  99. NSLog(@"urlString = %@",urlString);
  100. [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
  101. // 网络访问成功
  102. // NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  103. NSError * error;
  104. NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  105. // NSLog(@"gameFriends dictionary === %@ ",dictionary);
  106. if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
  107. int code = [dictionary[@"code"] intValue];
  108. if (code==0){//
  109. NSDictionary * dict = dictionary[@"data"];
  110. NSArray * arr = dict[@"list"];
  111. if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
  112. return;
  113. }
  114. NSMutableArray * jsonArr = [NSMutableArray new];//存储数据
  115. for (NSDictionary * object in arr){
  116. NSDictionary * socialInfo = object[@"socialInfo"];
  117. UserFriendsModel * model = [UserFriendsModel new];
  118. model.code = 0;
  119. [model setValuesForKeysWithDictionary:socialInfo];
  120. // NSLog(@"model =========== >>> %d %@ %@ %d %@ %@",model.trans_id,model.nickname,model.city,model.gender,model.status,model.avatar);
  121. NSMutableDictionary * gameFriends = [NSMutableDictionary new];
  122. NSMutableDictionary * userInfo = [NSMutableDictionary new];
  123. [userInfo setObject:[NSNumber numberWithInt:model.trans_id] forKey:@"id"];
  124. [userInfo setValue:model.nickname forKey:@"nickname"];
  125. [userInfo setObject:[NSNumber numberWithInt:model.gender] forKey:@"gender"];
  126. [userInfo setValue:model.city forKey:@"city"];
  127. [userInfo setValue:model.avatar forKey:@"avatar"];
  128. [gameFriends setValue:model.status forKey:@"status"];
  129. [gameFriends setValue:userInfo forKey:@"user"];
  130. [jsonArr addObject:gameFriends];
  131. // NSLog(@"gameFriends =========== >>>%@",gameFriends);
  132. }
  133. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArr options:NSJSONWritingPrettyPrinted error:nil];
  134. NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  135. // NSLog(@"GetUserFriends ==>> unity 请求好友列表 %@ ",jsonString);
  136. const char * cusChar =[jsonString UTF8String];
  137. userFriendsDataBlock(code,cusChar,jsonArr);
  138. }
  139. }
  140. }fail:^(id errorDes){
  141. }];
  142. }
  143. //邀请好友
  144. + (void)inviteFriends:(int)friendid inviteInfo:(NSString*)inviteInfo inviteDataBlock:(InviteDataBlock)inviteDataBlock{
  145. NSString * invite_user_id = [NSString stringWithFormat:@"%d",friendid];
  146. NSString *urlString = [NSString stringWithFormat:@"%@&invite_user_id=%@&invite=%@&game_id=%@",GAME_INVITE,invite_user_id,inviteInfo,[CacheTool getGameId]];
  147. NSLog(@"InviteFriend urlString ===>> %@",urlString);
  148. [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
  149. NSError * error;
  150. NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  151. // NSLog(@"gameFriends dictionary === %@ ",dictionary);
  152. if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
  153. int code = [dictionary[@"code"] intValue];
  154. if (code==0){//
  155. inviteDataBlock(@"邀请成功");
  156. }
  157. }
  158. }fail:^(id errorDes){
  159. }];
  160. }
  161. //获取排行榜
  162. + (void)GetRank:(int)type rankDataBlock:(RankDataBlock)rankDataBlock{
  163. NSString * scoreType;
  164. if (type ==0){
  165. scoreType = @"world";
  166. }else{
  167. scoreType = @"friend";
  168. }
  169. NSString *urlString = [NSString stringWithFormat:@"%@&game_id=%@&scope=%@",GAME_RANK,[CacheTool getGameId],scoreType];
  170. NSLog(@"urlString == %@",urlString);
  171. [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
  172. NSError * error;
  173. NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  174. // NSLog(@"GetRank dictionary === %@ ",dictionary);
  175. if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
  176. int code = [dictionary[@"code"] intValue];
  177. if (code==0){//
  178. // NSLog(@"榜单数据 ====>> %@",dictionary);
  179. if (dictionary!=nil){
  180. int code = [dictionary[@"code"] intValue];
  181. if (code==0){//
  182. NSDictionary * dict = dictionary[@"data"];
  183. NSArray * arr = dict[@"records"];
  184. if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
  185. return;
  186. }
  187. NSMutableArray * userArr = [NSMutableArray new];//存储数据
  188. NSMutableDictionary * list = [NSMutableDictionary new];
  189. int rank_i = 0;
  190. for (NSDictionary * object in arr){
  191. rank_i++;
  192. RankModel * model = [RankModel new];
  193. // model.code = 0;
  194. [model setValuesForKeysWithDictionary:object];
  195. NSMutableDictionary * rank = [NSMutableDictionary new];
  196. // [gameFriends setValue:model.status forKey:@"status"];
  197. NSMutableDictionary * user = [NSMutableDictionary new];
  198. [user setObject:[NSNumber numberWithInt:model.user_id] forKey:@"id"];
  199. [user setValue:model.user_name forKey:@"nickname"];
  200. [user setObject:[NSNumber numberWithInt:model.user_gender] forKey:@"gender"];
  201. [user setValue:@"" forKey:@"address"];
  202. [user setValue:model.user_avatar forKey:@"avatar"];
  203. [rank setObject:user forKey:@"user"];
  204. [rank setObject:[NSNumber numberWithInt:model.score] forKey:@"score"];
  205. [rank setObject:[NSNumber numberWithInt:rank_i] forKey:@"rank"];
  206. [userArr addObject:rank];
  207. [list setObject:userArr forKey:@"list"];
  208. }
  209. // NSLog(@"榜单数据 list ====>> %@",list);
  210. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:list options:NSJSONWritingPrettyPrinted error:nil];
  211. NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  212. // NSLog(@"HTTPDataProcession 请求榜单列表 GetRank 异步回调 ==>> %@ ",jsonString);
  213. const char * cusChar =[jsonString UTF8String];
  214. rankDataBlock(cusChar);
  215. }
  216. }
  217. }
  218. }
  219. }fail:^(id errorDes){
  220. NSLog(@"HTTPDataProcession 获取榜单数据 错误 ====>> %@",errorDes);
  221. }];
  222. }
  223. /**
  224. 开始游戏
  225. */
  226. +(void)gameStart{
  227. NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_START,[CacheTool getGameId]];
  228. [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
  229. NSError * error;
  230. NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  231. // NSLog(@"gameFriends dictionary === %@ ",dictionary);
  232. if (!error && dictionary!=nil && ![dictionary isKindOfClass:[NSNull class]]){
  233. int code = [dictionary[@"code"] intValue];
  234. if (code==0){//
  235. NSLog(@"gameStart 上传成功 ==>> %@",dictionary[@"message"]);
  236. }
  237. }
  238. }fail:^(id errorDes){
  239. NSLog(@"gameStart 上传失败 ==>> %@",errorDes);
  240. }];
  241. }
  242. /**
  243. 结束游戏
  244. */
  245. +(void)gameEnd{
  246. NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_END,[CacheTool getGameId]];
  247. [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken] success:^(id data){
  248. NSError * error;
  249. NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  250. // NSLog(@"gameFriends dictionary === %@ ",dictionary);
  251. if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
  252. int code = [dictionary[@"code"] intValue];
  253. if (code==0){//
  254. NSLog(@"gameEnd 上传成功 ==>> %@",dictionary[@"message"]);
  255. }
  256. }
  257. }fail:^(id errorDes){
  258. NSLog(@"gameEnd 上传失败 ==>> %@",errorDes);
  259. }];
  260. }
  261. /**
  262. 上传运动数据
  263. */
  264. +(void)postGameRecord:(int)level
  265. score:(double)score
  266. record:(int)record
  267. mode:(int)mode
  268. opponentId:(int)opponentId
  269. gameEndDataBlock:(GameEndDataBlock)gameEndDataBlock{
  270. NSMutableDictionary * gameRecord = [NSMutableDictionary new];
  271. //缓存的token、game_id
  272. NSString * game_id = [CacheTool getGameId];
  273. [gameRecord setObject:game_id forKey:@"game_id"];//游戏类型
  274. //预留字段:默认
  275. [gameRecord setObject:@0 forKey:@"distance"];//废弃
  276. [gameRecord setObject:@0 forKey:@"is_cancel"];//是否正常停止游戏 正常0 不正常1
  277. //unity回调数据
  278. [gameRecord setObject:[NSNumber numberWithDouble:score] forKey:@"score"];
  279. [gameRecord setObject:[NSNumber numberWithInt:mode] forKey:@"mode"];
  280. //缓存的动作数据和持续时间
  281. NSDictionary * movements = [IOS_NSUSERDEFAULT objectForKey:IOSSDK_MOTIONCOUNT];
  282. if (movements!=nil){
  283. NSDictionary * sub = movements[@"movements"];
  284. NSData * jsonData = [NSJSONSerialization dataWithJSONObject:sub options:NSJSONWritingPrettyPrinted error:nil];
  285. NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  286. [gameRecord setObject:jsonString forKey:@"movements"];
  287. [gameRecord setObject:movements[@"duration"] forKey:@"duration"];
  288. [gameRecord setObject:movements[@"play_group"] forKey:@"play_group"];
  289. }
  290. // NSLog(@"gameRecord = %@",gameRecord);
  291. [HTTPDataProcession postHTTPDataProcession:GAME_RECORD withParams:gameRecord token:[CacheTool getToken] success:^(id data){
  292. NSError * error;
  293. NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  294. if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
  295. int code = [dictionary[@"code"] intValue];
  296. if (code==0){
  297. NSDictionary * data = dictionary[@"data"];
  298. if (data!=nil) {
  299. NSDictionary * record = data[@"record"];
  300. if (record!=nil) {
  301. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:record options:NSJSONWritingPrettyPrinted error:nil];
  302. NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  303. const char * cusChar =[jsonString UTF8String];
  304. gameEndDataBlock(cusChar);
  305. NSLog(@"gameRecord 上传成功 %@",record);
  306. }
  307. }
  308. }else{
  309. NSLog(@"gameRecord 请求错误 =========== >>> %@",dictionary[@"msg"]);
  310. }
  311. }
  312. }fail:^(id errorDes){
  313. NSLog(@"gameRecord 请求失败 =========== >>> %@",errorDes);
  314. }];
  315. }
  316. //
  317. +(NSString*)getBaseUrl{
  318. NSString * baseUrl;
  319. int isdebug = [[CacheTool getGameDebug] intValue];
  320. if (isdebug == 1){//测试环境
  321. baseUrl = @"https://test-shoes-api.funfet.com";
  322. }else{
  323. baseUrl = @"https://shoes-api.funfet.com";
  324. }
  325. return baseUrl;
  326. }
  327. @end