学习iOS也有一段时间了。也在试着用iOS来写项目,感谢各路大神的帮助,就不一一@了。本文只是记载本人的学习过程。
---------------------学如逆水行舟不进则退。
创建工程的话就不一一解释了,这个大家都会。
.苹果的推送流程大家都应该已经知道了(不知道的去看看吧,很简单)
此方法可以满足一些小型聊天这都是没有问题的能做到消息的即使收取,收到消息后可以直接刷新消息页面
1.首先需要做出推送证书来,跟你的后台好好弄好推送,在收到推送那里写一个通知用于接受消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
DLog(@"userInfo == %@",userInfo);
NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
UIAlertView *createUserResponseAlert = [[UIAlertView alloc]initWithTitle:@"hint" message:message delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"confirm", nil];
// [createUserResponseAlert show];
[[NSNotificationCenter defaultCenter]postNotificationName:@"xinxiaoxi" object:nil];
}
2.这个需要的是跟后台商量如何来定出一个唯一的用户标示符。如:我定下的就是username。。。。。。。
在进入聊天界面的时候我们应该来开启一个聊天进程,不会的话,后台应该可以做到的。。。
首先用接口来获取到用户的所有聊天信息
//取到所有聊天
- (void)getAllChat
{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setValue:MyZenID forKey:@"zenid"];
ASIHTTPRequest *request = [ZJNerUtles getAllCustomerChat:self withValue:dic];
[g_ASIQuent addOperation:request];
g_ASIQuent.delegate=self;
}
具体代码在最后面会贴出来
发送消息的时候应该调用发送消息并即使及时更新表示图本地数据来显示出发送成功
//发送消息
- (void)sendMG
{
//新方法
CGSize abc = _tableView.contentSize;
CGPoint aaa = CGPointMake(0,abc.height-self.view.bounds.size.height+64+44);
[_tableView setContentOffset:aaa animated:YES];
if (textView.text.length == 0) {
NSLog(@"没有内容");
[textView resignFirstResponder];
//做动画过渡
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelegate:self];
TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);
[UIView commitAnimations];
}else{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setValue:MyZenID forKey:@"zenid"];
[dic setValue:textView.text forKey:@"content"];
[OftenTool autoDisappearTipview:@"message is sent"];
ASIHTTPRequest *request = [ZJNerUtles sendMg:self withValue:dic];
[g_ASIQuent addOperation:request];
g_ASIQuent.delegate=self;
//做动画过渡
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelegate:self];
TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);
[UIView commitAnimations];
//收回键盘并且清空数据
[textView resignFirstResponder];
}
}
getAllChat
具体的代码贴出来吧,UI是随便写的但是也实现了一些仿造的弹出效果
.h
//
// H_TestViewController.h
// Dragon
//
// Created by黄权浩 on 14-11-26.
// Copyright (c) 2014年 ZHAO. All rights reserved.
//
#import "BaseViewController.h"
@interface H_TestViewController : BaseViewController<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
{
@private
UITextField *textView;
//聊天框架搭起来
UITableView *_tableView;
//键盘弹起来的通知变化
UIView *TestV;
//最后4条记录
NSMutableArray *lastarr;
//取出大数据组
NSMutableArray *allChatArr;
UIButton *sendMg2;
//定时刷新聊天
// NSTimer *timer;
//加载
UILabel *load;
}
//取数据
@property (nonatomic, strong)NSDictionary *alldic;
@end
//
// H_TestViewController.m
// Dragon
//
// Created by黄权浩 on 14-11-26.
// Copyright (c) 2014年 ZHAO. All rights reserved.
//
#import "H_TestViewController.h"
#import "H_GSCell.h"
@interface H_TestViewController ()
@end
@implementation H_TestViewController
- (void)leftButtonClick
{
//取消定时器
// [timer invalidate];
[[AppDelegate getAppDelegate].navigationController popViewControllerAnimated:NO];
}
//取到所有聊天
- (void)getAllChat
{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setValue:MyZenID forKey:@"zenid"];
ASIHTTPRequest *request = [ZJNerUtles getAllCustomerChat:self withValue:dic];
[g_ASIQuent addOperation:request];
g_ASIQuent.delegate=self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.navigationBarView setNormalLeftButton];
[self.navigationBarView setTitle:@"Consult"];
//注册键盘弹起来的通知
[self registerForKeyboardNotifications];
//定时刷新.做防止丢失推送,暂定为1分钟刷新一次
// timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector: @selector(dingshi) userInfo:nil repeats:YES];
//拿到数据才开始搞界面
[self _init];
}
- (void)dingshi
{
[self getAllChat];
}
//注册键盘弹起来的通知
- (void)registerForKeyboardNotifications
{
//监听键盘抬起
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];
//监听键盘收回
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];
//监听键盘改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];
}
//键盘的通知
- (void)changeContentViewPoint:(NSNotification *)notification{
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyBoardEndY = value.CGRectValue.origin.y;
// 得到键盘弹出后的键盘视图所在y坐标
NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// 添加移动动画,使视图跟随键盘移动
[UIView animateWithDuration:duration.doubleValue animations:^{
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:[curve intValue]];
TestV.center = CGPointMake(TestV.center.x, keyBoardEndY - TestV.bounds.size.height/2.0);
// keyBoardEndY的坐标包括了状态栏的高度,要减去
}
];
}
- (void)showContentViewPoint:(NSNotification *)notification
{
// CGPoint adc;
NSDictionary *info = [notification userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGSize abc = _tableView.contentSize;
CGPoint aaa = CGPointMake(0,abc.height-self.view.bounds.size.height+64+44+keyboardSize.height);
[_tableView setContentOffset:aaa animated:YES];
NSLog(@"keyBoard:%f", keyboardSize.height); //216
///keyboardWasShown = YES;
}
- (void)hiddenContentViewPoint:(NSNotification *)notification
{
// CGSize abc = _tableView.contentSize;
// CGPoint aaa = CGPointMake(0,abc.height-self.view.bounds.size.height+64+44);
// [_tableView setContentOffset:aaa animated:YES];
}
- (void)_init{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dingshi) name:@"xinxiaoxi" object:nil];
//加载
load = [[UILabel alloc] initWithFrame:CGRectMake(0, 74, 320, 40)];
load.text = @"loading...";
load.textAlignment = NSTextAlignmentCenter;
load.textColor = [UIColor grayColor];
load.font = [UIFont systemFontOfSize:13];
load.hidden = YES;
[self.view addSubview:load];
//开始搭建聊天框架
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 320, self.view.bounds.size.height-64-50)];
_tableView.backgroundColor = [UIColor clearColor];
_tableView.delegate = self;
_tableView.dataSource = self;
_tableView.showsVerticalScrollIndicator = NO;
_tableView.separatorStyle = NO;
_tableView.rowHeight = 60;
allChatArr = [_alldic objectForKey:@"data"];
if (allChatArr.count == 0) {
NSLog(@"meiyouliaotian");
}else{
lastarr = [NSMutableArray array];
[lastarr addObject:allChatArr[0]];
[lastarr addObject:allChatArr[1]];
[lastarr addObject:allChatArr[2]];
[lastarr addObject:allChatArr[3]];
NSLog(@"%@",lastarr);
allChatArr = lastarr;
allChatArr = (NSMutableArray *)[[allChatArr reverseObjectEnumerator] allObjects];
NSLog(@"%@",allChatArr);
}
[self.view addSubview:_tableView];
//搭建聊天的页面
TestV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-50, 320, 50)];
//打开交互
TestV.userInteractionEnabled = YES;
TestV.backgroundColor = [UIColor grayColor];
//搞个UITextView
textView = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 230, 40)];
textView.delegate = self;
textView.borderStyle = UITextBorderStyleRoundedRect;
//搞个发送消息的按钮
UIButton *sendMg = [UIButton buttonWithType:UIButtonTypeCustom];
[sendMg setTitle:@"Send" forState:UIControlStateNormal];
[sendMg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sendMg addTarget:self action:@selector(sendMG) forControlEvents:UIControlEventTouchUpInside];
[sendMg setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
sendMg.frame = CGRectMake(250, 5, 60, 40);
[TestV addSubview:sendMg];
[TestV addSubview:textView];
[self.view addSubview:TestV];
}
//发送消息
- (void)sendMG
{
//新方法
CGSize abc = _tableView.contentSize;
CGPoint aaa = CGPointMake(0,abc.height-self.view.bounds.size.height+64+44);
[_tableView setContentOffset:aaa animated:YES];
if (textView.text.length == 0) {
NSLog(@"没有内容");
[textView resignFirstResponder];
//做动画过渡
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelegate:self];
TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);
[UIView commitAnimations];
}else{
NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
[dic setValue:MyZenID forKey:@"zenid"];
[dic setValue:textView.text forKey:@"content"];
[OftenTool autoDisappearTipview:@"message is sent"];
ASIHTTPRequest *request = [ZJNerUtles sendMg:self withValue:dic];
[g_ASIQuent addOperation:request];
g_ASIQuent.delegate=self;
//做动画过渡
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDelegate:self];
TestV.frame = CGRectMake(0, self.view.bounds.size.height-50, 320, 50);
[UIView commitAnimations];
//收回键盘并且清空数据
[textView resignFirstResponder];
}
}
#pragma mark - ASIDELEGATE
- (void)requestFinished:(ASIHTTPRequest *)_request
{
DLog(@"%@",[_request.responseString objectFromJSONString]);
NSDictionary * dic=[_request.responseString objectFromJSONString];
if (_request.tag == H_sendMg_tag) {
NSLog(@"发送结果");
[OftenTool directlyDisappear];
if ([[dic objectForKey:@"status"]isEqualToString:@"OK"]) {
[self getAllChat];
// [_tableView reloadData];
}else{
NSLog(@"发送错误");
}
}else if (_request.tag == H_getAllCustomer_tag) {
[OftenTool directlyDisappear];
// _tableView.scrollEnabled = YES;
NSLog(@"%@",dic);
if ([[dic objectForKey:@"status"]isEqualToString:@"OK"]) {
allChatArr = [dic objectForKey:@"data"];
allChatArr = (NSMutableArray *)[[allChatArr reverseObjectEnumerator] allObjects];
textView.text = @"";
[_tableView reloadData];
CGSize abc = _tableView.contentSize;
CGPoint aaa = CGPointMake(0,abc.height-self.view.bounds.size.height+64+44);
[_tableView setContentOffset:aaa animated:YES];
}
}
}
- (void)requestFailed:(ASIHTTPRequest *)_request
{
NSLog(@"发送失败");
}
#pragma mark - UITextFliedDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return allChatArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];
// static NSString *CellIdentifier = @"dadawdawdaw";
H_GSCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[H_GSCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[cell setDic:allChatArr[indexPath.row]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
H_GSCell *cell = (H_GSCell *)[self tableView:_tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
//监听滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y<0 && scrollView.contentOffset.y > -80) {
NSLog(@"在加载");
load.hidden = NO;
}else if (scrollView.contentOffset.y<0 && scrollView.contentOffset.y < -80)
{
NSLog(@"加载完成");
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
NSLog(@"%f",scrollView.contentOffset.y);
if (scrollView.contentOffset.y < 0 && scrollView.contentOffset.y <= -80) {
//获取所有数据
load.hidden = YES;
[OftenTool showLoadingview];
if (allChatArr.count < 3) {
//刷个毛线
[OftenTool directlyDisappear];
}else{
[self getAllChat];
}
}
}
/*
#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
//
// H_GSCell.h
// Dragon
//
// Created by黄权浩 on 14-11-26.
// Copyright (c) 2014年 ZHAO. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface H_GSCell : UITableViewCell
{
@private
//用户头像
UIImageView *img;
//用户消息
UILabel *test;
}
- (void)setDic:(NSDictionary *)dic;
@end
自定义cell.m
//
// H_GSCell.m
// Dragon
//
// Created by黄权浩 on 14-11-26.
// Copyright (c) 2014年 ZHAO. All rights reserved.
//
#import "H_GSCell.h"
@implementation H_GSCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self _init];
}
return self;
}
- (void)_init
{
//用户头像
img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 50, 50)];
img.image = [UIImage imageNamed:@"testGs"];
[self.contentView addSubview:img];
//用户消息
test = [[UILabel alloc] initWithFrame:CGRectMake(65, 5, 200, 30)];
test.textColor = [UIColor grayColor];
test.font = [UIFont systemFontOfSize:14];
test.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:test];
}
- (void)setDic:(NSDictionary *)dic
{
NSLog(@"dic === = = == ==%@",dic);
NSString *key = [dic objectForKey:@"role"];
//获得当前cell高度
CGRect frame = [self frame];
//文本赋值
test.text = [dic objectForKey:@"content"];
//设置label的最大行数
test.numberOfLines = 0;
CGSize size = CGSizeMake(300, 1000);
UILabel *sssss = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
sssss.font = [UIFont systemFontOfSize:17];
CGSize labelSize = [test.text sizeWithFont:sssss.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping];
test.frame = CGRectMake(65, test.frame.origin.y, 200, labelSize.height+30);
//计算出自适应的高度
frame.size.height = labelSize.height+44;
if ([key isEqualToString:@"0"]) {
if (labelSize.height < 40) {
test.textAlignment = NSTextAlignmentRight;
test = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 200, 30)];
// test.frame = CGRectMake(50, test.frame.origin.y, 200, labelSize.height);
img.frame = CGRectMake(260, 5, 50, 50);
img.image = [UIImage imageNamed:@"testKh"];
}else{
test.frame = CGRectMake(60, test.frame.origin.y, 200, labelSize.height+30);
// test.textAlignment = NSTextAlignmentRight;
img.frame = CGRectMake(260, 5, 50, 50);
img.image = [UIImage imageNamed:@"testKh"];
}
}
self.frame = frame;
}
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
-----------------------------------------日日精进 但求无愧------------------------------