[IOS]用户聊天界面

来源:互联网 发布:苹果id账号查询软件 编辑:程序博客网 时间:2024/05/21 21:43

用户聊天界面

Demo:http://download.csdn.net/detail/u012881779/8613413

部分代码:

@interface ProcessMessage ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate >@property (nonatomic) float     gKeyBoardH; @property (nonatomic) CGRect    gTVrect;@property (weak, nonatomic) IBOutlet UIView     *gSendV;         //发送栏视图@property (weak, nonatomic) IBOutlet UIButton   *gSendBut;       //发送@property (weak, nonatomic) IBOutlet UITextView *gImputTxtV;     //输入框@property (weak, nonatomic) IBOutlet UITableView *gProcessTV;    //消息TV@property (strong, nonatomic) NSMutableArray    *gCellHeightArr ;//cell高@property (strong, nonatomic) NSMutableArray    *gMessageInfo;   //消息内容@property (strong, nonatomic) VoiceInfo         *gVoice;         //语音@property (strong, nonatomic) PictureInfo       *gPicture;       //图片@property (strong, nonatomic) NSString          *gMyObjectID;    //自己的ID@property (strong, nonatomic) NSString          *gObjectID;      //交谈对象ID@property (strong, nonatomic) NSString          *gUserid;        //自己ID@property (strong, nonatomic) AudioRecord       *mAudioRecord;@property (strong, nonatomic) AVAudioPlayer     *gAudioPlayer;@property (strong, nonatomic) ProcessAudioPlay  *gProcessAPlayer;@property (strong, nonatomic) IBOutlet UIView *uploadView;      //加载更多视图@property (strong, nonatomic) IBOutlet UIView *uploadNilView;   //表尾为空@property (weak, nonatomic) IBOutlet UIButton *tapLoadBut;      //点击加载But@property (weak, nonatomic) IBOutlet UIView *loadingView;       //加载View@property (weak, nonatomic) IBOutlet UILabel *titleLab;@property (nonatomic) NSInteger leftPageNum;@end@implementation ProcessMessage- (void)viewDidLoad{    [super viewDidLoad];    [self.view setFrame:[[UIScreen mainScreen] bounds]];    if(!self.gCellHeightArr){        self.gCellHeightArr = [[NSMutableArray alloc] init];    }    if(!self.gMessageInfo){        self.gMessageInfo = [[NSMutableArray alloc] init];    }        [_gProcessTV setTransform:CGAffineTransformMakeRotation(M_PI)];    [_gProcessTV setTableFooterView:_uploadView];    [_uploadView setTransform:CGAffineTransformMakeRotation(M_PI)];        //参数设置    _leftPageNum = 1;    _gMyObjectID = @"50";    _gUserid = @"50";    _gObjectID = @"60";        //消息TableView    [self cMessageTableView];        //消息发送栏    [self cMessageSend:40];        //增加监听,当键盘出现或改变时收出消息    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillShow:)                                                 name:UIKeyboardWillShowNotification                                               object:nil];    //增加监听,当键退出时收出消息    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillHide:)                                                 name:UIKeyboardWillHideNotification                                            object:nil];    }//消息TableView-(void)cMessageTableView{    self.gTVrect = _gProcessTV.frame;    [_gProcessTV setSeparatorStyle:NO];}//消息发送栏-(void)cMessageSend:(float)sendVH{    if(sendVH < 40){        sendVH = 40;    }else if(sendVH > 100){        sendVH = 100;    }    if(sendVH == 60 || sendVH == 78){        [_gImputTxtV setContentOffset:CGPointMake(0, 0) animated:YES];    }        //消息发送栏高度动态调整    CGRect sendViewRect = _gSendV.frame;    sendViewRect.origin.y = sendViewRect.origin.y - (sendVH-sendViewRect.size.height);    sendViewRect.size.height = sendVH;    [UIView animateWithDuration:0.2 animations:^{        [_gSendV setFrame:sendViewRect];    } completion:^(BOOL finished){}];        //tablevie高度适配    CGRect tvRect = _gProcessTV.frame;    float tvHeight = _gSendV.frame.origin.y - tvRect.origin.y;    tvRect.size.height = tvHeight;    [_gProcessTV setFrame:tvRect];        //发送按钮状态    BOOL judge = 0;    for (int i = 0; i < [_gImputTxtV.text length]; i ++) {        NSString *str = [_gImputTxtV.text substringWithRange:NSMakeRange(i, 1)];        if(![str isEqualToString:@" "]){            if(![str isEqualToString:@"\n"]){                judge = 1;            }        }    }    if(judge){        [_gSendBut setBackgroundImage:[UIImage imageNamed:@"蓝按钮.png"] forState:UIControlStateNormal];        [_gSendBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];    }else{        [_gSendBut setBackgroundImage:[UIImage imageNamed:@"发送按钮.png"] forState:UIControlStateNormal];        [_gSendBut setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];    }        //输入框    [_gImputTxtV.layer setCornerRadius:5];    [_gImputTxtV.layer setBorderWidth:1];    [_gImputTxtV.layer setBorderColor:[[UIColor colorWithRed:228.0/255 green:228.0/255 blue:228.0/255 alpha:1] CGColor] ];    }//发送消息button关联事件- (IBAction)downTapAction:(id)sender {    UIButton *tempBut = (UIButton *)sender;    if(tempBut.tag == 4100){        //语音        if(!_gVoice){            NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"VoiceInfo" owner:nil options:nil];            _gVoice = (VoiceInfo*)[array objectAtIndex:0];            //关联事件            [_gVoice.but0 addTarget:self action:@selector(gCancelVoice:) forControlEvents:UIControlEventTouchUpInside];            [_gVoice.but1 addTarget:self action:@selector(gVoiceDown:) forControlEvents:UIControlEventTouchDown];            [_gVoice.but1 addTarget:self action:@selector(gVoiceInside:) forControlEvents:UIControlEventTouchUpInside];            [_gVoice.but1 addTarget:self action:@selector(gVoiceOutside:) forControlEvents:UIControlEventTouchUpOutside];        }        [_gVoice setFrame:[[UIScreen mainScreen] bounds]];        CGRect tempPicRect = _gVoice.gViewOne.frame;        tempPicRect.origin.y = [[UIScreen mainScreen] bounds].size.height - tempPicRect.size.height;        _gVoice.gViewOne.frame = tempPicRect;                CGRect rectOne = _gVoice.frame;        CGRect rectTwo = self.view.frame;        float changeF = rectTwo.size.height - rectOne.size.height;        rectOne.origin.y = changeF;        [_gVoice setFrame:rectOne];        [self.view addSubview:_gVoice];        CGRect tempRect = _gVoice.frame;        CGRect tempRectOne = tempRect;        tempRectOne.origin.y = self.view.frame.size.height;        [_gVoice setFrame:tempRectOne];        //动画        [_gVoice setAlpha:0];        [_gVoice.gViewOne setAlpha:0];        [_gVoice.gImgV setAlpha:0];        [UIView animateWithDuration:0.3 animations:^{            [_gVoice setFrame:tempRect];            [_gVoice setAlpha:1];            [_gVoice.gViewOne setAlpha:1];            [_gVoice.gImgV setAlpha:0.2];        } completion:^(BOOL finished){}];        [self cReturnLocation];            }else if(tempBut.tag == 4101){        //图片        if(!_gPicture){            NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"PictureInfo" owner:nil options:nil];            _gPicture = (PictureInfo*)[array objectAtIndex:0];            //关联事件            [_gPicture.but0 addTarget:self action:@selector(gCancel:) forControlEvents:UIControlEventTouchUpInside];            [_gPicture.but1 addTarget:self action:@selector(gPlot:) forControlEvents:UIControlEventTouchUpInside];            [_gPicture.but2 addTarget:self action:@selector(gPlot:) forControlEvents:UIControlEventTouchUpInside];            [_gPicture.but3 addTarget:self action:@selector(gPlot:) forControlEvents:UIControlEventTouchUpInside];        }        [_gPicture setFrame:[[UIScreen mainScreen] bounds]];        CGRect tempPicRect = _gPicture.gViewOne.frame;        tempPicRect.origin.y = [[UIScreen mainScreen] bounds].size.height - tempPicRect.size.height;        _gPicture.gViewOne.frame = tempPicRect;                CGRect rectOne = _gPicture.frame;        CGRect rectTwo = self.view.frame;        float changeF = rectTwo.size.height - rectOne.size.height;        rectOne.origin.y = changeF;        [_gPicture setFrame:rectOne];        [self.view addSubview:_gPicture];        CGRect tempRect = _gPicture.frame;        CGRect tempRectOne = tempRect;        tempRectOne.origin.y = self.view.frame.size.height;        [_gPicture setFrame:tempRectOne];        //动画        [_gPicture setAlpha:0];        [_gPicture.gViewOne setAlpha:0];        [_gPicture.gImgV setAlpha:0];        [UIView animateWithDuration:0.3 animations:^{            [_gPicture setFrame:tempRect];            [_gPicture setAlpha:1];            [_gPicture.gViewOne setAlpha:1];            [_gPicture.gImgV setAlpha:0.2];        } completion:^(BOOL finished){}];        [self cReturnLocation];            //文本    }else if(tempBut.tag == 4102){        //发送        BOOL judge = 0;        for (int i = 0; i < [_gImputTxtV.text length]; i ++) {            NSString *str = [_gImputTxtV.text substringWithRange:NSMakeRange(i, 1)];            if(![str isEqualToString:@" "]){                if(![str isEqualToString:@"\n"]){                    judge = 1;                }            }        }        if(judge){            long int temptime = [self cNowTimestamp ];            //消息发送时 立即插入数据库            [self cInsertLibaryWithID:temptime andContent:_gImputTxtV.text andType:1 andFileinfo:0];        }else{        }        [self.gCellHeightArr removeAllObjects];        [_gProcessTV reloadData];        _gImputTxtV.text = nil;    }    [self cMessageSend:40];    [_gProcessTV setContentOffset:CGPointMake(0, 0)];}//图片发送- (void)gCancel:(id)sender{    CGRect tempRect = _gPicture.gViewOne.frame;    tempRect.origin.y = _gPicture.frame.size.height;    //动画    [UIView animateWithDuration:0.35 animations:^{        [_gPicture.gViewOne setFrame:tempRect];        [_gPicture.gViewOne setAlpha:0];        [_gPicture.gImgV setAlpha:0];    } completion:^(BOOL finished){        [_gPicture removeFromSuperview];    }];}- (void)gPlot:(id)sender{    NSInteger tag = [sender tag];    CGFloat height = [UIScreen mainScreen].bounds.size.height;    UIView* subview = (UIView*)[self.view viewWithTag:135];    CGRect rect = subview.frame;    rect.origin.y = 1.0*height;        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{        _gPicture.alpha = 0.0;        subview.frame = rect;    } completion:^(BOOL finished) {        if (finished) {            [_gPicture removeFromSuperview];            if (tag == 13) {//拍照                [self presentImageViewControllerWithCameraAvailable:1];            } else if (tag == 15) {//我的标绘                           } else {//手机相册                [self presentImageViewControllerWithCameraAvailable:0];            }        }    }];}- (void)presentImageViewControllerWithCameraAvailable:(NSUInteger)isAvaiable{    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];    pickerController.delegate = self;    if (isAvaiable == 1) {        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {            UIAlertView* alertView =            [[UIAlertView alloc] initWithTitle:nil                                       message:@"设备不支持拍照"                                      delegate:nil                             cancelButtonTitle:@"确定"                             otherButtonTitles: nil];            [alertView show];            return;        }                pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;    } else {        pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;    }    pickerController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;    [self presentViewController:pickerController animated:YES completion:NULL];    }#pragma mark - UIImagePickerControllerDelegate- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    UIImage *sourceImage = (UIImage *)[info valueForKey:UIImagePickerControllerOriginalImage];    if (sourceImage == nil) {        NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset)        {            ALAssetRepresentation *representation = [asset defaultRepresentation];            UIImage *originalImage = [UIImage imageWithCGImage:[representation fullResolutionImage]];            NSData* data = UIImageJPEGRepresentation(originalImage, 0.8);            if (data) {                NSString* filePath = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];                filePath = [filePath stringFromMD5];                NSString* fileItem = [NSString stringWithFormat:@"%@_P.jpg",filePath];                NSString* picPath = [self getUserMessagePictureFileSavePath];                picPath = [picPath stringByAppendingPathComponent:fileItem];                if (![[NSFileManager defaultManager] fileExistsAtPath:picPath]) {                    BOOL bSuccess = [[NSFileManager defaultManager] createFileAtPath:picPath contents:data attributes:NULL];                    if (bSuccess) {                        [self cPicPicChioce:picPath];                    }                }            } else {                UIAlertView* alertView =                [[UIAlertView alloc] initWithTitle:nil                                           message:@"图片已损坏"                                          delegate:nil                                 cancelButtonTitle:@"确定"                                 otherButtonTitles: nil];                [alertView show];            }            [picker dismissViewControllerAnimated:YES completion:NULL];        };        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];        [assetslibrary assetForURL:imageURL                       resultBlock:resultblock                      failureBlock:nil];    } else {        NSData* data = UIImageJPEGRepresentation(sourceImage, 0.8);        NSString* filePath = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];        filePath = [filePath stringFromMD5];        NSString* fileItem = [NSString stringWithFormat:@"%@_P.jpg",filePath];        NSString* picPath = [self getUserMessagePictureFileSavePath];        picPath = [picPath stringByAppendingPathComponent:fileItem];        if (![[NSFileManager defaultManager] fileExistsAtPath:picPath]) {            BOOL bSuccess = [[NSFileManager defaultManager] createFileAtPath:picPath contents:data attributes:NULL];            if (bSuccess) {                [self cPicPicChioce:picPath];            }        }        [picker dismissViewControllerAnimated:YES completion:NULL];    }}-(void)cPicPicChioce:(NSString *)picPath{    if(picPath){        [self cMessageTableView];        long int temptime = [self cNowTimestamp];        //消息发送时 立即插入数据库        [self cInsertLibaryWithID:temptime andContent:picPath andType:2 andFileinfo:0];        [_gProcessTV reloadData];    }}- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{    [picker dismissViewControllerAnimated:YES completion:NULL];}//标绘图片1-(void)didEndCell:(NSInteger)mid path:(NSString*)path controller:(UIViewController *)VC{    if (path.length != 0) {        //消息中心,选择图片复制        UIImage *sourceImage = (UIImage *)[UIImage imageWithContentsOfFile:path];        NSData* data = UIImageJPEGRepresentation(sourceImage, 0.8);        NSString* filePath = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];        filePath = [filePath stringFromMD5];        NSString* fileItem = [NSString stringWithFormat:@"%@_P.jpg",filePath];        NSString* picPath = [self getUserMessagePictureFileSavePath];        picPath = [picPath stringByAppendingPathComponent:fileItem];        if (![[NSFileManager defaultManager] fileExistsAtPath:picPath]) {            BOOL bSuccess = [[NSFileManager defaultManager] createFileAtPath:picPath contents:data attributes:NULL];            if (bSuccess) {                if(picPath){                    long int temptime = [self cNowTimestamp];                    //消息发送时 立即插入数据库                    [self cInsertLibaryWithID:temptime andContent:picPath andType:2 andFileinfo:0];                    [_gProcessTV reloadData];                }            }        }    }}//语音//录音被取消- (void)gCancelVoice:(id)sender{    CGRect tempRect = _gVoice.gViewOne.frame;    tempRect.origin.y = _gVoice.frame.size.height;    [UIView animateWithDuration:0.35 animations:^{        [_gVoice.gViewOne setFrame:tempRect];        [_gVoice.gViewOne setAlpha:0];        [_gVoice.gImgV setAlpha:0];    } completion:^(BOOL finished){        [_gVoice removeFromSuperview];    }];}//录音开始- (void)gVoiceDown:(id)sender{    if (![AudioRecord hasMicphone]) {        UIAlertView* alertView =        [[UIAlertView alloc] initWithTitle:nil                                   message:@"设备不支持录音"                                  delegate:nil                         cancelButtonTitle:@"确定"                         otherButtonTitles: nil];        [alertView show];        return;    }    if ([AudioRecord isMuted]) {        UIAlertView* alertView =        [[UIAlertView alloc] initWithTitle:nil                                   message:@"设备处于静音状态,请调高音量"                                  delegate:nil                         cancelButtonTitle:@"确定"                         otherButtonTitles: nil];        [alertView show];        return;    }    if ([[self fetchSystemVersion] floatValue] >= 7.0) {        //麦克风授权        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {            if (granted) {                NSString* filePath = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];                filePath = [filePath stringFromMD5];                NSString* fileItem = [NSString stringWithFormat:@"%@_A.caf",filePath];                NSString* audioPath = [self getUserMessageAudioFileSavePath];                audioPath = [audioPath stringByAppendingPathComponent:fileItem];                if(!self.mAudioRecord){                    self.mAudioRecord = [[AudioRecord alloc] init];                }                [self.mAudioRecord startRecordWithPath:audioPath];            } else {                UIAlertView* alertView =                [[UIAlertView alloc] initWithTitle:nil                                           message:@"用户不允许使用麦克风"                                          delegate:nil                                 cancelButtonTitle:@"确定"                                 otherButtonTitles: nil];                [alertView show];                return;            }        }];    } else {        NSString* filePath = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];        filePath = [filePath stringFromMD5];        NSString* fileItem = [NSString stringWithFormat:@"%@_A.caf",filePath];        NSString* audioPath = [self getUserMessageAudioFileSavePath];        audioPath = [audioPath stringByAppendingPathComponent:fileItem];        if(!self.mAudioRecord){            self.mAudioRecord = [[AudioRecord alloc] init];        }        [self.mAudioRecord startRecordWithPath:audioPath];    }}//录音结束- (void)gVoiceInside:(id)sender{    [self.mAudioRecord stopRecord];    CGFloat height = [UIScreen mainScreen].bounds.size.height;    UIView* subview = (UIView*)[_gVoice.gViewOne viewWithTag:125];    CGRect rect = subview.frame;    rect.origin.y = 1.0*height;    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{        _gVoice.alpha = 0.0;        subview.frame = rect;    } completion:^(BOOL finished) {        if (finished) {            [_gVoice removeFromSuperview];        }    }];        if (self.mAudioRecord.recordTime < 0.5f) {//录音时间太短了        if ([[NSFileManager defaultManager] fileExistsAtPath:self.mAudioRecord.recordPath]) {            [[NSFileManager defaultManager] removeItemAtPath:self.mAudioRecord.recordPath error:NULL];        }        self.mAudioRecord = nil;        UIAlertView* alertView =        [[UIAlertView alloc] initWithTitle:nil                                   message:@"录音时间太短了"                                  delegate:nil                         cancelButtonTitle:@"确定"                         otherButtonTitles: nil];        [alertView show];        return;    } else if (self.mAudioRecord.averagePower < -40.0) {//小于-40分贝,表示没有说话        if ([[NSFileManager defaultManager] fileExistsAtPath:self.mAudioRecord.recordPath]) {            [[NSFileManager defaultManager] removeItemAtPath:self.mAudioRecord.recordPath error:NULL];        }        self.mAudioRecord = nil;        UIAlertView* alertView =        [[UIAlertView alloc] initWithTitle:nil                                   message:@"你的声音太小了"                                  delegate:nil                         cancelButtonTitle:@"确定"                         otherButtonTitles: nil];        [alertView show];        return;    }        NSString* destPath = self.mAudioRecord.recordPath;    destPath = [destPath substringToIndex:destPath.length-6];    //储存路径    NSString* path = [NSString stringWithFormat:@"%@_%d_A.caf", destPath, (int)self.mAudioRecord.recordTime+1];    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {        BOOL bSuccess = [[NSFileManager defaultManager] copyItemAtPath:self.mAudioRecord.recordPath toPath:path error:NULL];        if (bSuccess) {            [[NSFileManager defaultManager] removeItemAtPath:self.mAudioRecord.recordPath error:NULL];        }    }    self.mAudioRecord = nil;    //.caf转换为.mp3    NSString *voiPathMP3 = [self audio_PCMtoMP3:path];    if(voiPathMP3){        _gProcessAPlayer = [ProcessAudioPlay sharedProcessAudioPlayAction];        [_gProcessAPlayer cPlayerData:voiPathMP3];        _gAudioPlayer = [_gProcessAPlayer gAudioPlayer];        NSInteger voiInt = _gAudioPlayer.duration;//语音时间        if(voiInt < 1){            voiInt = 1;        }        long int temptime = [self cNowTimestamp];        //消息发送时 立即插入数据库        [self cInsertLibaryWithID:temptime andContent:voiPathMP3 andType:3 andFileinfo:voiInt];        [_gProcessTV reloadData];            }}//录音被取消- (void)gVoiceOutside:(id)sender{    [self.mAudioRecord cancelRecord];    self.mAudioRecord = nil;    CGFloat height = [UIScreen mainScreen].bounds.size.height;    UIView* subview = (UIView*)[_gVoice.gViewOne viewWithTag:125];    CGRect rect = subview.frame;    rect.origin.y = 1.0*height;    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{        _gVoice.alpha = 0.0;        subview.frame = rect;    } completion:^(BOOL finished) {        if (finished) {            [_gVoice removeFromSuperview];        }    }];    UIAlertView* alertView =    [[UIAlertView alloc] initWithTitle:nil                               message:@"录音被取消了"                              delegate:nil                     cancelButtonTitle:@"确定"                     otherButtonTitles: nil];    [alertView show];}//.caf转换为.mp3-(NSString *)audio_PCMtoMP3:(NSString *)cafPath{    NSString *cafFilePath = cafPath;    NSMutableString *changeName = [cafFilePath mutableCopy];    NSString *changePath;    if([[changeName substringFromIndex:changeName.length-3] isEqualToString:@"caf"]){        changePath = [changeName substringToIndex:changeName.length-3];    }    NSString *mp3FilePath;    if(changePath){        mp3FilePath = [NSString stringWithFormat:@"%@mp3",changePath];    }    @try {        int read, write;        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header                FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置                const int PCM_SIZE = 8192;        const int MP3_SIZE = 8192;        short int pcm_buffer[PCM_SIZE*2];        unsigned char mp3_buffer[MP3_SIZE];                lame_t lame = lame_init();        lame_set_num_channels(lame,2);//设置1为单通道,默认为2双通道        lame_set_in_samplerate(lame, 11025.0);//44100.0);//11025.0        lame_set_VBR(lame, vbr_default);        lame_set_brate(lame,8);        lame_set_mode(lame,3);        lame_set_quality(lame,2); /* 2=high 5 = medium 7=low 音质*/        lame_init_params(lame);        do {            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);            if (read == 0)                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);            else                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);                        fwrite(mp3_buffer, write, 1, mp3);                    } while (read != 0);                lame_close(lame);        fclose(mp3);        fclose(pcm);    }    @catch (NSException *exception) {            }    @finally {        //若转换成功, 删除caf文件        NSFileManager* fileManager=[NSFileManager defaultManager];        if([fileManager contentsAtPath:mp3FilePath]){            [fileManager removeItemAtPath:cafFilePath error:nil];        }    }    return mp3FilePath;}//消息发送时 立即插入数据库-(void)cInsertLibaryWithID:(long int)theID andContent:(NSString *)theContent andType:(NSInteger)theType andFileinfo:(NSInteger)theFileinfo{    NSString *groupID = @"0";    NSString *groupName = @"";    NSString *sendName = @"";    if([_titleLab.text isEqualToString:@"张三(收)"]){        sendName = @"张三";    }else{        sendName = @"李四";    }    NSString *myID = _gMyObjectID;    NSMutableDictionary *messageSend = [[NSMutableDictionary alloc] init];    [messageSend setObject:[NSNumber numberWithLong:theID] forKey:@"id"];    [messageSend setObject:theContent forKey:@"content"];    [messageSend setObject:[NSNumber numberWithInt:theType] forKey:@"type"];    [messageSend setObject:[NSNumber numberWithLong:theID] forKey:@"addtime"];    [messageSend setObject:@"" forKey:@"fileinfo"];    [messageSend setObject:_gObjectID forKey:@"receive_uid"];    [messageSend setObject:[NSNumber numberWithInt:0] forKey:@"rectime"];    [messageSend setObject:[NSString stringWithFormat:@"%@",myID] forKey:@"send_uid"];    [messageSend setObject:sendName forKey:@"send_uname"];    [messageSend setObject:[NSNumber numberWithInt:1] forKey:@"send"];//2 请求,0 失败,1 成功    [messageSend setObject:[NSNumber numberWithInt:theFileinfo] forKey:@"fileinfo"];    [messageSend setObject:groupID forKey:@"groupid"];    [messageSend setObject:groupName forKey:@"groupname"];    //插入数据库 默认为未发送成功    [self cSendTalkDatabaseInsertInto:messageSend];    messageSend = nil;}//消息发送时 数据库插入 用户交谈-(void)cSendTalkDatabaseInsertInto:(NSDictionary *)talkDict{    //特殊字符转换——    NSString *strContent = [talkDict objectForKey:@"content"];    if(strContent == nil || [strContent isEqualToString:@""]){        strContent = [talkDict objectForKey:@"content"];    }    //现在表中查询有没有相同的元素,如果有,做修改操作    NSString *sqlCodeOne = [NSString stringWithFormat:@"select * from UserTalk where Tid = %lld",[[talkDict objectForKey:@"id"] longLongValue]];    PTDBManage* manager = [[PTDBManage alloc] init];    FMResultSet *rs = [[manager startDB] executeQuery:sqlCodeOne];    BOOL result = NO;    if([rs next])    {        result = YES;    }    [rs close];    [manager endDB];        if(!result){        //3.插入        NSString *sqlCode = [NSString stringWithFormat:@"INSERT INTO UserTalk (Tid,Ttype,Tsend_uid,Tsend_uname,Treceive_uid,Tcontent,Taddtime,Trectime,Tsend,TfileInfo,Fuserid,Fobjectid,UGroupId,UGroupName) VALUES (%d,%d,'%@','%@','%@','%@',%d,%d,%d,%d,'%@','%@','%@','%@')",                             [[talkDict objectForKey:@"id"] intValue],                             [[talkDict objectForKey:@"type"] intValue],                             [talkDict objectForKey:@"send_uid"],                             [talkDict objectForKey:@"send_uname"],                             [talkDict objectForKey:@"receive_uid"],                             strContent,                             [[talkDict objectForKey:@"addtime"] intValue],                             [[talkDict objectForKey:@"rectime"] intValue],                             [[talkDict objectForKey:@"send"] intValue],                             [[talkDict objectForKey:@"fileinfo"] intValue],                             _gUserid,                             _gObjectID,                             [talkDict objectForKey:@"groupid"],                             [talkDict objectForKey:@"groupname"]                                                          ];        //插入数据使用OC中的类型 text对应为NSString integer对应为NSNumber的整形        manager = [[PTDBManage alloc] init];        BOOL success =   [[manager startDB] executeUpdate:sqlCode];        if(success){            NSLog(@"---------insert DB sucess-----------");        }else{             NSLog(@"---------insert DB faile------------");        }        [manager endDB];    }}-(void)cReturnDown{    UIView *tempV = (UIView *)[self.view viewWithTag:6500];    [UIView animateWithDuration:0.2 animations:^{        [tempV setFrame:CGRectMake(0, self.view.frame.size.height-150, self.view.frame.size.width, 150)];    } completion:^(BOOL finished){}];}//获得当前时间-(NSString *)cAcquireNowTime:(NSString *)timestamp{    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:[timestamp intValue]];    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:@"yyyy年M月d日 HH:mm"];    NSString *strTime = [dateFormatter stringFromDate:timeData];    [dateFormatter setDateFormat:@"HH:mm"];    NSString *strTimeTwo = [dateFormatter stringFromDate:timeData];    [dateFormatter setDateFormat:@"yyyy"];    NSString *strYear = [dateFormatter stringFromDate:timeData];    [dateFormatter setDateFormat:@"M"];    NSString *strMonth = [dateFormatter stringFromDate:timeData];    [dateFormatter setDateFormat:@"d"];    NSString *strDay = [dateFormatter stringFromDate:timeData];        if([timestamp isEqualToString:@""]){        return @"";    }else{        if(![strDay isEqualToString:[self cNowTimestamp:@"d"]]){            return strTime;        }else if([strYear isEqualToString:[self cNowTimestamp:@"yyyy"]] && [strMonth isEqualToString:[self cNowTimestamp:@"M"]] && [strDay isEqualToString:[self cNowTimestamp:@"d"]]){            return strTimeTwo;        }    }    return strTime;}//当前时间的时间戳_日-(NSString *)cNowTimestamp:(NSString *)theMark{    long int timeSp = [self cNowTimestamp];    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:timeSp];    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:theMark];    NSString *strTime = [dateFormatter stringFromDate:timeData];    return strTime;}//Cell自适应高度-(CGRect)cAdaptCellHeight:(NSString *)theStr{    NSString *desContent = theStr;   //获取文本内容    CGRect orgRect = CGRectMake(0, 0, 0, 0); //获取原始UITextView的frame    CGSize  size = [desContent sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(230-20, 2000) lineBreakMode:NSLineBreakByWordWrapping];    orgRect.size.height = size.height;    return orgRect;}//发送消息块 移动-(void)cMoveLocation{    CGRect sendRect = _gSendV.frame;    sendRect.origin.y = self.view.frame.size.height - _gKeyBoardH-_gSendV.frame.size.height;    CGRect tvrect =  self.gTVrect;    tvrect.size.height = tvrect.size.height - _gKeyBoardH;        [UIView animateWithDuration:0.25 animations:^{        [_gSendV setFrame:sendRect];        [_gProcessTV setFrame:tvrect];    } completion:^(BOOL finished){}];        [_gProcessTV setContentOffset:CGPointMake(0, 0) animated:YES];}//发送消息块 归位-(void)cReturnLocation{    CGRect tempRect = _gSendV.frame;    tempRect.origin.y = self.view.frame.size.height-_gSendV.frame.size.height;    [self.view endEditing:YES];    [_gProcessTV setFrame:self.gTVrect];    [_gProcessTV reloadData];    [UIView animateWithDuration:0.25 animations:^{        [_gSendV setFrame:tempRect];    } completion:^(BOOL finished){        _gKeyBoardH = 0;    }];}//当键盘出现或改变时调用- (void)keyboardWillShow:(NSNotification *)aNotification{    NSDictionary *userInfo = [aNotification userInfo];    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];    CGRect keyboardRect = [aValue CGRectValue];    int height = keyboardRect.size.height;    _gKeyBoardH = height;    [self cMoveLocation];}//当键退出时调用- (void)keyboardWillHide:(NSNotification *)aNotification{    [self cReturnLocation];}#pragma mark UITextViewDelegate- (void)textViewDidChange:(UITextView *)textView{    if (textView.tag == 4200) {        CGSize textSize = textView.contentSize;        textSize.height = textSize.height + 8;        [textView setContentSize:textSize];        [self cMessageSend:textView.contentSize.height];    }}#pragma mark UITableViewDataSource- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    [self.gCellHeightArr removeAllObjects];    return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    //从数据库获取数据    [self cTalkTVRowAction];    NSInteger returnRow;    returnRow = [self.gMessageInfo count];    return returnRow;}//数据准备-(void)cTalkTVRowAction{    NSMutableArray *sqlMarr = [[NSMutableArray alloc] init];    FMResultSet *rs;    NSString *myID = _gMyObjectID;    //sql语句    NSString *sqlCode = [NSString stringWithFormat:@"select * from UserTalk where (Tsend_uid='%@' and Treceive_uid='%@' and Fuserid = '%@' and UGroupId='%@')  or (Tsend_uid='%@' and Treceive_uid='%@' and Fuserid = '%@' and UGroupId='%@') order by Taddtime Desc",myID,_gObjectID,_gUserid,@"0",_gObjectID,myID,_gUserid,@"0"];        PTDBManage* manager = [[PTDBManage alloc] init];    rs = [[manager startDB] executeQuery:sqlCode];    //判断结果集中是否有数据,如果有则取出数据    while ([rs next]) {        NSMutableDictionary *tempdict = [[NSMutableDictionary alloc] init];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Tid"]] forKey:@"id"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Ttype"]] forKey:@"type"];        [tempdict setObject:[rs stringForColumn:@"Tsend_uid"] forKey:@"send_uid"];        [tempdict setObject:[rs stringForColumn:@"Tsend_uname"] forKey:@"send_uname"];        [tempdict setObject:[rs stringForColumn:@"Treceive_uid"] forKey:@"receive_uid"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Fuserid"]] forKey:@"userid"];        //转换为特殊字符        NSString  *strContent = [rs stringForColumn:@"Tcontent"];        [tempdict setObject:strContent forKey:@"content"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Taddtime"]] forKey:@"addtime"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Trectime"]] forKey:@"rectime"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"Tsend"]] forKey:@"send"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"TfileInfo"]] forKey:@"fileinfo"];        [tempdict setObject:[NSString stringWithFormat:@"%d",[[rs stringForColumn:@"UGroupId"] integerValue]] forKey:@"groupid"];        [tempdict setObject:[rs stringForColumn:@"UGroupName"] forKey:@"groupname"];                //将查询到的数据放入数组中。        [sqlMarr addObject:tempdict];    }    [rs close];    [manager endDB];        //点击查看更多    NSInteger tempInt = 15*_leftPageNum;    if([sqlMarr count] > tempInt ){        self.gMessageInfo = [[sqlMarr subarrayWithRange:NSMakeRange(0, tempInt)] mutableCopy];        //点击加载更多        [self startLoadingAction];    }else{        //加载完成        self.gMessageInfo = sqlMarr;        [self stopLoadingAction];    }    if(self.gMessageInfo.count < 15){        [_gProcessTV.tableFooterView setHidden:YES];    }else{        [_gProcessTV.tableFooterView setHidden:NO];    }        //5分钟内时间清空    for (int i = self.gMessageInfo.count-1; i >= 0; i --) {        NSDictionary *idict = [self.gMessageInfo objectAtIndex:i];        NSString *iaddtime = [idict objectForKey:@"addtime"];        NSInteger oldtime = [iaddtime integerValue];        for (int j = i-1 ; j >= 0 ; j --) {            NSDictionary *jdict = [self.gMessageInfo objectAtIndex:j];            NSString *jaddtime = [jdict objectForKey:@"addtime"];            NSInteger newtime = [jaddtime integerValue];            if((oldtime-newtime)>300 || (newtime-oldtime)>300){                        }else{                [jdict setValue:@"" forKey:@"addtime"];            }        }    }}//TV- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *cellIdentifier=@"GroupMessageCell";    GroupMessageCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];    [cell releaseAction];    if (!cell) {        cell = (GroupMessageCell*)[[[NSBundle mainBundle] loadNibNamed:@"GroupMessageCell" owner:nil options:nil] objectAtIndex:0];        cell.backgroundColor=[UIColor clearColor];        cell.selectionStyle = UITableViewCellSelectionStyleNone;    }    float cellHeight = [tableView rectForRowAtIndexPath:indexPath].size.height;    NSDictionary *cellDict = (NSDictionary *)[self.gMessageInfo objectAtIndex:indexPath.row];    if(cellDict){        BOOL result = NO;        if([[cellDict objectForKey:@"send_uid"] isEqualToString:_gMyObjectID]){            result = YES;        }        //文本        if([[cellDict objectForKey:@"type"] intValue] == 1){            [cell cProcessMessageTime:[self cAcquireNowTime:[cellDict objectForKey:@"addtime"] ] andInfo:[cellDict objectForKey:@"content"] andIsMy:result andInfoHeight:cellHeight andSend:[cellDict objectForKey:@"send"] andTalkID:_gObjectID andSendName:[cellDict objectForKey:@"send_uname"]];                    //图片        }else if ([[cellDict objectForKey:@"type"] intValue] == 2){                        [cell cProcessMessageTime:[self cAcquireNowTime:[cellDict objectForKey:@"addtime"] ]  andPicture:[cellDict objectForKey:@"content"] andIsMy:result andInfoHeight:cellHeight andSend:[cellDict objectForKey:@"send"] andTalkID:_gObjectID andSendName:[cellDict objectForKey:@"send_uname"]];                    //语音        }else if([[cellDict objectForKey:@"type"] intValue] == 3){            [cell cProcessMessageTime:[self cAcquireNowTime:[cellDict objectForKey:@"addtime"] ] andVoicePath:[cellDict objectForKey:@"content"]  andIsMy:result andInfoHeight:cellHeight andSend:[cellDict objectForKey:@"send"] andTalkID:_gObjectID andSendName:[cellDict objectForKey:@"send_uname"] andFileInfo:[[cellDict objectForKey:@"fileinfo"] intValue]];        }else{            [cell hidnViewAction];        }    }    [cell setTransform:CGAffineTransformMakeRotation(M_PI)];    return cell;}#pragma mark UITableViewDelegate- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    float returnHeight = 44;    if([self.gMessageInfo count]<15){        NSDictionary *cellDict = (NSDictionary *)[self.gMessageInfo objectAtIndex:indexPath.row];        if(cellDict){            if ([[cellDict objectForKey:@"type"] intValue] == 2){                UIImage *teImg = [UIImage imageWithContentsOfFile:[cellDict objectForKey:@"content"]];                UIImage *tempImg = teImg;                if(tempImg.size.height > 100){                    returnHeight = 100+50;                }else{                    returnHeight = tempImg.size.height;                    if(returnHeight<50){                        returnHeight = 50+50;                    }else{                        returnHeight = returnHeight +50;                    }                }            //语音            }else if([[cellDict objectForKey:@"type"] intValue] == 3){                returnHeight = 20+50;            }//文本            else{                NSString *tempStr = [cellDict objectForKey:@"content"];                //原因是从XML中读取出来的"\n",系统认为是字符串,会默认转换为"\\n",所以当显示的时候就是字符串了,要想显示换行,需要自己手动将"\\n"转换为"\n",这样才能换行.                NSString*b =[tempStr stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];                CGRect tempFrame = [self cAdaptCellHeight:b];                returnHeight = tempFrame.size.height+50;            }        }else{        }        [self.gCellHeightArr addObject:[NSNumber numberWithFloat:returnHeight]];    }else{        NSDictionary *cellDict = (NSDictionary *)[self.gMessageInfo objectAtIndex:indexPath.row];        if(cellDict){            if ([[cellDict objectForKey:@"type"] intValue] == 2){                UIImage *teImg = [UIImage imageWithContentsOfFile:[cellDict objectForKey:@"content"]];                UIImage *tempImg = teImg;                if(tempImg.size.height > 100){                    returnHeight = 100+50;                }else{                    returnHeight = tempImg.size.height;                    if(returnHeight<50){                        returnHeight = 50+50;                    }else{                        returnHeight = returnHeight +50;                    }                }            //语音            }else if([[cellDict objectForKey:@"type"] intValue] == 3){                returnHeight = 20+50;            //文本            }else{                NSString *tempStr = [cellDict objectForKey:@"content"];                NSString*b =[tempStr stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];                CGRect tempFrame = [self cAdaptCellHeight:b];                returnHeight = tempFrame.size.height+50;            }        }else{        }        [self.gCellHeightArr addObject:[NSNumber numberWithFloat:returnHeight]];    }    returnHeight = returnHeight + 15;    return returnHeight;}//正在加载- (IBAction)loadingMoreAction:(id)sender {    [_tapLoadBut setTitle:@"点击加载更多" forState:UIControlStateNormal];    [_tapLoadBut setHidden:YES];    [_loadingView setHidden:NO];    _leftPageNum = _leftPageNum + 1;    [_gProcessTV reloadData];    }//点击加载更多-(void)startLoadingAction{    [_tapLoadBut setTitle:@"点击加载更多" forState:UIControlStateNormal];    [_tapLoadBut setUserInteractionEnabled:YES];    [_tapLoadBut setHidden:NO];    [_loadingView setHidden:YES];}//加载完成-(void)stopLoadingAction{    [_tapLoadBut setTitle:@"加载完成" forState:UIControlStateNormal];    [_tapLoadBut setUserInteractionEnabled:NO];    [_tapLoadBut setHidden:NO];    [_loadingView setHidden:YES];}//判断字符串不全为空-(BOOL)judgeStringIsNull:(NSString *)string{    BOOL result = NO;    if(string != nil && string.length > 0){        for (int i = 0; i < string.length; i ++) {            NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];            if(![subStr isEqualToString:@" "] && ![subStr isEqualToString:@""]){                result = YES;            }        }    }    return result;}//当前时间的时间戳-(long int)cNowTimestamp{    NSDate *newDate = [NSDate date];    long int timeSp = (long)[newDate timeIntervalSince1970];    return timeSp;}- (NSString*)getUserMessagePictureFileSavePath{    NSString *path      = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Message"];    NSString *filePath  = [path stringByAppendingPathComponent:@"Pictures"];    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];    }    return filePath;}- (NSString*)getUserMessageAudioFileSavePath{    NSString *path      = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Message"];    NSString *filePath  = [path stringByAppendingPathComponent:@"Audios"];    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];    }    return filePath;}- (NSString *)fetchSystemVersion{    return [[UIDevice currentDevice] systemVersion];}@end


示图:









0 0
原创粉丝点击