Authored by 盖剑秋

Finish version 1.0.1

... ... @@ -30,6 +30,11 @@
2E64AB941D08099E004307A3 /* launchimage1@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 2E64AB921D08099E004307A3 /* launchimage1@2x.png */; };
2E64AB951D08099E004307A3 /* launchimage1@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 2E64AB931D08099E004307A3 /* launchimage1@3x.png */; };
2E6A3D9D1D18D407001A0E59 /* libstdc++.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 2E6A3D9C1D18D406001A0E59 /* libstdc++.tbd */; };
2E7FDB961D52F023005834F8 /* Hud.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E7FDB931D52F023005834F8 /* Hud.m */; };
2E7FDB971D52F023005834F8 /* MBProgressHUD.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E7FDB951D52F023005834F8 /* MBProgressHUD.m */; };
2E7FDB9A1D52F050005834F8 /* YH_Tool.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E7FDB991D52F050005834F8 /* YH_Tool.m */; };
2E7FDBCA1D5312EC005834F8 /* NSString+Wrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E7FDBA71D5312EC005834F8 /* NSString+Wrapper.m */; };
2E7FDBCB1D5312EC005834F8 /* NSString+YOHO.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E7FDBA91D5312EC005834F8 /* NSString+YOHO.m */; };
2EA13A2A1D05733B0037C9EB /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 2EA139F51D05733B0037C9EB /* AppDelegate.m */; };
2EA13A2B1D05733B0037C9EB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2EA139F61D05733B0037C9EB /* Assets.xcassets */; };
2EA13A2C1D05733B0037C9EB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2EA139F71D05733B0037C9EB /* LaunchScreen.storyboard */; };
... ... @@ -170,6 +175,16 @@
2E64AB921D08099E004307A3 /* launchimage1@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "launchimage1@2x.png"; sourceTree = "<group>"; };
2E64AB931D08099E004307A3 /* launchimage1@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "launchimage1@3x.png"; sourceTree = "<group>"; };
2E6A3D9C1D18D406001A0E59 /* libstdc++.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = "libstdc++.tbd"; path = "usr/lib/libstdc++.tbd"; sourceTree = SDKROOT; };
2E7FDB921D52F023005834F8 /* Hud.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Hud.h; sourceTree = "<group>"; };
2E7FDB931D52F023005834F8 /* Hud.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Hud.m; sourceTree = "<group>"; };
2E7FDB941D52F023005834F8 /* MBProgressHUD.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MBProgressHUD.h; sourceTree = "<group>"; };
2E7FDB951D52F023005834F8 /* MBProgressHUD.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MBProgressHUD.m; sourceTree = "<group>"; };
2E7FDB981D52F050005834F8 /* YH_Tool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = YH_Tool.h; sourceTree = "<group>"; };
2E7FDB991D52F050005834F8 /* YH_Tool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = YH_Tool.m; sourceTree = "<group>"; };
2E7FDBA61D5312EC005834F8 /* NSString+Wrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+Wrapper.h"; sourceTree = "<group>"; };
2E7FDBA71D5312EC005834F8 /* NSString+Wrapper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+Wrapper.m"; sourceTree = "<group>"; };
2E7FDBA81D5312EC005834F8 /* NSString+YOHO.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+YOHO.h"; sourceTree = "<group>"; };
2E7FDBA91D5312EC005834F8 /* NSString+YOHO.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+YOHO.m"; sourceTree = "<group>"; };
2EA139F41D05733B0037C9EB /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
2EA139F51D05733B0037C9EB /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
2EA139F61D05733B0037C9EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
... ... @@ -476,9 +491,35 @@
path = yoho;
sourceTree = "<group>";
};
2E7FDB911D52F023005834F8 /* MBProgressHUD */ = {
isa = PBXGroup;
children = (
2E7FDB981D52F050005834F8 /* YH_Tool.h */,
2E7FDB991D52F050005834F8 /* YH_Tool.m */,
2E7FDB921D52F023005834F8 /* Hud.h */,
2E7FDB931D52F023005834F8 /* Hud.m */,
2E7FDB941D52F023005834F8 /* MBProgressHUD.h */,
2E7FDB951D52F023005834F8 /* MBProgressHUD.m */,
);
path = MBProgressHUD;
sourceTree = "<group>";
};
2E7FDB9B1D5312EC005834F8 /* Categories */ = {
isa = PBXGroup;
children = (
2E7FDBA61D5312EC005834F8 /* NSString+Wrapper.h */,
2E7FDBA71D5312EC005834F8 /* NSString+Wrapper.m */,
2E7FDBA81D5312EC005834F8 /* NSString+YOHO.h */,
2E7FDBA91D5312EC005834F8 /* NSString+YOHO.m */,
);
path = Categories;
sourceTree = "<group>";
};
2EA139F31D05733B0037C9EB /* YohoLive */ = {
isa = PBXGroup;
children = (
2E7FDB9B1D5312EC005834F8 /* Categories */,
2E7FDB911D52F023005834F8 /* MBProgressHUD */,
2E6A85501D18E800001A0E59 /* yoho */,
2E4D5FBF1D057BD800D508BB /* Classes */,
2EA139F41D05733B0037C9EB /* AppDelegate.h */,
... ... @@ -931,6 +972,7 @@
2EB66FC31D18EEEB00E91AAE /* AFURLConnectionOperation+Performance.m in Sources */,
2EB670151D18F08D00E91AAE /* NSMutableArray+QueueAdditions.m in Sources */,
2EB6705D1D19088A00E91AAE /* SDWebImageDownloaderOperation+Performance.m in Sources */,
2E7FDB971D52F023005834F8 /* MBProgressHUD.m in Sources */,
2EEAD4BF1D112D04003EE0E9 /* GCDAsyncSocket+SocketHandler.m in Sources */,
2EB670641D19088A00E91AAE /* UIImage+WebP.m in Sources */,
2EB670021D18EF2F00E91AAE /* NSValueTransformer+MTLPredefinedTransformerAdditions.m in Sources */,
... ... @@ -961,9 +1003,12 @@
2E4D5FC21D057C6100D508BB /* YH_RootViewController.m in Sources */,
2EB670611D19088A00E91AAE /* UIButton+WebCache.m in Sources */,
2EB670091D18EFC800E91AAE /* HPTextViewInternal.m in Sources */,
2E7FDBCA1D5312EC005834F8 /* NSString+Wrapper.m in Sources */,
2EB66FFE1D18EF2F00E91AAE /* NSDictionary+MTLManipulationAdditions.m in Sources */,
31CCA53A1D26138700ADF9F0 /* M16HUDUtil.m in Sources */,
2E7FDBCB1D5312EC005834F8 /* NSString+YOHO.m in Sources */,
2EB6706C1D1908F600E91AAE /* Localisator.m in Sources */,
2E7FDB9A1D52F050005834F8 /* YH_Tool.m in Sources */,
2EB66FF91D18EF2F00E91AAE /* MTLModel+NSCoding.m in Sources */,
2EB66FF81D18EF2F00E91AAE /* MTLManagedObjectAdapter.m in Sources */,
2EB66FFB1D18EF2F00E91AAE /* MTLReflection.m in Sources */,
... ... @@ -979,6 +1024,7 @@
2EB6702D1D18F24900E91AAE /* M16Model.m in Sources */,
2EB6705E1D19088A00E91AAE /* SDWebImageDownloaderOperation.m in Sources */,
2EEAD4BE1D112D04003EE0E9 /* GCDAsyncSocket.m in Sources */,
2E7FDB961D52F023005834F8 /* Hud.m in Sources */,
2EB670631D19088A00E91AAE /* UIImage+MultiFormat.m in Sources */,
2EB670671D19088A00E91AAE /* UIView+WebCacheOperation.m in Sources */,
2EB66FD01D18EF0800E91AAE /* UITableView+FDTemplateLayoutCellDebug.m in Sources */,
... ... @@ -1072,7 +1118,7 @@
baseConfigurationReference = DF5CC49E6ACE4D402D22806C /* Pods.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "iPhone Distribution: New & Power Culture Dissemination Co.,Ltd";
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
... ... @@ -1126,7 +1172,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = cn.yoho.live.ent;
PRODUCT_NAME = YohoLive;
PROVISIONING_PROFILE = "a054e3fc-ce5a-4cd0-a13b-21f70ebeab79";
PROVISIONING_PROFILE = "";
USER_HEADER_SEARCH_PATHS = ./YohoLive/TXRTMPSDK.framework/Headers;
VALID_ARCHS = "arm64 armv7 armv7s i386";
};
... ... @@ -1226,7 +1272,7 @@
baseConfigurationReference = DF5CC49E6ACE4D402D22806C /* Pods.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "iPhone Distribution: New & Power Culture Dissemination Co.,Ltd";
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
... ... @@ -1276,7 +1322,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = cn.yoho.live.ent;
PRODUCT_NAME = YohoLive;
PROVISIONING_PROFILE = "a054e3fc-ce5a-4cd0-a13b-21f70ebeab79";
PROVISIONING_PROFILE = "";
USER_HEADER_SEARCH_PATHS = ./YohoLive/TXRTMPSDK.framework/Headers;
VALID_ARCHS = "arm64 armv7 armv7s i386";
};
... ... @@ -1287,7 +1333,7 @@
baseConfigurationReference = E02A0042E44F888A50E7158C /* Pods.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "iPhone Distribution: New & Power Culture Dissemination Co.,Ltd";
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
... ... @@ -1337,7 +1383,7 @@
);
PRODUCT_BUNDLE_IDENTIFIER = cn.yoho.live.ent;
PRODUCT_NAME = YohoLive;
PROVISIONING_PROFILE = "a054e3fc-ce5a-4cd0-a13b-21f70ebeab79";
PROVISIONING_PROFILE = "";
USER_HEADER_SEARCH_PATHS = ./YohoLive/TXRTMPSDK.framework/Headers;
VALID_ARCHS = "arm64 armv7 armv7s i386";
};
... ...
... ... @@ -42,7 +42,7 @@
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "DebugTest"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
... ...
//
// NSString+Wrapper.h
// WiFiHelpers
//
// Created by yy on 14-2-11.
// Copyright (c) 2014年 yy. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* NSString 工具类
*/
@interface NSString (Wrapper)
/** Return the char value at the specified index. */
- (unichar) charAt:(int)index;
/**
* Compares two strings lexicographically.
* the value 0 if the argument string is equal to this string;
* a value less than 0 if this string is lexicographically less than the string argument;
* and a value greater than 0 if this string is lexicographically greater than the string argument.
*/
- (int) compareTo:(NSString*) anotherString;
- (int) compareToIgnoreCase:(NSString*) str;
- (BOOL) contains:(NSString*) str;
- (BOOL) startsWith:(NSString*)prefix;
- (BOOL) endsWith:(NSString*)suffix;
- (BOOL) equals:(NSString*) anotherString;
- (BOOL) equalsIgnoreCase:(NSString*) anotherString;
- (int) indexOfChar:(unichar)ch;
- (int) indexOfChar:(unichar)ch fromIndex:(int)index;
- (int) indexOfString:(NSString*)str;
- (int) indexOfString:(NSString*)str fromIndex:(int)index;
- (int) lastIndexOfChar:(unichar)ch;
- (int) lastIndexOfChar:(unichar)ch fromIndex:(int)index;
- (int) lastIndexOfString:(NSString*)str;
- (int) lastIndexOfString:(NSString*)str fromIndex:(int)index;
- (NSString *) substringFromIndex:(int)beginIndex toIndex:(int)endIndex;
- (NSString *) toLowerCase;
- (NSString *) toUpperCase;
- (NSString *) trim;
- (NSString *) replaceAll:(NSString*)origin with:(NSString*)replacement;
- (NSArray *) split:(NSString*) separator;
+ (NSString*) uniqueString;
- (NSString*) urlEncodedString;
- (NSString*) urlDecodedString;
+ (NSString*) transformToString:(id)obj;
+ (NSNumber*) transformToNumber:(id)obj;
+ (NSString *)stringWithInt:(NSInteger)value;
@end
... ...
//
// NSString+Wrapper.m
// WiFiHelpers
//
// Created by yy on 14-2-11.
// Copyright (c) 2014年 yy. All rights reserved.
//
#import "NSString+Wrapper.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Wrapper)
#define JavaNotFound -1
/** Java-like method. Returns the char value at the specified index. */
- (unichar) charAt:(int)index {
return [self characterAtIndex:index];
}
/**
* Java-like method. Compares two strings lexicographically.
* the value 0 if the argument string is equal to this string;
* a value less than 0 if this string is lexicographically less than the string argument;
* and a value greater than 0 if this string is lexicographically greater than the string argument.
*/
- (int) compareTo:(NSString*) anotherString {
return [self compare:anotherString];
}
/** Java-like method. Compares two strings lexicographically, ignoring case differences. */
- (int) compareToIgnoreCase:(NSString*) str {
return [self compare:str options:NSCaseInsensitiveSearch];
}
/** Java-like method. Returns true if and only if this string contains the specified sequence of char values. */
- (BOOL) contains:(NSString*) str {
NSRange range = [self rangeOfString:str];
return (range.location != NSNotFound);
}
- (BOOL) startsWith:(NSString*)prefix {
return [self hasPrefix:prefix];
}
- (BOOL) endsWith:(NSString*)suffix {
return [self hasSuffix:suffix];
}
- (BOOL) equals:(NSString*) anotherString {
return [self isEqualToString:anotherString];
}
- (BOOL) equalsIgnoreCase:(NSString*) anotherString {
return [[self toLowerCase] equals:[anotherString toLowerCase]];
}
- (int) indexOfChar:(unichar)ch{
return [self indexOfChar:ch fromIndex:0];
}
- (int) indexOfChar:(unichar)ch fromIndex:(int)index{
int len = (int)self.length;
for (int i = index; i < len; ++i) {
if (ch == [self charAt:i]) {
return i;
}
}
return JavaNotFound;
}
- (int) indexOfString:(NSString*)str {
NSRange range = [self rangeOfString:str];
if (range.location == NSNotFound) {
return JavaNotFound;
}
return (int)range.location;
}
- (int) indexOfString:(NSString*)str fromIndex:(int)index {
NSRange fromRange = NSMakeRange(index, self.length - index);
NSRange range = [self rangeOfString:str options:NSLiteralSearch range:fromRange];
if (range.location == NSNotFound) {
return JavaNotFound;
}
return (int)range.location;
}
- (int) lastIndexOfChar:(unichar)ch {
int len = (int)self.length;
for (int i = len-1; i >=0; --i) {
if ([self charAt:i] == ch) {
return i;
}
}
return JavaNotFound;
}
- (int) lastIndexOfChar:(unichar)ch fromIndex:(int)index {
int len = (int)self.length;
if (index >= len) {
index = len - 1;
}
for (int i = index; i >= 0; --i) {
if ([self charAt:i] == ch) {
return index;
}
}
return JavaNotFound;
}
- (int) lastIndexOfString:(NSString*)str {
NSRange range = [self rangeOfString:str options:NSBackwardsSearch];
if (range.location == NSNotFound) {
return JavaNotFound;
}
return (int)range.location;
}
- (int) lastIndexOfString:(NSString*)str fromIndex:(int)index {
NSRange fromRange = NSMakeRange(0, index);
NSRange range = [self rangeOfString:str options:NSBackwardsSearch range:fromRange];
if (range.location == NSNotFound) {
return JavaNotFound;
}
return (int)range.location;
}
- (NSString *) substringFromIndex:(int)beginIndex toIndex:(int)endIndex {
if (endIndex <= beginIndex) {
return @"";
}
NSRange range = NSMakeRange(beginIndex, endIndex - beginIndex);
return [self substringWithRange:range];
}
- (NSString *) toLowerCase {
return [self lowercaseString];
}
- (NSString *) toUpperCase {
return [self uppercaseString];
}
- (NSString *) trim {
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString *) replaceAll:(NSString*)origin with:(NSString*)replacement {
return [self stringByReplacingOccurrencesOfString:origin withString:replacement];
}
- (NSArray *) split:(NSString*) separator {
return [self componentsSeparatedByString:separator];
}
+ (NSString*) uniqueString
{
CFUUIDRef uuidObj = CFUUIDCreate(nil);
NSString *uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(nil, uuidObj);
CFRelease(uuidObj);
return uuidString;
}
- (NSString*) urlEncodedString {
CFStringRef encodedCFString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef) self,
nil,
CFSTR("?!@#$^&%*+,:;='\"`<>()[]{}/\\| "),
kCFStringEncodingUTF8);
NSString *encodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) encodedCFString];
if(!encodedString)
encodedString = @"";
return encodedString;
}
- (NSString*) urlDecodedString {
CFStringRef decodedCFString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
(__bridge CFStringRef) self,
CFSTR(""),
kCFStringEncodingUTF8);
// We need to replace "+" with " " because the CF method above doesn't do it
NSString *decodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) decodedCFString];
return (!decodedString) ? @"" : [decodedString stringByReplacingOccurrencesOfString:@"+" withString:@" "];
}
+ (NSString *)transformToString:(id)obj
{
NSString *key = nil;
if ( [obj isKindOfClass:[NSNumber class]] )
{
key = [(NSNumber *)obj stringValue];
}
else if ( [obj isKindOfClass:[NSString class]] )
{
key = (NSString *)obj;
}
else
{
return @"";
}
return key;
}
+(NSNumber*)transformToNumber:(id)obj
{
NSNumber *key = nil;
if ( [obj isKindOfClass:[NSNumber class]] )
{
key = (NSNumber *)obj;
}
else if ( [obj isKindOfClass:[NSString class]] )
{
key = [NSNumber numberWithLongLong:[(NSString *)obj longLongValue]];
}
else
{
return [NSNumber numberWithInteger:NSNotFound];
}
return key;
}
+ (NSString *)stringWithInt:(NSInteger)value {
return [NSString stringWithFormat:@"%ld", (long)value];
}
@end
... ...
//
// NSString+YOHO.h
// YH_Mall
//
// Created by 张同海 on 15/5/28.
// Copyright (c) 2015年 YOHO. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (YOHO)
/**
* @brief 转换系统版本号为整数,示例:CFBundleShortVersionString 3.2.0->320
*
* @return 整型
@since 3.2
*/
+ (NSInteger)yh_getAPPVersionNumber;
/**
@brief 获取自定义UserAgent头
@return 自定义UserAgent
@since 3.5
*/
+ (NSString *)yh_getYohoUserAgent;
/**
@brief 对字符串MD5加密
@return 加密结果
@since 3.1
*/
- (NSString *)yh_md5String;
/**
@brief 根据配置对7牛的jpg的url进行webp处理
@return 返回webp格式的url
@since 3.8
*/
-(NSString *)yh_checkQiniuImageUrlAppendWebp;
/**
@brief 判断字符串移除空白字符后是否为空
@return 是否为空
@since 3.1
*/
- (BOOL)yh_isEmptyAfterTrimmingWhitespaceAndNewlineCharacters;
/**
@brief 去除字符串中包含的空白字符
@return 不含空白字符的字符串
@since 3.1
*/
- (NSString *)yh_stringByTrimmingWhitespaceAndNewlineCharacters;
/**
@brief 将字符串进行urlencoding
@return encoding之后的字符串
@since 3.1
*/
- (NSString *)yh_URLEncodedString;
/**
@brief 将形如¥123,456的价格标示转换为¥123456
@return 不含逗号分隔符的价格字符串
@since 3.1
*/
- (CGFloat)yh_priceValue;
/**
@brief 价格字符串加上人民币符号
@return 带人民币符号的价格字符串
@since 3.1
*/
- (NSString *)yh_stringByPrefixingWithRMBSymbol;
/**
@brief 去除价格字符串中的人民币符号
@return 不带人民币符号的价格字符串
@since 3.1
*/
- (NSString *)yh_stringByDeletingRMBSymbolPrefix;
/**
@brief 判断字符串是否满足邮箱格式
@return 是否是邮箱形式的字符串
@since 3.1
*/
- (BOOL)yh_conformsToEmailFormat;
/**
@brief 判断字符串是否是手机号码格式
@return 是否是手机号码形式的字符串
@since 3.1
*/
- (BOOL)yh_conformsToMobileFormat;
/**
@brief 判断字符串长度时候满足在最大值和最小值之间
@param minimum 字符串长度限制最小值
@param maximum 字符串长度限制最大值
@return 是否满足长度显示
@since 3.1
*/
- (BOOL)yh_isLenghGreaterThanOrEqual:(NSInteger)minimum lessThanOrEqual:(NSInteger)maximum;
/**
@brief 获取字符串中的第一个URL子串的位置
@return URL子串位置
@since 3.1
*/
- (NSRange)yh_firstRangeOfURLSubstringi;
/**
@brief 获取字符串中的第一个URL子串
@return URL子串
@since 3.1
*/
- (NSString *)yh_firstURLSubstring;
/**
@brief 获取字符串中的URL子串
@return URL子串集合
@since 3.1
*/
- (NSArray *)yh_URLSubstrings;
/**
@brief 获取字符串中第一段能头匹配正则表达的字符串
@param regularExpression 匹配正则表达
@return 第一段能匹配的字符串
@since 3.1
*/
- (NSString *)yh_firstMatchUsingRegularExpression:(NSRegularExpression *)regularExpression;
/**
@brief 获取字符串中第一段能头匹配正则表达的字符串
@param regularExpressionPattern 匹配字符串模板
@return 第一段能匹配的字符串
@since 3.1
*/
- (NSString *)yh_firstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern;
/**
@brief 判断字符串是否全部匹配目标字符串的正则表达
@param regularExpressionPattern 匹配字符串模板
@return 是否匹配
@since 3.1
*/
- (BOOL)yh_matchesRegularExpressionPattern:(NSString *)regularExpressionPattern;
/**
@brief 查找符合模板字符串正则表达的第一段字符串的rang
@param regularExpressionPattern 匹配字符串模板
@return 能匹配上的第一段字符串位置
@since 3.1
*/
- (NSRange)yh_rangeOfFirstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern;
/**
@brief 将符合模板字符串正则表达的字符串统一替换为目标字符串
@param regularExpressionPattern 匹配字符串模板
@param templ 替换字符串
@return 完成替换后的字符串
@since 3.1
*/
- (NSString *)yh_stringByReplacingMatchesUsingRegularExpressionPattern:(NSString *)regularExpressionPattern withTemplate:(NSString *)templ;
/**
@brief 将url请求的参数组织为字典形式
@return 参数列表
@since 3.1
*/
- (NSDictionary *)yh_URLParameters;
/**
@brief 判断NSString是数值型
@return 字符串是否是数值
@since 3.1
*/
- (BOOL)yh_isPureDigital;
/**
@brief 图片链接处理,自定义宽高和切图模式
@param width 期望图片宽度
@param height 期望图片高度
@param mode 切图模式
@return 图片url
@since 3.1
*/
- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height mode:(NSString *)mode;
/**
@brief 图片链接处理,自定义宽高,切图模式固定
@param width 期望图片宽度
@param height 期望图片高度
@return 图片url
@since 3.1
*/
- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height;
/**
@brief 获取设置行间距的字符串
@param lineSpacing 指定行间距
@param breakMode 指定换行模式
@param alignment 对齐方式
@return 属性字符串
@since 3.5
*/
- (NSMutableAttributedString *)yh_attributedStringWithLineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode textAlignment:(NSTextAlignment)alignment;
/**
@brief 获取属性字符串
@param font 字体
@param lineSpacing 行间距
@param breakMode 换行模式
@return 属性字符串
@since 3.1
*/
-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode;
/**
@brief 获取属性字符串
@param font 字体
@param lineSpacing 行间距
@param breakMode 换行模式
@param alignment 对齐方式
@return 属性字符串
@since 3.1
*/
-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode alignment:(NSTextAlignment)alignment;
/**
@brief 获取文字占据的尺寸
@param size 文字显示区域大小
@param font 字体
@param lineSpacing 行间距
@param breakMode 换行模式
@return 字符区域大小
@since 3.1
*/
-(CGSize)yh_boundingRectWithSize:(CGSize)size withTextFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode;
- (CGFloat)yh_heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width;
//获取浮点字符串(20.00)
- (NSString *)yh_floatString;
//处理匿名姓名
-(NSString *)yh_anonymousName;
- (NSString *)yh_stringByRemoveRMBSymbol;
//处理匿名号码
- (NSString *)yh_anonymousMoblie;
@end
... ...
//
// NSString+YOHO.m
// YH_Mall
//
// Created by 张同海 on 15/5/28.
// Copyright (c) 2015年 YOHO. All rights reserved.
//
#import "NSString+YOHO.h"
#import <CommonCrypto/CommonDigest.h>
#import <AdSupport/AdSupport.h>
@implementation NSString (YOHO)
- (NSString *)yh_md5String
{
const char *cStr = [self UTF8String];
unsigned char result[16];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
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]
];
}
- (CGFloat)yh_priceValue
{
return [[self stringByReplacingOccurrencesOfString:@"," withString:@""] floatValue];
}
- (BOOL)yh_isEmptyAfterTrimmingWhitespaceAndNewlineCharacters
{
return [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}
- (NSString *)yh_stringByTrimmingWhitespaceAndNewlineCharacters
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding
{
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self, NULL, CFSTR("=,!$&'()*+;@?\n\"<>#\t :/"), encoding));
}
- (NSString *)yh_URLEncodedString
{
return [self URLEncodedStringWithCFStringEncoding:kCFStringEncodingUTF8];
}
+ (NSString *)stringWithDate:(NSDate *)date dateFormat:(NSString *)format
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *dateFormat = nil;
if (format == nil) {
dateFormat = @"y.MM.dd HH: mm: ss";
} else {
dateFormat = format;
}
formatter.dateFormat = dateFormat;
NSString *dateString = [formatter stringFromDate:date];
return dateString;
}
// 长度是否在一个范围之内
- (BOOL)yh_isLenghGreaterThanOrEqual:(NSInteger)minimum lessThanOrEqual:(NSInteger)maximum
{
return ([self length] >= minimum) && ([self length] <= maximum);
}
- (NSRange)yh_firstRangeOfURLSubstringi
{
static NSDataDetector *dataDetector = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dataDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypeLink | NSTextCheckingTypeLink)
error:nil];
});
NSRange range = [dataDetector rangeOfFirstMatchInString:self
options:0
range:NSMakeRange(0, [self length])];
return range;
}
- (NSString *)yh_firstURLSubstring
{
NSRange range = [self yh_firstRangeOfURLSubstringi];
if (range.location == NSNotFound) {
return nil;
}
return [self substringWithRange:range];
}
- (NSArray *)yh_URLSubstrings
{
static NSDataDetector *dataDetector = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dataDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypeLink | NSTextCheckingTypeLink)
error:nil];
});
NSArray *matches = [dataDetector matchesInString:self
options:0
range:NSMakeRange(0, [self length])];
NSMutableArray *substrings = [NSMutableArray arrayWithCapacity:[matches count]];
for (NSTextCheckingResult *result in matches) {
[substrings addObject:[result.URL absoluteString]];
}
return [NSArray arrayWithArray:substrings];
}
- (NSString *)yh_firstMatchUsingRegularExpression:(NSRegularExpression *)regularExpression
{
NSRange range = [regularExpression rangeOfFirstMatchInString:self
options:0
range:NSMakeRange(0, [self length])];
if (range.location == NSNotFound) {
return nil;
}
return [self substringWithRange:range];
}
- (NSString *)yh_firstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern
{
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
options:NSRegularExpressionCaseInsensitive
error:nil];
return [self yh_firstMatchUsingRegularExpression:regularExpression];
}
- (BOOL)yh_matchesRegularExpressionPattern:(NSString *)regularExpressionPattern
{
NSRange fullRange = NSMakeRange(0, [self length]);
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSRange range = [regularExpression rangeOfFirstMatchInString:self
options:0
range:fullRange];
if (NSEqualRanges(fullRange, range)) {
return YES;
}
return NO;
}
- (NSRange)yh_rangeOfFirstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern
{
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSRange range = [regularExpression rangeOfFirstMatchInString:self
options:0
range:NSMakeRange(0, [self length])];
return range;
}
- (NSString *)yh_stringByReplacingMatchesUsingRegularExpressionPattern:(NSString *)regularExpressionPattern withTemplate:(NSString *)templ
{
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *string = [regularExpression stringByReplacingMatchesInString:self
options:0
range:NSMakeRange(0, [self length])
withTemplate:templ];
return string;
}
- (NSDictionary *)yh_URLParameters
{
NSString *urlString = [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSRange rangeOfQuestionMark = [urlString rangeOfString:@"?" options:NSBackwardsSearch];
if (rangeOfQuestionMark.location == NSNotFound) {
return nil;
}
NSString *parametersString = [urlString substringFromIndex:(rangeOfQuestionMark.location + 1)];
NSArray *pairs = [parametersString componentsSeparatedByString:@"&"];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[pairs count]];
for (NSString *aPair in pairs) {
NSArray *keyAndValue = [aPair componentsSeparatedByString:@"="];
if ([keyAndValue count] == 2) {
[parameters setObject:keyAndValue[1] forKey:keyAndValue[0]];
}
}
return parameters;
}
- (BOOL)yh_isPureDigital
{
NSScanner* scan = [NSScanner scannerWithString:self];
long long val;
return [scan scanLongLong:&val] && [scan isAtEnd];
}
- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height mode:(NSString *)mode
{
return [[[[self stringByReplacingOccurrencesOfString:@"{width}" withString:[NSString stringWithFormat:@"%zd",width.integerValue]] stringByReplacingOccurrencesOfString:@"{height}" withString:[NSString stringWithFormat:@"%zd",height.integerValue]] stringByReplacingOccurrencesOfString:@"{mode}" withString:mode] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height
{
return [self yh_splitUrlWithWidth:width height:height mode:@"2"];
}
- (NSMutableAttributedString *)yh_attributedStringWithLineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode textAlignment:(NSTextAlignment)alignment
{
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
[paragraphStyle setLineBreakMode:breakMode];
[paragraphStyle setAlignment:alignment];
[attributedStr addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self length])];
return attributedStr;
}
-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode
{
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font}];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
[paragraphStyle setLineBreakMode:breakMode];
[attributedStr addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self length])];
return attributedStr;
}
-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode alignment:(NSTextAlignment)alignment
{
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font}];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
[paragraphStyle setLineBreakMode:breakMode];
[paragraphStyle setAlignment:alignment];
[attributedStr addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self length])];
return attributedStr;
}
-(CGSize)yh_boundingRectWithSize:(CGSize)size withTextFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode
{
NSMutableAttributedString *attributedText = [self yh_attributedStringFromStingWithFont:font
withLineSpacing:lineSpacing withLineBreakMode:breakMode];
CGSize textSize = CGSizeZero;
if (attributedText.length > 0) {
textSize = [attributedText boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size;
}
return textSize;
}
- (CGFloat)yh_heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width
{
return ceilf([self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.height);
}
- (NSString *)yh_floatString
{
if ([self isKindOfClass:[NSString class]]) {
CGFloat tmp = [self floatValue];
NSString *str = [NSString stringWithFormat:@"%0.2f",tmp];
return str;
} else {
return @"";
}
}
- (NSString *)yh_anonymousName
{
if(self.length == 0) {
return self;
}
NSString *username = self;
if ([username length] == 1||[username length] == 2) {
NSRange range = NSMakeRange([username length]-1, 1);
username = [username stringByReplacingCharactersInRange:range withString:@"*"];
return username;
} else {
NSRange range = NSMakeRange(1, username.length-2);
username = [username stringByReplacingCharactersInRange:range withString:@"***"];
}
return username;
}
- (NSString *)yh_stringByRemoveRMBSymbol
{
return [[self stringByReplacingOccurrencesOfString:@"¥" withString:@""] stringByReplacingOccurrencesOfString:@"¥" withString:@""];
}
- (NSString *)yh_anonymousMoblie
{
if(self.length == 0) {
return self;
}
NSString *anonymousStr = self;
for (int i = 0; i < anonymousStr.length; i ++) {
if (anonymousStr.length < 3) {
break;
}else{
if (i >=3 && i < 7) {
NSRange range = NSMakeRange(i, 1);
anonymousStr = [anonymousStr stringByReplacingCharactersInRange:range withString:@"*"];
}
}
}
return anonymousStr;
}
@end
... ...
... ... @@ -24,10 +24,12 @@
#import "YH_SocketService.h"
#import "UIViewAdditions.h"
#import <CommonCrypto/CommonDigest.h>
#import "YH_Tool.h"
//static const NSInteger socketMaxRetryCount = 3;
#define ContinueAlertTag 9527
// 清晰度定义
#define HD_LEVEL_720P 1 // 1280 * 720
#define HD_LEVEL_540P 2 // 960 * 560
... ... @@ -144,12 +146,28 @@
- (void)viewDidLoad {
[super viewDidLoad];
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == AFNetworkReachabilityStatusNotReachable) {
[YH_Tool alert:@"网络已断开" type:YHBAlertTypeMessage autoHide:NO];
} else {
[YH_Tool hideAlert];
}
}];
[manager startMonitoring];
_currentChannelIndex = -1;
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kPushging];
if (data.length) {
_currentChannel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
if (_currentChannel) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"直播间:%@",_currentChannel.roomTitle] message:nil delegate:self cancelButtonTitle:@"继续上次直播" otherButtonTitles:nil, nil];
alert.tag = ContinueAlertTag;
[alert show];
}
self.view.backgroundColor = [UIColor orangeColor];
[self initUI];
[self loadChannelData];
... ... @@ -386,17 +404,24 @@
NSDictionary* dict = param;
dispatch_async(dispatch_get_main_queue(), ^{
if (EvtID == PUSH_ERR_NET_DISCONNECT) {
DLog(@"已经连接三次了");
dispatch_async(dispatch_get_main_queue(), ^{
;
});
}
long long time = [(NSNumber*)[dict valueForKey:EVT_TIME] longLongValue];
int mil = time % 1000;
NSDate* date = [NSDate dateWithTimeIntervalSince1970:time/1000];
NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
[self appendLog:Msg time:date mills:mil];
if (EvtID == PUSH_WARNING_NET_BUSY) {
[YH_Tool alert:@"网络状况不佳" type:YHBAlertTypeMessage autoHide:YES];
}
if (EvtID == PUSH_WARNING_RECONNECT) {
[YH_Tool alert:@"正在尝试重连,你也可以重启App" type:YHBAlertTypeMessage autoHide:NO];
}
if (EvtID == PUSH_ERR_NET_DISCONNECT) {
[YH_Tool alert:@"重连失败,请重启App" type:YHBAlertTypeMessage autoHide:NO];
}
if (EvtID == PUSH_EVT_PUSH_BEGIN) {
[YH_Tool hideAlert];
}
});
}
... ... @@ -736,10 +761,12 @@
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.firstOtherButtonIndex == buttonIndex) {
[_timer invalidate];
[self socketSendEndNotify];//通知结束。
}
if (alertView.tag == ContinueAlertTag && buttonIndex == 0) {
[self liveButtonPressed:_liveButton];
}
}
- (NSString *)md5:(NSString *)str
... ...
... ... @@ -31,7 +31,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>201607270001</string>
<string>201608080001</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
... ...
//
// Hud.h
// Pantheon
//
// Created by 常 屹 on 14/6/11.
// Copyright (c) 2014年 常 屹. All rights reserved.
//
#import <Foundation/Foundation.h>
@class MBProgressHUD;
@interface Hud : NSObject{
MBProgressHUD *mbProgressHUD;
}
+ (instancetype)defaultInstance;
- (void)showMessage:(NSString *)message;
- (void)loading:(UIView *)view;
- (void)loading:(UIView *)view withText:(NSString *)text;
- (void)hide:(UIView *)view;
- (void)showMessage:(NSString *)message withHud:(BOOL)flag;
@end
... ...
//
// Hud.m
// Pantheon
//
// Created by 常 屹 on 14/6/11.
// Copyright (c) 2014年 常 屹. All rights reserved.
//
#import "Hud.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#define IPHONE5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
@implementation Hud
static Hud *instance = nil;
+ (instancetype)defaultInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[Hud alloc] init];
});
return instance;
}
- (id)init
{
self = [super init];
if (self) {
UINavigationController *navController = (UINavigationController *)[UIApplication sharedApplication].delegate.window.rootViewController;
mbProgressHUD = [[MBProgressHUD alloc] initWithView:navController.view];
}
return self;
}
- (void)showMessage:(NSString *)message
{
[self showMessage:message withHud:NO];
}
- (void)showMessage:(NSString *)message withHud:(BOOL)flag
{
if (!flag) {
[[UIApplication sharedApplication].delegate.window addSubview:mbProgressHUD];
[mbProgressHUD show:YES];
}
mbProgressHUD.mode = MBProgressHUDModeText;
mbProgressHUD.labelText = @"";
mbProgressHUD.detailsLabelText = message;
mbProgressHUD.margin = 10.f;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
mbProgressHUD.yOffset = 80.f;
}
else {
if (IPHONE5) {
mbProgressHUD.yOffset = 200.f;
}
else {
mbProgressHUD.yOffset = 150.f;
}
}
mbProgressHUD.removeFromSuperViewOnHide = YES;
[mbProgressHUD hide:YES afterDelay:2.f];
}
- (void)loading:(UIView *)view
{
[self loading:view withText:@"加载中,请稍后..."];
}
- (void)loading:(UIView *)view withText:(NSString *)text
{
mbProgressHUD.margin = 20.f;
mbProgressHUD.labelText = text;
mbProgressHUD.detailsLabelText = @"";
mbProgressHUD.mode = MBProgressHUDModeIndeterminate;
mbProgressHUD.yOffset = 0.f;
[view addSubview:mbProgressHUD];
[mbProgressHUD show:YES];
}
- (void)hide:(UIView *)view
{
//[MBProgressHUD hideHUDForView:[AppDelegate appDelegate].window animated:YES];
[MBProgressHUD hideHUDForView:view animated:YES];
}
@end
... ...
//
// MBProgressHUD.h
// Version 0.5
// Created by Matej Bukovinski on 2.4.09.
//
// This code is distributed under the terms and conditions of the MIT license.
// Copyright (c) 2011 Matej Bukovinski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>
@protocol MBProgressHUDDelegate;
typedef enum {
/** Progress is shown using an UIActivityIndicatorView. This is the default. */
MBProgressHUDModeIndeterminate,
/** Progress is shown using a round, pie-chart like, progress view. */
MBProgressHUDModeDeterminate,
/** Progress is shown using a ring-shaped progress view. */
MBProgressHUDModeAnnularDeterminate,
/** Shows a custom view */
MBProgressHUDModeCustomView,
/** Shows only labels */
MBProgressHUDModeText
} MBProgressHUDMode;
typedef enum {
/** Opacity animation */
MBProgressHUDAnimationFade,
/** Opacity + scale animation */
MBProgressHUDAnimationZoom
} MBProgressHUDAnimation;
#ifndef MB_STRONG
#if __has_feature(objc_arc)
#define MB_STRONG strong
#else
#define MB_STRONG retain
#endif
#endif
#ifndef MB_WEAK
#if __has_feature(objc_arc_weak)
#define MB_WEAK weak
#elif __has_feature(objc_arc)
#define MB_WEAK unsafe_unretained
#else
#define MB_WEAK assign
#endif
#endif
#if NS_BLOCKS_AVAILABLE
typedef void (^MBProgressHUDCompletionBlock)();
#endif
/**
* Displays a simple HUD window containing a progress indicator and two optional labels for short messages.
*
* This is a simple drop-in class for displaying a progress HUD view similar to Apple's private UIProgressHUD class.
* The MBProgressHUD window spans over the entire space given to it by the initWithFrame constructor and catches all
* user input on this region, thereby preventing the user operations on components below the view. The HUD itself is
* drawn centered as a rounded semi-transparent view which resizes depending on the user specified content.
*
* This view supports four modes of operation:
* - MBProgressHUDModeIndeterminate - shows a UIActivityIndicatorView
* - MBProgressHUDModeDeterminate - shows a custom round progress indicator
* - MBProgressHUDModeAnnularDeterminate - shows a custom annular progress indicator
* - MBProgressHUDModeCustomView - shows an arbitrary, user specified view (@see customView)
*
* All three modes can have optional labels assigned:
* - If the labelText property is set and non-empty then a label containing the provided content is placed below the
* indicator view.
* - If also the detailsLabelText property is set then another label is placed below the first label.
*/
@interface MBProgressHUD : UIView
/**
* Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:.
*
* @param view The view that the HUD will be added to
* @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use
* animations while appearing.
* @return A reference to the created HUD.
*
* @see hideHUDForView:animated:
* @see animationType
*/
+ (MBProgressHUD *)showHUDAddedTo:(UIView *)view animated:(BOOL)animated;
/**
* Finds the top-most HUD subview and hides it. The counterpart to this method is showHUDAddedTo:animated:.
*
* @param view The view that is going to be searched for a HUD subview.
* @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use
* animations while disappearing.
* @return YES if a HUD was found and removed, NO otherwise.
*
* @see showHUDAddedTo:animated:
* @see animationType
*/
+ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated;
/**
* Finds all the HUD subviews and hides them.
*
* @param view The view that is going to be searched for HUD subviews.
* @param animated If set to YES the HUDs will disappear using the current animationType. If set to NO the HUDs will not use
* animations while disappearing.
* @return the number of HUDs found and removed.
*
* @see hideAllHUDForView:animated:
* @see animationType
*/
+ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated;
/**
* Finds the top-most HUD subview and returns it.
*
* @param view The view that is going to be searched.
* @return A reference to the last HUD subview discovered.
*/
+ (MBProgressHUD *)HUDForView:(UIView *)view;
/**
* Finds all HUD subviews and returns them.
*
* @param view The view that is going to be searched.
* @return All found HUD views (array of MBProgressHUD objects).
*/
+ (NSArray *)allHUDsForView:(UIView *)view;
/**
* A convenience constructor that initializes the HUD with the window's bounds. Calls the designated constructor with
* window.bounds as the parameter.
*
* @param window The window instance that will provide the bounds for the HUD. Should be the same instance as
* the HUD's superview (i.e., the window that the HUD will be added to).
*/
- (id)initWithWindow:(UIWindow *)window;
/**
* A convenience constructor that initializes the HUD with the view's bounds. Calls the designated constructor with
* view.bounds as the parameter
*
* @param view The view instance that will provide the bounds for the HUD. Should be the same instance as
* the HUD's superview (i.e., the view that the HUD will be added to).
*/
- (id)initWithView:(UIView *)view;
/**
* Display the HUD. You need to make sure that the main thread completes its run loop soon after this method call so
* the user interface can be updated. Call this method when your task is already set-up to be executed in a new thread
* (e.g., when using something like NSOperation or calling an asynchronous call like NSURLRequest).
*
* @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use
* animations while appearing.
*
* @see animationType
*/
- (void)show:(BOOL)animated;
/**
* Hide the HUD. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to
* hide the HUD when your task completes.
*
* @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use
* animations while disappearing.
*
* @see animationType
*/
- (void)hide:(BOOL)animated;
/**
* Hide the HUD after a delay. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to
* hide the HUD when your task completes.
*
* @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use
* animations while disappearing.
* @param delay Delay in secons until the HUD is hidden.
*
* @see animationType
*/
- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay;
/**
* Shows the HUD while a background task is executing in a new thread, then hides the HUD.
*
* This method also takes care of autorelease pools so your method does not have to be concerned with setting up a
* pool.
*
* @param method The method to be executed while the HUD is shown. This method will be executed in a new thread.
* @param target The object that the target method belongs to.
* @param object An optional object to be passed to the method.
* @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will not use
* animations while (dis)appearing
*/
- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated;
#if NS_BLOCKS_AVAILABLE
/**
* Shows the HUD while a block is executing on a background queue, then hides the HUD.
*
* @see showAnimated:whileExecutingBlock:onQueue:completion:
*/
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block;
/**
* Shows the HUD while a block is executing on a background queue, then hides the HUD.
*
* @see showAnimated:whileExecutingBlock:onQueue:completion:
*/
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(MBProgressHUDCompletionBlock)completion;
/**
* Shows the HUD while a block is executing on the specified dispatch queue, then hides the HUD.
*
* @see showAnimated:whileExecutingBlock:onQueue:completion:
*/
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue;
/**
* Shows the HUD while a block is executing on the specified dispatch queue, executes completion block on the main queue, and then hides the HUD.
*
* @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will
* not use animations while (dis)appearing.
* @param block The block to be executed while the HUD is shown.
* @param queue The dispatch queue on which the block should be execouted.
* @param completion The block to be executed on completion.
*
* @see completionBlock
*/
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue
completionBlock:(MBProgressHUDCompletionBlock)completion;
/**
* A block that gets called after the HUD was completely hiden.
*/
@property (copy) MBProgressHUDCompletionBlock completionBlock;
#endif
/**
* MBProgressHUD operation mode. The default is MBProgressHUDModeIndeterminate.
*
* @see MBProgressHUDMode
*/
@property (assign) MBProgressHUDMode mode;
/**
* The animation type that should be used when the HUD is shown and hidden.
*
* @see MBProgressHUDAnimation
*/
@property (assign) MBProgressHUDAnimation animationType;
/**
* The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView.
* For best results use a 37 by 37 pixel view (so the bounds match the built in indicator bounds).
*/
@property (MB_STRONG) UIView *customView;
/**
* The HUD delegate object.
*
* @see MBProgressHUDDelegate
*/
@property (MB_WEAK) id<MBProgressHUDDelegate> delegate;
/**
* An optional short message to be displayed below the activity indicator. The HUD is automatically resized to fit
* the entire text. If the text is too long it will get clipped by displaying "..." at the end. If left unchanged or
* set to @"", then no message is displayed.
*/
@property (copy) NSString *labelText;
/**
* An optional details message displayed below the labelText message. This message is displayed only if the labelText
* property is also set and is different from an empty string (@""). The details text can span multiple lines.
*/
@property (copy) NSString *detailsLabelText;
/**
* The opacity of the HUD window. Defaults to 0.8 (80% opacity).
*/
@property (assign) float opacity;
/**
* The color of the HUD window. Defaults to black. If this property is set, opacity is set using this UIColor and the
* opacity property is not used
*/
@property (assign) CGColorRef color;
/**
* The x-axis offset of the HUD relative to the centre of the superview.
*/
@property (assign) float xOffset;
/**
* The y-ayis offset of the HUD relative to the centre of the superview.
*/
@property (assign) float yOffset;
/**
* The amounth of space between the HUD edge and the HUD elements (labels, indicators or custom views).
* Defaults to 20.0
*/
@property (assign) float margin;
/**
* Cover the HUD background view with a radial gradient.
*/
@property (assign) BOOL dimBackground;
/*
* Grace period is the time (in seconds) that the invoked method may be run without
* showing the HUD. If the task finishes before the grace time runs out, the HUD will
* not be shown at all.
* This may be used to prevent HUD display for very short tasks.
* Defaults to 0 (no grace time).
* Grace time functionality is only supported when the task status is known!
* @see taskInProgress
*/
@property (assign) float graceTime;
/**
* The minimum time (in seconds) that the HUD is shown.
* This avoids the problem of the HUD being shown and than instantly hidden.
* Defaults to 0 (no minimum show time).
*/
@property (assign) float minShowTime;
/**
* Indicates that the executed operation is in progress. Needed for correct graceTime operation.
* If you don't set a graceTime (different than 0.0) this does nothing.
* This property is automatically set when using showWhileExecuting:onTarget:withObject:animated:.
* When threading is done outside of the HUD (i.e., when the show: and hide: methods are used directly),
* you need to set this property when your task starts and completes in order to have normal graceTime
* functionality.
*/
@property (assign) BOOL taskInProgress;
/**
* Removes the HUD from its parent view when hidden.
* Defaults to NO.
*/
@property (assign) BOOL removeFromSuperViewOnHide;
/**
* Font to be used for the main label. Set this property if the default is not adequate.
*/
@property (MB_STRONG) UIFont* labelFont;
/**
* Font to be used for the details label. Set this property if the default is not adequate.
*/
@property (MB_STRONG) UIFont* detailsLabelFont;
/**
* The progress of the progress indicator, from 0.0 to 1.0. Defaults to 0.0.
*/
@property (assign) float progress;
/**
* The minimum size of the HUD bezel. Defaults to CGSizeZero (no minimum size).
*/
@property (assign) CGSize minSize;
/**
* Force the HUD dimensions to be equal if possible.
*/
@property (assign, getter = isSquare) BOOL square;
@end
@protocol MBProgressHUDDelegate <NSObject>
@optional
/**
* Called after the HUD was fully hidden from the screen.
*/
- (void)hudWasHidden:(MBProgressHUD *)hud;
@end
/**
* A progress view for showing definite progress by filling up a circle (pie chart).
*/
@interface MBRoundProgressView : UIView
/**
* Progress (0.0 to 1.0)
*/
@property (nonatomic, assign) float progress;
/*
* Display mode - NO = round or YES = annular. Defaults to round.
*/
@property (nonatomic, assign, getter = isAnnular) BOOL annular;
@end
... ...
//
// MBProgressHUD.m
// Version 0.5
// Created by Matej Bukovinski on 2.4.09.
//
#import "MBProgressHUD.h"
#import "NSString+YOHO.h"
#if __has_feature(objc_arc)
#define MB_AUTORELEASE(exp) exp
#define MB_RELEASE(exp) exp
#define MB_RETAIN(exp) exp
#else
#define MB_AUTORELEASE(exp) [exp autorelease]
#define MB_RELEASE(exp) [exp release]
#define MB_RETAIN(exp) [exp retain]
#endif
static const CGFloat kPadding = 4.f;
static const CGFloat kLabelFontSize = 16.f;
static const CGFloat kDetailsLabelFontSize = 12.f;
static const CGFloat kDetailsLabelLineSpace = 4.0f;
@interface MBProgressHUD ()
- (void)setupLabels;
- (void)registerForKVO;
- (void)unregisterFromKVO;
- (NSArray *)observableKeypaths;
- (void)registerForNotifications;
- (void)unregisterFromNotifications;
- (void)updateUIForKeypath:(NSString *)keyPath;
- (void)hideUsingAnimation:(BOOL)animated;
- (void)showUsingAnimation:(BOOL)animated;
- (void)done;
- (void)updateIndicators;
- (void)handleGraceTimer:(NSTimer *)theTimer;
- (void)handleMinShowTimer:(NSTimer *)theTimer;
- (void)setTransformForCurrentOrientation:(BOOL)animated;
- (void)cleanUp;
- (void)launchExecution;
- (void)deviceOrientationDidChange:(NSNotification *)notification;
- (void)hideDelayed:(NSNumber *)animated;
@property (MB_STRONG) UIView *indicator;
@property (MB_STRONG) NSTimer *graceTimer;
@property (MB_STRONG) NSTimer *minShowTimer;
@property (MB_STRONG) NSDate *showStarted;
@property (assign) CGSize size;
@end
@implementation MBProgressHUD {
BOOL useAnimation;
SEL methodForExecution;
id targetForExecution;
id objectForExecution;
UILabel *label;
UILabel *detailsLabel;
BOOL isFinished;
CGAffineTransform rotationTransform;
}
#pragma mark - Properties
@synthesize animationType;
@synthesize delegate;
@synthesize opacity;
@synthesize color;
@synthesize labelFont;
@synthesize detailsLabelFont;
@synthesize indicator;
@synthesize xOffset;
@synthesize yOffset;
@synthesize minSize;
@synthesize square;
@synthesize margin;
@synthesize dimBackground;
@synthesize graceTime;
@synthesize minShowTime;
@synthesize graceTimer;
@synthesize minShowTimer;
@synthesize taskInProgress;
@synthesize removeFromSuperViewOnHide;
@synthesize customView;
@synthesize showStarted;
@synthesize mode;
@synthesize labelText;
@synthesize detailsLabelText;
@synthesize progress;
@synthesize size;
#if NS_BLOCKS_AVAILABLE
@synthesize completionBlock;
#endif
#pragma mark - Class methods
+ (MBProgressHUD *)showHUDAddedTo:(UIView *)view animated:(BOOL)animated {
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
[view addSubview:hud];
[hud show:animated];
return MB_AUTORELEASE(hud);
}
+ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated {
MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
if (hud != nil) {
hud.removeFromSuperViewOnHide = YES;
[hud hide:animated];
return YES;
}
return NO;
}
+ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated {
NSArray *huds = [self allHUDsForView:view];
for (MBProgressHUD *hud in huds) {
hud.removeFromSuperViewOnHide = YES;
[hud hide:animated];
}
return [huds count];
}
+ (MBProgressHUD *)HUDForView:(UIView *)view {
MBProgressHUD *hud = nil;
NSArray *subviews = view.subviews;
Class hudClass = [MBProgressHUD class];
for (UIView *aView in subviews) {
if ([aView isKindOfClass:hudClass]) {
hud = (MBProgressHUD *)aView;
}
}
return hud;
}
+ (NSArray *)allHUDsForView:(UIView *)view {
NSMutableArray *huds = [NSMutableArray array];
NSArray *subviews = view.subviews;
Class hudClass = [MBProgressHUD class];
for (UIView *aView in subviews) {
if ([aView isKindOfClass:hudClass]) {
[huds addObject:aView];
}
}
return [NSArray arrayWithArray:huds];
}
#pragma mark - Lifecycle
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Set default values for properties
self.animationType = MBProgressHUDAnimationFade;
self.mode = MBProgressHUDModeIndeterminate;
self.labelText = nil;
self.detailsLabelText = nil;
self.opacity = 0.7f;
self.color = nil;
self.labelFont = [UIFont boldSystemFontOfSize:kLabelFontSize];
self.detailsLabelFont = [UIFont boldSystemFontOfSize:kDetailsLabelFontSize];
self.xOffset = 0.0f;
self.yOffset = 0.0f;
self.dimBackground = NO;
self.margin = 20.0f;
self.graceTime = 0.0f;
self.minShowTime = 0.0f;
self.removeFromSuperViewOnHide = NO;
self.minSize = CGSizeZero;
self.square = NO;
self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
// Transparent background
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
// Make it invisible for now
self.alpha = 0.0f;
taskInProgress = NO;
rotationTransform = CGAffineTransformIdentity;
[self setupLabels];
[self updateIndicators];
[self registerForKVO];
[self registerForNotifications];
}
return self;
}
- (id)initWithView:(UIView *)view {
NSAssert(view, @"View must not be nil.");
id me = [self initWithFrame:view.bounds];
// We need to take care of rotation ourselfs if we're adding the HUD to a window
if ([view isKindOfClass:[UIWindow class]]) {
[self setTransformForCurrentOrientation:NO];
}
return me;
}
- (id)initWithWindow:(UIWindow *)window {
return [self initWithView:window];
}
- (void)dealloc {
[self unregisterFromNotifications];
[self unregisterFromKVO];
#if !__has_feature(objc_arc)
[indicator release];
[label release];
[detailsLabel release];
[labelText release];
[detailsLabelText release];
[graceTimer release];
[minShowTimer release];
[showStarted release];
[customView release];
#if NS_BLOCKS_AVAILABLE
[completionBlock release];
#endif
[super dealloc];
#endif
}
#pragma mark - Show & hide
- (void)show:(BOOL)animated {
useAnimation = animated;
// If the grace time is set postpone the HUD display
if (self.graceTime > 0.0) {
self.graceTimer = [NSTimer scheduledTimerWithTimeInterval:self.graceTime target:self
selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
}
// ... otherwise show the HUD imediately
else {
[self setNeedsDisplay];
[self showUsingAnimation:useAnimation];
}
}
- (void)hide:(BOOL)animated {
useAnimation = animated;
// If the minShow time is set, calculate how long the hud was shown,
// and pospone the hiding operation if necessary
if (self.minShowTime > 0.0 && showStarted) {
NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:showStarted];
if (interv < self.minShowTime) {
self.minShowTimer = [NSTimer scheduledTimerWithTimeInterval:(self.minShowTime - interv) target:self
selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO];
return;
}
}
// ... otherwise hide the HUD immediately
[self hideUsingAnimation:useAnimation];
}
- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay {
[self performSelector:@selector(hideDelayed:) withObject:[NSNumber numberWithBool:animated] afterDelay:delay];
}
- (void)hideDelayed:(NSNumber *)animated {
[self hide:[animated boolValue]];
}
#pragma mark - Timer callbacks
- (void)handleGraceTimer:(NSTimer *)theTimer {
// Show the HUD only if the task is still running
if (taskInProgress) {
[self setNeedsDisplay];
[self showUsingAnimation:useAnimation];
}
}
- (void)handleMinShowTimer:(NSTimer *)theTimer {
[self hideUsingAnimation:useAnimation];
}
#pragma mark - Internal show & hide operations
- (void)showUsingAnimation:(BOOL)animated {
self.alpha = 0.0f;
if (animated && animationType == MBProgressHUDAnimationZoom) {
self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f));
}
self.showStarted = [NSDate date];
// Fade in
if (animated) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.30];
self.alpha = 1.0f;
if (animationType == MBProgressHUDAnimationZoom) {
self.transform = rotationTransform;
}
[UIView commitAnimations];
}
else {
self.alpha = 1.0f;
}
}
- (void)hideUsingAnimation:(BOOL)animated {
// Fade out
if (animated && showStarted) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.30];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
// 0.02 prevents the hud from passing through touches during the animation the hud will get completely hidden
// in the done method
if (animationType == MBProgressHUDAnimationZoom) {
self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f));
}
self.alpha = 0.02f;
[UIView commitAnimations];
}
else {
self.alpha = 0.0f;
[self done];
}
self.showStarted = nil;
}
- (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context {
[self done];
}
- (void)done {
isFinished = YES;
self.alpha = 0.0f;
if ([delegate respondsToSelector:@selector(hudWasHidden:)]) {
[delegate performSelector:@selector(hudWasHidden:) withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if (self.completionBlock) {
self.completionBlock();
self.completionBlock = NULL;
}
#endif
if (removeFromSuperViewOnHide) {
[self removeFromSuperview];
}
}
#pragma mark - Threading
- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated {
methodForExecution = method;
targetForExecution = MB_RETAIN(target);
objectForExecution = MB_RETAIN(object);
// Launch execution in new thread
self.taskInProgress = YES;
[NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil];
// Show HUD view
[self show:animated];
}
#if NS_BLOCKS_AVAILABLE
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL];
}
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(void (^)())completion {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:completion];
}
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue {
[self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL];
}
- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue
completionBlock:(MBProgressHUDCompletionBlock)completion {
self.completionBlock = completion;
dispatch_async(queue, ^(void) {
block();
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self cleanUp];
});
});
[self show:animated];
}
#endif
- (void)launchExecution {
@autoreleasepool {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
// Start executing the requested task
[targetForExecution performSelector:methodForExecution withObject:objectForExecution];
#pragma clang diagnostic pop
// Task completed, update view in main thread (note: view operations should
// be done only in the main thread)
[self performSelectorOnMainThread:@selector(cleanUp) withObject:nil waitUntilDone:NO];
}
}
- (void)cleanUp {
taskInProgress = NO;
self.indicator = nil;
#if !__has_feature(objc_arc)
[targetForExecution release];
[objectForExecution release];
#endif
[self hide:useAnimation];
}
#pragma mark - UI
- (void)setupLabels {
label = [[UILabel alloc] initWithFrame:self.bounds];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = NSTextAlignmentCenter;
label.opaque = NO;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.font = self.labelFont;
label.text = self.labelText;
[self addSubview:label];
detailsLabel = [[UILabel alloc] initWithFrame:self.bounds];
detailsLabel.adjustsFontSizeToFitWidth = NO;
detailsLabel.textAlignment = NSTextAlignmentCenter;
detailsLabel.opaque = NO;
detailsLabel.backgroundColor = [UIColor clearColor];
detailsLabel.textColor = [UIColor whiteColor];
detailsLabel.numberOfLines = 0;
detailsLabel.font = self.detailsLabelFont;
// detailsLabel.text = self.detailsLabelText;
NSAttributedString *attributedStr = [self.detailsLabelText yh_attributedStringFromStingWithFont:self.detailsLabelFont lineSpacing:kDetailsLabelLineSpace lineBreakMode:NSLineBreakByCharWrapping alignment:NSTextAlignmentCenter];
detailsLabel.attributedText = attributedStr;
[self addSubview:detailsLabel];
}
- (void)updateIndicators {
BOOL isActivityIndicator = [indicator isKindOfClass:[UIActivityIndicatorView class]];
BOOL isRoundIndicator = [indicator isKindOfClass:[MBRoundProgressView class]];
if (mode == MBProgressHUDModeIndeterminate && !isActivityIndicator) {
// Update to indeterminate indicator
[indicator removeFromSuperview];
self.indicator = MB_AUTORELEASE([[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]);
[(UIActivityIndicatorView *)indicator startAnimating];
[self addSubview:indicator];
}
else if (mode == MBProgressHUDModeDeterminate || mode == MBProgressHUDModeAnnularDeterminate) {
if (!isRoundIndicator) {
// Update to determinante indicator
[indicator removeFromSuperview];
self.indicator = MB_AUTORELEASE([[MBRoundProgressView alloc] init]);
[self addSubview:indicator];
}
if (mode == MBProgressHUDModeAnnularDeterminate) {
[(MBRoundProgressView *)indicator setAnnular:YES];
}
}
else if (mode == MBProgressHUDModeCustomView && customView != indicator) {
// Update custom view indicator
[indicator removeFromSuperview];
self.indicator = customView;
[self addSubview:indicator];
} else if (mode == MBProgressHUDModeText) {
[indicator removeFromSuperview];
self.indicator = nil;
}
}
#pragma mark - Layout
- (void)layoutSubviews {
// Entirely cover the parent view
UIView *parent = self.superview;
if (parent) {
self.frame = parent.bounds;
}
CGRect bounds = self.bounds;
// Determine the total widt and height needed
CGFloat maxWidth = bounds.size.width - 4 * margin;
CGSize totalSize = CGSizeZero;
CGRect indicatorF = indicator.bounds;
indicatorF.size.width = MIN(indicatorF.size.width, maxWidth);
totalSize.width = MAX(totalSize.width, indicatorF.size.width);
totalSize.height += indicatorF.size.height;
CGSize labelSize = [label.text sizeWithAttributes:@{NSFontAttributeName : label.font}];
labelSize.width = MIN(labelSize.width, maxWidth);
totalSize.width = MAX(totalSize.width, labelSize.width);
totalSize.height += labelSize.height;
if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
totalSize.height += kPadding;
}
CGFloat remainingHeight = bounds.size.height - totalSize.height - kPadding - 4 * margin;
CGSize maxSize = CGSizeMake(maxWidth, remainingHeight);
// CGSize detailsLabelSize = [detailsLabel.text sizeWithFont:detailsLabel.font
// constrainedToSize:maxSize lineBreakMode:detailsLabel.lineBreakMode];
CGSize detailsLabelSize = CGSizeZero;
if (detailsLabel.attributedText.length > 0) {
detailsLabelSize = [detailsLabel.attributedText boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
detailsLabelSize.height = ceilf(detailsLabelSize.height)+2;
} else {
detailsLabelSize = [detailsLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : detailsLabel.font} context:nil].size;
}
totalSize.width = MAX(totalSize.width, detailsLabelSize.width);
totalSize.height += detailsLabelSize.height;
if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) {
totalSize.height += kPadding;
}
totalSize.width += 2 * margin;
totalSize.height += 2 * margin;
// Position elements
CGFloat yPos = roundf(((bounds.size.height - totalSize.height) / 2)) + margin + yOffset;
CGFloat xPos = xOffset;
indicatorF.origin.y = yPos;
indicatorF.origin.x = roundf((bounds.size.width - indicatorF.size.width) / 2) + xPos;
indicator.frame = indicatorF;
yPos += indicatorF.size.height;
if (labelSize.height > 0.f && indicatorF.size.height > 0.f) {
yPos += kPadding;
}
CGRect labelF;
labelF.origin.y = yPos;
labelF.origin.x = roundf((bounds.size.width - labelSize.width) / 2) + xPos;
labelF.size = labelSize;
label.frame = labelF;
yPos += labelF.size.height;
if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) {
yPos += kPadding;
}
CGRect detailsLabelF;
detailsLabelF.origin.y = yPos;
detailsLabelF.origin.x = roundf((bounds.size.width - detailsLabelSize.width) / 2) + xPos;
detailsLabelF.size = detailsLabelSize;
detailsLabel.frame = detailsLabelF;
// Enforce minsize and quare rules
if (square) {
CGFloat max = MAX(totalSize.width, totalSize.height);
if (max <= bounds.size.width - 2 * margin) {
totalSize.width = max;
}
if (max <= bounds.size.height - 2 * margin) {
totalSize.height = max;
}
}
if (totalSize.width < minSize.width) {
totalSize.width = minSize.width;
}
if (totalSize.height < minSize.height) {
totalSize.height = minSize.height;
}
self.size = totalSize;
}
#pragma mark BG Drawing
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
if (self.dimBackground) {
//Gradient colours
size_t gradLocationsNum = 2;
CGFloat gradLocations[2] = {0.0f, 1.0f};
CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
CGColorSpaceRelease(colorSpace);
//Gradient center
CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
//Gradient radius
float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;
//Gradient draw
CGContextDrawRadialGradient (context, gradient, gradCenter,
0, gradCenter, gradRadius,
kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient);
}
// Set background rect color
if(self.color){
CGContextSetFillColorWithColor(context, self.color);
} else {
CGContextSetGrayFillColor(context, 0.0f, self.opacity);
}
// Center HUD
CGRect allRect = self.bounds;
// Draw rounded HUD backgroud rect
CGRect boxRect = CGRectMake(roundf((allRect.size.width - size.width) / 2) + self.xOffset,
roundf((allRect.size.height - size.height) / 2) + self.yOffset, size.width, size.height);
float radius = 10.0f;
CGContextBeginPath(context);
CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect));
CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0);
CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0);
CGContextClosePath(context);
CGContextFillPath(context);
}
#pragma mark - KVO
- (void)registerForKVO {
for (NSString *keyPath in [self observableKeypaths]) {
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
}
}
- (void)unregisterFromKVO {
for (NSString *keyPath in [self observableKeypaths]) {
[self removeObserver:self forKeyPath:keyPath];
}
}
- (NSArray *)observableKeypaths {
return [NSArray arrayWithObjects:@"mode", @"customView", @"labelText", @"labelFont",
@"detailsLabelText", @"detailsLabelFont", @"progress", nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(updateUIForKeypath:) withObject:keyPath waitUntilDone:NO];
} else {
[self updateUIForKeypath:keyPath];
}
}
- (void)updateUIForKeypath:(NSString *)keyPath {
if ([keyPath isEqualToString:@"mode"] || [keyPath isEqualToString:@"customView"]) {
[self updateIndicators];
} else if ([keyPath isEqualToString:@"labelText"]) {
label.text = self.labelText;
} else if ([keyPath isEqualToString:@"labelFont"]) {
label.font = self.labelFont;
} else if ([keyPath isEqualToString:@"detailsLabelText"]) {
// detailsLabel.text = self.detailsLabelText;
NSAttributedString *attributedStr = [self.detailsLabelText yh_attributedStringFromStingWithFont:self.detailsLabelFont lineSpacing:kDetailsLabelLineSpace lineBreakMode:NSLineBreakByCharWrapping alignment:NSTextAlignmentCenter];
detailsLabel.attributedText = attributedStr;
} else if ([keyPath isEqualToString:@"detailsLabelFont"]) {
detailsLabel.font = self.detailsLabelFont;
} else if ([keyPath isEqualToString:@"progress"]) {
if ([indicator respondsToSelector:@selector(setProgress:)]) {
[(id)indicator setProgress:progress];
}
return;
}
[self setNeedsLayout];
[self setNeedsDisplay];
}
#pragma mark - Notifications
- (void)registerForNotifications {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(deviceOrientationDidChange:)
name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)unregisterFromNotifications {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)deviceOrientationDidChange:(NSNotification *)notification {
UIView *superview = self.superview;
if (!superview) {
return;
} else if ([superview isKindOfClass:[UIWindow class]]) {
[self setTransformForCurrentOrientation:YES];
} else {
self.bounds = self.superview.bounds;
[self setNeedsDisplay];
}
}
- (void)setTransformForCurrentOrientation:(BOOL)animated {
// Stay in sync with the superview
if (self.superview) {
self.bounds = self.superview.bounds;
[self setNeedsDisplay];
}
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
float radians = 0;
if (UIInterfaceOrientationIsLandscape(orientation)) {
if (orientation == UIInterfaceOrientationLandscapeLeft) { radians = -M_PI_2; }
else { radians = M_PI_2; }
// Window coordinates differ!
self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width);
} else {
if (orientation == UIInterfaceOrientationPortraitUpsideDown) { radians = M_PI; }
else { radians = 0; }
}
rotationTransform = CGAffineTransformMakeRotation(radians);
if (animated) {
[UIView beginAnimations:nil context:nil];
}
[self setTransform:rotationTransform];
if (animated) {
[UIView commitAnimations];
}
}
@end
@implementation MBRoundProgressView {
float _progress;
BOOL _annular;
}
#pragma mark - Accessors
- (float)progress {
return _progress;
}
- (void)setProgress:(float)progress {
_progress = progress;
[self setNeedsDisplay];
}
- (BOOL)isAnnular {
return _annular;
}
- (void)setAnnular:(BOOL)annular {
_annular = annular;
[self setNeedsDisplay];
}
#pragma mark - Lifecycle
- (id)init {
return [self initWithFrame:CGRectMake(0.f, 0.f, 37.f, 37.f)];
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
_progress = 0.f;
_annular = NO;
}
return self;
}
#pragma mark - Drawing
- (void)drawRect:(CGRect)rect {
CGRect allRect = self.bounds;
CGRect circleRect = CGRectInset(allRect, 2.0f, 2.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
if (_annular) {
// Draw background
CGFloat lineWidth = 5.f;
UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath];
processBackgroundPath.lineWidth = lineWidth;
processBackgroundPath.lineCapStyle = kCGLineCapRound;
CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
CGFloat radius = (self.bounds.size.width - lineWidth)/2;
CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees
CGFloat endAngle = (2 * (float)M_PI) + startAngle;
[processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.1] set];
[processBackgroundPath stroke];
// Draw progress
UIBezierPath *processPath = [UIBezierPath bezierPath];
processPath.lineCapStyle = kCGLineCapRound;
processPath.lineWidth = lineWidth;
endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
[processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
[[UIColor whiteColor] set];
[processPath stroke];
} else {
// Draw background
CGContextSetRGBStrokeColor(context, 1.0f, 1.0f, 1.0f, 1.0f); // white
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 0.1f); // translucent white
CGContextSetLineWidth(context, 2.0f);
CGContextFillEllipseInRect(context, circleRect);
CGContextStrokeEllipseInRect(context, circleRect);
// Draw progress
CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2);
CGFloat radius = (allRect.size.width - 4) / 2;
CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees
CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f); // white
CGContextMoveToPoint(context, center.x, center.y);
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0);
CGContextClosePath(context);
CGContextFillPath(context);
}
}
@end
... ...
//
// YH_Tool.h
// YH_Mall
//
// Created by XingYaXin on 14-10-10.
// Copyright (c) 2014年 YOHO. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MBProgressHUD.h"
typedef enum {
YHBAlertTypeMessage,
YHBAlertTypeSuccess,
YHBAlertTypeFail,
YHBAlertTypeNetwork,
YHBAlertTypeWait,
YHBAlertTypeCustom
} YHBAlertType;
extern NSTimeInterval const kAlertDelayTime;
@interface YH_Tool : NSObject
/**
@brief 显示一条弹出提示信息,所有不加view参数的,都是默认加在主window上,无法进行其他操作!!!
@param message 提示信息
@param type 消息类型 YHBAlertType
@param isAutoHide 自动隐藏提示开关
@param view alert view的父视图
@since 3.0.0
*/
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide inView:(UIView *)view;
/**
@brief 显示一条弹出提示信息,父视图是keywindow
@param message 提示信息
@param type 消息类型
@param isAutoHide 自动隐藏提示开关
@since 3.0.0
*/
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide;
/**
@brief 显示一条弹出提示信息,父视图是keywindow
@param message 提示信息
@param type 消息类型
@param time 提示时间
@since 3.9.2
*/
+ (void)alert:(NSString *)message type:(YHBAlertType)type durationTime:(NSTimeInterval)time;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 提示信息
@param type 消息类型
@since 3.0.0
*/
+ (void)alert:(NSString *)message type:(YHBAlertType)type;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 提示信息,消息类型为YHBAlertTypeMessage
@since 3.0.0
*/
+ (void)alertMessage:(NSString *)message;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 成功的提示语
@since 3.0.0
*/
+ (void)alertSuccess:(NSString *)message;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 失败的提示语
@since 3.0.0
*/
+ (void)alertFail:(NSString *)message;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 带网络标识的提示语
@since 3.0.0
*/
+ (void)alertNetwork:(NSString *)message;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param message 网络提示语“您的网络不给力,请稍后再试”
@since 3.0.0
*/
+ (void)alertNetworkLess;
/**
@brief 显示一条YHBAlertTypeWait类型的提示语
@since 3.0.0
*/
+ (void)alertWait;
/**
@brief 隐藏keywinow上的提示框
@since 3.0.0
*/
+ (void)hideAlert;
/**
@brief 隐藏指定视图上的提示框
@since 3.0.0
*/
+ (void)hideAlertInView:(UIView *)view;
/**
@brief 显示一条1s后自动隐藏的提示信息,父视图是keywindow
@param alertImage 自定义的提示图标
@param message 带网络标识的提示语
@param time 自动隐藏提示开关
@since 4.1.0
*/
+ (void)alertCustomView:(UIImage *)alertImage message:(NSString *)message durationTime:(NSTimeInterval)time;
@end
... ...
//
// YH_Tool.m
// YH_Mall
//
// Created by XingYaXin on 14-10-10.
// Copyright (c) 2014年 YOHO. All rights reserved.
//
#import "YH_Tool.h"
#import <UIKit/UIKit.h>
NSTimeInterval const kAlertDelayTime = 1.0f;
@implementation YH_Tool
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide inView:(UIView *)view
{
[self alert:message type:type autoHide:isAutoHide inView:view durationTime:kAlertDelayTime];
}
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide inView:(UIView *)view durationTime:(NSTimeInterval)duration
{
[self alert:message type:type autoHide:isAutoHide inView:view durationTime:duration alertImage:nil];
}
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide inView:(UIView *)view durationTime:(NSTimeInterval)duration alertImage:(UIImage *)alertImage
{
NSString *msg = @"";
if (IsNilOrNull(message) || [message isEqualToString:@""]) {
if (type == YHBAlertTypeFail) {
return;
}
msg = NSLocalizedString(@"loading...", nil);
}else{
msg = message;
}
if (view == nil) {
view = [[UIApplication sharedApplication] keyWindow];
}
[self hideAlertInView:view];
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
hud.detailsLabelFont = [UIFont systemFontOfSize:12];
hud.detailsLabelText = msg;
hud.yOffset = -60.0f;
hud.removeFromSuperViewOnHide = YES;
NSString *alertImageName = @"";
MBProgressHUDMode mode = MBProgressHUDModeCustomView;
if (type == YHBAlertTypeFail) {
alertImageName = @"shared_alert_fail";
}
else if (type == YHBAlertTypeSuccess) {
alertImageName = @"shared_alert_success";
}
else if (type == YHBAlertTypeNetwork) {
alertImageName = @"shared_alert_network";
}
else if (type == YHBAlertTypeMessage) {
alertImageName = @"shared_alert_message";
}
else if (type == YHBAlertTypeWait) {
mode = MBProgressHUDModeIndeterminate;
}
if (type == YHBAlertTypeCustom) {
hud.customView = [[UIImageView alloc] initWithImage:alertImage];
} else if (mode == MBProgressHUDModeCustomView){
hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:alertImageName]];
}
hud.mode = mode;
[view addSubview:hud];
[hud show:YES];
if (isAutoHide) {
double delayInSeconds = (duration > 0 ? duration : kAlertDelayTime);
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[hud hide:YES];
});
}
}
+ (void)alert:(NSString *)message type:(YHBAlertType)type autoHide:(BOOL)isAutoHide
{
[self alert:message type:type autoHide:isAutoHide inView:[[UIApplication sharedApplication] keyWindow]];
}
+ (void)alert:(NSString *)message type:(YHBAlertType)type durationTime:(NSTimeInterval)time
{
[self alert:message type:type autoHide:YES inView:[[UIApplication sharedApplication] keyWindow] durationTime:time];
}
+ (void)alert:(NSString *)message type:(YHBAlertType)type
{
[self alert:message type:type autoHide:YES];
}
+ (void)alertMessage:(NSString *)message
{
[self alert:message type:YHBAlertTypeMessage];
}
+ (void)alertSuccess:(NSString *)message
{
[self alert:message type:YHBAlertTypeSuccess];
}
+ (void)alertFail:(NSString *)message
{
[self alert:message type:YHBAlertTypeFail];
}
+ (void)alertNetwork:(NSString *)message
{
[self alert:message type:YHBAlertTypeNetwork];
}
+ (void)alertNetworkLess
{
[self alertNetwork:NSLocalizedString(@"bad network try later", nil)];
}
+ (void)alertWait
{
[self alert:NSLocalizedString(@"loading...", nil) type:YHBAlertTypeWait autoHide:NO];
}
+ (void)hideAlert
{
[MBProgressHUD hideAllHUDsForView:[[UIApplication sharedApplication] keyWindow] animated:NO];
}
+ (void)hideAlertInView:(UIView *)view
{
[MBProgressHUD hideAllHUDsForView:view animated:NO];
}
+ (void)alertCustomView:(UIImage *)alertImage message:(NSString *)message durationTime:(NSTimeInterval)time
{
[self alert:message type:YHBAlertTypeCustom autoHide:YES inView:[[UIApplication sharedApplication] keyWindow] durationTime:time alertImage:alertImage];
}
@end
... ...