Since many places in the project need to upload pictures, we can customize the request of uploading pictures, and customize the retrieval of albums and taking photos, which is convenient to call when used in many places.

Main steps:

  1. Customize ZLImagePicker, select photos from albums or upload photos to the page
  2. Request to upload your selected photo album or photo (compressed)
  3. Get the first step image URL and upload it to the server
  4. Display the picture (of course, enter the interface to determine whether there is a picture, no picture to display the placeholder picture, otherwise display the picture)

###Step1. Customize ZLImagePicker, select pictures from album or take photos to upload picture page

Present UIImagePickerController pair and allowsEditing whether to allow the user to edit an image:

+ (void)showImagePickerFromViewController:(UIViewController *)viewController allowsEditing:(BOOL)allowsEditing finishAction:(ZLImagePickerFinishAction)finishAction {
    if (ZLImagePickerInstance == nil) {
        ZLImagePickerInstance = [[ZLImagePicker alloc] init];
    }
    
    [ZLImagePickerInstance showImagePickerFromViewController:viewController
                                                allowsEditing:allowsEditing
                                                 finishAction:finishAction];
}
Copy the code
- (void)showImagePickerFromViewController:(UIViewController *)viewController
                            allowsEditing:(BOOL)allowsEditing
                             finishAction:(ZLImagePickerFinishAction)finishAction {
    _viewController = viewController;
    _finishAction = finishAction;
    _allowsEditing = allowsEditing;
    
    UIActionSheet *sheet = nil;
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sheet = [[UIActionSheet alloc] initWithTitle:nil
                                            delegate:self
                                   cancelButtonTitle:@"Cancel"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"Photos"The @"Select from album", nil];
    }else {
        sheet = [[UIActionSheet alloc] initWithTitle:nil
                                            delegate:self
                                   cancelButtonTitle:@"Cancel"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"Select from album", nil];
    }
    
    UIView *window = [UIApplication sharedApplication].keyWindow;
    [sheet showInView:window];
}
Copy the code

ZLUploadImage file uploads an image using AFN:

#import "AFNetworking.h"
Copy the code
/** ** network request for uploading images (image compression) ** @param url network request address for uploading images * @param name is the same as background package 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]; // NSDictionary *dict = @{@"userId": [YYPAccountTool getUserId]}; NSDictionary *dict; According to the actual circumstance of the user id / / here to upload / / 3. Send the request [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]]]; / / arbitrary binary data MIMEType application/octet - stream [formData appendPartWithFileData: imageData name: the 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); }}]; }Copy the code

Step3. Get the url of the first step image and upload it to the server

Call take photos or open photo albums to upload icon images:

[ZLImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            
            [btn setBackgroundImage:image forState:UIControlStateNormal];
            self.icon = image;
}];
Copy the code

Of course, when entering the interface, judge whether there is a picture first. If there is no picture, display the placeholder picture. Otherwise, display the picture

[iconBtn setBackgroundImage:(self.icon == nil ? [UIImage imageNamed:@"icon"]: self.icon) forState:UIControlStateNormal];
Copy the code

PS: By the way, our product does not allow the photos taken to be stored in the album:

// Save the image name: 001.png ~ 009.pngfor (int i = 1; i<=9; i++) {
     UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"00%d.png", i]];
       
	 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
       
	 [NSThread sleepForTimeInterval:1];
    }
Copy the code