http://blog.csdn.net/zhangyulin311/article/details/53134701
//
// WXUploadHeadImageModule.m
// yixiucar
//
// Created by 石家庄盛航 on 16/10/9.
// Copyright © 2016年 sjzshtx. All rights reserved.
//
#import "WXUploadHeadImageModule.h"
#import "AFNetworking.h"
#import "XDNetworking.h"
#define HMEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
//上传头像
@interface WXUploadHeadImageModule ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
UIImageView *headImageView;
NSString *myToken;
}
@end
@implementation WXUploadHeadImageModule
//open(String token, JSCallback callback)
WX_EXPORT_METHOD(@selector(open:callback:))
@synthesize weexInstance;
- (void)open:(NSString *)token callback:(WXModuleCallback)callback{
myToken = token;
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择图片"delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nilotherButtonTitles:@"拍照", @"相册", nil];
[sheet showInView:weexInstance.rootView];
}
#pragma mark - 选择手机拍照上传或者手机相册上传
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// 设置代理
ipc.delegate = self;
switch (buttonIndex) {
case 0: { // 拍照
if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
break;
}
case 1: { // 相册
if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
break;
}
default:
break;
}
// 显示控制器
[weexInstance.viewController presentViewController:ipc animated:YEScompletion:nil];
}
#pragma mark - 当在相册选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
//当选择的类型是图片
if ([type isEqualToString:@"public.image"]){
//先把图片转成NSData
UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//压缩图片
NSData *dataImage = UIImageJPEGRepresentation(image, 0.5);
//图片保存的路径 这里将图片放在沙盒的documents文件夹中
NSString * DocumentsPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
NSLog(@"图片储存路径:%@",DocumentsPath);
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//把刚刚图片转换的data对象拷贝至沙盒中 并保存为image
[fileManager createDirectoryAtPath:DocumentsPathwithIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:[DocumentsPathstringByAppendingString:@"/image.jpg"] contents:dataImage attributes:nil];
//得到选择后沙盒中图片的完整路径
NSString *filename = [[NSStringalloc]initWithFormat:@"%@%@",DocumentsPath,@"/image.jpg"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer.timeoutInterval = 8;
// NSMutableDictionary *params = [NSMutableDictionary dictionary];
// params[@"token"] = myToken;
//
// [manager.requestSerializer setValue:myToken forHTTPHeaderField:@"token"];
//
[manager POST:[NSStringstringWithFormat:@"http://www.yixiucar.com/yxapi/user/upIcon"]
parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFormData:[myTokendataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
[formData appendPartWithFileData:dataImage name:@"file"fileName:@"image.jpg" mimeType:@"image/jpg"];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(@"myToken=%@",myToken);
}progress:^(NSProgress *uploadProgress){
}success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"dic:====%@",responseObject);
// headImageView.image = image;
NSData *data1=[NSData dataWithContentsOfFile:filename];
headImageView.image = [UIImage imageWithData:data1];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error=%@",error);
}];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 取消图片选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"您取消了选择图片");
[picker dismissViewControllerAnimated:YES completion:nil];
}
/* [self kuaSuHuoQu];
}
- (void)kuaSuHuoQu{
backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, SCREEN_HEIGHT)];
backView.backgroundColor = RGBA(220, 220, 220, 0.5);
UITapGestureRecognizer *baseViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(baseViewTapAction:)];
[backView addGestureRecognizer:baseViewTap];
NSArray *arr = @[@"调用相机",@"调用图片库",@"取消"];
for (int i = 0; i < 3; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(20, 45 * i + SCREEN_HEIGHT-150, ScreenWidth-40, 40);
button.backgroundColor = [UIColor whiteColor];
[button setTitle:arr[i] forState:(UIControlStateNormal)];
[button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
button.layer.masksToBounds = YES;
button.layer.cornerRadius = 5;
if (i == 0) {
[button addTarget:self action:@selector(addCarema) forControlEvents:(UIControlEventTouchUpInside)];
}else if (i == 1){
[button addTarget:self action:@selector(openPicLibrary) forControlEvents:(UIControlEventTouchUpInside)];
}else if (i == 2){
[button addTarget:self action:@selector(baseViewTapAction:) forControlEvents:(UIControlEventTouchUpInside)];
}
[weexInstance.rootView addSubview:backView];
[backView addSubview:button];
}
}
#pragma mark - 调用相机
- (void)addCarema{
//判断是否可以打开相机,模拟器无法使用此功能
if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; //是否可编辑
//摄像头
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[weexInstance.viewController presentViewController:picker animated:YES completion:nil];
}else{
//如果没有提示用户
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error" message:@"你没有摄像头" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
}];
[alertController addAction:myAction];
[weexInstance.viewController presentViewController:alertController animated:YES completion:nil];
}
}
//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//得到图片
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//图片存入相册
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
[weexInstance.viewController dismissViewControllerAnimated:YES completion:nil];
/
NSDictionary *dict = @{@"token":myToken,
@"file":image};
NSLog(@"myDict=%@",dict);
// NSURL *url = [NSURL URLWithString:@"http://www.yixiucar.com/yxapi/user/upIcon"];
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// request.HTTPMethod = @"POST";
//
//
// NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
// NSString *rdata=[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
// rdata=[NSString stringWithFormat:@"req=%@",rdata];
// NSLog(@"%@",rdata);
// request.HTTPBody = [rdata dataUsingEncoding:NSUTF8StringEncoding];
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
// if (data == nil || connectionError) return;
// NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
// NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"result=%@", result);
// NSLog(@"dict=%@", dict);
// NSString *error = dict[@"error"];
// if (error) {
// } else {
// NSString *success = dict[@"success"];
// NSLog(@"success=%@",success);
// }
//
// }];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.yixiucar.com/yxapi/user/upIcon"]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url andFilenName:@"file" andLocalFilePath:[[NSBundle mainBundle]pathForResource:@"image.png" ofType:nil]];
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"post==%@",result);
}];
[dataTask resume];
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
// manager.requestSerializer.timeoutInterval = 8;
//
// [manager POST:[NSString stringWithFormat:@"http://www.yixiucar.com/yxapi/user/upIcon"] parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
// } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
// NSLog(@"dict=%@",dict);
//
// } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// NSLog(@"error = %@",error);
// }];
//
// NSData *data1=[NSData dataWithContentsOfFile:filename];
// headImageView.image = [UIImage imageWithData:data1];
}
//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[weexInstance.viewController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 调用图片库
-(void)openPicLibrary{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[weexInstance.viewController presentViewController:picker animated:YES completion:nil];
}else{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error" message:@"你没有摄像头" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
}];
[alertController addAction:myAction];
[weexInstance.viewController presentViewController:alertController animated:YES completion:nil];
}
}
//用post上传文件
-(void)PostFile{
//url
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.yixiucar.com/yxapi/user/upIcon"]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url andFilenName:@"Alvin.data" andLocalFilePath:[[NSBundle mainBundle]pathForResource:@"Alvin.png" ofType:nil]];
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"post==%@",result);
}];
[dataTask resume];
}
- (void)baseViewTapAction:(UITapGestureRecognizer *)tap{
[backView removeFromSuperview];
backView = nil;
}*/
@end