IOS常用方法封装(1)
来源:互联网 发布:java架构师视频双11 编辑:程序博客网 时间:2024/05/09 22:43
1:关于AFN的GET请求封装
+ (void)getWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id))success
failure:(void (^)(NSError *))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
/**
* 可以接受的类型
*/
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
/**
* 请求队列的最大并发数
*/
// manager.operationQueue.maxConcurrentOperationCount = 5;
/**
* 请求超时的时间
*/
manager.requestSerializer.timeoutInterval =5;
[manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError *_Nonnull error) {
if (failure) {
failure(error);
}
}];
}
2:代码屏幕适配#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define SP_W(width) WIDTH*(width/320.0)
#define SP_H(height) HEIGHT*(height/480.0)
//颜色的RGB
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(float)r/255.0f green:(float)g/255.0f blue:(float)b/255.0f alpha:a]
// 颜色
#define LTColor(r, g, b, a) ([UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a])
#define LTWhiteColor (LTColor(255,255,255,1))
// 构造CGRect
#define LTRect(x, y, w, h) (CGRectMake(x, y, w, h))
// 普通字体
#define LTFont(size) ([UIFont systemFontOfSize:size])
// 粗体字
#define LTBoldFont(size) ([UIFont boldSystemFontOfSize:size])
3:AFN上传图片
+(void)updatePhoto:(NSData *)photo block:(void (^)(NSDictionary *))block fail:(void (^)(void))fail{
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManagermanager];
NSString *path=[NSHomeDirectory()stringByAppendingPathComponent:@"tx.png"];
[photo writeToFile:pathatomically:YES];
[manager POST:BASE_URL(@"/add_photo")parameters:@{@"photo":path}constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:photoname:@"photo"fileName:@"file.jpg"mimeType:@"image/jpg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSDictionary *dic=responseObject;
block(dic);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
fail();
}];
}
4:AFNPost请求+(void)request:(NSString *)url dictionary:(NSDictionary*)dic block:(void(^)(NSDictionary*dic))block fail:(void(^)(void))fail{
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManagermanager];
manager.requestSerializer.timeoutInterval=10;
// [manager setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager POST:BASE_URL(url)parameters:dicconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSDictionary *dic=responseObject;
block(dic);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
fail();
NSLog(@"error==%@",error);
}];
}
5:显示文字的MBProgressHUD-(void)showMBHud:(NSString *)str{
MBProgressHUD *hud = [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];
hud.mode =MBProgressHUDModeText;
hud.labelText = str;
hud.margin =10.f;
hud.removeFromSuperViewOnHide =YES;
[hud hide:YESafterDelay:3];
}
6:获取一个APPDelegate 实例
+(AppDelegate *)getAppdelegate{
AppDelegate * appDelegate = (AppDelegate *)[[UIApplicationsharedApplication]delegate];
return appDelegate;
}
7:讲json字符串变成字典+ (id)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString ==nil) {
NSLog(@"解析失败");
returnnil;
}
NSData *jsonData = [jsonStringdataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
id dic = [NSJSONSerializationJSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
returnnil;
}
return dic;
}
8:判断身份证号+(BOOL)CardId:(NSString*)str{
NSString *regex =@"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicateevaluateWithObject:str]==YES) {
returnYES;
}else{
returnNO;
}
}
9:判断电话号+(BOOL)phoneNum:(NSString *)phoneNum{
//确定正则表达式;(只可以输入数字)
/**
* 手机号码
* 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
* 联通:130,131,132,152,155,156,185,186
* 电信:133,1349,153,180,189
*/
NSString * MOBILE =@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
/**
10 * 中国移动:China Mobile
11 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
12 */
NSString * CM =@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
/**
15 * 中国联通:China Unicom
16 * 130,131,132,152,155,156,185,186
17 */
NSString * CU =@"^1(3[0-2]|5[256]|8[56])\\d{8}$";
/**
20 * 中国电信:China Telecom
21 * 133,153,180,181,189,177
22 */
NSString * CT =@"^1((33|53|77|8[019])[0-9]|349)\\d{7}$";
/**
25 * 大陆地区固话及小灵通
26 * 区号:010,020,021,022,023,024,025,027,028,029
27 * 号码:七位或八位
28 */
// NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
NSPredicate *regextestmobile = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CT];
if (([regextestmobileevaluateWithObject:phoneNum])
|| ([regextestcm evaluateWithObject:phoneNum])
|| ([regextestct evaluateWithObject:phoneNum])
|| ([regextestcu evaluateWithObject:phoneNum])) {
if ([regextestcmevaluateWithObject:phoneNum]) {
NSLog(@"China Mobile");
} elseif ([regextestctevaluateWithObject:phoneNum]) {
NSLog(@"China Telecom");
} elseif ([regextestcuevaluateWithObject:phoneNum]) {
NSLog(@"China Unicom");
} else {
NSLog(@"Unknow");
}
returnYES;
} else {
returnNO;
}
}
10:获得当前的视图控制器+ (UIViewController *)getCurrentVC
{
UIViewController *result =nil;
UIWindow * window = [[UIApplicationsharedApplication]keyWindow];
if (window.windowLevel !=UIWindowLevelNormal)
{
NSArray *windows = [[UIApplicationsharedApplication]windows];
for(UIWindow * tmpWinin windows)
{
if (tmpWin.windowLevel ==UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
UIView *frontView = [[windowsubviews]objectAtIndex:0];
id nextResponder = [frontViewnextResponder];
if ([nextResponderisKindOfClass:[UIViewControllerclass]])
result = nextResponder;
else
result = window.rootViewController;
return result;
}
11:根据内容调整UILable的高度
+(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font :(CGRect) myRect
{
CGRect rect = [string boundingRectWithSize:myRect.size//限制最大的宽度和高度
options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
attributes:@{NSFontAttributeName: font}//传人的字体字典
context:nil];
return rect.size;
}
12:自定义导航栏
-(void)initNavigationBar{
UIBarButtonItem * leftBackBtn=[[UIBarButtonItemalloc]initWithImage:[UIImageimageNamed:@"back.png"]style:UIBarButtonItemStylePlaintarget:selfaction:@selector(navcBarBtnClick:)];
leftBackBtn.tag =10;
[leftBackBtn setTintColor:[UIColorwhiteColor]];
self.navigationItem.leftBarButtonItem = leftBackBtn;
UIBarButtonItem * rightBtn1 = [[UIBarButtonItemalloc]initWithImage:[UIImageimageNamed:@"sgt.png"]style:UIBarButtonItemStylePlaintarget:selfaction:@selector(navcBarBtnClick:)];
UIBarButtonItem * rightBtn2 = [[UIBarButtonItemalloc]initWithTitle:@"施工图"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(navcBarBtnClick:)];
rightBtn1.tag =20;
[rightBtn1 setTintColor:[UIColorwhiteColor]];
rightBtn2.tag =20;
[rightBtn2 setTintColor:[UIColorwhiteColor]];
NSArray * arr =@[rightBtn2,rightBtn1];
self.navigationItem.rightBarButtonItems = arr;
[self.navigationController.navigationBarsetBackgroundImage:[UIImageimageNamed:@"zh.png"]forBarMetrics:UIBarMetricsDefault];
// self.navigationItem.leftBarButtonItem=leftBackBtn;
//设置导航栏字体颜色
[self.navigationController.navigationBarsetTitleTextAttributes:
@{NSFontAttributeName:[UIFontsystemFontOfSize:19],
NSForegroundColorAttributeName:[UIColorwhiteColor]}];
self.title=@"订单详情";
}
13:把秒转换为时间- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
NSInteger minutes = floor(duration/60);
NSInteger seconds = round(duration - minutes * 60);
return [NSString stringWithFormat:@"%ld:%02ld", minutes, seconds];
}
14:转圈的HUD
MBProgressHUD * hud = [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];
hud.labelText=NSLocalizedString(@"Loading...", tooltexts.lodingtext);
// You can also adjust other label properties if needed.
hud.labelFont = [UIFontitalicSystemFontOfSize:15.f];
[hud hide:YES];
- IOS常用方法封装(1)
- iOS常用封装方法
- IOS 常用方法封装
- iOS常用的封装方法
- iOS封装常用的方法
- iOS开发常用方法的封装
- iOS之AFN常用封装(三)
- 常用js验证方法封装1
- JDBC常用方法封装
- Selenium2 常用方法封装
- js 常用封装方法
- 自己常用方法封装
- 常用的封装方法
- selenium封装常用方法
- Javascript封装常用方法
- extjs常用方法封装
- Selenium2常用方法封装
- httpclient常用方法封装
- Mac上有哪些冷门但却逆天的软件?
- iOS 导航栏Title不居中
- hdu 2035 - 人见人爱A^B
- delphi7+firebird+dbexpress
- 59. Spiral Matrix II
- IOS常用方法封装(1)
- Java 多线程实现接口Runnable和继承Thread区别
- DrawerLayout ---抽屉效果的导航菜单
- html5开发之viewport使用
- 装修日志(吊顶、防盗门)
- 使用ASI网络请求后,程序闪退的问题
- 趣味javascript程序
- TextView设置字间距和行间距
- Hadoop 配置本篇主要就是配置HDFS和YARN