iOS 模仿微信发朋友圈表情键盘

//

//  PostStatusViewController.m

//  HengTaiXinGolf

//

//  Created by 欧阳荣 on 15/7/31.

//  Copyright (c) 2015 HengTaiXinGolf. All rights reserved.

//


#import "PostStatusViewController.h"

#import "CircleFriendsViewController.h"

#import "ZMLKeyboardConst.h"

#import "HTXPreviewViewController.h"

#import "ZLPhotoActionSheet.h"

#import "ZMLEmotionListView.h"

#import "ZMLEmotion.h"

#import "NSString+ZMLEmoji.h"


@interface PostStatusViewController ()<UITextViewDelegate>

@property(nonatomic,strong)UILabel *labelText;

@property(nonatomic,assign)BOOL count;


@property (nonatomic,strong) UIView * keyBoardView;


@property (nonatomic, strong) UIButton *faceBtn;      // 切换表情键盘按钮

@property (nonatomic, strong) ZMLEmotionListView *faceView;  // 表情键盘视图



@end


@implementation PostStatusViewController

{

    BOOL _isOne;

    ZLPhotoActionSheet *zlActionSheet;

    NSString * _messageStr;

    NSMutableArray * _imgViewArr;

    BOOL isKeyboard;

    BOOL isEmotionShow;

}


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil];

    if (self)

    {

        

        _chosenPostImages = [NSMutableArray array];

        _imgViewArr = [NSMutableArray array];

        

    }

    return self;

}


#pragma mark - Life Cycle


- (void)viewDidLoad {

    [super viewDidLoad];

    //清除本地图片缓存

    [[JXTCacher cacher] clearObject:@"HTXPreviewViewController" userId:@"HTXPreviewViewController_HTX"];

    _chosenPostImages = [NSMutableArray arrayWithArray:_chosenPostImages];

    _isOne = NO;

    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    zlActionSheet = [[ZLPhotoActionSheet alloc] init];

    //设置照片最大选择数

    zlActionSheet.maxSelectCount = 9;

    //设置照片最大预览数

    zlActionSheet.maxPreviewCount = 20;

    [self createNavigationBar];

    [self createPostStatusView];

    //返回键

    [self creatBackItem];

    [self createKyeBoardView];

}


- (void)viewWillAppear:(BOOL)animated

{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwillHide:) name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];


    

    

    [super viewWillAppear:animated];

    [[JXTCacher cacher] objectForKey:@"HTXPreviewViewController" userId:@"HTXPreviewViewController_HTX" achive:^(JXTCacher *cacher, id obj, CacheError error) {

        dispatch_async(dispatch_get_main_queue(), ^{

            

            if (obj && error == 0) {  //local or cache have data

                

                NSMutableArray * arr = [NSMutableArray arrayWithArray:obj];

                

                if (self.chosenPostImages.count == arr.count) {

                    DSLog(@"没删除");

                }else{

                    if (arr.count == 0) {

                        self.chosenPostImages = [NSMutableArray array];

                    }else{

                        self.chosenPostImages = arr;

                    }

                    [self createPostStatusView];

                }

            }

        });

    }];

}


- (void)viewDidAppear:(BOOL)animated

{

    [super viewDidAppear:animated];

}


- (void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];


    

}

-(void)keyboardwillShow:(NSNotification *)notification{

    

    if (self.faceBtn.isSelected) {

        

        DSLog(@"  ****  表情");

        isEmotionShow = YES;

        isKeyboard = NO;


        

    }else{

        

        isEmotionShow = NO;

        isKeyboard = YES;

        DSLog(@"   ****   键盘");


    }

    

    

}

-(void)keyboardwillHide:(NSNotification *)notification{

   

}


-(void)keyboardDidHide:(NSNotification *)notification{

    

    if (isEmotionShow||isKeyboard) {

        [self.messageText1 becomeFirstResponder];

    }else{

        

    }


}


- (void)viewDidDisappear:(BOOL)animated

{

    [super viewDidDisappear:animated];

}



#pragma mark - Custom Method


#pragma mark - 创建UI

//创建界面

-(void)createPostStatusView{

//    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    

    for (NSInteger i = 0; i < _imgViewArr.count; i ++) {

        UIImageView * imgView = _imgViewArr[i];

        DSLog(@"   1   %@",imgView);

        imgView.image = nil;

        [imgView removeFromSuperview];

        imgView = nil;

        DSLog(@"   2   %@",imgView);


    }

    

//    _messageText1 = nil;

//    _labelText = nil;

    WS(ws);

    if (_messageText1 == nil) {

        _messageText1 = [UITextView new];

        [self.view addSubview:_messageText1];

        [_messageText1 mas_makeConstraints:^(MASConstraintMaker *make) {

            

            make.top.equalTo(ws.view).with.offset(0);

            make.left.equalTo(ws.view).with.offset(10);

            make.right.equalTo(ws.view).with.offset(-10);

            make.height.mas_equalTo(@(85*KWIDTH));

            

        }];

        _messageText1.backgroundColor = [UIColor whiteColor];

        _messageText1.font = [UIFont systemFontOfSize:18];

        _messageText1.scrollEnabled= YES;

        _messageText1.delegate=self;

        _labelText = [UILabel new];

        [self.view addSubview:_labelText];

        [_labelText mas_makeConstraints:^(MASConstraintMaker *make) {

            make.top.equalTo(ws.view).with.offset(8);

            make.left.equalTo(ws.view).with.offset(18);

            make.right.equalTo(ws.view).with.offset(18);

            make.height.mas_equalTo(20);

        }];

        

        if (_messageStr.length == 0) {

            _labelText.text=@"这一刻的想法...";

            _labelText.enabled= NO;

            _labelText.backgroundColor = [UIColor clearColor];

            

        }else{

            _messageText1.text = [NSString stringWithFormat:@"%@",_messageStr];


        }

    }

    

    CGFloat Gaping = 12;

    CGFloat startY = 90 * KWIDTH;

    CGFloat ImgWH = (IPHONE_WIDTH - 5 * 12)/4;

    int count = (int)[self.chosenPostImages count];

    for (int i = 0; i < count; i ++) {

        //计算位置

        int row = i/4;

        int column = i%4;

        CGFloat x = Gaping + column * (ImgWH + Gaping);

        CGFloat y = startY + row * (ImgWH + Gaping);

        UIImageView * imgView = [UIImageView new];

        [self.view addSubview:imgView];

        imgView.tag = i;

        imgView.userInteractionEnabled = YES;

        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImgClik:)];

        [imgView addGestureRecognizer:tap];

        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {

            make.left.mas_equalTo(ws.view).offset(x);

            make.top.mas_equalTo(ws.view).offset(y);

            make.size.mas_equalTo(CGSizeMake(ImgWH, ImgWH));

        }];

        imgView.contentMode = UIViewContentModeScaleAspectFill;

        imgView.clipsToBounds = YES;

        UIImage *image = self.chosenPostImages[i];

        imgView.image = image;

        [_imgViewArr addObject:imgView];

    }

    //添加按钮 +

    if ([self.chosenPostImages count] < 9) {

        NSInteger k = [self.chosenPostImages count];

        NSInteger row = k/4;

        NSInteger column = k%4;

        CGFloat x = Gaping + column * (ImgWH + Gaping);

        CGFloat y = startY + row * (ImgWH + Gaping);

        UIImageView * imgView1 = [UIImageView new];

        [self.view addSubview:imgView1];

        imgView1.userInteractionEnabled = YES;

        UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAddImgClik:)];

        [imgView1 addGestureRecognizer:tap1];

        [imgView1 mas_makeConstraints:^(MASConstraintMaker *make) {

            make.left.mas_equalTo(ws.view).offset(x);

            make.top.mas_equalTo(ws.view).offset(y);

            make.size.mas_equalTo(CGSizeMake(ImgWH, ImgWH));

        }];

        imgView1.contentMode = UIViewContentModeScaleAspectFill;

        imgView1.clipsToBounds = YES;

        UIImage *image = [UIImage imageNamed:@"zj_t"];

        imgView1.image = image;

        [_imgViewArr addObject:imgView1];


    }

}


#pragma mark - Event Response


#pragma mark - 点击图片预览


-(void)tapImgClik:(UITapGestureRecognizer *)tapGes{

    [self.view endEditing:YES];

    isEmotionShow=NO;

    isKeyboard=NO;


    UIImageView * imgView =(UIImageView*)tapGes.view;

    HTXPreviewViewController * preVC = [[HTXPreviewViewController alloc]init];

    preVC.backImgArr = [NSMutableArray arrayWithArray:self.chosenPostImages];//self.chosenPostImages;

    preVC.selectImgNum = (long)imgView.tag + 1;

    [self.navigationController pushViewController:preVC animated:YES];

    

}


#pragma mark - 点击继续添加图片


-(void)tapAddImgClik:(UITapGestureRecognizer *)tapGes{

    [self.view endEditing:YES];

    isEmotionShow=NO;

    isKeyboard=NO;


    DSLog(@"继续添加图片");

    _messageStr = _messageText1.text;

    [self.view endEditing:YES];

    UIViewController * cvc = [[UIViewController alloc] init];

    cvc.view.tag = 0;

    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:cvc, @"Hidden",nil] ;

    NSNotification *notification = [NSNotification notificationWithName:@"tongzhiHidden" object:nil userInfo:dict];

    [[NSNotificationCenter defaultCenter]postNotification:notification];

    zlActionSheet.maxSelectCount = 9 - _chosenPostImages.count;

    zlActionSheet.tag = 9;

    [zlActionSheet showWithSender:self animate:YES completion:^(NSArray<UIImage *> * _Nonnull selectPhotos) {

        

        UIViewController * cvc = [[UIViewController alloc] init];

        cvc.view.tag = 0;

        NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:cvc, @"Hidden",nil] ;

        NSNotification *notification = [NSNotification notificationWithName:@"tongzhiHidden" object:nil userInfo:dict];

        [[NSNotificationCenter defaultCenter]postNotification:notification];

        for (UIImage * img in selectPhotos) {

            UIImage * imageFix = [self fixOrientation:img];

            [_chosenPostImages addObject:imageFix];

        }

        [self createPostStatusView];//刷新UI


    }];

    

}




#pragma mark - ButtonClick Mehod


-(void)postBtnClick{

    NSLog(@"发送状态");

    [self.view endEditing:YES];

    NSString *createDynamicStr = [NSString stringWithFormat:KCreateDynamic];

    BOOL leng=[self isEmpty:self.messageText1.text] ;

    if ([self.messageText1.text length] < 500) {

        if (leng==YES&&self.chosenPostImages.count==0)

        {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil

                                  

                                                            message:@"内容不能为空"

                                  

                                                           delegate:nil

                                  

                                                  cancelButtonTitle:@"知道了"

                                  

                                                  otherButtonTitles:nil, nil];

            [alert show];

            

        } else

        {

            if (_isOne == NO) {

                _isOne = YES;

                //如果是拍照上传则选择第一个,如果是从相册里选择多张图则是第二个。

                [self postDynamicMoreRequest:createDynamicStr];

            }else{

                //第二次点击

                [WFHudView showMsg:@"不可重复提交!!!" inView:nil];

            }

        }

        

    }else

    {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil

                              

                                                        message:@"最大不能超过500个字"

                              

                                                       delegate:nil

                              

                                              cancelButtonTitle:@"知道了"

                              

                                              otherButtonTitles:nil, nil];

        

        [alert show];

        

    }

    

}


//创建返回按钮

-(void)creatBackItem{

    //    CGFloat frameY = 0.0f;

    UIBarButtonItem * leftItem = nil;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {

        //        frameY = 0.0f;

        leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"title_bar_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(returnClicked)];

    } else {

        //        frameY = 0.0f;

        leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"title_bar_back"] style:UIBarButtonItemStyleDone target:self action:@selector(returnClicked)];

    }

    self.navigationItem.leftBarButtonItem = leftItem;

}



-(void)returnClicked {

    //通知出现标签栏

    UIViewController *cvc1 = [[UIViewController alloc]init];

    cvc1.view.tag = 1;

    NSDictionary *dict1 = [[NSDictionary alloc]initWithObjectsAndKeys:cvc1,@"Hidden", nil];

    NSNotification *notification1 = [NSNotification notificationWithName:@"tongzhiHidden" object:nil userInfo:dict1];

    [[NSNotificationCenter defaultCenter]postNotification:notification1];

    [self.navigationController popViewControllerAnimated:YES];

}


#pragma mark - UITextViewDelegate


-(void)textViewDidChange:(UITextView *)textView

{

    if (textView.text.length==0) {

        self.labelText.text=@"这一刻的想法...";

    }else {

        self.labelText.text=@"";

    }

}


-(void)textViewDidBeginEditing:(UITextView *)textView{


    DSLog(@"开始编辑");


}


-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text


{

    

    if ([text isEqualToString:@"\n"]){

        

        return YES;

        

    }

    if ([text isEqualToString:@""]) {


        return YES;

        

    }

    

    

    if (range.location>=500)

        

    {

        

      

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil

                                  

                                                            message:@"最大不能超过500个字"

                                  

                                                           delegate:nil

                                  

                                                  cancelButtonTitle:@"知道了"

                                  

                                                  otherButtonTitles:nil, nil];

            

            [alert show];

            

            

            return NO;

            

        

        

    }

    

    return YES;

}



#pragma mark - 创建按钮


//创建左右两个按钮

-(void)createNavigationBar{


    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(postBtnClick)];

//    rightBtn.enabled=NO;

    [rightBtn setTitleTextAttributes:@{ NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];

    [rightBtn setTitleTextAttributes:@{ NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];

    self.navigationItem.rightBarButtonItem = rightBtn;


}



#pragma mark -  表情键盘



-(void)createKyeBoardView{

    

    self.keyBoardView = [[UIView alloc]initWithFrame:CGRectMake(0, IPHONE_HEIGHT - 44 - 64, IPHONE_WIDTH, 44)];

    self.keyBoardView.backgroundColor = [UIColor whiteColor];

    UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 0.5)];

    line.backgroundColor = kColor(200, 200, 200);

    [self.keyBoardView addSubview:line];

    UILabel * line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 43.7, IPHONE_WIDTH, 0.3)];

    line1.backgroundColor = kColor(200, 200, 200);

    [self.keyBoardView addSubview:line1];


    [self.view addSubview:_keyBoardView];

    [self.keyBoardView removeFromSuperview];

    self.messageText1.inputAccessoryView = self.keyBoardView;

    __weak typeof(self) weakSelf = self;

    

    [self.faceView setEmotions:[self loadEmojiEmotions] deleteBlock:^{

        // 表情键盘删除

        [weakSelf emotionDidDelete];

    } sendBlock:^{

        // 表情键盘发送

        [weakSelf emotionDidSend];

    } selectBlock:^(ZMLEmotion *emotion){

        // 表情键盘选中

        [weakSelf emotionDidSelect:emotion];

    }];


    CGFloat faceBtnWH = self.faceBtn.currentImage.size.width;

    self.faceBtn.frame = CGRectMake(16, (44 - faceBtnWH)/2, faceBtnWH, faceBtnWH);

    

    

}



#pragma mark - 交互事件


/**

 *  表情按钮被点击,切换表情键盘

 */

- (void)faceBtnClicked:(UIButton *)faceBtn{

    faceBtn.selected = !faceBtn.isSelected;

    DSLog(@"表情切换");

    if (!isEmotionShow) {

        DSLog(@"出现表情");

//        faceBtn.selected = YES;

        isEmotionShow = YES;

        isKeyboard = NO;

        self.messageText1.inputView = _faceView;

        [self.messageText1 resignFirstResponder];

        

    }else{

        DSLog(@"出现键盘");

//        faceBtn.selected = YES;

        isEmotionShow = NO;

        isKeyboard = YES;

        self.messageText1.inputView = nil;

        [self.messageText1 resignFirstResponder];


    

    }

    

  

}


/**

 *  选中了表情键盘中的某一个表情回调

 */

- (void)emotionDidSelect:(ZMLEmotion *)emotion{

    

    DSLog(@"选中表情");

    

    self.messageText1.text = [self.messageText1.text stringByAppendingString:emotion.code.emoji];

    

    if (self.messageText1.text.length==0) {

        self.labelText.text=@"这一刻的想法...";

    }else {

        self.labelText.text=@"";

    }


    

}


/**

 *  点击了表情键盘中的删除按钮回调

 */

- (void)emotionDidDelete{

    

    [self.messageText1 deleteBackward];


    if (self.messageText1.text.length==0) {

        self.labelText.text=@"这一刻的想法...";

    }else {

        self.labelText.text=@"";

    }


}


/**

 *  点击了表情键盘中的发送按钮回调

 */

- (void)emotionDidSend{

    

    DSLog(@"发送");

    [self.view endEditing:YES];

    isEmotionShow=NO;

    isKeyboard=NO;


}


/**

 *  输入框内容变化回调

 */

- (void)textDidChange{

    

}



- (UIButton *)faceBtn{

    if (_faceBtn == nil) {

        UIButton *faceBtn = [[UIButton alloc] init];

        [faceBtn setImage:ZMLKeyboardBundleImage(@"iocn_comment_expression") forState:UIControlStateNormal];

        [faceBtn setImage:ZMLKeyboardBundleImage(@"iocn_comment_keyboard") forState:UIControlStateSelected];

        [self.keyBoardView addSubview:faceBtn];

        [faceBtn addTarget:self action:@selector(faceBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

        _faceBtn = faceBtn;

    }

    return _faceBtn;

}


#pragma mark - 懒加载


- (ZMLEmotionListView *)faceView{

    if (_faceView == nil) {

        ZMLEmotionListView *view = [ZMLEmotionListView new];

        view.backgroundColor = ZMLRGB(245, 245, 245);

        view.frame = CGRectMake(0, 0, kScreenWidth, kFaceViewHeight);

        _faceView = view;

    }

    return _faceView;

}


#pragma mark - 加载表情包


/**

 *  加载emoji表情包

 */

- (NSArray <ZMLEmotion *>*)loadEmojiEmotions{

    

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Resourse.bundle/emoji.plist" ofType:nil];

    

    NSArray *emotions = [NSArray arrayWithContentsOfFile:path];

    NSMutableArray *emotionsMul = @[].mutableCopy;

    for (NSDictionary *dic in emotions) {

        ZMLEmotion *emotion = [[ZMLEmotion alloc] init];

        [emotion setValuesForKeysWithDictionary:dic];

        [emotionsMul addObject:emotion];

    }

    return emotionsMul.copy;

}



#pragma mark - Network Method


//多张图发表状态

-(void)postDynamicMoreRequest:(id)sender

{

    //分界线的标识符

    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";

    NSURL *url = [NSURL URLWithString:sender];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //分界线 -- AaB03x

    NSString *MPboundary = [[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];

    // 结束符 AaB03x--

    NSString *endMPboundary = [[NSString alloc]initWithFormat:@"%@--",MPboundary];

    //要上传的图片

    UIImage *image;

    //http body的字符串

    NSMutableString *body = [[NSMutableString alloc]init];

    //参数的集合的所有key的集合

//    NSDictionary *params = @{@"appSecret":@"4124bc0a9335c27f086f24ba207a4912",@"memberId":[UserModel sharedInstance].memberId,@"message":self.messageText1.text,@"positionX":@0,@"positionY":@0,@"positionYn":@"N",@"appId":@"ET12412"};

    

    NSString *memStr = [UserModel sharedInstance].memberId;

    NSMutableDictionary * _param = [NSMutableDictionary dictionary];

    NSString *paraString = [MD5 encodeString:self.messageText1.text];

    [_param setValue:memStr forKey:@"memberId"];

    [_param setValue:self.messageText1.text forKey:@"message"];

    [_param setValue:KAPPID forKey:@"appId"];

    [_param setValue:KappSecret forKey:@"appSecret"];

    [_param setValue:[CommonTools getTimeScamp] forKey:@"timestamp"];

    NSArray * paramArr = @[[NSString stringWithFormat:@"memberId%@",_param[@"memberId"]],[NSString stringWithFormat:@"message%@",paraString],[NSString stringWithFormat:@"appId%@",_param[@"appId"]],[NSString stringWithFormat:@"appSecret%@",_param[@"appSecret"]],[NSString stringWithFormat:@"timestamp%@",_param[@"timestamp"]]];

    [_param setValue:[CommonTools tokenmd5StringFromArray:paramArr] forKey:@"digest"];


    

    

    NSArray *keys= [_param allKeys];

    

    [ECDevice sharedInstance].delegate = [DeviceDelegateHelper sharedInstance];


    int countImg = (int)[self.chosenPostImages count];



    //遍历keys

    for(int i=0;i<[keys count];i++) {

        //得到当前key

        NSString *key=[keys objectAtIndex:i];

        //如果key不是pic,说明value是字符类型,比如nameBoris

        //if(![key isEqualToString:@"pic"]) {

        //添加分界线,换行

        [body appendFormat:@"%@\r\n",MPboundary];

        //添加字段名称,换2

        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

        //[body appendString:@"Content-Transfer-Encoding: 8bit"];

        //添加字段的值

        

        if (countImg == 0 && i == [keys count] - 1) {

            

            [body appendFormat:@"%@",[_param objectForKey:key]];


            break;

            

        }


        

        [body appendFormat:@"%@\r\n",[_param objectForKey:key]];

        //}

    }

    添加分界线,换行

    //[body appendFormat:@"%@\r\n",MPboundary];

    DSLog(@"------------body---------%@",body);

   

    

    //声明myRequestData,用来放入http body

    NSMutableData *myRequestData=[NSMutableData data];

    //body字符串转化为UTF8格式的二进制

    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];

    //循环加入上传图片

    

    

    for (int i = 0 ; i < countImg;  i ++ ) {

        //要上传的图片

        image = self.chosenPostImages[i];

        //得到图片的data

//        NSData *data;

        NSData *data = UIImageJPEGRepresentation(image, 0.5);

//        if (UIImagePNGRepresentation(image)) {

//            //返回为png图像。

//            data = UIImagePNGRepresentation(image);

//        }else {

//            //返回为JPEG图像。

//            data = UIImageJPEGRepresentation(image, 1);

//        }

        //       NSData *data = UIImageJPEGRepresentation(image, 0.00001);

        

//        NSUInteger length = [data length];


        

        NSMutableString *imgBody = [[NSMutableString alloc]init];

        //此处循环添加图片文件

        //添加图片信息字段

        //声明pic字段,文件名为boris.png

        //[body appendFormat:[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"File\"; filename=\"%@\"\r\n", [keys objectAtIndex:i]]];

        

        添加分界线,换行

        [imgBody appendFormat:@"%@\r\n",MPboundary];

        [imgBody appendFormat:@"Content-Disposition: form-data; name=\"img\"; filename=\"postImg%d.png\"\r\n", i];

        //声明上传文件的格式

//        [imgBody appendFormat:@"Content-Type: application/octet-stream"];

         //charset=utf-8\r\n\r\n"];

        [imgBody appendFormat:@"Content-Type: image/png\r\n\r\n"];


        //body字符串转化为UTF8格式的二进制

        //[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];

        [myRequestData appendData:[imgBody dataUsingEncoding:NSUTF8StringEncoding]];

        //imagedata加入

        [myRequestData appendData:data];

        [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


        

        

    }

    //声明结束符:--AaB03x--

//    NSString *end=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];

    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];


    //加入结束符--AaB03x--

    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

    

    //设置HTTPHeaderContent-Type的值

    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];

    //设置HTTPHeader

    [request setValue:content forHTTPHeaderField:@"Content-Type"];

    //[request setValue:@"keep-alive" forHTTPHeaderField:@"connection"];

    //[request setValue:@"UTF-8" forHTTPHeaderField:@"Charsert"];

    //设置Content-Length

    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];

    //设置http body

    [request setHTTPBody:myRequestData];

    //http method

    [request setHTTPMethod:@"POST"];


    // 发送请求

    __weak typeof(self) weakself = self;

    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];

    hud.labelText = @"正在发送...";

    hud.frame = CGRectMake(IPHONE_WIDTH/2, IPHONE_HEIGHT/2-60, 30, 30);

    hud.removeFromSuperViewOnHide = YES;


    

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (data) {

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

            NSLog(@"发表多张图片状态请求 == %@", dict);

            _isOne = NO;

            if([dict[@"returnCode"]isEqualToString:@"000000"]){

                //清除本地图片缓存

                [[JXTCacher cacher] clearObject:@"HTXPreviewViewController" userId:@"HTXPreviewViewController_HTX"];


                

                PostStatusViewController * cvc = [[PostStatusViewController alloc] init];

                cvc.view.tag = 300;

                NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:cvc, @"FreshView",nil] ;

                NSNotification *notification = [NSNotification notificationWithName:@"FreshView" object:nil userInfo:dict];

                [[NSNotificationCenter defaultCenter]postNotification:notification];

                

                //通知出现标签栏

                UIViewController *cvc1 = [[UIViewController alloc]init];

                cvc1.view.tag = 1;

                NSDictionary *dict1 = [[NSDictionary alloc]initWithObjectsAndKeys:cvc1,@"Hidden", nil];

                NSNotification *notification1 = [NSNotification notificationWithName:@"tongzhiHidden" object:nil userInfo:dict1];

                [[NSNotificationCenter defaultCenter]postNotification:notification1];

                

//                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"^_^恭喜你,发布成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

//                [alertView show];

                //                    MyLoginViewController *myLoginView = [[MyLoginViewController alloc]init];

                //                    [self dismissViewControllerAnimated:NO completion:nil];

//                [self.navigationController popToRootViewControllerAnimated:NO];

                [self.navigationController popViewControllerAnimated:YES];


                //                    [self presentViewController:myLoginView animated:NO completion:nil];

            }

            else if ([dict[@"returnCode"]integerValue] == 3){

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起,请求数据失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

                [alertView show];

            }else if ([dict[@"returnCode"]integerValue]==43){

                

                UIAlertView * aler = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"%@",dict[@"description"]] message:[NSString stringWithFormat:@"%@",dict[@"reason"]] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

                [aler show];

            }else{

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起,发布失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

                [alertView show];

            }

            

        } else {

            NSLog(@"上传失败");

        }

        __strong typeof(weakself) strongSelf = weakself;

        [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];

    }];

    

}



#pragma mark - ToolsMethod


//收起键盘

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    

    [self.view endEditing:YES];

    isEmotionShow=NO;

    isKeyboard=NO;

    

}

//判断有没有非法字符 有返回YES没有返回NO

- (BOOL)isContainsEmoji:(NSString *)string {

    

    __block BOOL isEomji = NO;

    

    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])

                               options:NSStringEnumerationByComposedCharacterSequences

                            usingBlock:

     

     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange,BOOL *stop) {

         

         const unichar hs = [substring characterAtIndex:0];

         

         // surrogate pair

         

         if (0xd800 <= hs && hs <= 0xdbff) {

             

             if (substring.length > 1) {

                 

                 const unichar ls = [substring characterAtIndex:1];

                 

                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;

                 

                 if (0x1d000 <= uc && uc <= 0x1f77f) {

                     

                     isEomji = YES;

                     

                 }

                 

             }

             

         } else if (substring.length > 1) {

             

             const unichar ls = [substring characterAtIndex:1];

             

             if (ls == 0x20e3) {

                 

                 isEomji = YES;

                 

             }

             

         } else {

             

             // non surrogate

             

             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {

                 

                 isEomji = YES;

                 

             } else if (0x2B05 <= hs && hs <= 0x2b07) {

                 

                 isEomji = YES;

                 

             } else if (0x2934 <= hs && hs <= 0x2935) {

                 

                 isEomji = YES;

                 

             } else if (0x3297 <= hs && hs <= 0x3299) {

                 

                 isEomji = YES;

                 

             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030|| hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs ==0x231a ) {

                 

                 isEomji = YES;

                 

             }

             

         }

         

     }];

    return isEomji;

}




//判断内容是否全部为空格  yes 全部为空格  no 不是

- (BOOL) isEmpty:(NSString *) str {

    if (!str) {

        return true;

    } else {

        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).

        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];

        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];

        if ([trimedString length] == 0) {

            return true;

        } else {

            return false;

        }

    }

}


- (UIImage *)fixOrientation:(UIImage *)aImage {

         

         // No-op if the orientation is already correct

         if (aImage.imageOrientation == UIImageOrientationUp)

             return aImage;

         

         // We need to calculate the proper transformation to make the image upright.

         // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.

         CGAffineTransform transform = CGAffineTransformIdentity;

         

         switch (aImage.imageOrientation) {

             case UIImageOrientationDown:

             case UIImageOrientationDownMirrored:

                 transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);

                 transform = CGAffineTransformRotate(transform, M_PI);

                 break;

                 

             case UIImageOrientationLeft:

             case UIImageOrientationLeftMirrored:

                 transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

                 transform = CGAffineTransformRotate(transform, M_PI_2);

                 break;

                 

             case UIImageOrientationRight:

             case UIImageOrientationRightMirrored:

                 transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);

                 transform = CGAffineTransformRotate(transform, -M_PI_2);

                 break;

             default:

                 break;

         }

         

         switch (aImage.imageOrientation) {

             case UIImageOrientationUpMirrored:

             case UIImageOrientationDownMirrored:

                 transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

                 transform = CGAffineTransformScale(transform, -1, 1);

                 break;

                 

             case UIImageOrientationLeftMirrored:

             case UIImageOrientationRightMirrored:

                 transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);

                 transform = CGAffineTransformScale(transform, -1, 1);

                 break;

             default:

                 break;

         }

         

         // Now we draw the underlying CGImage into a new context, applying the transform

         // calculated above.

         CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,

                                                  CGImageGetBitsPerComponent(aImage.CGImage), 0,

                                                  CGImageGetColorSpace(aImage.CGImage),

                                                  CGImageGetBitmapInfo(aImage.CGImage));

         CGContextConcatCTM(ctx, transform);

         switch (aImage.imageOrientation) {

             case UIImageOrientationLeft:

             case UIImageOrientationLeftMirrored:

             case UIImageOrientationRight:

             case UIImageOrientationRightMirrored:

                 // Grr...

                 CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);

                 break;

                 

             default:

                 CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);

                 break;

         }

         // And now we just create a new UIImage from the drawing context

         CGImageRef cgimg = CGBitmapContextCreateImage(ctx);

         UIImage *img = [UIImage imageWithCGImage:cgimg];

         CGContextRelease(ctx);

         CGImageRelease(cgimg);

         return img;

}

     


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/


@end


猜你喜欢

转载自blog.csdn.net/qq_27247497/article/details/52242728
今日推荐