//MARK: - 视图设置
/**!
* 设置视图阴影
*
* @para uView UIView 目标视图
* @para shadowColor UIColor 阴影颜色
* @para shadowOpacity Float 阴影透明度(0.0 ~ 1.0,默认0.5)
* @para shadowRadius CGFloat 阴影半径(默认3)
* @para shadowOffset CGSize 阴影偏移,x向右偏移,y向下偏移,默认(0, -3)
*/
+(void)setViewShadowStyle:(UIView *)uView AndShadowColor:(UIColor *)sColor AndShadowOpacity:(CGFloat)sOpacity AndShadowRadius:(CGFloat)sRadius WithShadowOffset:(CGSize)sOffset{
//shadowColor阴影颜色
uView.layer.shadowColor = [sColor CGColor];
//阴影透明度
uView.layer.shadowOpacity = sOpacity;
//阴影半径,默认3
uView.layer.shadowRadius = sRadius;
//shadowOffset阴影偏移,
//x向右偏移(正值),y向下偏移(正值),默认(0, -3),这个跟shadowRadius配合使用
uView.layer.shadowOffset = sOffset;
//设置阴影此属性要设置为 false(masksToBounds 会造成离屏渲染)
//uView.layer.masksToBounds = false
UIBezierPath *p = [UIBezierPath bezierPathWithRect:uView.bounds];
if(uView.layer.cornerRadius > 0){
//存在圆角
p = [UIBezierPath bezierPathWithRoundedRect:uView.bounds cornerRadius:uView.layer.cornerRadius];
}
uView.layer.shadowPath = p.CGPath;
}
/**! 视图抖动动画 */
+(void)shakeAnimationForView:(UIView *)view{
// 获取到当前的View
CALayer *viewLayer = view.layer;
// 获取当前View的位置
CGPoint position = viewLayer.position;
// 移动的两个终点位置
CGPoint x = CGPointMake(position.x + 10, position.y);
CGPoint y = CGPointMake(position.x - 10, position.y);
// 设置动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
// 设置运动形式
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
// 设置开始位置
[animation setFromValue:[NSValue valueWithCGPoint:x]];
// 设置结束位置
[animation setToValue:[NSValue valueWithCGPoint:y]];
// 设置自动反转
[animation setAutoreverses:YES];
// 设置时间
[animation setDuration:.06];
// 设置次数
[animation setRepeatCount:3];
// 添加上动画
[viewLayer addAnimation:animation forKey:nil];
}
//MARK: - 相关动画设置
/**! tabbar侧滑动画 */
+(void)tabBarChangeAnimation:(UITabBarController *)tabBarController WithDirection:(NSInteger)direction{
CATransition *transition = [[CATransition alloc] init];
transition.duration = 0.2;
transition.type = kCATransitionMoveIn;//kCATransitionReveal
if(direction == 0) {
transition.subtype = kCATransitionFromLeft;
}
else{
transition.subtype = kCATransitionFromRight;
}
//transition.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionDefault];
[[[tabBarController view] layer] addAnimation:transition forKey:@"reveal"];//switchView
}
//MARK: - Tabbar相关设置
/**!
* 设置tabBar的尺寸
* 调用方法:自定义View 继承自 UITabBarController,在 viewWillLayoutSubviews 中使用:
* [Utils setTabbarHeight:self.tabBar];
*/
+(void)setTabbarHeight:(UITabBar *)tabBar{
CGRect rectTabbar = tabBar.frame;
if (rectTabbar.size.height >= 49) {
rectTabbar.size.height = K_APP_TABBAR_HEIGHT;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGFloat statusBarHeight = statusBarFrame.size.height;
if (statusBarHeight > 20.0) {
rectTabbar.origin.y = K_APP_HEIGHT - K_APP_TABBAR_HEIGHT - 20;
}
else{
rectTabbar.origin.y = K_APP_HEIGHT - K_APP_TABBAR_HEIGHT;
}
tabBar.frame = rectTabbar;
}
}
/**!
* 设置tabBar的尺寸 顶部边框线
*/
+(void)setTopLine:(UITabBar *)tabBar{
// [S] 顶部边框线
NSData *topLineData = [[NSUserDefaults standardUserDefaults] dataForKey:K_APP_TABBAR_TOP_LINE];
if (topLineData == nil || [topLineData length] <= 0) {
CGRect rect = CGRectMake(0, 0, K_APP_WIDTH, 0.1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 223.0, 223.0, 223.0, 1.0);
CGContextFillRect(context, rect);
UIImage *imgTemp = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
topLineData = UIImagePNGRepresentation(imgTemp);
[[NSUserDefaults standardUserDefaults] setObject:topLineData forKey:K_APP_TABBAR_TOP_LINE];
[[NSUserDefaults standardUserDefaults] synchronize];
}
tabBar.shadowImage = [UIImage imageWithData:topLineData];
// [E] 顶部边框线
}
/**!
* 清除tabbar顶部边线
*/
+(void)clearnTabBarTopLine:(UITabBar *)tabBar{
NSData *clearnLineData = [[NSUserDefaults standardUserDefaults] dataForKey:K_APP_TABBAR_CLEARN_IMAGE];
if (clearnLineData == nil || [clearnLineData length] <= 0) {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.0);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
clearnLineData = UIImagePNGRepresentation(theImage);
[[NSUserDefaults standardUserDefaults] setObject:clearnLineData forKey:K_APP_TABBAR_CLEARN_IMAGE];
[[NSUserDefaults standardUserDefaults] synchronize];
}
tabBar.backgroundImage = [UIImage imageWithData:clearnLineData];
tabBar.shadowImage = [UIImage imageWithData:clearnLineData];
}
//MARK: - 图片相关处理
/**! 图片不变形处理 */
+(void)imgNoTransformation:(UIImageView *)img{
img.contentMode = UIViewContentModeScaleAspectFill;
img.clipsToBounds = YES; //是否剪切掉超出 UIImageView 范围的图片
img.contentScaleFactor = [UIScreen mainScreen].scale;
}
//MARK: - 信息验证
/**!
* 验证手机号
* @return true 通过验证
*/
+(BOOL)checkPhoneNo:(NSString *)strPhoneNo {
if (!strPhoneNo || [strPhoneNo isEqualToString:@""]) {
return NO;
}
NSString *strRegex = @"^1[34578]([0-9]{9})$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegex];
return [predicate evaluateWithObject:strPhoneNo];
}
/**!
* 验证邮箱
* @return true 通过验证
*/
+(BOOL)checkEmail:(NSString *)strEmail {
if (!strEmail || [strEmail isEqualToString:@""]) {
return NO;
}
NSString *strRegex = @"^[A-Z0-9a-z_\\.\\-]+\\@([A-Za-z0-9\\-]+\\.)+([A-Za-z0-9])+$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegex];
return [predicate evaluateWithObject:strEmail];
}
/**!
* 验证密码(密码为6~20位的数字字母)
* @return true 通过验证
*/
+(BOOL)checkPassword:(NSString *)strPwd {
if (!strPwd || [strPwd isEqualToString:@""]) {
return NO;
}
//长度限制
NSUInteger length = strPwd.length;
if (length < 6 || length > 20) {
return NO;
}
//是否含有Emoji 表情
if ([Utils stringContainsEmoji:strPwd]) {
return NO;
}
NSString *strRegex = @"^[A-Za-z0-9 ]{6,20}$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegex];
return [predicate evaluateWithObject:strPwd];
}
/**!
* 验证验证码(长度6位的数字字母)
* @return true 通过验证
*/
+(BOOL)checkPhoneCode:(NSString *)strCode {
if (!strCode || [strCode isEqualToString:@""]) {
return NO;
}
//长度限制
NSUInteger length = strCode.length;
if (length > 6) {
return NO;
}
NSString *strRegex = @"^[0-9a-zA-Z]{4,6}$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegex];
return [predicate evaluateWithObject:strCode];
}
/**!
* 验证姓名(字母或中文)
* @params strName NSString
* @params len NSInteger 长度
* @return true 通过验证
*/
+(BOOL)checkName:(NSString *)strName AndLength:(NSInteger)len {
if (!strName || [strName isEqualToString:@""]) {
return NO;
}
//长度限制
NSUInteger length = strName.length;
if (length > len) {
return NO;
}
NSString *strRegex = [NSString stringWithFormat:@"^[A-Za-z\\u4e00-\\u9fa5]{2,%lD}$",len];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegex];
return [predicate evaluateWithObject:strName];
}
/**!
* 验证身份证(15/18位)
* @params value NSString
* @return true 通过验证
*/
+(BOOL)checkIDCardNumber:(NSString *)value {
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSInteger length = 0;
if (!value) return NO;
else {
length = value.length;
//不满足15位和18位,即身份证错误
if (length != 15 && length != 18) return NO;
}
// 省份代码
NSArray *areasArray = @[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
// 检测省份身份行政区代码
NSString *valueStart2 = [value substringToIndex:2];
BOOL areaFlag = NO; //标识省份代码是否正确
for (NSString *areaCode in areasArray) {
if ([areaCode isEqualToString:valueStart2]) {
areaFlag = YES;
break;
}
}
if (!areaFlag) return NO;
NSRegularExpression *regularExpression;
NSUInteger numberofMatch;
int year = 0;
//分为15位、18位身份证进行校验
switch (length) {
case 15:
//获取年份对应的数字
year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
//创建正则表达式 NSRegularExpressionCaseInsensitive:不区分字母大小写的模式
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
else{
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
//使用正则表达式匹配字符串 NSMatchingReportProgress:找到最长的匹配字符串后调用block回调
numberofMatch = [regularExpression numberOfMatchesInString:value
options:NSMatchingReportProgress
range:NSMakeRange(0, value.length)];
if(numberofMatch >0) return YES;
else return NO;
case 18:
year = [value substringWithRange:NSMakeRange(6,4)].intValue;
if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
else{
regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$"
options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
}
numberofMatch = [regularExpression numberOfMatchesInString:value
options:NSMatchingReportProgress
range:NSMakeRange(0, value.length)];
if(numberofMatch >0) {
//1:校验码的计算方法 身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2。将这17位数字和系数相乘的结果相加。
int S = [value substringWithRange:NSMakeRange(0,1)].intValue*7 + [value substringWithRange:NSMakeRange(10,1)].intValue *7 + [value substringWithRange:NSMakeRange(1,1)].intValue*9 + [value substringWithRange:NSMakeRange(11,1)].intValue *9 + [value substringWithRange:NSMakeRange(2,1)].intValue*10 + [value substringWithRange:NSMakeRange(12,1)].intValue *10 + [value substringWithRange:NSMakeRange(3,1)].intValue*5 + [value substringWithRange:NSMakeRange(13,1)].intValue *5 + [value substringWithRange:NSMakeRange(4,1)].intValue*8 + [value substringWithRange:NSMakeRange(14,1)].intValue *8 + [value substringWithRange:NSMakeRange(5,1)].intValue*4 + [value substringWithRange:NSMakeRange(15,1)].intValue *4 + [value substringWithRange:NSMakeRange(6,1)].intValue*2 + [value substringWithRange:NSMakeRange(16,1)].intValue *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
//2:用加出来和除以11,看余数是多少?余数只可能有0-1-2-3-4-5-6-7-8-9-10这11个数字
int Y = S %11;
NSString *M =@"F";
NSString *JYM =@"10X98765432";
M = [JYM substringWithRange:NSMakeRange(Y,1)];
// 3:获取校验位
NSString *lastStr = [value substringWithRange:NSMakeRange(17,1)];
NSLog(@"%@",M);
NSLog(@"%@",[value substringWithRange:NSMakeRange(17,1)]);
//4:检测ID的校验位
if ([lastStr isEqualToString:@"x"]) {
if ([M isEqualToString:@"X"]) return YES;
else return NO;
}
else{
if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) return YES;
else return NO;
}
}
else return NO;
default:
return NO;
}
}
//MARK: - 相关App是否有安装检测
//https://www.zhihu.com/question/19907735
/**! 是否有安装QQ */
+(BOOL)isInstallForQQ{
//QQ mqq:// 或 mqqiapi://
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqqiapi://"]]) {
return NO;
}
}
return YES;
}
/**! 是否有安装微信 */
+(BOOL)isInstallForWechat {
//微信 weixin:// 或 wechat://
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]) {
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]]) {
return NO;
}
}
return YES;
}
/**! 是否有安装新浪微博 */
+(BOOL)isInstallForSina {
//新浪微博 weibo:// 或 sinaweibo://
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weibo://"]]) {
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"sinaweibo://"]]) {
return NO;
}
}
return YES;
}
/**! 是否有安装支付宝 */
+(BOOL)isInstallForAliPay {
//支付宝 alipay://
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]]) {
return NO;
}
return YES;
}
//MARK: - 获取设备信息
/**!
* 获取当前设备的UUID
*/
+(NSString *)getCurrentDeviceUUID {
NSUUID *uuid = [[UIDevice currentDevice] identifierForVendor];
return [uuid UUIDString];
}
/**!
* 获取手机具体型号
* 需要添加 #import <sys/utsname.h> 引用
* 定义:
@interface UIDevice (Information)
/// 手机具体型号
@property(nonatomic,copy,readonly) NSString *modelName;
@end
* 调用:[UIDevice currentDevice].modelName
*/
- (NSString *)modelName{
NSString *_mn = @"iPhone";
struct utsname systemInfo;
uname(&systemInfo);
NSString *identifier = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
NSDictionary<NSString *,NSString*> *dicTemp = @{
//TODO:iPod touch
@"iPod1,1":@"iPod touch",
@"iPod2,1":@"iPod touch (2nd generation)",
@"iPod3,1":@"iPod touch (3rd generation)",
@"iPod4,1":@"iPod touch (4th generation)",
@"iPod5,1":@"iPod touch (5th generation)",
@"iPod7,1":@"iPod touch (6th generation)",
@"iPod9,1":@"iPod touch (7th generation)",
//TODO:iPad
@"iPad1,1":@"iPad",
@"iPad2,1":@"iPad 2",
@"iPad2,2":@"iPad 2",
@"iPad2,3":@"iPad 2",
@"iPad2,4":@"iPad 2",
@"iPad3,1":@"iPad (3rd generation)",
@"iPad3,2":@"iPad (3rd generation)",
@"iPad3,3":@"iPad (3rd generation)",
@"iPad3,4":@"iPad (4th generation)",
@"iPad3,5":@"iPad (4th generation)",
@"iPad3,6":@"iPad (4th generation)",
@"iPad6,11":@"iPad (5th generation)",
@"iPad6,12":@"iPad (5th generation)",
@"iPad7,5":@"iPad (6th generation)",
@"iPad7,6":@"iPad (6th generation)",
@"iPad7,11":@"iPad (7th generation)",
@"iPad7,12":@"iPad (7th generation)",
@"iPad11,6":@"iPad (8th generation)",
@"iPad11,7":@"iPad (8th generation)",
@"iPad12,1":@"iPad (9th generation)",
@"iPad12,2":@"iPad (9th generation)",
//TODO:iPad Air
@"iPad4,1":@"iPad Air",
@"iPad4,2":@"iPad Air",
@"iPad4,3":@"iPad Air",
@"iPad5,3":@"iPad Air 2",
@"iPad5,4":@"iPad Air 2",
@"iPad11,3":@"iPad Air (3rd generation)",
@"iPad11,4":@"iPad Air (3rd generation)",
@"iPad13,1":@"iPad Air (4rd generation)",
@"iPad13,2":@"iPad Air (4rd generation)",
//TODO:iPad Pro
@"iPad6,3":@"iPad Pro (9.7-inch)",
@"iPad6,4":@"iPad Pro (9.7-inch)",
@"iPad7,3":@"iPad Pro (10.5-inch)",
@"iPad7,4":@"iPad Pro (10.5-inch)",
@"iPad8,1":@"iPad Pro (11-inch)",
@"iPad8,2":@"iPad Pro (11-inch)",
@"iPad8,3":@"iPad Pro (11-inch)",
@"iPad8,4":@"iPad Pro (11-inch)",
@"iPad8,9":@"iPad Pro (11-inch) (2nd generation)",
@"iPad8,10":@"iPad Pro (11-inch) (2nd generation)",
@"iPad13,4":@"iPad Pro (11-inch) (3rd generation)",
@"iPad13,5":@"iPad Pro (11-inch) (3rd generation)",
@"iPad13,6":@"iPad Pro (11-inch) (3rd generation)",
@"iPad13,7":@"iPad Pro (11-inch) (3rd generation)",
@"iPad6,7":@"iPad Pro (12.9-inch)",
@"iPad6,8":@"iPad Pro (12.9-inch)",
@"iPad7,1":@"iPad Pro (12.9-inch) (2nd generation)",
@"iPad7,2":@"iPad Pro (12.9-inch) (2nd generation)",
@"iPad8,5":@"iPad Pro (12.9-inch) (3rd generation)",
@"iPad8,6":@"iPad Pro (12.9-inch) (3rd generation)",
@"iPad8,7":@"iPad Pro (12.9-inch) (3rd generation)",
@"iPad8,8":@"iPad Pro (12.9-inch) (3rd generation)",
@"iPad8,11":@"iPad Pro (12.9-inch) (4th generation)",
@"iPad8,12":@"iPad Pro (12.9-inch) (4th generation)",
@"iPad13,8":@"iPad Pro (12.9-inch) (5th generation)",
@"iPad13,9":@"iPad Pro (12.9-inch) (5th generation)",
@"iPad13,10":@"iPad Pro (12.9-inch) (5th generation)",
@"iPad13,11":@"iPad Pro (12.9-inch) (5th generation)",
//TODO:iPad mini
@"iPad2,5":@"iPad mini",
@"iPad2,6":@"iPad mini",
@"iPad2,7":@"iPad mini",
@"iPad4,4":@"iPad Mini 2",
@"iPad4,5":@"iPad Mini 2",
@"iPad4,6":@"iPad Mini 2",
@"iPad4,7":@"iPad Mini 3",
@"iPad4,8":@"iPad Mini 3",
@"iPad4,9":@"iPad Mini 3",
@"iPad5,1":@"iPad Mini 4",
@"iPad5,2":@"iPad Mini 4",
@"iPad11,1":@"iPad mini (5th generation)",
@"iPad11,2":@"iPad mini (5th generation)",
@"iPad14,1":@"iPad mini (6th generation)",
@"iPad14,2":@"iPad mini (6th generation)",
//TODO:iPhone
@"iPhone1,1":@"iPhone",
@"iPhone1,2":@"iPhone 3G",
@"iPhone2,1":@"iPhone 3GS",
@"iPhone3,1":@"iPhone 4",
@"iPhone3,2":@"iPhone 4",
@"iPhone3,3":@"iPhone 4",
@"iPhone4,1": @"iPhone 4s",
@"iPhone5,1":@"iPhone 5",
@"iPhone5,2":@"iPhone 5",
@"iPhone5,3":@"iPhone 5c",
@"iPhone5,4":@"iPhone 5c",
@"iPhone6,1":@"iPhone 5s",
@"iPhone6,2":@"iPhone 5s",
@"iPhone7,2":@"iPhone 6",
@"iPhone7,1":@"iPhone 6 Plus",
@"iPhone8,1":@"iPhone 6s",
@"iPhone8,2":@"iPhone 6s Plus",
@"iPhone8,4":@"iPhone SE (1st generation)",
@"iPhone9,1":@"iPhone 7",
@"iPhone9,3":@"iPhone 7",
@"iPhone9,2":@"iPhone 7 Plus",
@"iPhone9,4":@"iPhone 7 Plus",
@"iPhone10,1":@"iPhone 8",
@"iPhone10,4":@"iPhone 8",
@"iPhone10,2":@"iPhone 8 Plus",
@"iPhone10,5":@"iPhone 8 Plus",
@"iPhone10,3":@"iPhone X",
@"iPhone10,6":@"iPhone X",
@"iPhone11,8":@"iPhone XR",
@"iPhone11,2":@"iPhone XS",
@"iPhone11,4":@"iPhone XS Max",
@"iPhone11,6":@"iPhone XS Max",
@"iPhone12,1":@"iPhone 11",
@"iPhone12,3":@"iPhone 11 Pro",
@"iPhone12,5":@"iPhone 11 Pro Max",
@"iPhone12,8":@"iPhone SE (2nd generation)",
@"iPhone13,1":@"iPhone 12 mini",
@"iPhone13,2":@"iPhone 12",
@"iPhone13,3":@"iPhone 12 Pro",
@"iPhone13,4":@"iPhone 12 Pro Max",
@"iPhone14,4":@"iPhone 13 mini",
@"iPhone14,5":@"iPhone 13",
@"iPhone14,2":@"iPhone 13 Pro",
@"iPhone14,3":@"iPhone 13 Pro Max",
@"iPhone14,6":@"iPhone SE (3rd generation)",
@"iPhone14,7":@"iPhone 14",
@"iPhone14,8":@"iPhone 14 Plus",
@"iPhone15,2":@"iPhone 14 Pro",
@"iPhone15,3":@"iPhone 14 Pro Max",
@"iPhone15,4":@"iPhone 15",
@"iPhone15,5":@"iPhone 15 Plus",
@"iPhone16,1":@"iPhone 15 Pro",
@"iPhone16,2":@"iPhone 15 Pro Max",
@"iPad14,8":@"iPad Pro (12.9-inch) 6(2022)",
@"iPad14,9":@"iPad Pro (12.9-inch) 6(2022)",
@"iPad14,10":@"iPad Pro (12.9-inch) 6(2022)",
@"iPad14,11":@"iPad Pro (12.9-inch) 6(2022)",
@"i386":@"iPhone Simulator",
@"x86_64":@"iPhone Simulator",
};
if(identifier && [dicTemp objectForKey:identifier]){
_mn = dicTemp[identifier];
}
else if(identifier && identifier.length > 0){
_mn = identifier;
}
return _mn;
}
//MARK: - Emoji表情检测
/**!
* 是否含有Emoji 表情(true 含有)
*/
+(BOOL)stringContainsEmoji:(NSString *)string{
__block BOOL returnValue = FALSE;
[string enumerateSubstringsInRange:NSMakeRange(0, string.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
unichar hs = [substring characterAtIndex:0];
// surrogate pair
if (0xd800 <= hs && hs <= 0xdbff) {
if (substring.length > 1) {
unichar ls =[substring characterAtIndex:1];
NSInteger uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f){
returnValue = YES;
}
}
}
else if (substring.length > 1) {
unichar ls =[substring characterAtIndex:1];
if (ls == 0x20e3){
returnValue = YES;
}
}
else {
// non surrogate
if (0x2100 <= hs && hs <= 0x27ff){
returnValue = YES;
}
else if (0x2B05 <= hs && hs <= 0x2b07){
returnValue = YES;
}
else if (0x2934 <= hs && hs <= 0x2935){
returnValue = YES;
}
else if (0x3297 <= hs && hs <= 0x3299){
returnValue = YES;
}
else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50){
returnValue = YES;
}
}
}];
return returnValue;
}
//MARK: - 时间处理
/** 将Linux时间装换为字符串时间 */
+(NSString *)formatDateToString:(NSTimeInterval)linuxTime WithFormat:(NSString *)format{
long long _timeInterval = linuxTime;
NSString *_temp = [NSString stringWithFormat:@"%.0f",linuxTime];
if (_temp.length > 10) {
_temp = [_temp substringToIndex:10];
_timeInterval = [_temp longLongValue];
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_timeInterval];
NSDateFormatter *fomatter = [[NSDateFormatter alloc] init];
[fomatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC+8"]];
[fomatter setDateFormat:format];
NSString *_strInfo = [fomatter stringFromDate:date];
return _strInfo;
}
/** 获取当前时间 */
+(NSString *)getCurrentDateToString:(NSString *)format{
NSDate *date = [NSDate date];
NSDateFormatter *fomatter = [[NSDateFormatter alloc] init];
[fomatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC+8"]];
[fomatter setDateFormat:format];
NSString *_strInfo = [fomatter stringFromDate:date];
return _strInfo;
}
//MARK: - 缓存相关设置
/**!
* 获取系统缓存
* //缓存目录
#define K_APPLICATION_CACHE_PATH [NSString stringWithFormat:@"%@/%@",[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject],K_APP_BUNDLE_ID]
*/
+(NSString *)getAppCacheSize{
NSFileManager *fileManage = [NSFileManager defaultManager];
NSString *strResult = @"0M";
BOOL isDirectory = NO;
//是否存在
if ([fileManage fileExistsAtPath:K_APPLICATION_CACHE_PATH isDirectory:&isDirectory]) {
@try {
float fsize = 0.0;
NSDictionary *attributDic;
//文件夹
if(isDirectory) {
NSString *tempPath;
//获取该目录下所有文件
for (NSString *strItem in [fileManage subpathsAtPath:K_APPLICATION_CACHE_PATH]) {
tempPath = [NSString stringWithFormat:@"%@/%@",K_APPLICATION_CACHE_PATH,strItem];
//存在,且为文件
if ([fileManage fileExistsAtPath:tempPath isDirectory:&isDirectory] && isDirectory == NO) {
attributDic = [fileManage attributesOfItemAtPath:tempPath error:nil];
fsize = fsize + [[attributDic valueForKey:NSFileSize] floatValue];
}
}
}
else{
attributDic = [fileManage attributesOfItemAtPath:K_APPLICATION_CACHE_PATH error:nil];
fsize = [[attributDic valueForKey:NSFileSize] floatValue];
}
//计算缓存大小
fsize = fsize / (1024.0 * 1024.0);
if (fsize > 0.0) {
strResult = [NSString stringWithFormat:@"%.2fM",fsize];
}
} @catch (NSException *exception) {
NSLog(@"获取缓存异常:%@",exception);
}
}
return strResult;
}
/**!
* 清理系统缓存
*/
+(BOOL)clearnAppCache{
NSFileManager *fileManage = [NSFileManager defaultManager];
NSString *tempPath;
BOOL isDic = NO;
BOOL isOk = NO;
//路径存在,且为文件夹
if ([fileManage fileExistsAtPath:K_APPLICATION_CACHE_PATH isDirectory:&isDic] && isDic) {
@try {
for (NSString *strItem in [fileManage subpathsAtPath:K_APPLICATION_CACHE_PATH]) {
tempPath = [NSString stringWithFormat:@"%@/%@",K_APPLICATION_CACHE_PATH,strItem];
//移除
if ([fileManage fileExistsAtPath:tempPath]) {
[fileManage removeItemAtPath:tempPath error:nil];
}
}
isOk = YES;
} @catch (NSException *exception) {
NSLog(@"清理缓存异常:%@",exception);
}
}
return isOk;
}
//MARK: - 公共的请求方法
/**! 开启设置权限 */
+(void)openSetting{
NSString *strUrl = UIApplicationOpenSettingsURLString;
NSURL *url = [NSURL URLWithString:strUrl];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
//MARK: - 获取文本的宽度
/**!
* 获取文本的宽度
*/
+(CGFloat)getWidthForString:(NSString *)value andFontSize:(UIFont *)font andHeight:(CGFloat)height{
CGSize sizeToFit = [value sizeWithFont:font constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置
return sizeToFit.width;
}
/** 获取文本的高度 */
+(CGFloat)getHeightForString:(NSString *)value andFontSize:(UIFont *)font andWidth:(CGFloat)width{
CGSize sizeToFit = [value sizeWithFont:font constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置
return sizeToFit.height;
}
/**!
* 获取文本框的高度
*/
+(CGFloat)getTextViewHeight:(UITextView *)textView AndFixedWidth:(CGFloat)width {
CGFloat fw = 0.0;
CGSize size = CGSizeMake(width, CGFLOAT_MAX);
CGSize constraint = [textView sizeThatFits:size];
fw = constraint.height + 10.0;
return fw;
}
//MARK: - 设置富文本
/**! 设置富文本 */
+(NSAttributedString *)setAttributeStringText:(NSString *)strFullText andFullTextFont:(UIFont *)textFont andFullTextColor:(UIColor *)textColor withChangeText:(NSString *)changeText withChangeFont:(UIFont *)changFont withChangeColor:(UIColor *)changeColor isLineThrough:(BOOL)lineThrough{
NSDictionary<NSAttributedStringKey,id> *dicAttr;
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:strFullText];
//需要改变的文本
NSRange range = [strFullText rangeOfString:changeText];
dicAttr = @{
NSFontAttributeName:changFont,
NSForegroundColorAttributeName:changeColor
};
if (lineThrough) {
[dicAttr setValue:[[NSNumber alloc] initWithInt:1] forKey:NSStrikethroughStyleAttributeName];
}
[attributeString addAttributes:dicAttr range:range];
//不需要改变的文本
NSString *oldText = [strFullText stringByReplacingOccurrencesOfString:changeText withString:@""];
range = [strFullText rangeOfString:oldText];
dicAttr = @{
NSFontAttributeName:textFont,
NSForegroundColorAttributeName:textColor
};
[attributeString addAttributes:dicAttr range:range];
return attributeString;
}
//MARK: - Json 与 字典、数组类型转换
/**!
* 数组转换为NString
* @returns: NString
*/
+(NSString *)getJSONStringFromData:(id)idData{
if (![NSJSONSerialization isValidJSONObject:idData]) {
NSLog(@"无法解析出JSONString");
return @"";
}
NSData *data = [NSJSONSerialization dataWithJSONObject:idData
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *strReturn = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return strReturn;
}
//MARK: - 网络请求方法
/**
* 格式化请求参数
* @param dicParasm NSDictionary
*/
+(NSDictionary *)formatRequestParams:(NSDictionary *)dicParasm{
NSMutableDictionary *_dicTemp = [[NSMutableDictionary alloc] initWithDictionary:dicParasm];
if ([TDUser userIsLogin]) {
[_dicTemp setObject:[TDUser getLoginToken] forKey:@"token"];
}
return _dicTemp;
}
/**!
* post 接口请求
* @para strUrl String 请求地址
* @para paras [String:Any] 请求参数
* @para successBack 成功回调
* @para failureBack 失败回调
*/
+(void)postRequestForServerData:(NSString *)strUrl withParameters:(NSDictionary *)paras AndHTTPHeaderField:(void(^)(AFHTTPRequestSerializer *_requestSerializer))headerField AndSuccessBack:(void(^)(id _responseData))successBack AndFailureBack:(void(^)(NSString *_strError))failureBack WithisLoading:(BOOL)isLoading{
NSLog(@"请求地址:%@,参数:%@",strUrl,paras);
if (![K_APP_REACHABILITY isReachable]) {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD showError:@"网络连接异常"];
});
NSLog(@"网络连接异常");
return;
}
__block UIView *_view;
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
_view = [[AppDelegate shareInstance] window].rootViewController.view;
if (_view) {
[MBProgressHUD showMessage:@"" toView:_view];
}
else {
[MBProgressHUD showMessage:@""];
}
});
}
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
//设置HTTPHeaderField
if (headerField) {
AFHTTPRequestSerializer *_requestSerializer = [AFHTTPRequestSerializer serializer];
headerField(_requestSerializer);
sessionManager.requestSerializer = _requestSerializer;
}
//提交请求
[sessionManager POST:strUrl
parameters:paras
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil){
BOOL exists = NO;
for (UIView *object in _view.subviews) {
if ([object isMemberOfClass:[MBProgressHUD class]]) {
exists = YES;
break;
}
}
if (!exists) {
[MBProgressHUD showMessage:@"" toView:_view];
}
}
else
[MBProgressHUD hideHUD];
});
}
NSLog(@"请求结果:%@",responseObject);
NSDictionary *jsonData = responseObject;
NSInteger resultCode = [[jsonData valueForKey:K_APP_REQUEST_CODE] integerValue];
NSString *strMessage = [jsonData valueForKey:K_APP_REQUEST_MSG];
//成功
if (resultCode == K_APP_REQUEST_SUCCESS_CODE) {
if (successBack != nil) {
successBack([jsonData valueForKey:K_APP_REQUEST_DATA]);
}
}
else if(resultCode == 200){
if (successBack != nil) {
successBack(jsonData);
}
}
//token 失效,需重新登录
else if(resultCode == K_APP_REQUEST_TOKEN_FAILURE_CODE){
if (failureBack != nil) {
failureBack(strMessage);
}
NSLog(@"登录Token 失效");
[[NSNotificationCenter defaultCenter] postNotificationName:K_APP_TOKEN_FAILURE_NOTICE object:nil];
}
else{
[MBProgressHUD showError:strMessage];
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil)
[MBProgressHUD hideHUDForView:_view];
else
[MBProgressHUD hideHUD];
});
}
if (failureBack != nil) {
failureBack([error localizedDescription]);
}
NSLog(@"请求异常:%@",[error localizedDescription]);
}];
}
/**!
* get 接口请求
* @para strUrl String 请求地址
* @para paras [String:Any] 请求参数
* @para successBack 成功回调
* @para failureBack 失败回调
*/
+(void)getRequestForServerData:(NSString *)strUrl withParameters:(NSDictionary *)paras AndHTTPHeaderField:(void(^)(AFHTTPRequestSerializer *_requestSerializer))headerField AndSuccessBack:(void(^)(id _responseData))successBack AndFailureBack:(void(^)(NSString *_strError))failureBack WithisLoading:(BOOL)isLoading{
NSLog(@"请求地址:%@,参数:%@",strUrl,paras);
if (![K_APP_REACHABILITY isReachable]) {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD showError:@"网络连接异常"];
});
NSLog(@"网络连接异常");
return;
}
__block UIView *_view;
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
_view = [[AppDelegate shareInstance] window].rootViewController.view;
if (_view) {
[MBProgressHUD showMessage:@"" toView:_view];
}
else {
[MBProgressHUD showMessage:@""];
}
});
}
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
//设置HTTPHeaderField
if (headerField) {
AFHTTPRequestSerializer *_requestSerializer = [AFHTTPRequestSerializer serializer];
headerField(_requestSerializer);
sessionManager.requestSerializer = _requestSerializer;
}
//提交请求
[sessionManager GET:strUrl
parameters:paras
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil){
BOOL exists = NO;
for (UIView *object in _view.subviews) {
if ([object isMemberOfClass:[MBProgressHUD class]]) {
exists = YES;
break;
}
}
if (!exists) {
[MBProgressHUD showMessage:@"" toView:_view];
}
}
else
[MBProgressHUD hideHUD];
});
}
NSLog(@"请求结果:%@",responseObject);
NSDictionary *jsonData = responseObject;
NSInteger resultCode = [[jsonData valueForKey:K_APP_REQUEST_CODE] integerValue];
NSString *strMessage = [jsonData valueForKey:K_APP_REQUEST_MSG];
//成功
if (resultCode == K_APP_REQUEST_SUCCESS_CODE) {
if (successBack != nil) {
if ([jsonData.allKeys containsObject:K_APP_REQUEST_DATA]) {
successBack([jsonData valueForKey:K_APP_REQUEST_DATA]);
}
else{
successBack(jsonData);
}
}
}
else if(resultCode == 200 || resultCode == 0){
//token 失效,需重新登录
if(resultCode == K_APP_REQUEST_TOKEN_FAILURE_CODE && [strMessage containsString:@"token"]){
if (failureBack != nil) {
failureBack(strMessage);
}
NSLog(@"登录Token 失效");
[[NSNotificationCenter defaultCenter] postNotificationName:K_APP_TOKEN_FAILURE_NOTICE object:nil];
}
else{
if (successBack != nil) {
successBack(jsonData);
}
}
}
else{
[MBProgressHUD showError:strMessage];
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil)
[MBProgressHUD hideHUDForView:_view];
else
[MBProgressHUD hideHUD];
});
}
if (failureBack != nil) {
failureBack([error localizedDescription]);
}
NSLog(@"请求异常:%@",[error localizedDescription]);
}];
}
/**
* 异步POST请求:以body方式,支持数组
*
* @param url 请求的url
* @param body body数据
* @param success 成功回调
* @param failure 失败回调
* @param isLoading BOOL
*/
+(void)postWithUrl:(NSString *)url body:(NSData *)body WithSuccess:(void(^)(id _Nonnull response))success WithFailure:(void(^)(NSString *error))failure WithisLoading:(BOOL)isLoading{
NSLog(@"请求地址:%@",url);
if (![K_APP_REACHABILITY isReachable]) {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD showError:@"网络连接异常"];
});
NSLog(@"网络连接异常");
return;
}
__block UIView *_view;
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
_view = [[AppDelegate shareInstance] window].rootViewController.view;
if (_view) {
BOOL exists = NO;
for (UIView *object in _view.subviews) {
if ([object isMemberOfClass:[MBProgressHUD class]]) {
exists = YES;
break;
}
}
if (!exists) {
[MBProgressHUD showMessage:@"" toView:_view];
}
}
else {
[MBProgressHUD showMessage:@""];
}
});
}
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
request.timeoutInterval = K_APP_URLTIME_OUT_INTERVAL;
[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-plist;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//设置body
[request setHTTPBody:body];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/html",
@"text/json",
@"text/javascript",
@"text/plain",
nil];
manager.responseSerializer = responseSerializer;
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"请求结果:%@",responseObject);
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil)
[MBProgressHUD hideHUDForView:_view];
else
[MBProgressHUD hideHUD];
});
}
if (error == nil) {
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[responseObject mj_JSONData]
options:NSJSONReadingMutableContainers
error:nil];
NSLog(@"请求结果2:%@",responseObject);
NSInteger resultCode = [[jsonData valueForKey:K_APP_REQUEST_CODE] integerValue];
NSString *strMessage = [jsonData valueForKey:K_APP_REQUEST_MSG];
//成功
if (resultCode == K_APP_REQUEST_SUCCESS_CODE) {
if (success) {
if ([jsonData.allKeys containsObject:K_APP_REQUEST_DATA]) {
success([jsonData valueForKey:K_APP_REQUEST_DATA]);
}
else{
success(jsonData);
}
}
}
//token 失效,需重新登录
else if(resultCode == K_APP_REQUEST_TOKEN_FAILURE_CODE){
if (failure != nil) {
failure(strMessage);
}
NSLog(@"登录Token 失效");
[[NSNotificationCenter defaultCenter] postNotificationName:K_APP_TOKEN_FAILURE_NOTICE object:nil];
}
else{
if (failure != nil) {
if (strMessage && ![strMessage isEqualToString:@""]) {
failure(strMessage);
}
else{
failure([error localizedDescription]);
}
}
}
}
else {
if (failure != nil) {
failure([error localizedDescription]);
}
}
}] resume];
}
/**!
* 文件或图片上传
* @para strUrl String 上传地址
* @para uploadformDataBack 上传参数设置
* @para successBack 成功回调
* @para failureBack 失败回调
*/
+(void)postImageUploadToServer:(NSString *)strUrl AndUploadformDataBack:(void(^)(id<AFMultipartFormData> formData))formDataBack AndSuccessBack:(void(^)(NSObject *_responseData))successBack AndFailureBack:(void(^)(NSString *_strError))failureBack WithisLoading:(BOOL)isLoading{
NSLog(@"请求地址:%@",strUrl);
if (![K_APP_REACHABILITY isReachable]) {
[MBProgressHUD showError:@"网络连接异常"];
NSLog(@"网络连接异常");
return;
}
__block UIView *_view;
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
_view = [[AppDelegate shareInstance] window].rootViewController.view;
if (_view) {
BOOL exists = NO;
for (UIView *object in _view.subviews) {
if ([object isMemberOfClass:[MBProgressHUD class]]) {
exists = YES;
break;
}
}
if (!exists) {
[MBProgressHUD showMessage:@"" toView:_view];
}
}
else {
[MBProgressHUD showMessage:@""];
}
});
}
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
[sessionManager POST:strUrl
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//指定参数
if (formDataBack) {
formDataBack(formData);
}
}
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求结果:%@",responseObject);
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil)
[MBProgressHUD hideHUDForView:_view];
else
[MBProgressHUD hideHUD];
});
}
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSInteger resultCode = [[jsonData valueForKey:K_APP_REQUEST_CODE] integerValue];
NSString *strMessage = [jsonData valueForKey:K_APP_REQUEST_MSG];
//成功
if (resultCode == K_APP_REQUEST_SUCCESS_CODE) {
if (successBack) {
successBack([jsonData valueForKey:K_APP_REQUEST_DATA]);
}
}
//token 失效,需重新登录
else if(resultCode == K_APP_REQUEST_TOKEN_FAILURE_CODE){
if (failureBack != nil) {
failureBack(strMessage);
}
NSLog(@"登录Token 失效");
[[NSNotificationCenter defaultCenter] postNotificationName:K_APP_TOKEN_FAILURE_NOTICE object:nil];
}
else{
[MBProgressHUD showError:strMessage];
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (isLoading) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_view != nil)
[MBProgressHUD hideHUDForView:_view];
else
[MBProgressHUD hideHUD];
});
}
if (failureBack != nil) {
failureBack([error localizedDescription]);
}
NSLog(@"请求结果:%@",[error localizedDescription]);
}];
}
/// 访问Bundle资源包中的图片
/// - Parameters:
/// - bclass: Bundle的class([self class]?可选)
/// - bName: Bundle的名称
/// - imgName: 带后缀的图片名 "xx.png"
/// - _imgFileName: 图片资源所在文件夹名称,可选
+(UIImage *_Nullable)imageForBuncleClass:(Class _Nullable)_bclass
andBundleName:(NSString *_Nonnull)_bName
withImageName:(NSString *_Nonnull)_imgName
andImagesFileName:(NSString *_Nonnull)_imgFileName {
UIImage *_img;
@try {
Class _class = _bclass;
if(!_bclass){
_class = NSClassFromString(_bName);
}
NSBundle *_bundle = [NSBundle bundleForClass:_class];
NSURL *_url = [_bundle URLForResource:_bName withExtension:@"bundle"];
NSString *_imgFN = _imgName;
if(_imgFileName && ![_imgFileName isEqualToString:@""]) {
_imgFN = [NSString stringWithFormat:@"%@/%@",_imgFileName,_imgName];
}
if (@available(iOS 13.0, *)) {
NSBundle *_imageBundle = [NSBundle bundleWithURL:_url];
_img = [UIImage imageNamed:_imgFN inBundle:_imageBundle withConfiguration:nil];
} else {
// Fallback on earlier versions
NSString *_path = [NSString stringWithFormat:@"%@/%@",[_url path],_imgFN];
_img = [UIImage imageWithContentsOfFile:_path];
}
} @catch (NSException *exception) {
NSLog(@"%@-%@",@"imageForBuncleClass",exception);
} @finally {
return _img;
}
}
/// 获取资源包里面的Xib
/// - Parameters:
/// - _bclass: Bundle的class([self class]可选)
/// - _bName: Bundle的名称
/// - _xibName: xib的名称
-(UINib *_Nullable)xibForBuncleClass:(Class _Nullable)_bclass
andBundleName:(NSString *_Nonnull)_bName
withXibName:(NSString *_Nonnull)_xibName{
UINib *nib;
@try {
Class _class = _bclass;
if(!_bclass){
_class = NSClassFromString(_bName);
}
NSBundle *_bundleClass = [NSBundle bundleForClass:_class];
NSURL *_url = [_bundleClass URLForResource:_bName withExtension:@"bundle"];
NSBundle *_bundle = [NSBundle bundleWithURL:_url];
if(!_bundle) {
_bundle = [NSBundle mainBundle];
}
nib = [UINib nibWithNibName:_xibName bundle:_bundle];
} @catch (NSException *exception) {
NSLog(@"%@-%@",@"xibForBuncleClass",exception);
} @finally {
return nib;
}
}
IOS 常用工具类方法(OC版本)
于 2019-02-14 16:09:48 首次发布