同一个cell上的同一个按钮调用系统相册并上传图片

#import

#define ZXUPLOAD_IMAGE [ZXUploadImage shareUploadImage]

//写了一个代理方法

@protocolZXUploadImageDelegate

@optional

- (void)uploadImageToServerWithImage:(UIImage*)image;

@end

@interface ZXUploadImage : NSObject

UINavigationControllerDelegate,

UIImagePickerControllerDelegate>

{

    //如果你调不出来UIViewController,请添加UIKit头文件

    UIViewController*_fatherViewController;

}

@property(nonatomic,weak)id uploadImageDelegate;

//单例方法

+ (ZXUploadImage*)shareUploadImage;

//弹出选项的方法

- (void)showActionSheetInFatherViewController:(UIViewController*)fatherVC delegate:(id)aDelegate;

@end


#import "ZXUploadImage.h"

staticZXUploadImage*zxUploadImage =nil;

@implementation ZXUploadImage

+ (ZXUploadImage*)shareUploadImage {


    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        zxUploadImage = [[ZXUploadImage alloc] init];

    });

    return zxUploadImage;

}

- (void)showActionSheetInFatherViewController:(UIViewController*)fatherVC delegate:(id)aDelegate {


    zxUploadImage.uploadImageDelegate = aDelegate;

    _fatherViewController = fatherVC;

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil

                                                       delegate:self

                                              cancelButtonTitle:@"取消"

                                         destructiveButtonTitle:nil

                                              otherButtonTitles:@"从手机相册上传",@"相机拍照",nil];

    [sheetshowInView:fatherVC.view];

}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if(buttonIndex ==0) {

        [selffromPhotos];

    }elseif(buttonIndex ==1) {

        [self createPhotoView];

    }

}

#pragma mark - 头像(相机和从相册中选择)

- (void)createPhotoView {

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        UIImagePickerController *imagePC = [[UIImagePickerController alloc] init];

        imagePC.sourceType                =UIImagePickerControllerSourceTypeCamera;

        imagePC.delegate                  =self;

        imagePC.allowsEditing            =YES;

        [_fatherViewController presentViewController:imagePC

                                            animated:YES

                                          completion:^{

                                          }];

    }else{

        UIAlertView* alert = [[UIAlertViewalloc]initWithTitle:@"提示"

                                                         message:@"该设备没有照相机"

                                                        delegate:nil

                                               cancelButtonTitle:@"确定"

                                               otherButtonTitles:nil];

        [alertshow];

    }

}

//图片库方法(从手机的图片库中查找图片)

- (void)fromPhotos {

    UIImagePickerController *imagePC = [[UIImagePickerController alloc] init];

    imagePC.sourceType                =UIImagePickerControllerSourceTypePhotoLibrary;

    imagePC.delegate                  =self;

    imagePC.allowsEditing            =YES;

    [_fatherViewController presentViewController:imagePC

                                        animated:YES

                                      completion:^{

                                      }];

}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {

    [pickerdismissViewControllerAnimated:YES completion:^{

    }];

    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

    /**

     *  上传用户头像

     */

    if(self.uploadImageDelegate&& [self.uploadImageDelegaterespondsToSelector:@selector(uploadImageToServerWithImage:)]) {

        [self.uploadImageDelegate uploadImageToServerWithImage:image];

    }

}

在cellForRowAtIndexPath:里

__weak typeof(self) weakSelf = self;

        cell.cameraNameBtnBlock = ^{

            [weakSelfchoseImage:indexPath.row];

        };

#pragma mark ----相册单例 刷新单行cell

- (void)choseImage:(NSInteger) index{

 [ZXUPLOAD_IMAGE showActionSheetInFatherViewController:self delegate:self];

    self.index= index;

    NSLog(@"====%ld",self.index);

    NSIndexPath*indexPathA = [NSIndexPath indexPathForRow:indexinSection:0];

    [self.tabelView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationRight];

}

#pragma mark - ZXUploadImageDelegate

- (void)uploadImageToServerWithImage:(UIImage*)image {

    //在这里处理得到的image

    self.image= image;

    [self.cell.cameraNameBtn setImage:self.image forState:UIControlStateNormal];

}

#pragma mark --上传图片

- (void)upImag{

    //此处image是在项目中自取的image,读者注意自己拿到图片的方式,测试的话可以在项目中加入一张11.png的图片

  //  UIImage *image = [UIImage imageNamed:@"11.png"];

    //下面是iOS两种获取图片的方法,一种获取为jpeg,一种获取为png

    //转为jpeg上传可以让图片的大小压缩

    NSMutableArray *photos = [NSMutableArray array];

    [photosaddObject:_image];

    //temp为服务器URL;

    NSString *url = @"------------------";

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id formData) {

        //参数name:是后台给你的图片在服务器上字段名;

        //参数fileNmae:自己起得一个名字,

        //参数mimeType:这个是决定于后来接收什么类型的图片,接收的时png就用image/png ,接收的时jpeg就用image/jpeg

        for(inti =0; i < photos.count; i++) {

            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];

            formatter.dateFormat=@"yyyyMMddHHmmss";

            NSString*str=[formatterstringFromDate:[NSDatedate]];

            NSString*fileName=[NSStringstringWithFormat:@"%@.jpg",str];

            UIImage*image = photos[i];

            NSData*imageData =UIImageJPEGRepresentation(image,0.28);

            [formDataappendPartWithFileData:imageDataname:[NSStringstringWithFormat:@"upload%d",i+1]fileName:fileNamemimeType:@"image/jpeg"];

        }

        //        [formData appendPartWithFileData:imageData name:@"Filedata" fileName:@"Filedate.png" mimeType:@"image/png"];

    }error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    //设置服务器返回内容的接受格式

    AFHTTPResponseSerializer *responseSer = [AFHTTPResponseSerializer serializer];

    responseSer.acceptableContentTypes= [NSSetsetWithObjects:@"text/html",nil];

    manager.responseSerializer= responseSer;

    //    NSProgress *progress = nil;

    NSURLSessionUploadTask*uploadTask = [manageruploadTaskWithStreamedRequest:requestprogress:nilcompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error) {

        if(error) {

            NSLog(@"Error: %@", error);

        }else{

            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

            NSLog(@"%@\n %@", response, str);

        }

    }];

    [uploadTaskresume];

}

你可能感兴趣的:(同一个cell上的同一个按钮调用系统相册并上传图片)