ios利用 AFN 上传相册或者拍照图片

时间:2022-09-19 21:25:51

由于项目中多处需要上传图片,我们可以自定义上传图片请求,自定义调取相册及拍照,方便多处使用时调用。

主要步骤:

1.第一步:请求上传你选取的相册图片或者拍照图片(经过压缩处理)

2.第二步:获取到第一步图片url上传给服务器

3.第三步:回显图片(当然进入该界面时先判断是否有图片,无图则展示占位图片,否则就回显图片)

废话不多说,直接上代码:

1)封装的上传图片的网络请求(图片压缩) QTXUploadImage 文件

?
1
2
3
4
5
6
7
8
9
// 利用 afn 上传一张图片
#import <Foundation/Foundation.h>
 
@interface QTXUploadImage : NSObject
 
// 上传图片的网络请求(图片压缩)
+ (void)post:(NSString *)url image:(UIImage *)image name:(NSString *)name success:(void (^)(id json))success failure:(void (^)(NSError *error))failure;
 
@end
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#import "QTXUploadImage.h"
#import "AFNetworking.h"
#import "QTXAccount.h"
#import "QTXAccountTool.h"
 
@implementation QTXUploadImage
 
/**
 * 上传图片的网络请求(图片压缩)
 *
 * @param url       上传图片的网络请求地址
 * @param name       和后台包名一致
 *
 */
+ (void)post:(NSString *)url image:(UIImage *)image name:(NSString *)name success:(void (^)(id json))success failure:(void (^)(NSError *error))failure {
 
  // 1.创建网络管理者
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 
  // 2.拼接请求参数url 也可在具体控制器请求里传入
  NSDictionary *dict = @{@"userId" : [QTXAccountTool account].userId};
 
  // 3.发送请求
  [manager POST:url parameters:dict constructingBodyWithBlock:
   ^void(id<AFMultipartFormData> formData) {
 
     NSData *imageData = UIImageJPEGRepresentation(image, 0.5);//进行图片压缩
 
     // 使用日期生成图片名称
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     formatter.dateFormat = @"yyyyMMddHHmmss";
     NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
     // 任意的二进制数据MIMEType application/octet-stream
     [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
 
   } success:^void(NSURLSessionDataTask * task, id responseObject) {
 
     if (success) {
       success(responseObject);
     }
 
   } failure:^void(NSURLSessionDataTask * task, NSError * error) {
 
     if (failure) {
       failure(error);
     }
   }];
}
@end

2)封装的拍照/从相册选择 QTXImagePicker 文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 拍照/从相册选择
#import <Foundation/Foundation.h>
 
typedef void(^QTXImagePickerFinishAction)(UIImage *image);
 
@interface QTXImagePicker : NSObject
 
/**
 @param viewController 用于present UIImagePickerController对象
 @param allowsEditing  是否允许用户编辑图像
 */
+ (void)showImagePickerFromViewController:(UIViewController *)viewController
              allowsEditing:(BOOL)allowsEditing
               finishAction:(QTXImagePickerFinishAction)finishAction;
 
 
@end
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#import "QTXImagePicker.h"
 
@interface QTXImagePicker()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
 
@property (nonatomic, weak) UIViewController *viewController;
@property (nonatomic, copy) QTXImagePickerFinishAction finishAction;
@property (nonatomic, assign) BOOL allowsEditing;
 
@end
 
static QTXImagePicker *qtxImagePickerInstance = nil;
 
@implementation QTXImagePicker
 
+ (void)showImagePickerFromViewController:(UIViewController *)viewController allowsEditing:(BOOL)allowsEditing finishAction:(QTXImagePickerFinishAction)finishAction {
  if (qtxImagePickerInstance == nil) {
    qtxImagePickerInstance = [[QTXImagePicker alloc] init];
  }
 
  [qtxImagePickerInstance showImagePickerFromViewController:viewController
                        allowsEditing:allowsEditing
                        finishAction:finishAction];
}
 
- (void)showImagePickerFromViewController:(UIViewController *)viewController
              allowsEditing:(BOOL)allowsEditing
               finishAction:(QTXImagePickerFinishAction)finishAction {
  _viewController = viewController;
  _finishAction = finishAction;
  _allowsEditing = allowsEditing;
 
  UIActionSheet *sheet = nil;
 
  if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    sheet = [[UIActionSheet alloc] initWithTitle:nil
                      delegate:self
                  cancelButtonTitle:@"取消"
               destructiveButtonTitle:nil
                  otherButtonTitles:@"拍照", @"从相册选择", nil];
  }else {
    sheet = [[UIActionSheet alloc] initWithTitle:nil
                      delegate:self
                  cancelButtonTitle:@"取消"
               destructiveButtonTitle:nil
                  otherButtonTitles:@"从相册选择", nil];
  }
 
  UIView *window = [UIApplication sharedApplication].keyWindow;
  [sheet showInView:window];
}
 
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
  if ([title isEqualToString:@"拍照"]) {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = _allowsEditing;
    [_viewController presentViewController:picker animated:YES completion:nil];
 
  }else if ([title isEqualToString:@"从相册选择"]) {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//    [picker.navigationBar setBarTintColor:QTXNavColor]; // 修改相册的导航条的背景颜色
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [_viewController presentViewController:picker animated:YES completion:nil];
 
  }else {
    qtxImagePickerInstance = nil;
  }
}
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  UIImage *image = info[UIImagePickerControllerEditedImage];
  if (image == nil) {
    image = info[UIImagePickerControllerOriginalImage];
  }
 
  if (_finishAction) {
    _finishAction(image);
  }
 
  [picker dismissViewControllerAnimated:YES completion:^{}];
 
  qtxImagePickerInstance = nil;
}
 
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  if (_finishAction) {
    _finishAction(nil);
  }
 
  [picker dismissViewControllerAnimated:YES completion:^{}];
 
  qtxImagePickerInstance = nil;
}
 
@end

当使用时,在所需使用的控制器里调用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[QTXImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
      if (image) {
 
        self.idSideImage = image;
        [QTXUploadImage post:QTX_xsz1Url image:image name:@"xsz1" success:^(id json) {
          // 第一步请求上传
          QTXLog(@"图像上传请求成功 %@", json);
 
          self.idSide = json[@"data"];
 
        } failure:^(NSError *error) {
          QTXLog(@"学生证图像上传请求失败 %@", error);
        }];
      }
    }];

第二步和第三步 需要和各位自己后台server联调,就属于普通的get/post请求了,这边就不放代码了哟

插一下,我们产品没让拍照的照片存储到相册

?
1
2
3
4
5
6
7
8
9
// 存储图片名称:001.png ~ 009.png
 
for (int i = 1; i<=9; i++) {
   UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"00%d.png", i]];
 
   UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
 
   [NSThread sleepForTimeInterval:1];
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.jianshu.com/p/990d3e60c1e9?utm_source=tuicool&utm_medium=referral