Commit 6d2728bb by zhangyunjie

添加工具

parent 1f19e36e
This source diff could not be displayed because it is too large. You can view the blob instead.
//
//
// ConfigrationNetwork.h
// OffcnLiveSDK
//
// Created by vockey on 2018/7/25.
// Copyright © 2018年 中公教育. All rights reserved.
//@"https://api.live.offcncloud.com/"//@"http://test-api.live.offcncloud.com/"
#ifndef ConfigrationNetwork_h
#define ConfigrationNetwork_h
//默认大班课开发模式接口
#define DEV_BASEURL @"https://live.offcncloud.com/"
#define DEV_IMAGEBASEURL @""
#define DEV_h5live @"https://h5live.offcncloud.com/"
#define DEV_call_server_topic @"rtc.offcncloud.com"
//默认大班课测试模式接口
#define TEST_BASEURL @"http://test-live.offcncloud.com/"
#define TEST_IMAGEBASEURL @""
#define TEST_h5live @"http://test-h5live.offcncloud.com/"
#define TEST_call_server_topic @"test-rtc.offcncloud.com"
//默认大班课生产模式接口
#define PRO_BASEURL @"https://live.offcncloud.com/"
#define PRO_IMAGEBASEURL @""
#define PRO_h5live @"https://h5live.offcncloud.com/"
#define PRO_call_server_topic @"rtc.offcncloud.com"
//小班课开发模式接口
#define DEV_BASEURL_SMALLCLASS @"https://api.live.offcncloud.com/"
#define DEV_IMAGEBASEURL_SMALLCLASS @""
#define DEV_h5live_SMALLCLASS @"https://api.h5live.offcncloud.com/"
#define DEV_call_server_topic_SMALLCLASS @"rtc.smallroom.offcncloud.com"
//小班课测试模式接口
#define TEST_BASEURL_SMALLCLASS @"http://test-api.live.offcncloud.com/"
#define TEST_IMAGEBASEURL_SMALLCLASS @""
#define TEST_h5live_SMALLCLASS @"http://test-api.h5live.offcncloud.com/"
#define TEST_call_server_topic_SMALLCLASS @"test-rtc.smallroom.offcncloud.com"
//小班课生产模式接口
#define PRO_BASEURL_SMALLCLASS @"https://api.live.offcncloud.com/"
#define PRO_IMAGEBASEURL_SMALLCLASS @""
#define PRO_h5live_SMALLCLASS @"https://api.h5live.offcncloud.com/"
#define PRO_call_server_topic_SMALLCLASS @"rtc.smallroom.offcncloud.com"
//切换连麦call_server_topic
#define BASE_GetCallServerTopic_URL [OffcnBaseNetworking get_call_server_topic]
//切换域名
#define BASE_DOMAIN_URL [OffcnBaseNetworking get_BASEURL]
//图片的前缀
#define BASE_IMAGE_URL [OffcnBaseNetworking get_ImageBaseUrl]
//h5
#define BASE_H5_URL [OffcnBaseNetworking get_h5live]
#define BASE_URL [NSString stringWithFormat:@"%@api/v1/",BASE_DOMAIN_URL]
#define BASE_USER_URL [NSString stringWithFormat:@"%@api/user/",BASE_DOMAIN_URL]
#define HTTPS_IMAGEBASEURL @""
#pragma mark - 二级API
//客户端登陆
//#define LoginURL [NSString stringWithFormat:@"%@users",BASE_URL]
//回放拉流
//#define PlaybackPullURL [NSString stringWithFormat:@"%@on_demand",BASE_USER_URL]
#endif /* ConfigrationNetwork_h */
//
// SDEnum.h
// OffcnLiveSDK
//
// Created by vockey on 2018/8/13.
// Copyright © 2018年 中公教育. All rights reserved.
//
#ifndef SDEnum_h
#define SDEnum_h
//typedef NS_ENUM(NSUInteger, OffcnSmallClassControllerType) {
// OffcnSmallClassControllerTypeDefaultTeaching = 0,//默认授课模式
// OffcnSmallClassControllerTypeStructureInside,//结构化场内模式
// OffcnSmallClassControllerTypeStructureOutside,//结构化场外模式
// OffcnSmallClassControllerTypeNoLeader,//无领导模式
//};
#endif /* SDEnum_h */
//
//
// GeneralDefine.h
//
//
#ifndef GeneralDefine_h
#define GeneralDefine_h
#define NSLog(format, ...) do { \
fprintf(stderr, "<%s : %d> %s\n", \
[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \
__LINE__, __func__); \
(NSLog)((format), ##__VA_ARGS__); \
fprintf(stderr, "-------\n"); \
} while (0)
#undef NSLog
#if DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"\nfunction:%s line:%d content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...)
#endif
#define KCustomerAPPKEY @""
#pragma mark - 尺寸所有宏
#define Screen_Height [UIScreen mainScreen].bounds.size.height
#define Screen_Width [UIScreen mainScreen].bounds.size.width
#define kScreen_Height MAX(Screen_Width, Screen_Height)
#define kScreen_Width MIN(Screen_Width, Screen_Height)
//iphone6屏幕比例
#define KWidth_Scale kScreen_Width/375.0f
#define KKeyWindow [UIApplication sharedApplication].keyWindow
#define KFirstWindow [UIApplication sharedApplication].windows.firstObject
//判断是否有刘海
#define kIsIPhoneXSerious @available(iOS 11.0, *) && [UIApplication sharedApplication].windows.firstObject.safeAreaInsets.bottom > 0.0
#define kIsIphoneX kIsIPhoneXSerious
//iphoneX 竖屏安全区域顶部(如果导航栏是系统的写0就好)
#define kSafeAreaTopHeigth (kIsIphoneX?44:0)
//iphoneX 竖屏安全区域底部(如果导航栏是系统的写0就好)
#define kSafeAreaBottomHeigth (kIsIphoneX?34:0)
// 竖屏导航栏高度
#define kNavigationHeight (kIsIphoneX?88:64)
//竖屏状态栏
#define KStatusBarHeight (kIsIphoneX?44:20)
#define KFontNameBoldSize(f) [UIFont boldSystemFontOfSize:f]
#define KFontNameMediumSize(f) [UIFont systemFontOfSize:f]
#define KSetFont(size) [UIFont systemFontOfSize:size]
#define KImageNamed(name) [UIImage imageNamed:[NSString stringWithFormat:@"OffcnLiveSDK.bundle/%@",name]]
#define KEmojiImageNamed(name) [UIImage imageNamed:[NSString stringWithFormat:@"OffcnLiveSDK.bundle/emoji/%@",name]]
#define KWeakSelf __weak typeof(self) weakSelf = self;
/** 从RGB转换成UIColor (16进制->10进制)*/
#define kUIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//****************设置颜色
#define UICOLOR_RGB_Alpha(_color,_alpha) [UIColor colorWithRed:((_color>>16)&0xff)/255.0f green:((_color>>8)&0xff)/255.0f blue:(_color&0xff)/255.0f alpha:_alpha]
#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
//小班课控制器的背景颜色
#define KOffcnSmallClassBackColor UICOLOR_RGB_Alpha(0x484d5c, 1)
//大班课控制器的背景颜色
#define KControllerBackColor UICOLOR_RGB_Alpha(0xf5f5f5, 1)
//直播状态
#define KRoomStateReasonsBackColor UICOLOR_RGB_Alpha(0x292929, 1)
//按钮普通状态
#define KButtonNormalColor UICOLOR_RGB_Alpha(0x333333, 1)
//按钮高亮状态
#define KButtonHighlightedColor UICOLOR_RGB_Alpha(0xFF5656, 1)
//按钮选中状态
#define KButtonSelectColor UICOLOR_RGB_Alpha(0xff895f, 1)
//按钮禁止状态
#define KButtonDisColor UICOLOR_RGB_Alpha(0xbfbfbf, 1)
//通知状态
#define KAlartBackColor UICOLOR_RGB_Alpha(0xffe6e0, 1)
//文字基本颜色
#define KTextColor UICOLOR_RGB_Alpha(0x333333, 1)
//标签文字基本颜色
#define KSubTagTextColor UICOLOR_RGB_Alpha(0x666666, 1)
//标签描边颜色
#define KSubTagLineColor UICOLOR_RGB_Alpha(0xcccccc, 1)
//副标题颜色
#define KSubTextColor UICOLOR_RGB_Alpha(0x999999, 1)
//人数颜色
#define KNumColor UICOLOR_RGB_Alpha(0x0d152d, 1)
//separatorColor颜色
#define KSeparatorColor UICOLOR_RGB_Alpha(0xe6e6e6, 1)
//textFiledplaceholder 文字颜色
#define KplaceholderLabelColor UICOLOR_RGB_Alpha(0xb3b3b3, 1)
//switch按钮颜色
#define KSwitchColor UICOLOR_RGB_Alpha(0x007aff, 1)
#define RGB(r, g, b) \
[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a) \
[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
////获取版本号
#define KAppVersion [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
//#define KUUIDString [UIDevice currentDevice].identifierForVendor.UUIDString
#define KRootTabBarController KKeyWindow.rootViewController
#define KUSERDEFAULT [NSUserDefaults standardUserDefaults]
//字符串是否为空
#define KStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
//全字符串是否为空
#define KOffcnStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str isEqual: @"null"] || [str isEqual: @"<null>"] || [str isEqual: @"nil"] || [str length] < 1 ? YES : NO )
//数组是否为空
#define KArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
/// View 圆角
#define ViewRadius(View, Radius)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES]
/// View加边框
#define ViewBorder(View, BorderColor, BorderWidth)\
\
View.layer.borderColor = BorderColor.CGColor;\
View.layer.borderWidth = BorderWidth;
//获取系统版本
#define XZSystemVersion ([UIDevice currentDevice].systemVersion.floatValue)
#define iOS11 (XZSystemVersion >= 11.0)
#define iOS10 (XZSystemVersion >= 10.0)
#define iOS9 (XZSystemVersion >= 9.0)
#define iOS8 (XZSystemVersion >= 8.0)
#define iOS7 (XZSystemVersion >= 7.0)
#define iOS6 (XZSystemVersion < 7.0)
/**
单例宏定义,可用可不用
*/
// .h文件
#define HHSingletonH(name) + (instancetype)shared##name;
// .m文件
#define HHSingletonM(name) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
#endif /* GeneralDefine_h */
//
//
// SDKeyBoard.h
// OffcnLiveSDK
//
// Created by vockey on 2018/9/6.
// Copyright © 2018年 中公教育. All rights reserved.
//
#ifndef SDKeyBoard_h
#define SDKeyBoard_h
//mqtt通知
//#define kMQTTNotification @"kMQTTNotification"
#endif /* SDKeyBoard_h */
//
//
// DataSafe.h
// HomeHealth
//
// Created by newuser on 17/1/3.
// Copyright © 2017年 ChiJian. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DataSafe : NSObject
@end
@interface NSNumber (safeCJ)
//防止类型错误出现崩溃
-(NSUInteger)length;
@end
@interface NSString (safeCJ)
//防止类型错误出现崩溃
-(NSString *)stringValue;
@end
@interface NSMutableArray (safeCJ)
-(void)addObjectOnSafe:(id)anObject;
@end
@interface NSArray (safeCJ)
-(id)objectAtIndexOnSafe:(NSUInteger)index;
@end
@interface NSMutableDictionary (safeCJ)
-(void)setObjectOnSafe:(id)anObject forKey:(id<NSCopying>)aKey;
@end
@interface NSDictionary (safeCJ)
- (NSString*)dictionaryToJson;
-(id)objectForKeyOnSafe:(id)aKey;
@end
//
//
// DataSafe.m
// HomeHealth
//
// Created by newuser on 17/1/3.
// Copyright © 2017年 ChiJian. All rights reserved.
//
#import "DataSafe.h"
@implementation DataSafe
@end
@implementation NSNumber (safeCJ)
//防止类型错误出现崩溃
-(NSUInteger)length{
return [self stringValue].length;
}
@end
@implementation NSString (safeCJ)
-(NSString *)stringValue{
return self;
}
@end
@implementation NSMutableArray (safeCJ)
-(void)addObjectOnSafe:(id)anObject{
if (!anObject) {
NSLog(@"warning:Array试图插入空对象");
return;
}
[self addObject:anObject];
}
@end
@implementation NSArray(safeCJ)
-(id)objectAtIndexOnSafe:(NSUInteger)index{
if (index >= self.count) {
return nil;
}
id obj = [self objectAtIndex:index];
return obj;
}
@end
@implementation NSMutableDictionary (safeCJ)
-(void)setObjectOnSafe:(id)anObject forKey:(id<NSCopying>)aKey{
if (!anObject || !aKey) {
NSLog(@"warning:Dictionary的试图对key--%@--字段置入空对象",aKey);
return;
}
[self setObject:anObject forKey:aKey];
}
@end
@implementation NSDictionary(safeCJ)
- (NSString*)dictionaryToJson{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
-(id)objectForKeyOnSafe:(id)aKey{
if (!aKey) {
return nil;
}
id obj = [self objectForKey:aKey];
return obj;
}
@end
//
//
// NSDictionary+NullReplacement.h
// JinSeJiaYuanWang
//
// Created by honghong on 16/7/22.
// Copyright © 2016年 JYall Network Technology Co.,Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (NullReplacement)
- (NSDictionary *)dictionaryByReplacingNullsWithBlanks;
@end
@interface NSArray (NullReplacement)
- (NSArray *)arrayByReplacingNullsWithBlanks;
@end
//
//
// NSDictionary+NullReplacement.m
// JinSeJiaYuanWang
//
// Created by honghong on 16/7/22.
// Copyright © 2016年 JYall Network Technology Co.,Ltd. All rights reserved.
//
#import "NSDictionary+NullReplacement.h"
@implementation NSDictionary (NullReplacement)
- (NSDictionary *)dictionaryByReplacingNullsWithBlanks {
const NSMutableDictionary *replaced = [self mutableCopy];
const id nul = [NSNull null];
const NSString *blank = @"";
for (NSString *key in self) {
id object = [self objectForKey:key];
if (object == nul) {
[replaced setObject:blank forKey:key];
} else if ([object isKindOfClass:[NSDictionary class]]) {
[replaced setObject:[object dictionaryByReplacingNullsWithBlanks] forKey:key];
} else if ([object isKindOfClass:[NSArray class]]) {
[replaced setObject:[object arrayByReplacingNullsWithBlanks] forKey:key];
}
}
return [NSDictionary dictionaryWithDictionary:[replaced copy]];
}
@end
@implementation NSArray (NullReplacement)
- (NSArray *)arrayByReplacingNullsWithBlanks {
NSMutableArray *replaced = [self mutableCopy];
const id nul = [NSNull null];
const NSString *blank = @"";
for (int idx = 0; idx < [replaced count]; idx++) {
id object = [replaced objectAtIndex:idx];
if (object == nul){
[replaced replaceObjectAtIndex:idx withObject:blank];
} else if ([object isKindOfClass:[NSDictionary class]]) {
[replaced replaceObjectAtIndex:idx withObject:[object dictionaryByReplacingNullsWithBlanks]];
} else if ([object isKindOfClass:[NSArray class]]) {
[replaced replaceObjectAtIndex:idx withObject:[object arrayByReplacingNullsWithBlanks]];
}
}
return [replaced copy];
}
@end
//
//
// NSFileManager+Paths.h
// iOS-Categories (https://github.com/shaojiankui/iOS-Categories)
//
// Created by Jakey on 14/12/30.
// Copyright (c) 2014年 www.skyfox.org. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSFileManager (Paths)
/**
Get URL of Documents directory.
@return Documents directory URL.
*/
+ (NSURL *)documentsURL;
/**
Get path of Documents directory.
@return Documents directory path.
*/
+ (NSString *)documentsPath;
/**
Get URL of Library directory.
@return Library directory URL.
*/
+ (NSURL *)libraryURL;
/**
Get path of Library directory.
@return Library directory path.
*/
+ (NSString *)libraryPath;
/**
Get URL of Caches directory.
@return Caches directory URL.
*/
+ (NSURL *)cachesURL;
/**
Get path of Caches directory.
@return Caches directory path.
*/
+ (NSString *)cachesPath;
/**
Adds a special filesystem flag to a file to avoid iCloud backup it.
@param path Path to a file to set an attribute.
*/
+ (BOOL)addSkipBackupAttributeToFile:(NSString *)path;
/**
Get available disk space.
@return An amount of available disk space in Megabytes.
*/
+ (double)availableDiskSpace;
@end
//
//
// NSFileManager+Paths.m
// iOS-Categories (https://github.com/shaojiankui/iOS-Categories)
//
// Created by Jakey on 14/12/30.
// Copyright (c) 2014年 www.skyfox.org. All rights reserved.
//
#import "NSFileManager+Paths.h"
#include <sys/xattr.h>
@implementation NSFileManager (Paths)
+ (NSURL *)URLForDirectory:(NSSearchPathDirectory)directory {
return [self.defaultManager URLsForDirectory:directory inDomains:NSUserDomainMask].lastObject;
}
+ (NSString *)pathForDirectory:(NSSearchPathDirectory)directory {
return NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES)[0];
}
+ (NSURL *)documentsURL {
return [self URLForDirectory:NSDocumentDirectory];
}
+ (NSString *)documentsPath {
return [self pathForDirectory:NSDocumentDirectory];
}
+ (NSURL *)libraryURL {
return [self URLForDirectory:NSLibraryDirectory];
}
+ (NSString *)libraryPath {
return [self pathForDirectory:NSLibraryDirectory];
}
+ (NSURL *)cachesURL {
return [self URLForDirectory:NSCachesDirectory];
}
+ (NSString *)cachesPath {
return [self pathForDirectory:NSCachesDirectory];
}
+ (BOOL)addSkipBackupAttributeToFile:(NSString *)path {
return [[NSURL.alloc initFileURLWithPath:path] setResourceValue:@(YES) forKey:NSURLIsExcludedFromBackupKey error:nil];
}
+ (double)availableDiskSpace {
NSDictionary *attributes = [self.defaultManager attributesOfFileSystemForPath:self.documentsPath error:nil];
return [attributes[NSFileSystemFreeSize] unsignedLongLongValue] / (double)0x100000;
}
@end
//
//
// NSAttributedString+SDSize.h
// OffcnLiveSDK
//
// Created by vockey on 2018/8/23.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSAttributedString (SDSize)
- (CGSize)sizeWithMaxSize:(CGSize)maxSize;
- (CGFloat)sizeWithMaxWidth:(CGFloat)maxWidth;
@end
//
// NSAttributedString+SDSize.m
// OffcnLiveSDK
//
// Created by vockey on 2018/8/23.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "NSAttributedString+SDSize.h"
@implementation NSAttributedString (SDSize)
#pragma mark 计算字符串大小
- (CGSize)sizeWithMaxSize:(CGSize)maxSize
{
CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
return textSize;
}
- (CGFloat)sizeWithMaxWidth:(CGFloat)maxWidth
{
CGSize textSize = [self boundingRectWithSize:CGSizeMake(maxWidth, 10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
return textSize.height;
}
@end
//
//
// NSMutableAttributedString+SDSize.h
// OffcnLiveSDK
//
// Created by vockey on 2018/8/23.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSMutableAttributedString (SDSize)
- (CGSize)sizeWithMaxSize:(CGSize)maxSize;
- (CGFloat)sizeWithMaxWidth:(CGFloat)maxWidth;
@end
//
//
// NSMutableAttributedString+SDSize.m
// OffcnLiveSDK
//
// Created by vockey on 2018/8/23.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "NSMutableAttributedString+SDSize.h"
@implementation NSMutableAttributedString (SDSize)
#pragma mark 计算字符串大小
- (CGSize)sizeWithMaxSize:(CGSize)maxSize
{
CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
return CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
}
- (CGFloat)sizeWithMaxWidth:(CGFloat)maxWidth
{
CGSize textSize = [self boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
return ceilf(textSize.height);
}
@end
#import <UIKit/UIKit.h>
@interface NSString (Extension)
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize;
- (CGFloat)sizeWithFont:(UIFont *)font maxWidth:(CGFloat)maxWidth;
//请求的时候给特殊字符转码
- (NSString *)URLEncodedString;
//给链接添加source=app
+ (NSString *)getAddSourceAppUrl:(NSString *)url;
//判断是否图片链接带http。返回正确的链接
+(NSString *)isHttpImageUrl:(NSString *)imageUrl;
//拆成数组再获取指定字符串
- (NSString *)subStringFromStartString:(NSString *)startString withSeparatedByString:(NSString *)str;
//截取字符串
- (NSString *)subStringFrom:(NSString *)startString to:(NSString *)endString;
@end
//
//
// NSString+Extension.m
//
// Created by xc on 15/3/6.
// Copyright (c) 2015年 xc. All rights reserved.
//
#import "NSString+Extension.h"
#import "OffcnBaseNetworking.h"
#import "SDConfigrationNetwork.h"
#import "SDGeneralDefine.h"
@implementation NSString (Extension)
#pragma mark 拆成数组再获取指定字符串
- (NSString *)subStringFromStartString:(NSString *)startString withSeparatedByString:(NSString *)str{
NSString *returnStr = @"";
NSArray *arr = [self componentsSeparatedByString:str];
for (int i=0; i<arr.count; i++) {
NSString *subStr = arr[i];
if ([subStr rangeOfString:startString].length) {
returnStr = [subStr substringFromIndex:startString.length];
break;
}
}
return returnStr;
}
#pragma mark 截取两个字符之间字符串
- (NSString *)subStringFrom:(NSString *)startString to:(NSString *)endString{
NSRange startRange = [self rangeOfString:startString];
NSRange endRange = [self rangeOfString:endString];
NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
return [self substringWithRange:range];
}
#pragma mark 计算字符串大小
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
// NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
// paraStyle.lineSpacing = 6;
NSDictionary *dict = @{NSFontAttributeName: font,NSKernAttributeName:@0.0f};
CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dict context:nil].size;
return textSize;
}
- (CGFloat)sizeWithFont:(UIFont *)font maxWidth:(CGFloat)maxWidth
{
// NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
// paraStyle.lineSpacing = 6;
//
// NSDictionary *dict = @{NSFontAttributeName: font,NSParagraphStyleAttributeName:paraStyle,NSKernAttributeName:@0.0f};
NSDictionary *dict = @{NSFontAttributeName: font,NSKernAttributeName:@0.0f};
CGSize textSize = [self boundingRectWithSize:CGSizeMake(maxWidth, 10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dict context:nil].size;
return textSize.height;
}
- (NSString *)URLEncodedString{
NSString *encodedString = (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL,
kCFStringEncodingUTF8));
return encodedString;
}
+ (NSString *)getAddSourceAppUrl:(NSString *)url{
NSString *retUrl;
if ([url containsString:@"?source=app"]) {
retUrl = url;
}else if ([url containsString:@"?"]){
retUrl = [url stringByAppendingString:@"&source=app"];
}else{
retUrl = [url stringByAppendingString:@"?source=app"];
}
retUrl = [NSString CustomAddUrl:retUrl];
return retUrl;
}
//判断是否图片链接带http。返回正确的链接
+(NSString *)isHttpImageUrl:(NSString *)imageUrl{
if ([imageUrl containsString:@"http"]) {
return imageUrl;
}
return [BASE_IMAGE_URL stringByAppendingString:imageUrl];
}
#pragma mark 链接新添加的
+ (NSString *)CustomAddUrl:(NSString *)url{
NSString *appkeyParam = [NSString stringWithFormat:@"APPkey=%@",KCustomerAPPKEY];
// NSString *deviceIdParam = [NSString stringWithFormat:@"deviceid=%@",[UMSAgent getUMSUDID]];
// NSString *appendStr = [NSString stringWithFormat:@"%@&%@&%@",url,appkeyParam,deviceIdParam];
// NSString *userId = [[[CommonManager shareInstance] getAccount] userId];
// if ([userId length] > 0) {
// appendStr = [appendStr stringByAppendingFormat:@"&userId=%@",userId];
// }
return appkeyParam;
}
@end
//
//
// NSString+JSON.h
// JinSeJiaYuanWang
//
// Created by honghong on 16/3/21.
// Copyright © 2016年 JYall Network Technology Co.,Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (JSON)
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString;
+ (NSString*)dictonaryTOjsonString:(id)object;
@end
//
//
// NSString+JSON.m
// JinSeJiaYuanWang
//
// Created by honghong on 16/3/21.
// Copyright © 2016年 JYall Network Technology Co.,Ltd. All rights reserved.
//
#import "NSString+JSON.h"
@implementation NSString (JSON)
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {return nil;}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];NSError *err;
NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
+(NSString*)dictonaryTOjsonString:(id)object
{
NSString *jsonString = nil;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
@end
//
//
// NSString+MD5Encrypt.h
// Smile
//
// Created by 周 敏 on 12-11-24.
//
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>
@interface NSString (MD5)
- (NSString *)md5Encrypt;
@end
//
//
// NSString+MD5Encrypt.h
// Smile
//
// Created by 周 敏 on 12-11-24.
//
#import "NSString+MD5.h"
@implementation NSString (MD5)
- (NSString *)md5Encrypt
{
const char *cStr = [self UTF8String];
unsigned char result[16];
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]
];
}
@end
//
//
// JYButton.h
// 张云杰
//
// Created by mac on 16/3/13.
// Copyright © 2016年 com.jyall. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JYButton : UIButton
+ (JYButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage targert:(id)targert action:(SEL)action;
+ (JYButton *)initWithNorBackgroundImage:(NSString *)norBackgroundImage higBackgroundImage:(NSString *)higBackgroundImage targert:(id)targert action:(SEL)action;
@end
//
//
// JYButton.m
// 张云杰
//
// Created by mac on 16/3/13.
// Copyright © 2016年 com.jyall. All rights reserved.
//
#import "JYButton.h"
#import "SDGeneralDefine.h"
@implementation JYButton
+ (JYButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage targert:(id)targert action:(SEL)action{
JYButton *btn = [[self alloc]init];
if (norImage != nil && ![norImage isEqualToString:@""]) {
[btn setImage:KImageNamed(norImage) forState:UIControlStateNormal];
}
if (higImage != nil && ![higImage isEqualToString:@""]) {
[btn setImage:KImageNamed(higImage) forState:UIControlStateHighlighted];
}
if (title != nil && ![title isEqualToString:@""]) {
[btn setTitle:title forState:UIControlStateNormal];
}
[btn sizeToFit];
[btn addTarget:targert action:action forControlEvents:UIControlEventTouchUpInside];
return btn;
}
+ (JYButton *)initWithNorBackgroundImage:(NSString *)norBackgroundImage higBackgroundImage:(NSString *)higBackgroundImage targert:(id)targert action:(SEL)action{
JYButton *btn = [self buttonWithType:UIButtonTypeCustom];
if (norBackgroundImage != nil && ![norBackgroundImage isEqualToString:@""]) {
[btn setBackgroundImage:KImageNamed(norBackgroundImage) forState:UIControlStateNormal];
}
if (higBackgroundImage != nil && ![higBackgroundImage isEqualToString:@""]) {
[btn setBackgroundImage:KImageNamed(higBackgroundImage) forState:UIControlStateSelected];
}
[btn sizeToFit];
[btn addTarget:targert action:action forControlEvents:UIControlEventTouchDown];
return btn;
}
// 让按钮在高亮的状态不要做其他操作
- (void)setHighlighted:(BOOL)highlighted
{
//[super setHighlighted:highlighted];
}
@end
//
//
// SDButton.h
// OffcnLiveSDK
//
// Created by vockey on 2018/7/31.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SDButton : UIButton
+ (SDButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage targert:(id)targert action:(SEL)action;
+ (SDButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage offset:(CGFloat)offset targert:(id)targert action:(SEL)action;
+ (SDButton *)initWithNorBackgroundImage:(NSString *)norBackgroundImage higBackgroundImage:(NSString *)higBackgroundImage targert:(id)targert action:(SEL)action;
@end
//
//
// SDButton.m
// OffcnLiveSDK
//
// Created by vockey on 2018/7/31.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "SDButton.h"
#import "SDGeneralDefine.h"
@implementation SDButton
+ (SDButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage targert:(id)targert action:(SEL)action{
SDButton *btn = [[self alloc]init];
if (norImage != nil && ![norImage isEqualToString:@""]) {
[btn setImage:KImageNamed(norImage) forState:UIControlStateNormal];
}
if (higImage != nil && ![higImage isEqualToString:@""]) {
[btn setImage:KImageNamed(higImage) forState:UIControlStateHighlighted];
}
if (title != nil && ![title isEqualToString:@""]) {
[btn setTitle:title forState:UIControlStateNormal];
}
[btn sizeToFit];
[btn addTarget:targert action:action forControlEvents:UIControlEventTouchUpInside];
return btn;
}
+ (SDButton *)initWithTitle:(NSString *)title norImage:(NSString *)norImage higImage:(NSString *)higImage offset:(CGFloat)offset targert:(id)targert action:(SEL)action{
SDButton *btn = [[self alloc] init];
[btn setBackgroundImage:KImageNamed(@"SDVideo_tiwen_beijing") forState:UIControlStateNormal];
if (norImage != nil && ![norImage isEqualToString:@""]) {
[btn setImage:KImageNamed(norImage) forState:UIControlStateNormal];
}
if (higImage != nil && ![higImage isEqualToString:@""]) {
[btn setImage:KImageNamed(higImage) forState:UIControlStateHighlighted];
}
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.titleLabel.font = KFontNameMediumSize(10);
btn.titleLabel.textAlignment = NSTextAlignmentCenter;
if (title != nil && ![title isEqualToString:@""]) {
[btn setTitle:title forState:UIControlStateNormal];
}
btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.intrinsicContentSize.width, -btn.imageView.intrinsicContentSize.height- offset/2.0, 0);
btn.imageEdgeInsets = UIEdgeInsetsMake(-btn.titleLabel.intrinsicContentSize.height- offset/2.0, 0, 0, -btn.titleLabel.intrinsicContentSize.width);
[btn addTarget:targert action:action forControlEvents:UIControlEventTouchUpInside];
return btn;
}
+ (SDButton *)initWithNorBackgroundImage:(NSString *)norBackgroundImage higBackgroundImage:(NSString *)higBackgroundImage targert:(id)targert action:(SEL)action{
SDButton *btn = [self buttonWithType:UIButtonTypeCustom];
if (norBackgroundImage != nil && ![norBackgroundImage isEqualToString:@""]) {
[btn setBackgroundImage:KImageNamed(norBackgroundImage) forState:UIControlStateNormal];
}
if (higBackgroundImage != nil && ![higBackgroundImage isEqualToString:@""]) {
[btn setBackgroundImage:KImageNamed(higBackgroundImage) forState:UIControlStateSelected];
}
[btn sizeToFit];
[btn addTarget:targert action:action forControlEvents:UIControlEventTouchDown];
return btn;
}
@end
//
//
// UIBarButtonItem+WNXBarButtonItem.h
// WNXHuntForCity
//
// Created by MacBook on 15/6/29.
// Copyright (c) 2015年 维尼的小熊. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (WNXBarButtonItem)
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target size:(CGSize)size isLeftButton:(BOOL)isleft action:(SEL)action;
/**
* 根据图片快速创建一个UIBarButtonItem,返回小号barButtonItem
*/
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target isLeftButton:(BOOL)isleft action:(SEL)action;
/**
*根据图片快速创建一个UIBarButtonItem,返回大号barButtonItem
*/
+ (UIBarButtonItem *)initWithNormalImageBig:(NSString *)image target:(id)target action:(SEL)action;
/**
*根据图片快速创建一个UIBarButtonItem,自定义大小
*/
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target action:(SEL)action width:(CGFloat)width height:(CGFloat)height;
//创建有图片,有文字的
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image title:(NSString *)title target:(id)target action:(SEL)action;
/**
*根据文字快速创建一个UIBarButtonItem,自定义大小
*/
+ (UIBarButtonItem *)initWithTitle:(NSString *)title titleColor:(UIColor *)titleColor target:(id)target action:(SEL)action;
@end
//
//
// UIBarButtonItem+WNXBarButtonItem.m
// WNXHuntForCity
//
// Created by MacBook on 15/6/29.
// Copyright (c) 2015年 维尼的小熊. All rights reserved.
//
#import "UIBarButtonItem+WNXBarButtonItem.h"
#import "SDGeneralDefine.h"
@implementation UIBarButtonItem (WNXBarButtonItem)
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target size:(CGSize)size isLeftButton:(BOOL)isleft action:(SEL)action
{
UIImage *normalImage = KImageNamed(image);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, size.width, size.height);
btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
if (isleft) {
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}else{
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
}
// button.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
// [btn setBackgroundImage:normalImage forState:UIControlStateNormal];
[btn setImage:normalImage forState:UIControlStateNormal];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target isLeftButton:(BOOL)isleft action:(SEL)action
{
UIImage *normalImage = KImageNamed(image);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 30, 30);
btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
if (isleft) {
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}else{
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
}
// button.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
// [btn setBackgroundImage:normalImage forState:UIControlStateNormal];
[btn setImage:normalImage forState:UIControlStateNormal];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image title:(NSString *)title target:(id)target action:(SEL)action
{
UIImage *normalImage = KImageNamed(image);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:normalImage forState:UIControlStateNormal];
[btn setTitle:title forState:UIControlStateNormal];
// CGSize titleSize = [titleSize bo]
// UIFont *temp1 = [UIFont fontWithName:@"Helvetica Neue" size:12];
btn.titleLabel.font = [UIFont systemFontOfSize:14];
// NSDictionary *attributes = @{NSFontAttributeName:label3.font};
[btn.titleLabel sizeThatFits:CGSizeMake(100, 20)];
CGSize size = [title sizeWithAttributes: [NSDictionary dictionaryWithObjectsAndKeys:btn.titleLabel.font,NSFontAttributeName,nil]];
btn.frame = CGRectMake(0, 0, size.width+15, 30);
btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
// [btn setBackgroundImage:normalImage forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -size.width-25);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, -size.width-5, 0, 0);
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)initWithNormalImageBig:(NSString *)image target:(id)target action:(SEL)action
{
UIImage *normalImage = KImageNamed(image);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 35, 35);
[btn setBackgroundImage:normalImage forState:UIControlStateNormal];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)initWithNormalImage:(NSString *)image target:(id)target action:(SEL)action width:(CGFloat)width height:(CGFloat)height
{
UIImage *normalImage = KImageNamed(image);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, width, height);
[btn setBackgroundImage:normalImage forState:UIControlStateNormal];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)initWithTitle:(NSString *)title titleColor:(UIColor *)titleColor target:(id)target action:(SEL)action
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 35, 35);
btn.titleLabel.font = [UIFont systemFontOfSize:15];
btn.titleLabel.textAlignment = NSTextAlignmentRight;
[btn setTitle:title forState:UIControlStateNormal];
if (!titleColor) {
titleColor = [UIColor blackColor];
}
[btn setTitleColor:titleColor forState:UIControlStateNormal];
[btn setTitleColor:UICOLOR_RGB_Alpha(0xcccccc, 1) forState:UIControlStateDisabled];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
return item;
}
@end
//
//
// UIColor+applianceHex.h
// 张云杰
//
// Created by mac on 16/3/13.
// Copyright © 2016年 com.jyall. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (applianceHex)
/*
* 输入6位数返回一个颜色值
*/
+ (UIColor *)colorFromHex:(NSString *)hex;
/*
* 输入6位数和透明度返回一个颜色值
*/
+ (UIColor *)colorFromHex:(NSString *)hex alpha:(CGFloat)alpha;
//背景
+ (UIColor *)colorBackWithBackView;
//主题
+ (UIColor *)colorTheme;
//虚线
+ (UIColor *)colorLine;
//文字
+ (UIColor *)colorTextBlack;
//未输入颜色
+ (UIColor *)colorPlaceholderTextBlack;
//按钮边框颜色
+ (UIColor *)colorcornerRadiusBtnLayerBlack;
@end
//
//
// UIColor+applianceHex.m
// 张云杰
//
// Created by mac on 16/3/13.
// Copyright © 2016年 com.jyall. All rights reserved.
//
#import "UIColor+applianceHex.h"
@implementation UIColor (applianceHex)
+ (UIColor *)colorFromHex:(NSString *)hex
{
return [UIColor colorFromHex:hex alpha:1.0];
}
+ (UIColor *)colorFromHex:(NSString *)hex alpha:(CGFloat)alpha
{
NSString *cleanString = [hex stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6) {
cleanString = [cleanString stringByAppendingString:@"ff"];
}
unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
float red = ((baseValue >> 24) & 0xFF)/255.0f;
float green = ((baseValue >> 16) & 0xFF)/255.0f;
float blue = ((baseValue >> 8) & 0xFF)/255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
#pragma mark - #
+ (UIColor *)colorBackWithBackView{
return [UIColor colorFromHex:@"#f8f8f8"];
}
+ (UIColor *)colorTheme{
return [UIColor colorFromHex:@"#00a0e9"];
}
+ (UIColor *)colorLine{
return [UIColor colorFromHex:@"#dcdcdc"];
}
+ (UIColor *)colorTextBlack{
return [UIColor colorFromHex:@"#333333"];
}
+ (UIColor *)colorPlaceholderTextBlack{
return [UIColor colorFromHex:@"#999999"];
}
+ (UIColor *)colorcornerRadiusBtnLayerBlack{
return [UIColor colorFromHex:@"#f8b851"];
}
@end
//
//
// UIImage+Color.h
// JYallXiangMuTong
//
// Created by 葬花桥 on 16/1/4.
// Copyright © 2016年 陈石. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (Color)
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;
//给我一种颜色,一个尺寸,我给你返回一个UIImage:不透明
+(UIImage *)imageFromContextWithColor:(UIColor *)color;
+(UIImage *)imageFromContextWithColor:(UIColor *)color size:(CGSize)size;
@end
//
//
// UIImage+Color.m
// JYallXiangMuTong
//
// Created by 葬花桥 on 16/1/4.
// Copyright © 2016年 陈石. All rights reserved.
//
#import "UIImage+Color.h"
@implementation UIImage (Color)
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
//给我一种颜色,一个尺寸,我给你返回一个UIImage
+(UIImage *)imageFromContextWithColor:(UIColor *)color size:(CGSize)size{
CGRect rect=(CGRect){{0.0f,0.0f},size};
//开启一个图形上下文
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
//获取图形上下文
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
//获取图像
UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
return image;
}
+(UIImage *)imageFromContextWithColor:(UIColor *)color{
CGSize size=CGSizeMake(1.0f, 1.0f);
return [self imageFromContextWithColor:color size:size];
}
@end
#import <UIKit/UIKit.h>
@interface UIImage (Extension)
/**
* 圆形剪裁图片
*
* @param borderW 圆环宽度
* @param color 圆环颜色
* @param imageName 图片名称
*
* @return 剪裁好的图片
*/
+ (UIImage *)imageWithBorderW:(CGFloat)borderW color:(UIColor *)color CircleImageName:(NSString *)imageName;
//- (instancetype)yzt_drawRectWithRoundCorner:(UIRectCorner)rectCorner radius:(CGFloat)radius size:(CGSize)size;
+ (UIImage *)resizableImageWithName:(NSString *)imageName;
+ (UIImage *) imageWithName:(NSString *) imageName;
- (UIImage*) scaleImageWithSize:(CGSize)size;
- (UIImage*) scaleImageWithFrame:(CGRect)frame;
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize;
//图片image旋转
+ (UIImage *)offcnImage:(UIImage *)image rotation:(UIImageOrientation)orientation;
@end
#import "UIImage+Extension.h"
#import "SDGeneralDefine.h"
@implementation UIImage (Extension)
+ (UIImage *)imageWithBorderW:(CGFloat)borderW color:(UIColor *)color CircleImageName:(NSString *)imageName
{
UIImage *img = KImageNamed(imageName);
CGFloat w = img.size.width + 2 * borderW;
CGFloat h = img.size.height + 2 * borderW;
CGRect bigCricleRect = CGRectMake(0, 0, w, h);
// 1.开启位图上下文
UIGraphicsBeginImageContextWithOptions(bigCricleRect.size, NO, 0);
// 2.拼接路径
// 2.1绘制大圆
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:bigCricleRect];
// 设置圆环颜色
[color set];
[path fill];
// 2.2设置裁剪区域
CGRect clipRect = CGRectMake(borderW, borderW, img.size.width, img.size.height);
// 描述裁剪区域路径
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:clipRect];
[clipPath addClip];
// 绘制图片
[img drawAtPoint:CGPointMake(borderW, borderW)];
// 获取图片
img = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
return img;
}
- (UIImage *)drawCircleImage {
// UIImage *img = KImageNamed(imageName);
// CGFloat w = img.size.width + 2 * borderW;
// CGFloat h = img.size.height + 2 * borderW;
// CGRect bigCricleRect = CGRectMake(0, 0, w, h);
CGRect rect = CGRectMake(0, 0, 50, 50);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:50] addClip];
[self drawInRect:rect];
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return output;
}
+ (UIImage *)resizableImageWithName:(NSString *)imageName{
UIImage *image = KImageNamed(imageName);
// 获取原有图片的宽高的一半
CGFloat w = image.size.width * 0.5;
CGFloat h = image.size.height * 0.5;
// 生成可以拉伸指定位置的图片
UIImage *newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w) resizingMode:UIImageResizingModeStretch];
return newImage;
}
/**
* 争对ios7以上的系统适配新的图片资源
*
* @param imageName 图片名称
*
* @return 新的图片
*/
+ (UIImage *)imageWithName:(NSString *)imageName
{
UIImage *newImage = nil;
if (newImage == nil) {
newImage = KImageNamed(imageName);
}
return newImage;
}
/**
* 实现图片的缩小或者放大
*
* @param size 大小范围
*
* @return 新的图片
*/
-(UIImage*) scaleImageWithSize:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size,NO,0); //size 为CGSize类型,即你所需要的图片尺寸
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage; //返回的就是已经改变的图片
}
- (UIImage*) scaleImageWithFrame:(CGRect)frame{
UIGraphicsBeginImageContextWithOptions(frame.size,NO,0); //size 为CGSize类型,即你所需要的图片尺寸
[self drawInRect:frame];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage; //返回的就是已经改变的图片
}
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image)
{
newimage = nil;
} else {
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height)
{
rect.size.width = asize.height*oldsize.width/oldsize.height;
rect.size.height = asize.height;
rect.origin.x = (asize.width - rect.size.width)/2;
rect.origin.y = 0;
} else {
rect.size.width = asize.width;
rect.size.height = asize.width*oldsize.height/oldsize.width;
rect.origin.x = 0;
rect.origin.y = (asize.height - rect.size.height)/2;
}
UIGraphicsBeginImageContext(asize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
//图片image旋转
+ (UIImage *)offcnImage:(UIImage *)image rotation:(UIImageOrientation)orientation{
long double rotate = 0.0;
CGRect rect;
float translateX = 0;
float translateY = 0;
float scaleX = 1.0;
float scaleY = 1.0;
switch (orientation) {
case UIImageOrientationLeft:
rotate = M_PI_2;
rect = CGRectMake(0, 0, image.size.height, image.size.width);
translateX = 0;
translateY = -rect.size.width;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientationRight:
rotate = 3 * M_PI_2;
rect = CGRectMake(0, 0, image.size.height, image.size.width);
translateX = -rect.size.height;
translateY = 0;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientationDown:
rotate = M_PI;
rect = CGRectMake(0, 0, image.size.width, image.size.height);
translateX = -rect.size.width;
translateY = -rect.size.height;
break;
default:
rotate = 0.0;
rect = CGRectMake(0, 0, image.size.width, image.size.height);
translateX = 0;
translateY = 0;
break;
}
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
//做CTM变换
CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextRotateCTM(context, rotate);
CGContextTranslateCTM(context, translateX, translateY);
CGContextScaleCTM(context, scaleX, scaleY);
//绘制图片
CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newPic;
}
@end
//
//
// SDLabel.h
// OffcnLiveSDK
//
// Created by vockey on 2018/8/8.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SDLabel : UILabel
@property (assign, nonatomic) UIEdgeInsets edgeInsets;
@end
//
// SDLabel.m
// OffcnLiveSDK
//
// Created by vockey on 2018/8/8.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "SDLabel.h"
#import "SDGeneralDefine.h"
@implementation SDLabel
- (instancetype)initWithFrame:(CGRect)frame
{
if(self = [super initWithFrame:frame])
{
self.edgeInsets = UIEdgeInsetsMake(15*KWidth_Scale, 0, 15*KWidth_Scale, 0);
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
self.edgeInsets = UIEdgeInsetsMake(15*KWidth_Scale, 0, 15*KWidth_Scale, 0);
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
self.edgeInsets = UIEdgeInsetsMake(15*KWidth_Scale, 0, 15*KWidth_Scale, 0);
}
// 修改绘制文字的区域,edgeInsets增加bounds
-(CGRect)textRectForBounds:(CGRect)bounds
limitedToNumberOfLines:(NSInteger)numberOfLines
{
/*
调用父类该方法
注意传入的UIEdgeInsetsInsetRect(bounds, self.edgeInsets),bounds是真正的绘图区域
*/
CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,
self.edgeInsets) limitedToNumberOfLines:numberOfLines];
//根据edgeInsets,修改绘制文字的bounds
rect.origin.x -= self.edgeInsets.left;
rect.origin.y -= self.edgeInsets.top;
rect.size.width += self.edgeInsets.left + self.edgeInsets.right;
rect.size.height += self.edgeInsets.top + self.edgeInsets.bottom;
return rect;
}
//绘制文字
- (void)drawTextInRect:(CGRect)rect
{
//令绘制区域为原始区域,增加的内边距区域不绘制
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
@end
//
//
// Slider.h
// CLPlayerDemo
//
// Created by JmoVxia on 2016/11/2.
// Copyright © 2016年 JmoVxia. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CLSlider : UISlider
@property (nonatomic, copy) void(^tapValueCallAction)(CLSlider *slider);
@end
//
//
// Slider.m
// CLPlayerDemo
//
// Created by JmoVxia on 2016/11/2.
// Copyright © 2016年 JmoVxia. All rights reserved.
//
#import "CLSlider.h"
#import "SDGeneralDefine.h"
#define SLIDER_X_BOUND 30
#define SLIDER_Y_BOUND 40
@interface CLSlider ()
/**lastBounds*/
@property (nonatomic,assign) CGRect lastBounds;
@end
@implementation CLSlider
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
-(void)sliderTap:(UIGestureRecognizer *)tap{
CGPoint point = [tap locationInView:self];
CGFloat value = point.x/self.bounds.size.width;
if (value>0 && value<=1) {
[self setValue:value animated:YES];
if (self.tapValueCallAction) {
self.tapValueCallAction(self);
}
}
}
- (void)setup {
UIImage *thumbImage = KImageNamed(@"SDVideo_progress_dian");
[self setThumbImage:thumbImage forState:UIControlStateHighlighted];
[self setThumbImage:thumbImage forState:UIControlStateNormal];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTap:)];
[self addGestureRecognizer:tap];
}
// 控制slider的宽和高,这个方法才是真正的改变slider滑道的高的
- (CGRect)trackRectForBounds:(CGRect)bounds{
[super trackRectForBounds:bounds];
return CGRectMake(bounds.origin.x, bounds.origin.y, CGRectGetWidth(bounds), 2);
}
//修改滑块位置
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {
rect.origin.x = rect.origin.x - 6 ;
rect.size.width = rect.size.width + 12;
CGRect result = [super thumbRectForBounds:bounds trackRect:rect value:value];
//记录下最终的frame
_lastBounds = result;
return result;
}
//检查点击事件点击范围是否能够交给self处理
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//调用父类方法,找到能够处理event的view
UIView* result = [super hitTest:point withEvent:event];
if (result != self) {
/*如果这个view不是self,我们给slider扩充一下响应范围,
这里的扩充范围数据就可以自己设置了
*/
if ((point.y >= -15) &&
(point.y < (_lastBounds.size.height + SLIDER_Y_BOUND)) &&
(point.x >= 0 && point.x < CGRectGetWidth(self.bounds))) {
//如果在扩充的范围类,就将event的处理权交给self
result = self;
}
}
//否则,返回能够处理的view
return result;
}
//检查是点击事件的点是否在slider范围内
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
//调用父类判断
BOOL result = [super pointInside:point withEvent:event];
if (!result) {
//同理,如果不在slider范围类,扩充响应范围
if ((point.x >= (_lastBounds.origin.x - SLIDER_X_BOUND)) && (point.x <= (_lastBounds.origin.x + _lastBounds.size.width + SLIDER_X_BOUND))
&& (point.y >= -SLIDER_Y_BOUND) && (point.y < (_lastBounds.size.height + SLIDER_Y_BOUND))) {
//在扩充范围内,返回yes
result = YES;
}
}
//否则返回父类的结果
return result;
}
#pragma mark - 获取资源图片
//- (UIImage *)getPictureWithName:(NSString *)name{
// NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"CLPlayer" ofType:@"bundle"]];
// NSString *path = [bundle pathForResource:name ofType:@"png"];
// return [[UIImage imageWithContentsOfFile:path] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//}
@end
//
//
// UIView+IBExtension.h
// Weibo11
//
// Created by JYJ on 15/12/6.
// Copyright © 2015年 itheima. All rights reserved.
//
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UIView (IBExtension)
/// 边线颜色
@property (nonatomic, strong) IBInspectable UIColor *borderColor;
/// 边线宽度
@property (nonatomic, assign) IBInspectable CGFloat borderWidth;
/// 脚半径
@property (nonatomic, assign) IBInspectable CGFloat cornerRadius;
@end
//
//
// UIView+IBExtension.m
// Weibo11
//
// Created by JYJ on 15/12/6.
// Copyright © 2015年 itheima. All rights reserved.
//
#import "UIView+IBExtension.h"
@implementation UIView (IBExtension)
- (void)setBorderColor:(UIColor *)borderColor {
self.layer.borderColor = borderColor.CGColor;
}
- (UIColor *)borderColor {
return [UIColor colorWithCGColor:self.layer.borderColor];
}
- (void)setBorderWidth:(CGFloat)borderWidth {
self.layer.borderWidth = borderWidth;
}
- (CGFloat)borderWidth {
return self.layer.borderWidth;
}
- (void)setCornerRadius:(CGFloat)cornerRadius {
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = YES;
// 栅格化 - 提高性能
// 设置栅格化后,图层会被渲染成图片,并且缓存,再次使用时,不会重新渲染
self.layer.rasterizationScale = [UIScreen mainScreen].scale;
self.layer.shouldRasterize = YES;
}
- (CGFloat)cornerRadius {
return self.layer.cornerRadius;
}
@end
//
//
// UIView+bezierShape.h
// FeiPaiCustomer
//
// Created by honghong on 2017/9/19.
// Copyright © 2017年 cj. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (bezierShape)
/**
** lineView: 需要绘制成虚线的view
** lineLength: 虚线的宽度
** lineSpacing: 虚线的间距
** lineColor: 虚线的颜色
**/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor;
/**
圆角
使用自动布局,需要在layoutsubviews 中使用
@param radius 圆角尺寸
@param corner 圆角位置
*/
- (void)drawRadiusWithRadius:(CGFloat)radius corner:(UIRectCorner)corner;
@end
//
//
// UIView+bezierShape.m
// FeiPaiCustomer
//
// Created by honghong on 2017/9/19.
// Copyright © 2017年 cj. All rights reserved.
//
#import "UIView+bezierShape.h"
@implementation UIView (bezierShape)
/**
** lineView: 需要绘制成虚线的view
** lineLength: 虚线的宽度
** lineSpacing: 虚线的间距
** lineColor: 虚线的颜色
**/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
NSLog(@"&&&&&&&&&&&&&&&& left is %@",NSStringFromCGRect(lineView.frame));
NSLog(@"width is %lf height is %lf",CGRectGetWidth(lineView.frame),CGRectGetHeight(lineView.frame));
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:lineView.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 设置虚线颜色为blackColor
[shapeLayer setStrokeColor:lineColor.CGColor];
// 设置虚线宽度
[shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
[shapeLayer setLineJoin:kCALineJoinRound];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
// 设置路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
// 把绘制好的虚线添加上来
[lineView.layer addSublayer:shapeLayer];
}
- (void)drawRadiusWithRadius:(CGFloat)radius corner:(UIRectCorner)corner{
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = path.CGPath;
self.layer.mask = maskLayer;
}
@end
/*
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 3.0 Edition
BSD License, Use at your own risk
*/
#import <UIKit/UIKit.h>
CGPoint CGRectGetCenter(CGRect rect);
CGRect CGRectMoveToCenter(CGRect rect, CGPoint center);
@interface UIView (ViewFrameGeometry)
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGSize size;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@property CGPoint origin;
@property (readonly) CGPoint bottomLeft;
@property (readonly) CGPoint bottomRight;
@property (readonly) CGPoint topRight;
@property CGFloat top;
@property CGFloat left;
@property CGFloat bottom;
@property CGFloat right;
@property (nonatomic, assign) CGFloat middleX;
@property (nonatomic, assign) CGFloat middleY;
@property (nonatomic, assign) CGFloat tail;
+ (instancetype)viewFromXib;
//判断一个控件是否真正显示在主窗口
- (BOOL)isShowingOnKeyWindow;
- (void)reboundEffectAnimationDuration:(CGFloat)duration;
- (void) moveBy: (CGPoint) delta;
- (void) scaleBy: (CGFloat) scaleFactor;
- (void) fitInSize: (CGSize) aSize;
- (void)removeAllSubViews;
@end
/*
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 3.0 Edition
BSD License, Use at your own risk
*/
#import "UIViewExt.h"
#import "SDGeneralDefine.h"
CGPoint CGRectGetCenter(CGRect rect)
{
CGPoint pt;
pt.x = CGRectGetMidX(rect);
pt.y = CGRectGetMidY(rect);
return pt;
}
CGRect CGRectMoveToCenter(CGRect rect, CGPoint center)
{
CGRect newrect = CGRectZero;
newrect.origin.x = center.x-CGRectGetMidX(rect);
newrect.origin.y = center.y-CGRectGetMidY(rect);
newrect.size = rect.size;
return newrect;
}
@implementation UIView (ViewGeometry)
- (void)setX:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)x
{
return self.frame.origin.x;
}
- (void)setY:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)y
{
return self.frame.origin.y;
}
// Retrieve and set the origin
- (CGPoint) origin
{
return self.frame.origin;
}
- (void) setOrigin: (CGPoint) aPoint
{
CGRect newframe = self.frame;
newframe.origin = aPoint;
self.frame = newframe;
}
// Retrieve and set the size
- (CGSize) size
{
return self.frame.size;
}
- (void) setSize: (CGSize) aSize
{
CGRect newframe = self.frame;
newframe.size = aSize;
self.frame = newframe;
}
- (void)setCenterX:(CGFloat)centerX
{
CGPoint center = self.center;
center.x = centerX;
self.center = center;
}
- (CGFloat)centerX
{
return self.center.x;
}
- (void)setCenterY:(CGFloat)centerY
{
CGPoint center = self.center;
center.y = centerY;
self.center = center;
}
- (CGFloat)centerY
{
return self.center.y;
}
// Query other frame locations
- (CGPoint) bottomRight
{
CGFloat x = self.frame.origin.x + self.frame.size.width;
CGFloat y = self.frame.origin.y + self.frame.size.height;
return CGPointMake(x, y);
}
- (CGPoint) bottomLeft
{
CGFloat x = self.frame.origin.x;
CGFloat y = self.frame.origin.y + self.frame.size.height;
return CGPointMake(x, y);
}
- (CGPoint) topRight
{
CGFloat x = self.frame.origin.x + self.frame.size.width;
CGFloat y = self.frame.origin.y;
return CGPointMake(x, y);
}
// Retrieve and set height, width, top, bottom, left, right
- (CGFloat) height
{
return self.frame.size.height;
}
- (void) setHeight: (CGFloat) newheight
{
CGRect newframe = self.frame;
newframe.size.height = newheight;
self.frame = newframe;
}
- (CGFloat) width
{
return self.frame.size.width;
}
- (void) setWidth: (CGFloat) newwidth
{
CGRect newframe = self.frame;
newframe.size.width = newwidth;
self.frame = newframe;
}
- (CGFloat) top
{
return self.frame.origin.y;
}
- (void) setTop: (CGFloat) newtop
{
CGRect newframe = self.frame;
newframe.origin.y = newtop;
self.frame = newframe;
}
- (CGFloat) left
{
return self.frame.origin.x;
}
- (void) setLeft: (CGFloat) newleft
{
CGRect newframe = self.frame;
newframe.origin.x = newleft;
self.frame = newframe;
}
- (CGFloat) bottom
{
return self.frame.origin.y + self.frame.size.height;
}
- (void) setBottom: (CGFloat) newbottom
{
CGRect newframe = self.frame;
newframe.origin.y = newbottom - self.frame.size.height;
self.frame = newframe;
}
- (CGFloat) right
{
return self.frame.origin.x + self.frame.size.width;
}
- (void) setRight: (CGFloat) newright
{
CGFloat delta = newright - (self.frame.origin.x + self.frame.size.width);
CGRect newframe = self.frame;
newframe.origin.x += delta ;
self.frame = newframe;
}
// Move via offset
- (void) moveBy: (CGPoint) delta
{
CGPoint newcenter = self.center;
newcenter.x += delta.x;
newcenter.y += delta.y;
self.center = newcenter;
}
// Scaling
- (void) scaleBy: (CGFloat) scaleFactor
{
CGRect newframe = self.frame;
newframe.size.width *= scaleFactor;
newframe.size.height *= scaleFactor;
self.frame = newframe;
}
// Ensure that both dimensions fit within the given size by scaling down
- (void) fitInSize: (CGSize) aSize
{
CGFloat scale;
CGRect newframe = self.frame;
if (newframe.size.height && (newframe.size.height > aSize.height))
{
scale = aSize.height / newframe.size.height;
newframe.size.width *= scale;
newframe.size.height *= scale;
}
if (newframe.size.width && (newframe.size.width >= aSize.width))
{
scale = aSize.width / newframe.size.width;
newframe.size.width *= scale;
newframe.size.height *= scale;
}
self.frame = newframe;
}
- (void)setMiddleX:(CGFloat)middleX
{
CGRect frame = self.frame;
frame.origin.x = middleX - frame.size.width / 2;
self.frame = frame;
}
- (CGFloat)middleX
{
return CGRectGetMidX(self.frame);
}
- (void)setMiddleY:(CGFloat)middleY
{
CGRect frame = self.frame;
frame.origin.y = middleY - frame.size.height / 2 ;
self.frame = frame;
}
- (CGFloat)middleY
{
return CGRectGetMidY(self.frame);
}
- (CGFloat)tail
{
return CGRectGetMaxX(self.frame);
}
- (void)setTail:(CGFloat)tail
{
CGRect frame = self.frame;
frame.origin.x = tail - frame.size.width;
self.frame = frame;
}
- (void)removeAllSubViews
{
// for (int i = 0; i<self.subviews.count; i++) {
//
// }
for (UIView *view in self.subviews) {
[view removeFromSuperview];
}
}
+ (instancetype)viewFromXib
{
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
}
- (BOOL)isShowingOnKeyWindow
{
// 主窗口
UIWindow *keyWindow = KKeyWindow;
// 以主窗口左上角为坐标原点, 计算self的矩形框
CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];
CGRect winBounds = keyWindow.bounds;
// 主窗口的bounds 和 self的矩形框 是否有重叠
BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
}
- (void)reboundEffectAnimationDuration:(CGFloat)duration
{ //缩放的动画 效果
CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.duration=duration;
animation.values = [NSArray arrayWithObjects:
[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)],
[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)],
[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)],
[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)],
nil];//x y z 放大缩小的倍数
[self.layer addAnimation:animation forKey:nil];
}
@end
//
//
// UIViewController+SDIphoneX.h
// OffcnLiveSDK
//
// Created by vockey on 2018/8/16.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (SDIphoneX)
/**
状态栏加背景
*/
-(void)fixIphoneStatusBar;
/**
苹果X及以上手机适配底部安全区域加背景
*/
-(void)fixIphoneXBottom;
//是否含有刘海 即是否为X XS XS Max XR
-(BOOL)isHasFringe;
@end
//
//
// UIViewController+SDIphoneX.m
// OffcnLiveSDK
//
// Created by vockey on 2018/8/16.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "UIViewController+SDIphoneX.h"
#import "ZYJMasonry.h"
#import "UIViewExt.h"
#import "SDGeneralDefine.h"
@implementation UIViewController (SDIphoneX)
-(void)fixIphoneStatusBar{
UIView *statusBarBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, KStatusBarHeight)];
statusBarBackView.backgroundColor = [UIColor blackColor];
statusBarBackView.tag = 44;
[self.view addSubview:statusBarBackView];
[statusBarBackView mas_makeConstraints:^(ZYJMASConstraintMaker *make) {
make.top.leading.trailing.equalTo(self.view);
make.height.mas_equalTo(KStatusBarHeight);
}];
}
-(void)fixIphoneXBottom{
if (kIsIphoneX) {
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 34, kScreen_Width, 34)];
bottomView.backgroundColor = [UIColor whiteColor];
bottomView.tag = 34;
[self.view addSubview:bottomView];
[bottomView mas_makeConstraints:^(ZYJMASConstraintMaker *make) {
make.bottom.leading.trailing.equalTo(self.view);
make.height.mas_equalTo(34);
}];
}
}
//是否含有刘海 即是否为X XS XS Max XR
-(BOOL)isHasFringe{
CGFloat iPhoneNotchDirectionSafeAreaInsets = 0;
if (iOS11) {
UIEdgeInsets safeAreaInsets = [UIApplication sharedApplication].windows[0].safeAreaInsets;
switch ([UIApplication sharedApplication].statusBarOrientation) {
case UIInterfaceOrientationPortrait:{
iPhoneNotchDirectionSafeAreaInsets = safeAreaInsets.top;
}
break;
case UIInterfaceOrientationLandscapeLeft:{
iPhoneNotchDirectionSafeAreaInsets = safeAreaInsets.left;
}
break;
case UIInterfaceOrientationLandscapeRight:{
iPhoneNotchDirectionSafeAreaInsets = safeAreaInsets.right;
}
break;
case UIInterfaceOrientationPortraitUpsideDown:{
iPhoneNotchDirectionSafeAreaInsets = safeAreaInsets.bottom;
}
break;
default:
iPhoneNotchDirectionSafeAreaInsets = safeAreaInsets.top;
break;
}
return iPhoneNotchDirectionSafeAreaInsets > 20;
} else {
return NO;
}
}
@end
//
//
// DSToast.h
// DSToast
//
// Created by LS on 8/18/15.
// Copyright (c) 2015 LS. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, DSToastShowType)
{
DSToastShowTypeTop,
DSToastShowTypeCenter,
DSToastShowTypeBottom
};
@interface DSToast : UILabel
@property (nonatomic, assign) CFTimeInterval forwardAnimationDuration;
@property (nonatomic, assign) CFTimeInterval backwardAnimationDuration;
@property (nonatomic, assign) UIEdgeInsets textInsets;
@property (nonatomic, assign) CGFloat maxWidth;
@property (nonatomic, assign) DSToastShowType toastShowType;
+ (id)toastWithText:(NSString *)text;
- (id)initWithText:(NSString *)text;
- (void)showInView:(UIView *)view; //Default is DSToastShowTypeBottom
- (void)showInView:(UIView *)view showType:(DSToastShowType)type;
@end
//
//
// DSToast.m
// DSToast
//
// Created by LS on 8/18/15.
// Copyright (c) 2015 LS. All rights reserved.
//
#import "DSToast.h"
#import "SDGeneralDefine.h"
#import "UIViewExt.h"
@interface DSToast ()<CAAnimationDelegate>
@end
static CFTimeInterval const kDefaultForwardAnimationDuration = 0.5;
static CFTimeInterval const kDefaultBackwardAnimationDuration = 0.5;
static CFTimeInterval const kDefaultWaitAnimationDuration = 1.0;
static CGFloat const kDefaultTopMargin = 50.0;
static CGFloat const kDefaultBottomMargin = 50.0;
//static CGFloat const kDefalultTextInset = 10.0;
@implementation DSToast
+ (id)toastWithText:(NSString *)text
{
DSToast *toast = [[DSToast alloc] initWithText:text];
return toast;
}
- (id)initWithText:(NSString *)text
{
self = [self initWithFrame:CGRectZero];
if(self)
{
self.text = text;
[self sizeToFit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
self.forwardAnimationDuration = kDefaultForwardAnimationDuration;
self.backwardAnimationDuration = kDefaultBackwardAnimationDuration;
self.textInsets = UIEdgeInsetsMake(13.5, 44, 13.5, 44);
self.maxWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]) - 20.0;
self.layer.cornerRadius = 6.0;
self.layer.masksToBounds = YES;
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
self.numberOfLines = 0;
self.textAlignment = NSTextAlignmentLeft;
self.textColor = [UIColor whiteColor];
self.font = KFontNameMediumSize(13.0);
self.toastShowType = DSToastShowTypeCenter;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
}
return self;
}
- (void)changeRotate:(NSNotification*)noti{
[self endEditing:YES];
if (self.toastShowType == DSToastShowTypeCenter) {
self.center = KFirstWindow.center;
}else{
self.centerX = KFirstWindow.centerX;
self.centerY = KFirstWindow.centerY-100;
}
}
#pragma mark - Show Method
- (void)showInView:(UIView *)view
{
[self addAnimationGroup];
CGPoint point = view.center;
point.y = CGRectGetHeight(view.bounds)- kDefaultBottomMargin;
self.center = point;
for (int i=0; i<view.subviews.count; i++) {
if (i == view.subviews.count-1) {
if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
[view.subviews[i] removeFromSuperview];
[view addSubview:self];
}else{
[view addSubview:self];
}
}else{
if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
[view.subviews[i] removeFromSuperview];
}
}
}
}
- (void)showInView:(UIView *)view showType:(DSToastShowType)type
{
self.toastShowType = type;
[self addAnimationGroup];
CGPoint point = view.center;
switch (type) {
case DSToastShowTypeTop:
point.y = kDefaultTopMargin;
break;
case DSToastShowTypeBottom:
point.y = CGRectGetHeight(view.bounds)- kDefaultBottomMargin;
break;
default:
break;
}
self.center = point;
self.layer.cornerRadius = self.frame.size.height/2;
self.layer.masksToBounds = YES;
for (int i=0; i<view.subviews.count; i++) {
if (i == view.subviews.count-1) {
if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
[view.subviews[i] removeFromSuperview];
[view addSubview:self];
}else{
[view addSubview:self];
}
}else{
if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
[view.subviews[i] removeFromSuperview];
}
}
}
}
-(void)layoutSubviews{
[super layoutSubviews];
if (self.toastShowType == DSToastShowTypeCenter) {
self.center = KFirstWindow.center;
}else{
self.centerX = KFirstWindow.centerX;
self.centerY = KFirstWindow.centerY-100;
}
}
#pragma mark - Animation
- (void)addAnimationGroup
{
CABasicAnimation *forwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
forwardAnimation.duration = self.forwardAnimationDuration;
forwardAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.5f :1.7f :0.6f :0.85f];
forwardAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
forwardAnimation.toValue = [NSNumber numberWithFloat:1.0f];
CABasicAnimation *backwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
backwardAnimation.duration = self.backwardAnimationDuration;
backwardAnimation.beginTime = forwardAnimation.duration + kDefaultWaitAnimationDuration;
backwardAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.4f :0.15f :0.5f :-0.7f];
backwardAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
backwardAnimation.toValue = [NSNumber numberWithFloat:0.0f];
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.animations = @[forwardAnimation,backwardAnimation];
animationGroup.duration = forwardAnimation.duration + backwardAnimation.duration + kDefaultWaitAnimationDuration;
animationGroup.removedOnCompletion = NO;
animationGroup.delegate = self;
animationGroup.fillMode = kCAFillModeForwards;
[self.layer addAnimation:animationGroup forKey:nil];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
if(flag)
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self removeFromSuperview];
}
}
- (void)setTextInsets:(UIEdgeInsets)textInsets{
CGRect frame = self.frame;
CGFloat width = CGRectGetWidth(self.bounds) + textInsets.left + textInsets.right;
frame.size.width = width > self.maxWidth? self.maxWidth : width;
frame.size.height = CGRectGetHeight(self.bounds) + textInsets.top + textInsets.bottom;
self.frame = frame;
self.textAlignment = NSTextAlignmentCenter;
}
#pragma mark - Text Configurate
- (void)sizeToFit
{
[super sizeToFit];
CGRect frame = self.frame;
CGFloat width = CGRectGetWidth(self.bounds) + self.textInsets.left + self.textInsets.right;
frame.size.width = width > self.maxWidth? self.maxWidth : width;
frame.size.height = CGRectGetHeight(self.bounds) + self.textInsets.top + self.textInsets.bottom;
self.frame = frame;
}
- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.textInsets)];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
bounds.size = [self.text boundingRectWithSize:CGSizeMake(self.maxWidth - self.textInsets.left - self.textInsets.right,
CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
return bounds;
}
@end
//
//
// OffcnToast.h
// OffcnLiveSDK
//
// Created by vockey on 2019/4/9.
// Copyright © 2019年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "DSToast.h"
@interface OffcnToast : NSObject
/**
Toast提示
@param titlemessage 提示内容
*/
+(void)toastWithTitlemessage:(NSString *)titlemessage;
/**
Toast提示
@param titlemessage 提示内容
@param type 位置
*/
+(void)toastWithTitlemessage:(NSString *)titlemessage showType:(DSToastShowType)type;
@end
//
//
// OffcnToast.m
// OffcnLiveSDK
//
// Created by vockey on 2019/4/9.
// Copyright © 2019年 中公教育. All rights reserved.
//
#import "OffcnToast.h"
#import "DSToast.h"
#import "SDGeneralDefine.h"
@implementation OffcnToast
//toast
+(void)toastWithTitlemessage:(NSString *)titlemessage{
if(titlemessage.length>0){
DSToast *toast = [[DSToast alloc] initWithText:titlemessage];
toast.maxWidth = 284.0;
toast.textInsets = UIEdgeInsetsMake(13.5, 44, 13.5, 44);
[toast showInView:KKeyWindow showType:DSToastShowTypeCenter];
}
}
+(void)toastWithTitlemessage:(NSString *)titlemessage showType:(DSToastShowType)type{
if(titlemessage.length>0){
DSToast *toast = [[DSToast alloc] initWithText:titlemessage];
toast.maxWidth = 284.0;
toast.textInsets = UIEdgeInsetsMake(13.5, 44, 13.5, 44);
[toast showInView:KKeyWindow showType:type];
}
}
@end
//
//
// SDGeneralTool.h
// HomeHealth
//
// Created by newuser on 16/12/30.
// Copyright © 2016年 ChiJian. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "OffcnBaseNetworking.h"
@interface SDGeneralTool : NSObject
//toast
+(void)toastWithTitlemessage:(NSString *)titlemessage;
+(void)removeDSToast;
//Alert弹框
+(void)popAlertControllerWithTarget:(UIViewController *)target title:(NSString *)title message:(NSString *)message finished:(void(^)(UIAlertAction * _Nonnull action))finished;
//push
+(void)pushViewControllerWithController:(UIViewController *)Controller;
+ (NSString*)deviceVersion;
+ (NSString *)getDouble2Num:(id)num;
#pragma mark - 计算时间差
+(BOOL)isPassMinute:(int)min startTime:(NSString *)startTime endTime:(NSString *)endTime;
//聊天获取下一条消息时间标签
+(NSString*)getNextMsgTimeWithTime:(NSString *)Time;
//当天时间
+(NSString*)getHistorySameDayTimeWithTime:(NSString *)Time;
//获取当前的时间
+(NSString*)getCurrentTimes;
+(NSString*)getAllCurrentTimes;
//获取当前时间戳(以毫秒为单位)
+(NSString *)getNowTimeTimestampMillisecond;
+(NSString *)getHHTimeWithSeconds:(NSTimeInterval)s;
+ (NSString *)getTimeWithSeconds:(NSTimeInterval)s;
+(NSString *)getTimeWithDate:(NSDate *)date;
+ (BOOL)isAllowInputPasssword:(NSString *)str;
//[6-20位字符,可由中文、英文、数字及“_”、“-”组成]
+(BOOL)isValidateName:(NSString *)name;
//手机号验证
+(BOOL)checkTelNumber:(NSString *)telNumber;
+ (BOOL)isIPhoneX;
+ (BOOL)isIPhone4;
//base64编码
+(NSString *)encode:(NSString *)string;
//base64解码
+(NSString *)dencode:(NSString *)base64String;
//获取系统开机时间到1970时间差值
+(double)getLaunchSystemTime;
//将某个时间转化成时间戳
+(NSInteger)timeSwitchTimestamp:(NSString *)formatTime;
+(NSInteger)timeSwitchDayTimestamp:(NSString *)formatTime;
//GMT格式---@"d MMM yyyy HH:mm:ss 'GMT'"
+(NSString *)getGMTTimestamp;
//隐藏手机号
+(NSString *)hidNameWithStr:(NSString *)str;
@end
//
//
// CJLoadingView.h
// FeiPaiCustomer
//
// Created by newuser on 2017/9/26.
// Copyright © 2017年 cj. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CJLoadingView : UIView
-(void)startAnimation;
-(void)stopAnimation;
@end
//
//
// CJLoadingView.m
// FeiPaiCustomer
//
// Created by newuser on 2017/9/26.
// Copyright © 2017年 cj. All rights reserved.
//
#import "CJLoadingView.h"
#import "UIViewExt.h"
@interface CJLoadingView()
@property (nonatomic, strong)UIImageView* loadingImageView;
@end
@implementation CJLoadingView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self uiConfig];
}
return self;
}
-(void)uiConfig{
// self.loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 8, 5.5)];
self.loadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 21.5, 14)];
self.loadingImageView.center = CGPointMake(self.width/2, self.height/2 - 10);
[self addSubview:self.loadingImageView];
NSMutableArray *imgArray = [NSMutableArray array];
for (int i=1; i<=8; i++) {
// UIImage *image = KImageNamed([NSString stringWithFormat:@"loading_%i",i]);
// [imgArray addObject:image];
}
self.loadingImageView.animationImages = imgArray;
self.loadingImageView.animationDuration = 0.8;
self.loadingImageView.animationRepeatCount = MAXFLOAT;
}
-(void)startAnimation{
self.loadingImageView.center = CGPointMake(self.width/2, self.height/2 - 10);
[self.loadingImageView startAnimating];
}
-(void)stopAnimation{
[self.loadingImageView stopAnimating];
}
@end
//
//
// SDTool.h
// HomeHealth
//
// Created by newuser on 17/1/4.
// Copyright © 2017年 ChiJian. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface SDTool : NSObject
+(instancetype)instance;
+ (void)showHUDWithText:(NSString *)text;
+ (void)showHUDCustomSucceesWithText:(NSString *)text;
+ (void)showHUDWithText:(NSString *)text callback:(void(^)(void))callback;
+ (void)showHUDWithTextAndNotNoMessage:(NSString *)text;
//菊花
+(void)showLoadingOnView:(UIView *)view;
//主要是为了解决在找不到vc.view的时候方便使用
+(void)showLoadingOnWindowCustomFrame:(CGRect)frame;
+(void)showLoadingOnWindow;
+(void)hideLoading;
//本地打电话
+ (void)callPhone:(NSString *)phoneNum;
//判断网络状态
+ (BOOL)isExistenceNetwork;
//设置状态栏颜色
//+ (void)setStatusBarBackgroundColor:(UIColor *)color;
@end
//
//
// SDTool.m
// HomeHealth
//
// Created by newuser on 17/1/4.
// Copyright © 2017年 ChiJian. All rights reserved.
//
#import "SDTool.h"
#import "CJLoadingView.h"
#import "ZYJRealReachability.h"
#import "ZYJMBProgressHUD.h"
#import "SDGeneralDefine.h"
@interface SDTool ()
@property (strong,nonatomic)UIActivityIndicatorView *indicatorView;
@property (strong,nonatomic)CJLoadingView *loadingView;
@end
@implementation SDTool
+(instancetype)instance{
static SDTool *tl = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
tl = [[SDTool alloc]init];
});
return tl;
}
-(UIActivityIndicatorView *)indicatorView{
if (!_indicatorView) {
_indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
_indicatorView.frame = KKeyWindow.bounds;
}
return _indicatorView;
}
-(CJLoadingView *)loadingView{
if (!_loadingView) {
_loadingView = [[CJLoadingView alloc] initWithFrame:KKeyWindow.bounds];
}
return _loadingView;
}
+ (void)showHUDWithText:(NSString *)text
{
if ([text length]<=0) {
return;
}
[SDTool showWarning:KKeyWindow mText:text seconds:2.0 callback:nil];
}
+ (void)showHUDWithText:(NSString *)text callback:(void(^)(void))callback
{
[SDTool showWarning:KKeyWindow mText:text seconds:2.0 callback:callback];
}
+ (void)showHUDWithTextAndNotNoMessage:(NSString *)text{
if (text && [text respondsToSelector:@selector(length)] &&text.length && ![text isEqualToString:@"请求失败"]) {
[SDTool showHUDWithText:text];
}
}
+(void)showWarning:(UIView *)view mText:(NSString *)text seconds:(CGFloat)seconds callback:(void(^)(void))hudCallBack{
ZYJMBProgressHUD *hud = [ZYJMBProgressHUD showHUDAddedTo:view animated:YES];
NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc]init];
[pStyle setLineSpacing:0.5];
[pStyle setLineBreakMode:NSLineBreakByWordWrapping];
CGRect matchRect = [text boundingRectWithSize:CGSizeMake(190, 150) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:KFontNameMediumSize(13),NSFontAttributeName,pStyle,NSParagraphStyleAttributeName, nil] context:nil];
hud.mode = ZYJMBProgressHUDModeCustomView;
UILabel *mLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, matchRect.size.width, matchRect.size.height)];
mLabel.backgroundColor = [UIColor clearColor];
mLabel.textColor = [UIColor whiteColor];
mLabel.font = KFontNameMediumSize(13);
mLabel.textAlignment = NSTextAlignmentCenter;
mLabel.lineBreakMode = NSLineBreakByWordWrapping;
mLabel.numberOfLines = 0;
mLabel.text = text;
hud.customView = mLabel;
hud.bezelView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
if (hudCallBack) {
hud.completionBlock = [hudCallBack copy];
}
[hud hideAnimated:YES afterDelay:seconds];
}
+ (void)showHUDCustomSucceesWithText:(NSString *)text
{
if ([text length]<=0) {
return;
}
[SDTool showCustomSuccees:KKeyWindow mText:text seconds:2.0 callback:nil];
}
+(void)showCustomSuccees:(UIView *)view mText:(NSString *)text seconds:(CGFloat)seconds callback:(void(^)(void))hudCallBack{
ZYJMBProgressHUD *hud = [ZYJMBProgressHUD showHUDAddedTo:view animated:YES];
hud.mode = ZYJMBProgressHUDModeCustomView;
hud.customView = [[UIImageView alloc] initWithImage:KImageNamed(@"SDVideo_tiJiaoChengGong")];
hud.label.text = text;
hud.label.textColor = [UIColor whiteColor];
hud.label.font = KFontNameMediumSize(13);
hud.bezelView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
if (hudCallBack) {
hud.completionBlock = [hudCallBack copy];
}
[hud hideAnimated:YES afterDelay:seconds];
}
+(void)showLoadingOnView:(UIView *)view{
[SDTool instance].indicatorView.frame = view.bounds;
[view addSubview:[SDTool instance].indicatorView];
[[SDTool instance].indicatorView startAnimating];
// [SDTool instance].loadingView.frame = view.bounds;
// [view addSubview:[SDTool instance].loadingView];
// [[SDTool instance].loadingView startAnimation];
}
+(void)showLoadingOnWindowCustomFrame:(CGRect)frame{
[SDTool instance].indicatorView.frame = frame;
[KKeyWindow addSubview:[SDTool instance].indicatorView];
[[SDTool instance].indicatorView startAnimating];
// [SDTool instance].loadingView.frame = frame;
// [KKeyWindow addSubview:[SDTool instance].loadingView];
// [[SDTool instance].loadingView startAnimation];
}
+(void)showLoadingOnWindow{
[SDTool instance].indicatorView.frame = [UIScreen mainScreen].bounds;
[KKeyWindow addSubview:[SDTool instance].indicatorView];
[[SDTool instance].indicatorView startAnimating];
// [SDTool instance].loadingView.frame = [UIScreen mainScreen].bounds;
// [KKeyWindow addSubview:[SDTool instance].loadingView];
// [[SDTool instance].loadingView startAnimation];
}
+(void)hideLoading{
[[SDTool instance].indicatorView stopAnimating];
[[SDTool instance].indicatorView removeFromSuperview];
// [[SDTool instance].loadingView removeFromSuperview];
// [[SDTool instance].loadingView stopAnimation];
}
+ (void)callPhone:(NSString *)phoneNum{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:phoneNum message:@"" delegate:[SDTool instance] cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
alertView.tag = 10086;
[alertView show];
// NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneNum];
// // NSLog(@"str======%@",str);
// [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1 && alertView.tag == 10086) {
NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",alertView.title]];
[[UIApplication sharedApplication] openURL:phoneURL];
}
}
+ (BOOL)isExistenceNetwork
{
BOOL isExistenceNetwork = false;
ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
NSLog(@"Initial reachability status:%@",@(status));
if (status == RealStatusNotReachable)
{
isExistenceNetwork = false;
}
if (status == RealStatusViaWiFi)
{
isExistenceNetwork = true;
}
if (status == RealStatusViaWWAN)
{
isExistenceNetwork = true;
}
return isExistenceNetwork;
}
//设置状态栏颜色
//+ (void)setStatusBarBackgroundColor:(UIColor *)color{
// [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
// UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
// if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
// statusBar.backgroundColor = color;
// }
//}
@end
//
//
// OffcnBaseNetworking.h
// OffcnLiveSDK
//
// Created by vockey on 2018/7/25.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ZYJAFNetworking.h"
@class BaseResponse;
//token 失效的code
//static NSInteger const KtokenCode = 401;
//无网的code(此code为自定义)
static NSInteger const KNoNetWorkCode = 20170109;
typedef void(^NetworkCallBack)(BaseResponse * baseResponse);
@interface OffcnBaseNetworking : NSObject
@property(strong, nonatomic) ZYJAFHTTPSessionManager *manager;
//需要对接传入参数serviceType;httpHeaderDic
/// 设置默认服务器 1为开发服务器, 2为测试服务器, 3为正式服务器
@property (nonatomic , assign)NSInteger serviceType;
//登陆后获取的token
@property (nonatomic , copy)NSString *token;
@property (nonatomic , copy)NSString *imageBaseUrl;
@property (nonatomic , strong)NSDictionary *httpHeaderDic;
+ (instancetype)sharedInstance;
+ (void)configureHttpHeaderWithDict:(NSDictionary *)dict;
+(NSString *)get_BASEURL;
//图片服务器
+(NSString *)get_ImageBaseUrl;
//h5服务器
+(NSString *)get_h5live;
//call_server_topic服务器
+(NSString *)get_call_server_topic;
+ (void)getFromURL:(NSString *)URLString
params:(NSDictionary *)params
finished:(NetworkCallBack)finished;
+ (void)postToURL:(NSString *)URLString
bodyParams:(id)bodyParams
finished:(NetworkCallBack)finished;
+ (void)putToURL:(NSString *)URLString
bodyParams:(id)bodyParams
finished:(NetworkCallBack)finished;
+ (void)deleteToURL:(NSString *)URLString
bodyParams:(id)bodyParams
finished:(NetworkCallBack)finished;
/**
* 取消去全部
*/
- (void)cancelAllOperations;
//上传图片
//+ (void)getImgurl:(NSString *)url imgArr:(NSMutableArray *)imgArr index:(NSInteger)index finished:(NetworkCallBack)finished;
@end
@interface BaseResponse : NSObject
///返回的httpCode
@property (assign,nonatomic) NSInteger httpCode;
@property (assign,nonatomic) NSInteger code;
///返回的错误信息
@property (copy,nonatomic) NSString *errorMessage;
///是否成功
@property (assign) BOOL isSuccess;
@property(copy, nonatomic) NSString *url;//请求url
@property (nonatomic) id responseObject;
@property (nonatomic,strong) NSError *error;
@property (nonatomic, strong) NSURLSessionDataTask *task;
- (instancetype)initWithTask:(NSURLSessionDataTask *)task responseObject :(id)responseObject error :(NSError *) error;
-(BaseResponse *)checkNotReachability;
@end
//
//
// OffcnNetworkExecutor.h
// OffcnLiveSDK
//
// Created by vockey on 2018/7/25.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "OffcnBaseNetworking.h"
@interface OffcnNetworkExecutor : NSObject
+ (void)cancelAllOperations;
//客户端登陆
//+ (void)requestLoginWithPassword:(NSString *)password nickname:(NSString *)nickname hook:(NSString *)hook extensionDic:(NSDictionary *)extensionDic Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished;
//检测房间是否启录制
//+ (void)requestPlaybackRecordCheckWithAccount:(NSString *)account Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished;
//获取图片json
//+ (void)requesImgJsonWithUrlStr:(NSString *)urlStr Finished:(void(^)(BOOL success,id response,NSString *message))finished;
@end
//
//
// OffcnNetworkExecutor.m
// OffcnLiveSDK
//
// Created by vockey on 2018/7/25.
// Copyright © 2018年 中公教育. All rights reserved.
//
#import "OffcnNetworkExecutor.h"
#import "DataSafe.h"
#import "SDConfigrationNetwork.h"
@implementation OffcnNetworkExecutor
+ (void)cancelAllOperations{
[[OffcnBaseNetworking sharedInstance] cancelAllOperations];
}
//客户端登陆
//+ (void)requestLoginWithPassword:(NSString *)password nickname:(NSString *)nickname hook:(NSString *)hook extensionDic:(NSDictionary *)extensionDic Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{
//
// NSMutableDictionary *dic = [NSMutableDictionary dictionary];
// password = [password stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// [dic setObjectOnSafe:password forKey:@"password"];
// [dic setObjectOnSafe:nickname forKey:@"nickname"];
// [dic setObjectOnSafe:hook forKey:@"hook"];
//
// if (extensionDic && [extensionDic allKeys].count) {
// [extensionDic enumerateKeysAndObjectsUsingBlock:^(NSString *key, id _Nonnull obj, BOOL * _Nonnull stop) {
// if ([key isEqualToString:@"password"] || [key isEqualToString:@"nickname"] || [key isEqualToString:@"uuid"]) {
//
// }else{
// [dic setObjectOnSafe:obj forKey:key];
// }
// }];
// }
//
// [OffcnBaseNetworking postToURL:LoginURL bodyParams:dic finished:^(BaseResponse *baseResponse) {
// if (baseResponse.isSuccess) {
//
// finished(YES,baseResponse.responseObject,nil);
// }else{
//
// finished(NO,nil,baseResponse);
// }
// }];
//}
//检测房间是否启录制
//+ (void)requestPlaybackRecordCheckWithAccount:(NSString *)account Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{
//
// NSString *url = [NSString stringWithFormat:@"%@%@",Record_check,account];
// [OffcnBaseNetworking getFromURL:url params:nil finished:^(BaseResponse *baseResponse) {
// if (baseResponse.isSuccess) {
// finished(YES,baseResponse.responseObject,nil);
// }else{
// finished(NO,nil,baseResponse);
// }
// }];
//}
//获取图片json
//+ (void)requesImgJsonWithUrlStr:(NSString *)urlStr Finished:(void(^)(BOOL success,id response,NSString *message))finished{
//
// NSURL *url = [NSURL URLWithString:urlStr];
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//
// if (!connectionError) {
// if (!data) {
// data = [NSData data];
// }
// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// finished(YES,dic,nil);
// }else{
// finished(NO,nil,connectionError.localizedDescription);
// }
// }];
//}
@end
//
//
// OffcnZYJFMDBHandler.h
// OffcnLiveSDK
//
// Created by vockey on 2019/4/9.
// Copyright © 2019年 中公教育. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ZYJZYJFMDB.h"
@interface FMDBSensitiveWordsModel: NSObject
@property (nonatomic,copy) NSString *wordsBase64;
@property (nonatomic,copy) NSString *originalWords;
@end
//获取数据库中历史消息记录
typedef void (^getFMDBHistoryMessagesBlock)(NSArray *messagesArray);
typedef void (^callBackIsSuccess)(BOOL isSuccess);
@interface OffcnZYJFMDBHandler : NSObject
@property (nonatomic,strong) ZYJZYJFMDatabaseQueue *database;
@property (nonatomic,strong) ZYJZYJFMDatabaseQueue *gongGaoDataBase;
+ (OffcnZYJFMDBHandler *)sharedInstance;
//获取用户聊天数据库
- (void)getUserDBWithItemSqlitePath:(NSString *)itemSqlitePath;
/**
查询聊天记录(time正叙排序)
@param time 从第几秒开始查询
@param limit 时间范围
@param messagesBack callback
*/
- (void)getChatInfoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack;
/**
查询聊天记录(seek获取当前时间之前的)
@param time 从第几秒开始查询
@param limit 时间范围
@param messagesBack callback
*/
- (void)getChatInfoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack;
/**
查询所有聊天记录(time正叙排序)
@param messagesBack callback
*/
- (void)getChatInfoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack;
//公告
- (void)getUserGongGaoDBWithItemSqlitePath:(NSString *)itemSqlitePath;
- (void)getGongGaoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack;
- (void)getGongGaoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack;
- (void)getGongGaoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack;
//聊天本地数据库
-(void)createChatDB;
-(void)deleteSensitiveWordsDataTable;
-(void)updateSensitiveWords:(FMDBSensitiveWordsModel *)model callBack:(callBackIsSuccess)isSuccess;
-(void)getSensitiveWordsArrayWithWordsBase64:(NSString *)wordsBase64 callback:(getFMDBHistoryMessagesBlock)messagesBack;
@end
//
//
// OffcnZYJFMDBHandler.m
// OffcnLiveSDK
//
// Created by vockey on 2019/4/9.
// Copyright © 2019年 中公教育. All rights reserved.
//
#import "OffcnZYJFMDBHandler.h"
@implementation FMDBSensitiveWordsModel
@end
@interface OffcnZYJFMDBHandler()
@property (nonatomic,strong) ZYJZYJFMDatabaseQueue *chatDBDatabase;
@end
@implementation OffcnZYJFMDBHandler
static OffcnZYJFMDBHandler *FMDBHandler;
+ (OffcnZYJFMDBHandler *)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
FMDBHandler = [[self alloc] init];
});
return FMDBHandler;
}
- (instancetype)init {
if (self = [super init]) {
}
return self;
}
- (void)getUserDBWithItemSqlitePath:(NSString *)itemSqlitePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:itemSqlitePath]) {
_database = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:itemSqlitePath];
}
}
//@"SELECT * FROM xyu_room_chat order by time asc limit ?,?"
//ZYJFMResultSet *rs = [db executeQuery:sql,time,limit];
- (void)getChatInfoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
if (!_database) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat WHERE time==?"];
[_database inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
messagesBack(tmpArray);
}
}];
}
- (void)getChatInfoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
if (!_database) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat WHERE time<=? order by time asc"];
[_database inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
// NSArray *reversedArray = [[tmpArray reverseObjectEnumerator] allObjects];
messagesBack(tmpArray);
}
}];
}
- (void)getChatInfoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack{
if (!_database) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat order by time asc"];
[_database inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
messagesBack(tmpArray);
}
}];
}
- (void)getUserGongGaoDBWithItemSqlitePath:(NSString *)itemSqlitePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:itemSqlitePath]) {
_gongGaoDataBase = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:itemSqlitePath];
}
}
- (void)getGongGaoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
if (!_gongGaoDataBase) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce WHERE time==? order by time desc"];
[_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
messagesBack(tmpArray);
}
}];
}
- (void)getGongGaoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
if (!_gongGaoDataBase) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce WHERE time<=? order by time desc"];
[_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
// NSArray *reversedArray = [[tmpArray reverseObjectEnumerator] allObjects];
messagesBack(tmpArray);
}
}];
}
- (void)getGongGaoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack{
if (!_gongGaoDataBase) {
return;
}
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce order by time desc"];
[_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调历史消息记录
if (messagesBack) {
messagesBack(tmpArray);
}
}];
}
#pragma mark - 聊天本地数据库
//创建聊天本地数据库
NS_INLINE ZYJZYJFMDatabaseQueue * getFMDBInstance(){
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"ZYJFMDBChat.db"];
ZYJZYJFMDatabaseQueue *database = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:filePath];
return database;
}
-(void)createChatDB{
_chatDBDatabase = getFMDBInstance();
[self createTable];
}
-(void)createTable{
if (!_chatDBDatabase) {
_chatDBDatabase = getFMDBInstance();
}
// [self deleteSensitiveWordsDataTable];
//敏感词更新表
NSString *creatSensitiveWordsSqlStr = @"create table sensitiveWords(wordsBase64 varchar(1000000),originalWords varchar(1000000));";
[_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
if (![db tableExists:@"sensitiveWords"]) {
BOOL resCreatSensitiveWordsSqlStr = [db executeUpdate:creatSensitiveWordsSqlStr];
if (!resCreatSensitiveWordsSqlStr) {
NSLog(@"error when creating database table");
NSLog(@"%d",db.lastErrorCode);
NSLog(@"%@",db.lastErrorMessage);
}
}
}];
}
-(void)deleteSensitiveWordsDataTable{
if (!_chatDBDatabase) {
_chatDBDatabase = getFMDBInstance();
}
NSString *sqlSensitiveWordsStr = @"DROP TABLE sensitiveWords";
[_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
BOOL resSensitiveWordsSqlStr = [db executeUpdate:sqlSensitiveWordsStr];
if (!resSensitiveWordsSqlStr) {
NSLog(@"error when drop database table");
NSLog(@"%d",db.lastErrorCode);
NSLog(@"%@",db.lastErrorMessage);
}
}];
}
-(void)updateSensitiveWords:(FMDBSensitiveWordsModel *)model callBack:(callBackIsSuccess)isSuccess{
if (!_chatDBDatabase) {
_chatDBDatabase = getFMDBInstance();
}
[_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
//插入记录到表中
NSString *sqlStr = @"update sensitiveWords set originalWords = ? where wordsBase64 = ?";
BOOL result = [db executeUpdate:sqlStr,model.originalWords,model.wordsBase64];
if (!result) {
NSLog(@"error when insert into database table");
NSLog(@"%d",db.lastErrorCode);
NSLog(@"%@",db.lastErrorMessage);
}
if (isSuccess) {
isSuccess(result);
}
}];
}
-(void)getSensitiveWordsArrayWithWordsBase64:(NSString *)wordsBase64 callback:(getFMDBHistoryMessagesBlock)messagesBack{
if (!_chatDBDatabase) {
_chatDBDatabase = getFMDBInstance();
}
NSString * sql = @"SELECT * FROM sensitiveWords where wordsBase64 = ?";
[_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
ZYJZYJFMResultSet *rs = [db executeQuery:sql,wordsBase64];
NSMutableArray *tmpArray = [NSMutableArray array];
while ([rs next]) {
[tmpArray addObject:rs.resultDictionary];
}
//回调匹配的敏感词
if (messagesBack) {
messagesBack(tmpArray);
}
}];
}
@end
#import <Foundation/Foundation.h>
#import <Foundation/Foundation.h>
FOUNDATION_EXPORT double ZYJZYJFMDBVersionNumber;
FOUNDATION_EXPORT const unsigned char ZYJZYJFMDBVersionString[];
#import "ZYJZYJFMDatabase.h"
#import "ZYJZYJFMResultSet.h"
#import "ZYJZYJFMDatabaseAdditions.h"
#import "ZYJZYJFMDatabaseQueue.h"
#import "ZYJZYJFMDatabasePool.h"
//
//
// ZYJZYJFMDatabaseAdditions.h
// ZYJZYJFMdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ZYJZYJFMDatabase.h"
NS_ASSUME_NONNULL_BEGIN
/** Category of additions for `<ZYJZYJFMDatabase>` class.
### See also
- `<ZYJZYJFMDatabase>`
*/
@interface ZYJZYJFMDatabase (ZYJZYJFMDatabaseAdditions)
///----------------------------------------
/// @name Return results of SQL to variable
///----------------------------------------
/** Return `int` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `int` value.
@note This is not available from Swift.
*/
- (int)intForQuery:(NSString*)query, ...;
/** Return `long` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `long` value.
@note This is not available from Swift.
*/
- (long)longForQuery:(NSString*)query, ...;
/** Return `BOOL` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `BOOL` value.
@note This is not available from Swift.
*/
- (BOOL)boolForQuery:(NSString*)query, ...;
/** Return `double` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `double` value.
@note This is not available from Swift.
*/
- (double)doubleForQuery:(NSString*)query, ...;
/** Return `NSString` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSString` value.
@note This is not available from Swift.
*/
- (NSString * _Nullable)stringForQuery:(NSString*)query, ...;
/** Return `NSData` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSData` value.
@note This is not available from Swift.
*/
- (NSData * _Nullable)dataForQuery:(NSString*)query, ...;
/** Return `NSDate` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSDate` value.
@note This is not available from Swift.
*/
- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...;
// Notice that there's no dataNoCopyForQuery:.
// That would be a bad idea, because we close out the result set, and then what
// happens to the data that we just didn't copy? Who knows, not I.
///--------------------------------
/// @name Schema related operations
///--------------------------------
/** Does table exist in database?
@param tableName The name of the table being looked for.
@return `YES` if table found; `NO` if not found.
*/
- (BOOL)tableExists:(NSString*)tableName;
/** The schema of the database.
This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
- `type` - The type of entity (e.g. table, index, view, or trigger)
- `name` - The name of the object
- `tbl_name` - The name of the table to which the object references
- `rootpage` - The page number of the root b-tree page for tables and indices
- `sql` - The SQL that created the entity
@return `ZYJZYJFMResultSet` of schema; `nil` on error.
@see [SQLite File Format](http://www.sqlite.org/fileformat.html)
*/
- (ZYJZYJFMResultSet * _Nullable)getSchema;
/** The schema of the database.
This will be the schema for a particular table as report by SQLite `PRAGMA`, for example:
PRAGMA table_info('employees')
This will report:
- `cid` - The column ID number
- `name` - The name of the column
- `type` - The data type specified for the column
- `notnull` - whether the field is defined as NOT NULL (i.e. values required)
- `dflt_value` - The default value for the column
- `pk` - Whether the field is part of the primary key of the table
@param tableName The name of the table for whom the schema will be returned.
@return `ZYJZYJFMResultSet` of schema; `nil` on error.
@see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info)
*/
- (ZYJZYJFMResultSet * _Nullable)getTableSchema:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return `YES` if column exists in table in question; `NO` otherwise.
*/
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return `YES` if column exists in table in question; `NO` otherwise.
@see columnExists:inTableWithName:
@warning Deprecated - use `<columnExists:inTableWithName:>` instead.
*/
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead");
/** Validate SQL statement
This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`.
@param sql The SQL statement being validated.
@param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned.
@return `YES` if validation succeeded without incident; `NO` otherwise.
*/
- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable *)error;
///-----------------------------------
/// @name Application identifier tasks
///-----------------------------------
/** Retrieve application ID
@return The `uint32_t` numeric value of the application ID.
@see setApplicationID:
*/
@property (nonatomic) uint32_t applicationID;
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
/** Retrieve application ID string
@see setApplicationIDString:
*/
@property (nonatomic, retain) NSString *applicationIDString;
#endif
///-----------------------------------
/// @name user version identifier tasks
///-----------------------------------
/** Retrieve user version
@see setUserVersion:
*/
@property (nonatomic) uint32_t userVersion;
@end
NS_ASSUME_NONNULL_END
//
//
// ZYJZYJFMDatabaseAdditions.m
// ZYJZYJFMdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import "ZYJZYJFMDatabase.h"
#import "ZYJZYJFMDatabaseAdditions.h"
#import "TargetConditionals.h"
#if ZYJZYJFMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
@interface ZYJZYJFMDatabase (PrivateStuff)
- (ZYJZYJFMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args;
@end
@implementation ZYJZYJFMDatabase (ZYJZYJFMDatabaseAdditions)
#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \
va_list args; \
va_start(args, query); \
ZYJZYJFMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \
va_end(args); \
if (![resultSet next]) { return (type)0; } \
type ret = [resultSet sel:0]; \
[resultSet close]; \
[resultSet setParentDB:nil]; \
return ret;
- (NSString *)stringForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex);
}
- (int)intForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex);
}
- (long)longForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex);
}
- (BOOL)boolForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex);
}
- (double)doubleForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex);
}
- (NSData*)dataForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex);
}
- (NSDate*)dateForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex);
}
- (BOOL)tableExists:(NSString*)tableName {
tableName = [tableName lowercaseString];
ZYJZYJFMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName];
//if at least one next exists, table exists
BOOL returnBool = [rs next];
//close and free object
[rs close];
return returnBool;
}
/*
get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
check if table exist in database (patch from OZLB)
*/
- (ZYJZYJFMResultSet * _Nullable)getSchema {
//result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
ZYJZYJFMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"];
return rs;
}
/*
get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
*/
- (ZYJZYJFMResultSet * _Nullable)getTableSchema:(NSString*)tableName {
//result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
ZYJZYJFMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]];
return rs;
}
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName {
BOOL returnBool = NO;
tableName = [tableName lowercaseString];
columnName = [columnName lowercaseString];
ZYJZYJFMResultSet *rs = [self getTableSchema:tableName];
//check if column is present in table schema
while ([rs next]) {
if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) {
returnBool = YES;
break;
}
}
//If this is not done ZYJZYJFMDatabase instance stays out of pool
[rs close];
return returnBool;
}
- (uint32_t)applicationID {
#if SQLITE_VERSION_NUMBER >= 3007017
uint32_t r = 0;
ZYJZYJFMResultSet *rs = [self executeQuery:@"pragma application_id"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"ZYJZYJFMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return 0;
#endif
}
- (void)setApplicationID:(uint32_t)appID {
#if SQLITE_VERSION_NUMBER >= 3007017
NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID];
ZYJZYJFMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"ZYJZYJFMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
#endif
}
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
- (NSString*)applicationIDString {
#if SQLITE_VERSION_NUMBER >= 3007017
NSString *s = NSFileTypeForHFSTypeCode([self applicationID]);
assert([s length] == 6);
s = [s substringWithRange:NSMakeRange(1, 4)];
return s;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"ZYJZYJFMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return nil;
#endif
}
- (void)setApplicationIDString:(NSString*)s {
#if SQLITE_VERSION_NUMBER >= 3007017
if ([s length] != 4) {
NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]);
}
[self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])];
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Application ID functions require SQLite 3.7.17", @"ZYJZYJFMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
#endif
}
#endif
- (uint32_t)userVersion {
uint32_t r = 0;
ZYJZYJFMResultSet *rs = [self executeQuery:@"pragma user_version"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
}
- (void)setUserVersion:(uint32_t)version {
NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version];
ZYJZYJFMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) {
return [self columnExists:columnName inTableWithName:tableName];
}
#pragma clang diagnostic pop
- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error {
sqlite3_stmt *pStmt = NULL;
BOOL validationSucceeded = YES;
int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0);
if (rc != SQLITE_OK) {
validationSucceeded = NO;
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:[self lastErrorCode]
userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage]
forKey:NSLocalizedDescriptionKey]];
}
}
sqlite3_finalize(pStmt);
return validationSucceeded;
}
@end
//
//
// ZYJZYJFMDatabasePool.h
// ZYJZYJFMdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class ZYJZYJFMDatabase;
/** Pool of `<ZYJZYJFMDatabase>` objects.
### See also
- `<ZYJZYJFMDatabaseQueue>`
- `<ZYJZYJFMDatabase>`
@warning Before using `ZYJZYJFMDatabasePool`, please consider using `<ZYJZYJFMDatabaseQueue>` instead.
If you really really really know what you're doing and `ZYJZYJFMDatabasePool` is what
you really really need (ie, you're using a read only database), OK you can use
it. But just be careful not to deadlock!
For an example on deadlocking, search for:
`ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_ZYJZYJFMDATABASEQUEUE_INSTEAD`
in the main.m file.
*/
@interface ZYJZYJFMDatabasePool : NSObject
/** Database path */
@property (atomic, copy, nullable) NSString *path;
/** Delegate object */
@property (atomic, assign, nullable) id delegate;
/** Maximum number of databases to create */
@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
/** Open flags */
@property (atomic, readonly) int openFlags;
/** Custom virtual file system name */
@property (atomic, copy, nullable) NSString *vfsName;
///---------------------
/// @name Initialization
///---------------------
/** Create pool using path.
@param aPath The file path of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath;
/** Create pool using file URL.
@param url The file `NSURL` of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url;
/** Create pool using path and specified flags
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create pool using file URL and specified flags
@param url The file `NSURL` of the database.
@param openFlags Flags passed to the openWithFlags method of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create pool using path.
@param aPath The file path of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath;
/** Create pool using file URL.
@param url The file `NSURL of the database.
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags;
/** Create pool using file URL and specified flags.
@param url The file `NSURL` of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Create pool using file URL and specified flags.
@param url The file `NSURL` of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@param vfsName The name of a custom virtual file system
@return The `ZYJZYJFMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName;
/** Returns the Class of 'ZYJZYJFMDatabase' subclass, that will be used to instantiate database object.
Subclasses can override this method to return specified Class of 'ZYJZYJFMDatabase' subclass.
@return The Class of 'ZYJZYJFMDatabase' subclass, that will be used to instantiate database object.
*/
+ (Class)databaseClass;
///------------------------------------------------
/// @name Keeping track of checked in/out databases
///------------------------------------------------
/** Number of checked-in databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases;
/** Number of checked-out databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases;
/** Total number of databases in pool
*/
@property (nonatomic, readonly) NSUInteger countOfOpenDatabases;
/** Release all databases in pool */
- (void)releaseAllDatabases;
///------------------------------------------
/// @name Perform database operations in pool
///------------------------------------------
/** Synchronously perform database operations in pool.
@param block The code to be run on the `ZYJZYJFMDatabasePool` pool.
*/
- (void)inDatabase:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db))block;
/** Synchronously perform database operations in pool using transaction.
@param block The code to be run on the `ZYJZYJFMDatabasePool` pool.
@warning Unlike SQLite's `BEGIN TRANSACTION`, this method currently performs
an exclusive transaction, not a deferred transaction. This behavior
is likely to change in future versions of ZYJZYJFMDB, whereby this method
will likely eventually adopt standard SQLite behavior and perform
deferred transactions. If you really need exclusive tranaction, it is
recommended that you use `inExclusiveTransaction`, instead, not only
to make your intent explicit, but also to future-proof your code.
*/
- (void)inTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using exclusive transaction.
@param block The code to be run on the `ZYJZYJFMDatabasePool` pool.
*/
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using deferred transaction.
@param block The code to be run on the `ZYJZYJFMDatabasePool` pool.
*/
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using immediate transactions.
@param block The code to be run on the queue of `ZYJZYJFMDatabaseQueue`
*/
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using save point.
@param block The code to be run on the `ZYJZYJFMDatabasePool` pool.
@return `NSError` object if error; `nil` if successful.
@warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[ZYJZYJFMDatabase startSavePointWithName:error:]>` instead.
*/
- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block;
@end
/** ZYJZYJFMDatabasePool delegate category
This is a category that defines the protocol for the ZYJZYJFMDatabasePool delegate
*/
@interface NSObject (ZYJZYJFMDatabasePoolDelegate)
/** Asks the delegate whether database should be added to the pool.
@param pool The `ZYJZYJFMDatabasePool` object.
@param database The `ZYJZYJFMDatabase` object.
@return `YES` if it should add database to pool; `NO` if not.
*/
- (BOOL)databasePool:(ZYJZYJFMDatabasePool*)pool shouldAddDatabaseToPool:(ZYJZYJFMDatabase*)database;
/** Tells the delegate that database was added to the pool.
@param pool The `ZYJZYJFMDatabasePool` object.
@param database The `ZYJZYJFMDatabase` object.
*/
- (void)databasePool:(ZYJZYJFMDatabasePool*)pool didAddDatabase:(ZYJZYJFMDatabase*)database;
@end
NS_ASSUME_NONNULL_END
//
//
// ZYJZYJFMDatabasePool.m
// ZYJZYJFMdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#if ZYJZYJFMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#endif
#import "ZYJZYJFMDatabasePool.h"
#import "ZYJZYJFMDatabase.h"
typedef NS_ENUM(NSInteger, ZYJZYJFMDBTransaction) {
ZYJZYJFMDBTransactionExclusive,
ZYJZYJFMDBTransactionDeferred,
ZYJZYJFMDBTransactionImmediate,
};
@interface ZYJZYJFMDatabasePool () {
dispatch_queue_t _lockQueue;
NSMutableArray *_databaseInPool;
NSMutableArray *_databaseOutPool;
}
- (void)pushDatabaseBackInPool:(ZYJZYJFMDatabase*)db;
- (ZYJZYJFMDatabase*)db;
@end
@implementation ZYJZYJFMDatabasePool
@synthesize path=_path;
@synthesize delegate=_delegate;
@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;
@synthesize openFlags=_openFlags;
+ (instancetype)databasePoolWithPath:(NSString *)aPath {
return ZYJZYJFMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
}
+ (instancetype)databasePoolWithURL:(NSURL *)url {
return ZYJZYJFMDBReturnAutoreleased([[self alloc] initWithPath:url.path]);
}
+ (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags {
return ZYJZYJFMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]);
}
+ (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags {
return ZYJZYJFMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]);
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName {
return [self initWithPath:url.path flags:openFlags vfs:vfsName];
}
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName {
self = [super init];
if (self != nil) {
_path = [aPath copy];
_lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"ZYJZYJFMdb.%@", self] UTF8String], NULL);
_databaseInPool = ZYJZYJFMDBReturnRetained([NSMutableArray array]);
_databaseOutPool = ZYJZYJFMDBReturnRetained([NSMutableArray array]);
_openFlags = openFlags;
_vfsName = [vfsName copy];
}
return self;
}
- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags {
return [self initWithPath:aPath flags:openFlags vfs:nil];
}
- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags {
return [self initWithPath:url.path flags:openFlags vfs:nil];
}
- (instancetype)initWithPath:(NSString*)aPath {
// default flags for sqlite3_open
return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
}
- (instancetype)initWithURL:(NSURL *)url {
return [self initWithPath:url.path];
}
- (instancetype)init {
return [self initWithPath:nil];
}
+ (Class)databaseClass {
return [ZYJZYJFMDatabase class];
}
- (void)dealloc {
_delegate = 0x00;
ZYJZYJFMDBRelease(_path);
ZYJZYJFMDBRelease(_databaseInPool);
ZYJZYJFMDBRelease(_databaseOutPool);
ZYJZYJFMDBRelease(_vfsName);
if (_lockQueue) {
ZYJZYJFMDBDispatchQueueRelease(_lockQueue);
_lockQueue = 0x00;
}
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)executeLocked:(void (^)(void))aBlock {
dispatch_sync(_lockQueue, aBlock);
}
- (void)pushDatabaseBackInPool:(ZYJZYJFMDatabase*)db {
if (!db) { // db can be null if we set an upper bound on the # of databases to create.
return;
}
[self executeLocked:^() {
if ([self->_databaseInPool containsObject:db]) {
[[NSException exceptionWithName:@"Database already in pool" reason:@"The ZYJZYJFMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
}
[self->_databaseInPool addObject:db];
[self->_databaseOutPool removeObject:db];
}];
}
- (ZYJZYJFMDatabase*)db {
__block ZYJZYJFMDatabase *db;
[self executeLocked:^() {
db = [self->_databaseInPool lastObject];
BOOL shouldNotifyDelegate = NO;
if (db) {
[self->_databaseOutPool addObject:db];
[self->_databaseInPool removeLastObject];
}
else {
if (self->_maximumNumberOfDatabasesToCreate) {
NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count];
if (currentCount >= self->_maximumNumberOfDatabasesToCreate) {
NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
return;
}
}
db = [[[self class] databaseClass] databaseWithPath:self->_path];
shouldNotifyDelegate = YES;
}
//This ensures that the db is opened before returning
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName];
#else
BOOL success = [db open];
#endif
if (success) {
if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) {
[db close];
db = 0x00;
}
else {
//It should not get added in the pool twice if lastObject was found
if (![self->_databaseOutPool containsObject:db]) {
[self->_databaseOutPool addObject:db];
if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) {
[self->_delegate databasePool:self didAddDatabase:db];
}
}
}
}
else {
NSLog(@"Could not open up the database at path %@", self->_path);
db = 0x00;
}
}];
return db;
}
- (NSUInteger)countOfCheckedInDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseInPool count];
}];
return count;
}
- (NSUInteger)countOfCheckedOutDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count];
}];
return count;
}
- (NSUInteger)countOfOpenDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count] + [self->_databaseInPool count];
}];
return count;
}
- (void)releaseAllDatabases {
[self executeLocked:^() {
[self->_databaseOutPool removeAllObjects];
[self->_databaseInPool removeAllObjects];
}];
}
- (void)inDatabase:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db))block {
ZYJZYJFMDatabase *db = [self db];
block(db);
[self pushDatabaseBackInPool:db];
}
- (void)beginTransaction:(ZYJZYJFMDBTransaction)transaction withBlock:(void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
BOOL shouldRollback = NO;
ZYJZYJFMDatabase *db = [self db];
switch (transaction) {
case ZYJZYJFMDBTransactionExclusive:
[db beginTransaction];
break;
case ZYJZYJFMDBTransactionDeferred:
[db beginDeferredTransaction];
break;
case ZYJZYJFMDBTransactionImmediate:
[db beginImmediateTransaction];
break;
}
block(db, &shouldRollback);
if (shouldRollback) {
[db rollback];
}
else {
[db commit];
}
[self pushDatabaseBackInPool:db];
}
- (void)inTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
[self beginTransaction:ZYJZYJFMDBTransactionExclusive withBlock:block];
}
- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
[self beginTransaction:ZYJZYJFMDBTransactionDeferred withBlock:block];
}
- (void)inExclusiveTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
[self beginTransaction:ZYJZYJFMDBTransactionExclusive withBlock:block];
}
- (void)inImmediateTransaction:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
[self beginTransaction:ZYJZYJFMDBTransactionImmediate withBlock:block];
}
- (NSError*)inSavePoint:(__attribute__((noescape)) void (^)(ZYJZYJFMDatabase *db, BOOL *rollback))block {
#if SQLITE_VERSION_NUMBER >= 3007000
static unsigned long savePointIdx = 0;
NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
ZYJZYJFMDatabase *db = [self db];
NSError *err = 0x00;
if (![db startSavePointWithName:name error:&err]) {
[self pushDatabaseBackInPool:db];
return err;
}
block(db, &shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[db rollbackToSavePointWithName:name error:&err];
}
[db releaseSavePointWithName:name error:&err];
[self pushDatabaseBackInPool:db];
return err;
#else
NSString *errorMessage = NSLocalizedStringFromTable(@"Save point functions require SQLite 3.7", @"ZYJZYJFMDB", nil);
if (self.logsErrors) NSLog(@"%@", errorMessage);
return [NSError errorWithDomain:@"ZYJZYJFMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}];
#endif
}
@end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment