宽容他人,放过自己。

各种快捷函数的创建

Posted on By anchoriteFili

#ifndef videoTest_GlobalFunctions_h
#define videoTest_GlobalFunctions_h

#import "MessageTypeInfo.h"
#import "VideoPlayerInfo.h"
#import "ChatUserInfo.h"
#import "MessageJsonInfo.h"


#pragma mark - 聊天室函数

// 获取用户的JID
XMPPJID *getJid(NSString* username);

// 获取聊天室的JID
XMPPJID *getRoomJid(NSString* roomname);


#pragma mark - 登录用户的信息

NSInteger getUserId();
NSInteger getYodou();
BOOL getIsStar();


#pragma mark - 一些常用的函数

// 获取view所在的viewController
UIViewController *getViewControllerForView(UIView* view);

// 弹出一个只有“确定”按钮的提示框
void TTAlert(NSString* message);

// 获取字符串的宽高
CGSize sizeWithFont(NSString *text, UIFont *font, CGFloat maxWidth);

// 字符串的md5加密
NSString *md5(NSString *string);

// 格式化日期
NSString *stringFromDate(NSDate *date);

// 获取加密参数
NSString *getAuth(NSString *params);

// 获取时间戳
NSString *getMillisecondsDifferential();

// 获取当前时间
NSString *getCurrDate();

// 从缓存中读取字符串
NSString *getStringValueForCache(NSString *objectkey);

#pragma mark - 消息函数

// 解析消息
MessageTypeInfo *parseMessage(NSString *messageJson);

// 创建消息
NSString *createMessage(MessageJsonInfo *message);

// 创建更新视频状态消息
NSString *createUpdateVideoStateMsg(BOOL isPlaying, NSTimeInterval currentPlaybackTime);

// 创建开始直播消息
NSString *createStartLiveMsg();

// 创建停止直播消息
NSString *createStopLiveMsg();

// 创建开始放映消息
NSString *createStartVideoMsg();

// 开启摄像头的消息
NSString *createStartCarmerMsg();

// 创建发送爱心的消息
NSString *createSendHeartMsg(NSString *message);

// 创建系统聊天消息
NSString *createSendSystemMsg(NSString *message);

// 创建停止放映消息
NSString *createStopVideoMsg();

NSString *createSetVideoNameMsg(NSString *videoName);

// 创建离开房间消息
NSString *createLeaveRoomMsg();

// 创建切换直播房间消息
NSString *createSwitchLiveRoomMsg(NSString *message);

// 创建切换视频房间消息
NSString *createSwitchVideoRoomMsg(NSString *message);

// 创建切换视频源消息
NSString *createSwitchVideoMsg(NSString *message);

// 创建主播开启声音的消息
NSString *createOpenVoiceMsg();

// 创建主播关闭声音的消息
NSString *createCloseVoiceMsg();

// 创建主播开始讲话的消息
NSString *createBeginSpeakMsg();

// 创建主播关闭讲话的消息
NSString *createEndSpeakMsg();

#pragma mark - 其它函数

NSInteger addVideoPlayerInfo(VideoPlayerInfo *playerInfo, NSMutableArray *playerInfos);

NSString *getSoundFile(NSString *soundUrl);
void setSoundReaded(NSString *soundUrl, NSString *opRoomId);
NSArray *getSoundReadedArray(NSString *opRoomId);
BOOL isSoundReaded(NSArray *soundFileArray, NSString *soundUrl);
NSString *getJsonObjectString(NSDictionary *dict, NSString *param);

// 如果version1比version2大或者version1跟version2相等,返回YES,
// 否则,返回NO。
BOOL versionCompare(NSString *version1, NSString *version2);

#endif

.m文件

#import <CommonCrypto/CommonDigest.h>
#import "GlobalFunctions.h"

#pragma mark - 聊天室函数
//获取用于的JID
XMPPJID *getJid(NSString* username) {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    return [XMPPJID jidWithUser:username domain:appDelegate.openfireHost resource:nil];
}

//获取聊天室的JID
XMPPJID *getRoomJid(NSString* roomname) {
    NSString *roomJid = [NSString stringWithFormat:@"%@@%@", roomname, XMPP_CONFERENCE];
    return [XMPPJID jidWithString:roomJid];
}


#pragma mark - 登录用户的信息
//获取用户userId
NSInteger getUserId() {
    NSInteger userId = 0;
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (appDelegate.loginUser != nil) {
        userId = appDelegate.loginUser.user_id;
    }
    
    return userId;
}

//获取优豆
NSInteger getYodou() {
    NSInteger yodou = 0;
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (appDelegate.loginUser != nil) {
        yodou = appDelegate.loginUser.yodou;
    }
    
    return yodou;
}


BOOL getIsStar()
{
    BOOL isStar = 0;
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (appDelegate.loginUser != nil) {
        isStar = appDelegate.loginUser.isStar;
    }
    
    return isStar;
}


#pragma mark - 一些常用的函数
// 获取view所在的viewController
UIViewController *getViewControllerForView(UIView* view)
{
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

// 弹出只有确认按钮的提示窗
void TTAlert(NSString* message)
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

// 获取字符串的宽高
CGSize sizeWithFont(NSString *text, UIFont *font, CGFloat maxWidth)
{
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

// 字符串的md5加密
NSString *md5(NSString *string)
{
    const char *cStr = [string UTF8String];
    unsigned char result[32];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3], result[4],
             result[5], result[6], result[7], result[8], result[9],
             result[10], result[11], result[12], result[13], result[14],
             result[15]] lowercaseString];
}

// 格式化日期
NSString *stringFromDate(NSDate *date)
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    if (dateString == nil) {
        dateString = @"";
    }
    
    return dateString;
}

//
NSString *Keymd5(NSString *auth1)
{
    NSString * auth3 = [auth1 uppercaseString];
    const NSString *key = @"zxnva0923fsdfwerkfvasdfkjwe";//固定的值
    NSString *auth2 = [NSString stringWithFormat:@"%@%@%@%@",
                       [auth3 substringWithRange:NSMakeRange(9, 8)],
                       [NSString stringWithFormat:@"%@%@", key, key],
                       [auth3 substringWithRange:NSMakeRange(20, 5)], key];//根据要求截取第一次加密的值并拼接
    return auth2;
}

// 获取加密参数
NSString *getAuth(NSString *params)
{
    return md5(Keymd5(md5(params)));
}

// 获取时间戳
NSString *getMillisecondsDifferential()
{
    NSDate *date = [NSDate date];
    UInt64 recordTime = [date timeIntervalSince1970] * 1000;
    NSString *timeStr = [NSString stringWithFormat:@"%llu", recordTime];
    return timeStr;
}

// 获取当前时间
NSString *getCurrDate()
{
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY/MM/dd HH:mm:ss"];
    NSString *currDate = [dateformatter stringFromDate:senddate];
    
    return currDate;
}

// 从缓存中读取字符串
NSString *getStringValueForCache(NSString *objectkey) {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];
    
    if ([defaults stringForKey:objectkey] == nil) {
        return @"";
    } else {
        return [defaults stringForKey:objectkey];
    }
}


#pragma mark - 消息函数
// 解析消息
MessageTypeInfo *parseMessage(NSString *messageJson)
{
    MessageTypeInfo *messageTypeInfo = [[MessageTypeInfo alloc] init];
    
    NSData *data = [messageJson dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
    if (!error && [jsonObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = (NSDictionary *)jsonObject;
        
        EMessageType messageType = [dictionary[@"messagetype"] integerValue];
        NSString *message = dictionary[@"message"];
        
        if (messageType == MSG_TYPE_UPDATE_VIDEOSTATE) {
            NSArray *dataArray = [message componentsSeparatedByString: @","];
            
            if ([dataArray count] == 3) {
                messageTypeInfo.messageType = messageType;
                messageTypeInfo.message = message;
                messageTypeInfo.mediaInfo.mediaState = [dataArray[1] integerValue] == 1 ? MEDIA_STATE_PLAY : MEDIA_STATE_PAUSE;
                messageTypeInfo.mediaInfo.position = [dataArray[2] integerValue] / 1000.0;
            }
        } else {
            messageTypeInfo.messageType = messageType;
            messageTypeInfo.message = message;
        }
    }
    
    return messageTypeInfo;
}

// 创建消息
NSString *createMessage(MessageJsonInfo *message)
{
    message.time = getCurrDate();
    return [message createJsonString];
}

// 创建更新视频状态消息
NSString *createUpdateVideoStateMsg(BOOL isPlaying, NSTimeInterval currentPlaybackTime)
{
    NSString *message = [NSString stringWithFormat:@"updateVideoState,%i,%li", isPlaying ? 1 : 0, (long)currentPlaybackTime * 1000];
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.message = message;
    messageJsonInfo.messagetype = MSG_TYPE_UPDATE_VIDEOSTATE;
    
    return createMessage(messageJsonInfo);
}

// 创建开始直播消息
NSString *createStartLiveMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_START_LIVE;
    
    return createMessage(messageJsonInfo);
}

// 创建停止直播消息
NSString *createStopLiveMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_STOP_LIVE;
    
    return createMessage(messageJsonInfo);
}

// 创建开始放映消息
NSString *createStartVideoMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_START_VIDEO;
    
    return createMessage(messageJsonInfo);
}

// 创建停止放映消息
NSString *createStopVideoMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_STOP_VIDEO;
    
    return createMessage(messageJsonInfo);
}

// 创建设置视频名字消息
NSString *createSetVideoNameMsg(NSString *videoName) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_SET_VIDEO_NAME;
    messageJsonInfo.message = videoName;
    
    return createMessage(messageJsonInfo);
}

// 创建离开房间消息
NSString *createLeaveRoomMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_LEAVE_ROOM;
    
    return createMessage(messageJsonInfo);
}

// 创建切换直播房间消息
NSString *createSwitchLiveRoomMsg(NSString *message) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_SWITCH_LIVE_ROOM;
    messageJsonInfo.message = message;
    
    return createMessage(messageJsonInfo);
}

// 创建切换视频房间消息
NSString *createSwitchVideoRoomMsg(NSString *message) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_SWITCH_VIDEO_ROOM;
    messageJsonInfo.message = message;
    
    return createMessage(messageJsonInfo);
}

// 创建切换视频源消息
NSString *createSwitchVideoMsg(NSString *message) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_SWITCH_VIDEO;
    messageJsonInfo.message = message;
    
    return createMessage(messageJsonInfo);
}

// 开启摄像头的消息
NSString *createStartCarmerMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_START_CARMER;
    
    return createMessage(messageJsonInfo);
}

// 创建发送爱心的消息
NSString *createSendHeartMsg(NSString *message) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_SEND_HEART;
    messageJsonInfo.message = message;
    messageJsonInfo.userid = getUserId();
    messageJsonInfo.username = @"系统消息";
    
    return createMessage(messageJsonInfo);
}

// 创建系统聊天儿消息
NSString *createSendSystemMsg(NSString *message) {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_CHAT;
    messageJsonInfo.message = message;
    messageJsonInfo.userid = 0;
    messageJsonInfo.username = @"系统消息";
    
    return createMessage(messageJsonInfo);
}

// 创建
NSString *createOpenVoiceMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_OPEN_VOICE;
    
    return createMessage(messageJsonInfo);
}

NSString *createCloseVoiceMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_CLOSE_VOICE;
    
    return createMessage(messageJsonInfo);
}

NSString *createBeginSpeakMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_BEGIN_SPEAK;
    
    return createMessage(messageJsonInfo);
}

NSString *createEndSpeakMsg() {
    MessageJsonInfo *messageJsonInfo = [[MessageJsonInfo alloc] init];
    messageJsonInfo.messagetype = MSG_TYPE_END_SPEAK;
    
    return createMessage(messageJsonInfo);
}

#pragma mark - 其它函数

BOOL playerInfoEqual(VideoPlayerInfo *playerInfo1, VideoPlayerInfo *playerInfo2) {
    if (playerInfo1 == nil || playerInfo2 == nil) {
        return (playerInfo1 == playerInfo2);
    }
    
    BOOL isEqual = NO;
    
    if (playerInfo1.isMyVideoRoom == playerInfo2.isMyVideoRoom
        && playerInfo1.roomId == playerInfo2.roomId
        && playerInfo1.isHistory == playerInfo2.isHistory
        && playerInfo1.isAnchor == playerInfo2.isAnchor
        && playerInfo1.anchorUserId == playerInfo2.anchorUserId
        && playerInfo1.videoId == playerInfo2.videoId
        && [playerInfo1.videoName isEqualToString:playerInfo2.videoName]) {
        isEqual = YES;
    }
    
    return isEqual;
}

NSInteger addVideoPlayerInfo(VideoPlayerInfo *playerInfo, NSMutableArray *playerInfos) {
    BOOL isExists = NO;
    NSInteger index = 0;
    
    for (int i = 0; i < playerInfos.count; ++i) {
        VideoPlayerInfo *item = playerInfos[i];
        if (playerInfoEqual(item, playerInfo)) {
            isExists = YES;
            index = i;
            break;
        }
    }
    
    if (!isExists) {
        [playerInfos addObject:playerInfo];
        index = [playerInfos count] - 1;
    }
    
    return index;
}


NSString *getSoundFile(NSString *soundUrl) {
    return [[soundUrl lastPathComponent] copy];
}

void setSoundReaded(NSString *soundUrl, NSString *opRoomId) {
    NSString *soundFile = getSoundFile(soundUrl);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];
    
    NSString *soundReadedString = [defaults stringForKey:opRoomId];
    
    if (!soundReadedString) {
        soundReadedString = soundFile;
    } else {
        soundReadedString = [soundReadedString stringByAppendingString:[NSString stringWithFormat:@",%@", soundFile]];
    }
    
    [defaults setValue:soundReadedString forKey:opRoomId];
    
    [defaults synchronize];
}

NSArray *getSoundReadedArray(NSString *opRoomId) {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];
    
    NSString *soundReadedString = [defaults stringForKey:opRoomId];
    
    NSArray *soundFileArray = [NSMutableArray array];
    
    if (soundReadedString) {
        soundFileArray = [soundReadedString componentsSeparatedByString:@","];
    }
    
    return soundFileArray;
}

BOOL isSoundReaded(NSArray *soundFileArray, NSString *soundUrl) {
    NSString *soundFile = getSoundFile(soundUrl);
    return [soundFileArray containsObject:soundFile];
}

NSString *getJsonObjectString(NSDictionary *dict, NSString *param) {
    if (dict == nil || param == nil) {
        return @"";
    }
    
    NSString *object = dict[param];
    if (object == nil) {
        object = @"";
    }
    
    return object;
}

BOOL versionCompare(NSString *version1, NSString *version2) {
    BOOL result = YES;
    
    NSString *upperVersion1 = [version1 uppercaseString];
    NSString *upperVersion2 = [version2 uppercaseString];
    
    if ([upperVersion1 rangeOfString:@"V"].location != NSNotFound) {
        upperVersion1 = [upperVersion1 substringFromIndex:1];
    }
    
    if ([upperVersion2 rangeOfString:@"V"].location != NSNotFound) {
        upperVersion2 = [upperVersion2 substringFromIndex:1];
    }
    
    NSArray *versionArray1 = [upperVersion1 componentsSeparatedByString:@"."];
    NSArray *versionArray2 = [upperVersion2 componentsSeparatedByString:@"."];
    
    if (versionArray1.count == versionArray2.count) {
        NSInteger length = versionArray1.count;
        for (NSInteger i = 0; i < length; ++i) {
            if (versionArray2[i] > versionArray1[i]) {
                result = NO;
                break;
            }
        }
    }
    
    return result;
}