iOS开发项目中使用七牛保存用户头像

在公司的项目中使用七牛来进行用户头像的存储。

上传头像的实现步骤如下

首先从后端获取QN的key和token

- (void)getTokenFromQN{    
    NSDictionary *parameter = @{ @"type":@"avatar", };
    [[QLBaseNetWorking shareManager]QL_Get:[NSString stringWithFormat:@"%@%@",API_AHead,API_AGetQiniuToken] parameters:parameter resultWithBlock:^(BOOL success, id responseData) {
        if (success) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
            if (((NSNumber *)[dic objectForKey:@"code"]).intValue == 0) {
                NSDictionary *dataDic = [dic objectForKey:@"item"];
                self.domain = dataDic[@"key"];//七牛key
                self.token = dataDic[@"uploadToken"];//七牛token
                [self uploadImageToQNFilePath:[self getImagePath:self.pickImage]];
            }
        }
    }];
}

然后使用QNUploadManager进行文件上传

-(void)uploadImageToQNFilePath:(NSString *)filePath
{
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption * uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
        PTTLog(@"percent == %.2f",percent);
        
    } params:nil checkCrc:NO cancellationSignal:nil];

    PTTLog(@"%@%@",filePath,self.token);
    
    [upManager putFile:filePath key: self.domain token:self.token  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {

        [self showTextOnly:@"头像上传成功"];
        [UserManager shareEngine].token.headimgurl =[[resp objectForKey:@"item"] objectForKey:@"imgUrl"];
        [[UserManager shareEngine] loginWithUserModel:[UserManager shareEngine].token];
        [self dataFactory:[UserManager shareEngine].token.headimgurl name:[UserManager shareEngine].token.nickname phone:[UserManager shareEngine].token.phone];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
        
    } option:uploadOption];
 
}

上述方法是使用本地保存的图片地址来进行上传操作,还有一种方法直接上传图片的数据

- (void)uploadWithFile:(NSString *)file withProgress:(QNUpProgressHandler)progress success:(void(^)(NSString*url))success failure:(void(^)())failure {
    UIImage *getImage = [UIImage imageWithContentsOfFile:file];
    QNUploadOption *option = [[QNUplLBHTTPRequestoadOption alloc] initWithMime:nil progressHandler:progress params:nil checkCrc:NO cancellationSignal:nil];
    //先获取token
    [LBHTTPRequest postImage:[LBHTTPRequest getUserId] token:[LBHTTPRequest getUserToken] userType:@"1" fileExt:@"png" SuccessBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
  if (isSuccess) {
    NSString * token = resultDic[@"uploadToken"];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    NSData *data;
    if (UIImagePNGRepresentation(getImage) == nil){
      data = UIImageJPEGRepresentation(getImage, 1);
    } else {
      data = UIImagePNGRepresentation(getImage);
    }
  [upManager putData:data key:resultDic[@"fileKey"] token:token
complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp)   {
      [SVProgressHUD dismiss];
      // isLoadLogo = NO;
      if([resp[@"result"] intValue] == 200){
        [LBUploadManager sharedInstance].imageUrl = resp[@"fileUrl"];
        success([LBUploadManager sharedInstance].imageUrl);
      }
    } option:option];
  }
  }];
}

上传多张图片到七牛,利用简单的异步处理多个图片上传

并且在用户使用手机网络的时候进行提示

//上传多张图片

- (void)uploadImagesWithFileArray:(NSMutableArray *)fileArray progress:(void(^)(CGFloat))progress success:(void(^)(NSString *))success failure:(void(^)())failure {
  //判断网络状态
  AFNetworkReachabilityManager *netStatus = [AFNetworkReachabilityManager sharedManager];
  [netStatus startMonitoring];
  [netStatus setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  if (status == AFNetworkReachabilityStatusNotReachable) {//无网络连接
    [SVProgressHUD showWithStatus:@"当前无网络连接"];
  }
  if (status == AFNetworkReachabilityStatusReachableViaWWAN) { //手机自带网络
  //提示用户是否继续进行上传图片
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"当前使用的手机流量,您是否继续?" delegate:[LBUploadManager sharedInstance] cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
  }
  if (status == AFNetworkReachabilityStatusReachableViaWiFi) { //wifi
  //1.获取所有的图片
    NSMutableArray *imageArray = [[LBUploadManager sharedInstance]getImageArrayWithFileArray:fileArray];
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
    for (int i = 0; i < imageArray.count; i ++ ) {
      dispatch_async(queue, ^{  //上传头像
      [[LBUploadManager sharedInstance]uploadWithFile:imageArray[i] withProgress:^(NSString *key, float percent) {
        progress(percent);
      } success:^(NSString *url) {
        success(url);
      //获取studentId
      NSString *key = [[LBUploadManager sharedInstance].fileArray[i] allKeys].lastObject;
      [LBHTTPRequest PostUpdataStudentImageWithStudentId:key withStudentImage:url andSuccessBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"refresh" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"updataStudentData" object:nil];
        }
          [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:imageArray[i]];
          [[LBUploadManager sharedInstance].fileArray removeObject:imageArray[i]];
        }];
      } failure:^{
    }];
    });
   }
  });
 }
    if (status == AFNetworkReachabilityStatusUnknown) { //未知网络
    }
  }];
}

你可能感兴趣的:(iOS开发项目中使用七牛保存用户头像)