移動端即便通信

    這個地方回屢次提到「Qos」,不知道「Qos」的童鞋能夠看看http://my.oschina.net/u/1778933/blog/717615ios

    一個項目須要作到輪詢,提供了一個接口:高頻率接口輪詢查詢新消息,這顯然對於流量、電量都是一個很大的開銷。還有的地方須要查看新主題,須要打紅點,這樣又提供一個新主題接口,難道又要輪詢?在與接口人員討論事後,肯定了一個解決方案,全部的輪詢用一個接口搞定,只不過不一樣的接口須要一個「類型」參數判斷,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裏面設立一個收通知、設置輪詢頻率就不會浪費流量了。post

相關文章
相關標籤/搜索