iOS代码规范

1.网络层:
@interface WM_NetworkManager : AFHTTPSessionManager

单例:+(WM_NetworkManager *)shareInstance
{
static WM_NetworkManager * shareInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
shareInstance = [[self alloc] init];
});
return shareInstance;
}

  • (instancetype)init
    {
    if (self = [super init]) {
    [self Reachability];
    [self setSessionManagerParameter];
    }
    return self;
    }

pragma mark -- 网络监听

  • (void)Reachability
    {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    //debugLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    }
    AFHTTPSessionManager:

  • (void)setSessionManagerParameter
    {
    //设置请求头参数
    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    _sessionManager.requestSerializer.timeoutInterval = 20;
    _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    }
    实例方法:

pragma mark 数据请求封装

-(void)postPath:(NSString *)path parameters:(NSDictionary *)parameters withBlock:(void (^)(NSDictionary *, NSError *))block
{

NSString * url = [[WM_Single defaultSingle].APIHOST stringByAppendingString:path];

// NSString * url = @"http://192.168.2.165:8888/WebMobile.asmx/GetDepartByUserId";
[_sessionManager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
debugLog(@"成功");
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (block) {
//NSLog(@"responseObject:%@",responseObject);
if (![[responseObject objectForKey:@"msg"] isEqualToString:@"ok"]) {
NSError *error = [NSError errorWithDomain:@"Message" code:[[responseObject objectForKey:@"ErrCode"] intValue] userInfo:[NSDictionary dictionaryWithDictionary:responseObject]];
block(nil,error);
// debugLog(@"%@", responseObject);
}else{
// NSString * str = [[WM_NetworkManager shareInstance] dictionaryToJson:responseObject];
block(responseObject,nil);
debugLog(@"请求成功");
// debugLog(@"responseObject11:%@", responseObject);
}
}
debugLog(@"%@", task);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
debugLog(@"%@", task);
debugLog(@"%@", error);
block(nil,error);

}];

}
//词典转换为字符串

  • (NSString*)dictionaryToJson:(NSDictionary *)dic
    {

    NSError *parseError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

pragma mark - 将解析的数据转化成字典

-(NSMutableDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(@"解析失败");
return nil;
}
return dic;
}
//将解析的数据转化成数组
-(NSMutableArray *)arrayWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(@"解析失败");
return nil;
}
return array;
}
2.网络层第二层:类方法
//根据登录人获得其有权限的仓库

  • (void)getDepartWithBlock:(void(^)(NSDictionary * result, NSError * error))block
    {
    NSString *userId = [[WM_Single defaultSingle] getTheValueOfUserName];
    NSDictionary * params = @{@"userId" : userId};
    [[WM_NetworkManager shareInstance] postPath:GetDepartURL parameters:params withBlock:block];
    }
    3.单例:保存到本地:
  • (WM_Single *)defaultSingle
    {
    static WM_Single * single;
    if (!single) {
    single = [[WM_Single alloc] init];
    }
    return single;
    }
    //将用户名存入本地
  • (void)setValueWithUserName:(NSString *)userName
    {
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:userName forKey:@"userName"];
    [ud synchronize];
    }
    //从本地取得用户名

  • (NSString *)getTheValueOfUserName
    {
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    return [ud stringForKey:@"userName"];
    }
    4.属性懒加载:
    -(NSMutableArray *)comNameArray{
    if (!_comNameArray) {
    _comNameArray = [[NSMutableArray alloc]init];
    }
    return _comNameArray;
    }
    5.自动登录:记住密码
    6.找回密码功能
    7.用户配置功能:
    if ([[WM_Single defaultSingle]getTheValueOfAPI] == nil) {

          _textField.text = @"http://192.168.2.165:8888/WebMobile.asmx/";
      }else{
      
          _textField.text = [[WM_Single defaultSingle]getTheValueOfAPI];
      }
    

8.请求加载:
UIWindow* window = [UIApplication sharedApplication].keyWindow;
__weak MBProgressHUD *hud = [ShowMessage showLoadingData:window];
[hud hide:YES];
9.判断手机是否联网:
//判断手机是否联网
AFNetworkReachabilityManager *managerAF = [AFNetworkReachabilityManager sharedManager];
[managerAF startMonitoring];
[managerAF setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

  switch (status) {
      case AFNetworkReachabilityStatusUnknown:
          [ShowMessage showTextOnly:@"暂时没有网络,登录时请检查网络" messageView:self.view];
          wangluo = false;
          break;
          
      case AFNetworkReachabilityStatusNotReachable:
          
          [ShowMessage showTextOnly:@"暂时没有网络,登录时请检查网络" messageView:self.view];
          wangluo = false;
          break;
          
      default:
          wangluo = true;
          break;
  }

}];
10.点击view缩放键盘:

  • (void)tapView{

    UITapGestureRecognizer tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap1.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap1];
    }
    -(void)viewTapped:(UITapGestureRecognizer
    )tap1
    {
    [self.view endEditing:YES];
    }

  1. 加载启动图片:在ViewController的viewDidLoad中
    if ([[WM_Single defaultSingle]getTheValueOfUserName]) {

    self.password.text = [[WM_Single defaultSingle]getTheValueOfPassword];
    self.userName.text = [[WM_Single defaultSingle]getTheValueOfUserName];
    self.OrganizeStructureTf.text = [[WM_Single defaultSingle]getValueOfComName];
    [WM_Single defaultSingle].APIHOST = @"http://192.168.2.165:8888/WebMobile.asmx/";
    
    UIImageView *startImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    _startImage = startImage;
    startImage.image = [UIImage imageNamed:@"云仓储启动页"];
    
    [self.view addSubview:startImage];
    [self LoginClick:nil];
    

    }
    11.设置占位符颜色:
    self.userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor],NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    12.输入框的监听来判断登录按钮的监听事件:
    //创建通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    _center = center;
    //注册通知
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.userName];
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.password];
    [center addObserver:self selector:@selector(textValueChanged) name:UITextFieldTextDidChangeNotification object:self.OrganizeStructureTf];

  • (void)textValueChanged
    {
    LoginButton.enabled = ((self.userName.text.length != 0) && (self.password.text.length != 0) && (self.OrganizeStructureTf.text.length != 0));
    if (LoginButton.enabled) {
    [LoginButton setImage:[UIImage imageNamed:@"登录1"] forState:UIControlStateNormal];
    }else{
    [LoginButton setImage:[UIImage imageNamed:@"登录2"] forState:UIControlStateNormal];
    }
    }
    千万一处通知:
    //移除通知
  • (void)dealloc
    {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    13.下拉框实现
    14.cellForRowAtIndexPath:

import "Masonry/Masonry.h"

//一些操作在cell中进行
PopupViewCell *cell = [PopupViewCell popupViewCellWithTableView:tableView];
cell.iconView.image = self.iconArray[indexPath.row];
cell.titleLable.text = self.textArray[indexPath.row];
//cell分割线
if (indexPath.row == self.textArray.count - 1) {
cell.haveSeparatorLine = YES;
}else{
cell.haveSeparatorLine = NO;
}
----------------cell-------------属性---------------

  • (instancetype)popupViewCellWithTableView:(UITableView *)tableView;

@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UILabel *titleLable;

@property (nonatomic, assign, getter=isHaveSeparatorLine) BOOL haveSeparatorLine; //是否有分割线
----------------cell---------------------------------

  • (instancetype)popupViewCellWithTableView:(UITableView *)tableView {

    static NSString *cellID = @"PopupViewCell";

    PopupViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell) {
    cell = [[PopupViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
    }

  • (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if ( self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    self.selectionStyle = UITableViewCellSelectionStyleNone;

      self.iconView = [[UIImageView alloc] init];
      [self.contentView addSubview:self.iconView];
      
      self.titleLable = [[UILabel alloc] init];
      self.titleLable.textColor = [UIColor blackColor];
      self.titleLable.font = [UIFont systemFontOfSize:14];
      [self.contentView addSubview:self.titleLable];
      
      //添加分割线
      self.separatorLineView = [[UIImageView alloc] init];
      self.separatorLineView.backgroundColor = [UIColor grayColor];
      [self.contentView addSubview:self.separatorLineView];
    

// self.separatorLineView.hidden = YES;
}
return self;
}

  • (void)layoutSubviews{

    [super layoutSubviews];

    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.contentView).offset(padding);
    make.centerY.equalTo(self.contentView);
    make.width.equalTo(@(0));
    make.height.equalTo(@(0));
    }];

    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.iconView.mas_trailing).offset(padding);
    make.centerY.equalTo(self.contentView);
    make.trailing.equalTo(self.contentView).offset(-padding);
    make.bottom.equalTo(self.contentView);
    }];

    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.textLabel);
    make.trailing.equalTo(self.contentView);
    make.bottom.equalTo(self.contentView.mas_bottom);
    make.height.equalTo(@(1 / ([UIScreen mainScreen].scale)));
    }];
    }

-(void)setHaveSeparatorLine:(BOOL)haveSeparatorLine{
_haveSeparatorLine = haveSeparatorLine;
self.separatorLineView.hidden = haveSeparatorLine;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • iOS编程规范0规范 0.1前言 为􏰀高产品代码质量,指导广大软件开发人员编写出简洁、可维护、可靠、可 测试、高效...
    iOS行者阅读 4,418评论 21 35
  • 命名的规范 以下摘自raywenderlich代码规范 Language US English should be...
    太二道士阅读 363评论 0 0
  • Version:1.0.0 Objective-C工程及代码规范 一、工程总述 1.工程名称为英文 工程名称必须为...
    小霍同学阅读 454评论 2 4
  • 一、命名规范 1、统一要求含义清楚,尽量做到不需要注释也能了解其作用,若做不到,就加注释,使用全称,不使用缩写。 ...
    Untils阅读 532评论 0 0
  • iOS代码规范 命名规范 1.0 对于常量的命名最好在前面加上字母k作为标记. 如: 定义作为NSDictiona...
    Suneday阅读 444评论 1 1