移动端即使通讯
移动端即使通讯
杭城小刘 发表于2年前
移动端即使通讯
  • 发表于 2年前
  • 阅读 7
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

摘要: 最近项目用环信做客户端通讯,但是有的地方却用到了轮询,项目做完后做以总结。

    这个地方回多次提到“Qos”,不知道“Qos”的童鞋可以看看http://my.oschina.net/u/1778933/blog/717615

    一个项目需要做到轮询,提供了一个接口:高频率接口轮询查询新消息,这显然对于流量、电量都是一个很大的开销。还有的地方需要查看新主题,需要打红点,这样又提供一个新主题接口,难道又要轮询?在与接口人员讨论过后,确定了一个解决方案,所有的轮询用一个接口搞定,只不过不同的接口需要一个“类型”参数判断,ios写了一个工具,规定了几种轮询频率,有高、中、低三种轮询频率可选,当客户端轮询到新的主题、消息等时发送通知,在相应的viewController收取通知,然后处理数据源,更新UI。

.h
//
//...

#import <Foundation/Foundation.h>

static NSTimeInterval const HighMessageRequestFrequency = 3.0;
static NSTimeInterval const LowMessageRequestFrequency  = 20.0;


static NSString * const ConsultMessageStateTopicChangedNotification = @"ConsultMessageStateTopicChangedNotification";
static NSString * const ConsultMessageStateReplyChangedNotification = @"ConsultMessageStateReplyChangedNotification";
static NSString * const ConsultMessageStateVisitChangedNotification = @"ConsultMessageStateVisitChangedNotification";
static NSString * const ConsultMessageStateAssociationDocotrChangedNotification = @"ConsultMessageStateAssociationDocotrChangedNotification";

typedef NS_ENUM(NSInteger, RequestFrequency) {
    RequestFrequencyHigh = 1,
    RequestFrequencyLow     ,
    RequestFrequencyStop
};


typedef NS_ENUM(NSUInteger, HLNewMessageType) {
    HLNewMessageTopic   = 1,
    HLNewMessageReplay  = 2
};

@interface MessageManager : NSObject
+ (MessageManager *)sharedManager;

- (void)setRequestRequency:(RequestFrequency)frequency;


/**
 *  获取新消息
 *
 *  @param status  要获取的类型
 *  @param success 成功回调
 *  @param fail    失败回调
 */
-(void)getNewMessagesWithStatus:(HLNewMessageType)status success:(void (^)(id responseObject))success fail:(void (^)())fail;


-(NSArray *)getTopicsInUserDefaults;
-(void)addTopicsToUserDefaultsWithTopic:(NSArray *)topics;
-(void)removeTopicFromUserDefaultsWithID:(NSInteger)topicid;
@end


.m
//
//...

#import "MessageManager.h"
#import "AFNetPackage.h"

@interface MessageManager ()
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation MessageManager
+ (MessageManager *)sharedManager{
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

/**
 *  设置轮询的时间间隔
 *
 */
- (void)setRequestRequency:(RequestFrequency)rf {
    [self.timer invalidate];
    switch (rf) {
        case RequestFrequencyHigh:
            self.timer = [NSTimer scheduledTimerWithTimeInterval:HighMessageRequestFrequency target:self selector:@selector(requestUnreadFlag) userInfo:nil repeats:YES];
            break;
        case RequestFrequencyLow:
            self.timer = [NSTimer scheduledTimerWithTimeInterval:LowMessageRequestFrequency target:self selector:@selector(requestUnreadFlag) userInfo:nil repeats:YES];
            break;
            
        default:
            break;
    }
    
}


- (void)requestUnreadFlag {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"userid"] = LoginHuanxinId;

    [AFNetPackage getJSONWithUrl:[Consult_Base_Url stringByAppendingString:@"messages/getmessagestate"] parameters:dic success:^(id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([dict[@"status"] integerValue]==200) {
            NSDictionary *messageDic = [dict[@"data"] firstObject];
            if ([messageDic[@"TopicFlag"] boolValue]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:ConsultMessageStateTopicChangedNotification object:self];
            }
            if ([messageDic[@"ReplyFlag"] boolValue]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:ConsultMessageStateReplyChangedNotification object:self];
            }
            if ([messageDic[@"VisitFlag"] boolValue]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:ConsultMessageStateVisitChangedNotification object:self];
            }
            if ([messageDic[@"AssociationDoctorFlag"] boolValue]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:ConsultMessageStateAssociationDocotrChangedNotification object:self];
            }
            
        }
    } fail:^{
        
    }];
}


-(void)getNewMessagesWithStatus:(HLNewMessageType)status success:(void (^)(id responseObject))success fail:(void (^)())fail{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Consult_Base_Url,@"messages/getnewmessages"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"status"] = @(status);
    dic[@"userid"] = LoginHuanxinId;
    
    [AFNetPackage getJSONWithUrl:url parameters:dic success:^(id responseObject) {
        if (success) {
            success(responseObject);
        }
    } fail:^{
        
        if (fail) {
            fail();
        }
        
    }];
    
}




-(NSSet *)getTopicsInUserDefaults{

    NSMutableDictionary *newMessageDic = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"newMessage"]];
    NSMutableArray *topicIDs = [NSMutableArray arrayWithArray:newMessageDic[@"topicIDs"]];
    NSMutableSet *topicIDSet = [NSMutableSet setWithArray:topicIDs];
    return [topicIDSet copy];

}

-(void)addTopicsToUserDefaultsWithTopic:(NSArray *)topics{

    NSMutableDictionary *newMessageDic = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"newMessage"]];

    NSMutableSet *topicIDs = [NSMutableSet setWithArray:newMessageDic[@"topicIDs"]];
    [topicIDs addObjectsFromArray:topics];
    NSMutableArray *ntopicIDs = [NSMutableArray array];

    for (NSNumber *topicID in topicIDs) {
        [ntopicIDs addObject:topicID];
    }

    newMessageDic[@"topicIDs"] = ntopicIDs;
    [[NSUserDefaults standardUserDefaults] setObject:newMessageDic forKey:@"newMessage"];

}
-(void)removeTopicFromUserDefaultsWithID:(NSInteger)topicid{
    NSMutableDictionary *newMessageDic = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"newMessage"]];

    NSSet *topicIDs = [NSSet setWithArray:newMessageDic[@"topicIDs"]];
    NSMutableArray *ntopicIDs = [NSMutableArray array];

    for (NSNumber *topicID in topicIDs) {
        if ([topicID integerValue] == topicid) {
            continue;
        }else{
            [ntopicIDs addObject:topicID];
        }
    }
    newMessageDic[@"topicIDs"] = ntopicIDs;
    [[NSUserDefaults standardUserDefaults] setObject:newMessageDic forKey:@"newMessage"];
}
@end

这样在每个vc里面设立一个收通知、设置轮询频率就不会浪费流量了。

 

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 13
博文 104
码字总数 45891
×
杭城小刘
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: