LCCommonHttp.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. //
  2. // LCCommonHttp.m
  3. // LiveChat
  4. //
  5. // Created by 张灿 on 2018/4/11.
  6. // Copyright © 2018年 caicai. All rights reserved.
  7. //
  8. #import "LCCommonHttp.h"
  9. #import <AliyunOSSiOS/AliyunOSSiOS.h>
  10. OSSClient *client;
  11. @interface LCCommonHttp ()
  12. @end
  13. @implementation LCCommonHttp
  14. + (void)initOSSClientWithModel:(YOUPAILZStsModel *)model{
  15. id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
  16. OSSFederationToken * token = [OSSFederationToken new];
  17. token.tAccessKey = model.youpaipAccessKeyId;
  18. token.tSecretKey = model.youpaipAccessKeySecret;
  19. token.tToken = model.youpaipSecurityToken;
  20. token.expirationTimeInGMTFormat = model.youpaipExpiration;
  21. return token;
  22. }];
  23. NSString *endpoint = [NSString stringWithFormat:@"https://%@",model.youpaipEndpoint];
  24. client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
  25. }
  26. //关注
  27. + (void)followUserId:(NSString*)userId{
  28. [LCCommonHttp followUserId:userId liveId:nil];
  29. }
  30. + (void)followUserId:(NSString*)userId liveId:(NSString *)liveId{
  31. [LCHttpHelper requestWithURLString:UserFollow parameters:@{@"follow_uid":userId,@"live_id":liveId.length == 0 ? @"" : liveId} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  32. NSDictionary* dict = (NSDictionary*)responseObject;
  33. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  34. if (code==0) {//成功
  35. NSInteger is_follow = 0;
  36. NSString* action = [[dict objectForKey:@"data"]objectForKey:@"action"];
  37. if ([action isEqualToString:@"add"]) {
  38. [ZCHUDHelper showTitle:@"已关注"];
  39. is_follow = 1;
  40. }else if ([action isEqualToString:@"delete"]){
  41. [ZCHUDHelper showTitle:@"已取消关注"];
  42. }
  43. /// 关注状态改变,发送通知
  44. [[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeFollowState" object:self userInfo:@{@"follow_uid":userId,@"is_follow":@(is_follow)}];
  45. }
  46. } failure:^(NSError *error) {
  47. }];
  48. }
  49. //拉黑
  50. + (void)blackUserId:(NSString*)userId{
  51. [self blackUserId:userId liveId:nil];
  52. }
  53. + (void)blackUserId:(NSString *)userId liveId:(NSString *)liveId{
  54. [LCHttpHelper requestWithURLString:UserBlack parameters:@{@"black_uid":userId,@"live_id":liveId.length == 0 ? @"" : liveId} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  55. NSDictionary* dict = (NSDictionary*)responseObject;
  56. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  57. if (code==0) {//成功
  58. NSString* action = [[dict objectForKey:@"data"]objectForKey:@"action"];
  59. if ([action isEqualToString:@"add"]) {
  60. [ZCHUDHelper showTitle:@"已拉黑"];
  61. }else if ([action isEqualToString:@"delete"]){
  62. [ZCHUDHelper showTitle:@"已取消拉黑"];
  63. }
  64. }
  65. } failure:^(NSError *error) {
  66. }];
  67. }
  68. + (void)dynamicLike:(NSString*)dynamicId type:(NSInteger)type{//0点赞 1取消点赞
  69. [LCHttpHelper requestWithURLString:DynamicLike parameters:@{@"dynamic_id":dynamicId,@"type":@(type)} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  70. NSDictionary* dict = (NSDictionary*)responseObject;
  71. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  72. if (code==0) {//成功
  73. }
  74. } failure:^(NSError *error) {
  75. }];
  76. }
  77. + (void)uploadImages:(NSArray*)images type:(NSString*)type succress:(succressBlock)succress{
  78. NSMutableArray* imgNameArray = [NSMutableArray array];
  79. for (int i =0; i<images.count; i++) {
  80. NSString* str = [NSString stringWithFormat:@"file[%d]",i];
  81. [imgNameArray addObject:str];
  82. }
  83. // [LCCommonHttp uploadWithImages:images Type:@"anchor" successBlock:^(NSArray<NSString *> *ossImagePaths) {
  84. // [ZCHUDHelper dismiss];
  85. //
  86. // }];
  87. // + (void)uploadWithImages:(NSArray *)images Type:(NSString *)type successBlock:(void (^)(NSArray <NSString *>*ossImagePaths))succress;
  88. [LCHttpHelper postImageArrayToSeverWithURLString:UploadImages imgArray:images imgNameArray:imgNameArray parmeters:@{@"type":type} needToken:YES success:^(id responseObject) {
  89. NSDictionary* dict = (NSDictionary*)responseObject;
  90. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  91. if (code==0) {
  92. NSArray* imageA = [dict objectForKey:@"data"];
  93. if (succress) {
  94. succress(imageA);
  95. }
  96. }
  97. } failure:^(NSError *error) {
  98. [ZCHUDHelper dismiss];
  99. }];
  100. }
  101. /// 获取sts凭证
  102. /// @param type 类型
  103. /// album 个人相册
  104. /// anchor 女神认证
  105. /// @param succress 成功回调
  106. + (void)loadStsWithType:(NSString *)type successBlock:(void (^)(YOUPAILZStsModel *model))succress{
  107. [LCHttpHelper requestWithURLString:STS parameters:@{@"type":type} needToken:YES type:HttpRequestTypePost success:^(id responseObject) {
  108. NSDictionary* dict = (NSDictionary*)responseObject;
  109. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  110. if (code==0) {
  111. YOUPAILZStsModel *model = [YOUPAILZStsModel mj_objectWithKeyValues:[dict objectForKey:@"data"]];
  112. if (succress) {
  113. succress(model);
  114. }
  115. }
  116. } failure:^(NSError *error) {
  117. if (succress) {
  118. // succress(nil,error);
  119. }
  120. }];
  121. }
  122. /// 上传视频文件
  123. /// @param videoPath 视频文件目录
  124. /// @param type 类型 (album 个人相册,anchor 女神认证,dynamic 动态)
  125. /// @param succress 成功回调
  126. + (void)uploadWithVideoPath:(NSString *)videoPath Type:(NSString *)type successBlock:(void (^)(NSString *ossFilePath))succress{
  127. [self loadStsWithType:type successBlock:^(YOUPAILZStsModel *model) {
  128. [self ossUploadFileWithModel:model filePath:videoPath fileData:nil fileType:@".mp4" successBlock:^(NSString *ossFilePath) {
  129. dispatch_async(dispatch_get_main_queue(), ^{
  130. if (succress) {
  131. succress(ossFilePath);
  132. }
  133. });
  134. }];
  135. }];
  136. }
  137. + (void)uploadWithLocalFile:(NSString *)localPath successBlock:(void (^)(NSString *ossFilePath))succress{
  138. [self loadStsWithType:@"log" successBlock:^(YOUPAILZStsModel *model) {
  139. [self ossUploadFileWithModel:model filePath:localPath fileData:nil fileType:@".log" successBlock:^(NSString *ossFilePath) {
  140. dispatch_async(dispatch_get_main_queue(), ^{
  141. if (succress) {
  142. succress(ossFilePath);
  143. }
  144. });
  145. }];
  146. }];
  147. }
  148. /// 上传音频文件
  149. /// @param videoPath 音频文件目录
  150. /// @param type 类型
  151. /// album 个人相册
  152. /// anchor 女神认证
  153. /// game/img 游戏陪玩上传战绩截图等
  154. /// game/mp3 游戏陪玩上传15秒录音
  155. /// dynamic 动态
  156. /// @param succress 成功回调
  157. + (void)uploadWithAudioPath:(NSString *)videoPath Type:(NSString *)type successBlock:(void (^)(NSString *ossFilePath))succress{
  158. [self loadStsWithType:type successBlock:^(YOUPAILZStsModel *model) {
  159. [self ossUploadFileWithModel:model filePath:videoPath fileData:nil fileType:@".mp3" successBlock:^(NSString *ossFilePath) {
  160. dispatch_async(dispatch_get_main_queue(), ^{
  161. if (succress) {
  162. succress(ossFilePath);
  163. }
  164. });
  165. }];
  166. }];
  167. }
  168. /// 上传AAC格式音频
  169. + (void)uploadWithAACAudioPath:(NSString *)audioPath successBlock:(void (^)(NSString *ossFilePath))succress{
  170. [self loadStsWithType:@"aac" successBlock:^(YOUPAILZStsModel *model) {
  171. [self ossUploadFileWithModel:model filePath:audioPath fileData:nil fileType:@".aac" successBlock:^(NSString *ossFilePath) {
  172. dispatch_async(dispatch_get_main_queue(), ^{
  173. if (succress) {
  174. succress(ossFilePath);
  175. }
  176. });
  177. }];
  178. }];
  179. }
  180. /// 上传图片
  181. /// @param images 图片数组 只能传递UIImage 或者 NSdata
  182. /// @param type 类型 (album 个人相册,anchor 女神认证,dynamic 动态)
  183. /// @param succress 成功回调
  184. + (void)uploadWithImages:(NSArray *)images Type:(NSString *)type successBlock:(void (^)(NSArray <NSString *>*ossImagePaths))succress{
  185. if (images.count == 0) {
  186. return;
  187. }
  188. [self loadStsWithType:type successBlock:^(YOUPAILZStsModel *model) {
  189. __block NSMutableArray *ossImagePaths = [NSMutableArray array];
  190. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  191. dispatch_async(queue, ^{
  192. dispatch_group_t groupE = dispatch_group_create();
  193. for (NSInteger i = 0 ; i < images.count; i ++) {
  194. NSData *data = images[i];
  195. if ([data isKindOfClass:[UIImage class]]) {
  196. data = UIImageJPEGRepresentation((UIImage *)data, 1.0f);
  197. }
  198. dispatch_group_enter(groupE);
  199. [self ossUploadFileWithModel:model filePath:nil fileData:data fileType:@".jpg" successBlock:^(NSString *ossFilePath) {
  200. dispatch_group_leave(groupE);
  201. [ossImagePaths addObject:ossFilePath];
  202. }];
  203. }
  204. //所有请求都成功以后刷新页面
  205. dispatch_group_notify(groupE, dispatch_get_main_queue(), ^{
  206. if (succress) {
  207. succress(ossImagePaths);
  208. }
  209. });
  210. });
  211. }];
  212. }
  213. /// 阿里云文件上传
  214. /// @param model sts凭证
  215. /// @param filePath 文件路径
  216. /// @param fileData 16进制文件
  217. /// @param fileType 文件类型 例如:.mp4 .jpg
  218. /// @param succress 成功回调
  219. + (void)ossUploadFileWithModel:(YOUPAILZStsModel *)model filePath:(NSString *)filePath fileData:(NSData *)fileData fileType:(NSString *)fileType successBlock:(void (^)(NSString *ossFilePath))succress{
  220. // if (!client){
  221. [self initOSSClientWithModel:model];
  222. // }
  223. OSSPutObjectRequest * put = [OSSPutObjectRequest new];
  224. // 配置必填字段,其中bucketName为存储空间名称;objectKey等同于objectName,表示将文件上传到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
  225. NSString *ossFilePath = [model.youpaipdir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[LCTools randomFilename],fileType]];
  226. put.bucketName = model.youpaipBucketName;
  227. put.objectKey = ossFilePath;
  228. if (filePath) {
  229. put.uploadingFileURL = [NSURL fileURLWithPath:filePath]; // 根据文件目录上传
  230. }else{
  231. put.uploadingData = fileData; // 直接上传NSData
  232. }
  233. // 配置可选字段。
  234. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  235. // 指定当前上传长度、当前已经上传总长度、待上传的总长度。
  236. // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  237. };
  238. // 配置可选字段。
  239. // put.contentType = @"";
  240. // put.contentMd5 = @"";
  241. // put.contentEncoding = @"";
  242. // put.contentDisposition = @"";
  243. // 可以在上传文件时设置元信息或者HTTP头部。
  244. // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil];
  245. OSSTask * putTask = [client putObject:put];
  246. [putTask continueWithBlock:^id(OSSTask *task) {
  247. if (!task.error && succress) {
  248. succress(ossFilePath);
  249. } else {
  250. [ZCHUDHelper showTitle:task.error.localizedDescription];
  251. NSLog(@"upload object failed, error: %@" , task.error);
  252. }
  253. return nil;
  254. }];
  255. if (fileData) {
  256. [putTask waitUntilFinished];
  257. }
  258. }
  259. @end