您的位置:首页 > 移动开发 > IOS开发

iOS 开发实训第二周周报

2019-03-31 01:00 1336 查看

iOS 开发实训第二周周报

学习笔记

UI 编程

  • 常用 UI 控件:

    UILabel
  • UIIamgeView
  • UIButton
  • UISwitch
  • UITextField
  • UITextView
  • iOS 绘图:

      主要的绘图系统: UIKit:最常用的视图框架,封装度最高,都是OC对象,比如UIView、UIButton等,可以通过UI前缀来识别UIKit元素
    • Core Graphics:UIKit下的主要绘图系统,用于绘制自定义视图,可以通过CG前缀来识别Core Graphics元素
    • Core Animation:提供了强大的2D和3D动画
    • Core Image:对图片进行各种滤镜处理,比如高斯模糊、锐化等
    • OpenGL ES:主要用于游戏绘图
  • UIView 的绘制方式:
      视图叠加
    • 设置透明度/边框/背景颜色
    • 实现 drawRect
  • 视图绘制周期:
      调用视图的 setNeedsDisplay 会将视图标记为重新绘制,在下一个次绘制周期中会进行重新绘制,视图会回调 drawRect 方法(drawRect 是系统回调,主动调用是无效的),在drawRect 上实现绘制代码,setNeedsDisplayInRect 会触发局部区域重绘
    • 触发重绘的情况: 当遮挡你的视图的其他视图被移动或者删除操作的时候
    • 视图的 hidden 属性改变的时候
    • 视图移除屏幕范围,或者从屏幕外重现屏幕前时
    • 显式调用 setNeedsDisplay 或者 setNeedsDisplayInRect 时
  • UITableView:

      UITableView继承自UIScrollView,可以用来展示一组或多组内容样式相似的数据,支持垂直滚动,而且性能极佳,有两种样式 UITableViewStylePlain 和 UITableViewStyleGrouped
    • UITableView 的常见属性:
    @property (nonatomic, readonly) UITableViewStyle style;
    // tableView有两种样式
    //     UITableViewStylePlain  普通的表格样式
    //    UITableViewStyleGrouped  分组模式
    
    /* tableView的数据源 */
    @property (nonatomic, weak, nullable) id <UITableViewDataSource> dataSource;
    /* tableView的代理 */
    @property (nonatomic, weak, nullable) id <UITableViewDelegate> delegate;
    
    #pragma mark - 高度相关
    /* tableView每一行的高度,默认为44 */
    @property (nonatomic) CGFloat rowHeight;
    /* tableView统一的每一组头部的高度 */
    @property (nonatomic) CGFloat sectionHeaderHeight;
    /* tableView统一的每一组头部的高度 */
    @property (nonatomic) CGFloat sectionFooterHeight;
    /* 估算的tableView的统一的每一行行高 */
    @property (nonatomic) CGFloat estimatedRowHeight;
    /* 估算的统一的每一组头部高度,设置估算高度可以优化性能 */
    @property (nonatomic) CGFloat estimatedSectionHeaderHeight;
    /* 估算的统一的每一组的尾部高度 */
    @property (nonatomic) CGFloat estimatedSectionFooterHeight;
    
    /* 总共有多少组 */
    @property (nonatomic, readonly) NSInteger numberOfSections;
    /* 选中行的indexPath */
    @property (nonatomic, readonly, nullable) NSIndexPath *indexPathForSelectedRow;
    
    #pragma mark - 索引条
    /* 索引条文字的颜色 */
    @property (nonatomic, strong, nullable) UIColor *sectionIndexColor;
    /* 索引条的背景色 */
    @property (nonatomic, strong, nullable) UIColor *sectionIndexBackgroundColor;
    
    #pragma mark - 分隔线
    /* 分隔线的样式 */
    @property (nonatomic) UITableViewCellSeparatorStyle separatorStyle;
    // 分隔线的样式有:
    // UITableViewCellSeparatorStyleNone,  没有分隔线
    // UITableViewCellSeparatorStyleSingleLine, 正常分隔线
    @property (nonatomic, strong, nullable) UIColor *separatorColor; // 分隔线的颜色
    
    #pragma mark - 头尾部控件
    /* tableView的头部控件,只能设置高度,宽度默认填充表格 */
    @property (nonatomic, strong, nullable) UIView *tableHeaderView;
    /* tableView的尾部控件,只能设置高度,宽度默认填充表格*/
    @property (nonatomic, strong, nullable) UIView *tableFooterView;
    
    #pragma mark - 编辑模式
    /* 是否是编辑模式,默认是NO */
    @property (nonatomic, getter=isEditing) BOOL editing;
    /* tableView处在编辑模式的时候是否允许选中行,默认是NO */
    @property (nonatomic) BOOL allowsSelectionDuringEditing;
    /* tableView处在编辑模式的时候是否允许选中多行数据,默认是NO */
    @property (nonatomic) BOOL allowsMultipleSelectionDuringEditing;
    • UITableViewCell的常见属性:
    #pragma mark - Cell内部子控件
    /*  默认为nil,imageView是懒加载,用到时才加载 */
    @property (nonatomic, readonly, strong, nullable) UIImageView *imageView;
    /* 默认为nil,是懒加载,用到时才加载 */
    @property (nonatomic, readonly, strong, nullable) UILabel *textLabel;
    /* 只有当Cell的样式为UITableViewCellStyleSubtitle时才会显示出来,默认为nil,是懒加载,用到时才加载 */
    @property (nonatomic, readonly, strong, nullable) UILabel *detailTextLabel;
    
    /* 当你想要自定义一个cell的时候,子控件最好添加到cell的contentView上,方便编辑表格 */
    @property (nonatomic, readonly, strong) UIView *contentView;
    
    /* cell的复用标识 */
    @property (nonatomic, readonly, copy, nullable) NSString *reuseIdentifier;
    
    /* cell的选中样式 */
    @property (nonatomic) UITableViewCellSelectionStyle   selectionStyle;
    /* cell是否是选中状态 */
    @property (nonatomic, getter=isSelected) BOOL         selected;
    
    /* cell的编辑样式,默认是UITableViewCellEditingStyleNone */
    @property (nonatomic, readonly) UITableViewCellEditingStyle editingStyle;
    // cell的编辑样式有:
    // UITableViewCellEditingStyleNone,
    // UITableViewCellEditingStyleDelete, 删除模式
    // UITableViewCellEditingStyleInsert   插入模式
    
    /* 指示器的样式,默认是UITableViewCellAccessoryNone */
    @property (nonatomic) UITableViewCellAccessoryType    accessoryType;
    // 指示器的样式有:
    // UITableViewCellAccessoryNone   不显示指示器
    // UITableViewCellAccessoryDisclosureIndicator cell右侧显示一个箭头
    // UITableViewCellAccessoryDetailDisclosureButton cell右侧显示一个箭头和一个详情图标
    // UITableViewCellAccessoryCheckmark cell右侧显示一个对勾
    // UITableViewCellAccessoryDetailButton cell右侧显示一个详情图标
    
    /* cell右侧指示器view,设置了以后,cell的accessoryType就会失效  */
    @property (nonatomic, strong, nullable) UIView       *accessoryView;
    • UITableView的常用方法:
    /* 全局刷新 */
    - (void)reloadData;
    /* 刷新
    4000
    索引条 */
    - (void)reloadSectionIndexTitles;
    
    /* 返回第section组有多少行 */
    - (NSInteger)numberOfRowsInSection:(NSInteger)section;
    /* 返回indexPath对应的那一行的cell */
    - (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /* 返回第section组的头部view */
    - (nullable UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section;
    /* 返回第section组的尾部view */
    - (nullable UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section;
    
    /**
    *  插入数据,刷新数据
    *  @param indexPaths 插入在哪个位置
    *  @param animation  动画效果,枚举UITableViewRowAnimation
    */
    - (void)insertRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
    
    /**
    *  删除数据
    *  @param indexPaths 删除数据的位置
    *  @param animation  动画效果,枚举UITableViewRowAnimation
    */
    - (void)deleteRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
    // 枚举UITableViewRowAnimation包括:
    // UITableViewRowAnimationFade,  淡入淡出
    // UITableViewRowAnimationRight,  向右滑动
    // UITableViewRowAnimationLeft,  向左滑动
    // UITableViewRowAnimationTop,  向上滑动
    // UITableViewRowAnimationBottom,  向下滑动
    // UITableViewRowAnimationNone,  无动画效果,iOS 3.0以后可用
    // UITableViewRowAnimationMiddle,  保持cell的中间,iOS 3.2以后可用
    // UITableViewRowAnimationAutomatic  自动选择一个合适的动画效果
    
    /**
    *  刷新某一行的数据
    *  @param indexPaths 刷新数据的位置
    *  @param animation  动画效果,枚举UITableViewRowAnimation
    */
    - (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
    
    /** 动画开启/关闭编辑模式 */
    - (void)setEditing:(BOOL)editing animated:(BOOL)animated;
    
    /** 返回一个带有复用标识的cell */
    - (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
    
    /**
    *  使用xib时注册自定义的cell
    *  @param nib        要注册的nib
    *  @param identifier 复用标识
    */
    - (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier;
    
    /**
    *   代码自定义cell时注册自定义的cell
    *  @param cellClass  注册的自定义cell的类型
    *  @param identifier 复用标识
    */
    - (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;
    
    /** 初始化一个带有复用标识的cell */
    - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier
    • UITableViewDataSource中的常用方法:
    // 必须实现的方法:
    /* 设置第section组有多少行数据 */
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
    /* 设置每一行cell的内容,每当有一个cell进入视野屏幕的时候就会调用这个方法,所以在这个方法内部进行优化(cell的复用) */
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    
    // 可实现可不实现的方法:
    /* 总共有多少组,如果不实现,默认是一组 */
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
    
    /* 第section组的头部标题 */
    - (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
    /* 第section组的尾部标题 */
    - (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
    
    /** 设置索引条 */
    - (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView;
    • UITableViewDelegate中的常用方法:
    /** 设置每一行cell的高度 */
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
    /** 设置第section组的头部高度 */
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
    /** 设置第section组的尾部高度 */
    - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
    
    /** 每一行的估算高度 */
    - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /** 设置第section组的headerView */
    - (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
    /** 设置第section组的footerView */
    - (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
    
    /** 选中了某一行cell的时候就会调用这个方法 */
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /**
    *  设置左滑删除按钮的文字
    *  @param tableView         被编辑的tableView
    *  @param indexPath         indexPath
    *  @return 返回删除按钮显示的文字
    */
    - (nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /**
    *  创建一个左滑出现按钮的操作(UITableViewRowAction)数组
    *  @param tableView         添加操作的tableView
    *  @param indexPath         indexPath,可以指定每一行有不同的效果
    *  @return 返回一个操作(UITableViewRowAction)数组
    */
    - (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /**
    *  移动cell
    *  @param tableView            操作的tableView
    *  @param sourceIndexPath      移动的行
    *  @param destinationIndexPath 目标行
    */
    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;
    
    /** 根据editingStyle处理是删除还是添加操作,完成删除、插入操作刷新表格 */
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
    
    /**
    *  设置表格编辑模式,不实现默认都是删除
    *  @param tableView 操作的tableView
    *  @param indexPath cell的位置
    *  @return 返回表格编辑样式
    */
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
    tableView如何展示数据:
    • UITableView 展示数据的过程:
    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
    
    @property (weak, nonatomic) IBOutlet UITableView *tableView;
    
    @end
    
    - (void)viewDidLoad{
    [super viewDidLoad];
    
    self.tableView.dataSource = self;
    }
    
    #pragma mark - UITableViewDataSource
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // 在这个方法中设置总共有多少组数据
    // 这个方法如果不实现,默认是一组
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // 在这个方法中设置第section组有多行数据
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 1.定义一个cell的复用标识
    static NSString *ID = @"cell";
    
    // 2.根据复用标识,从缓存池中取出带有同样的复用标识的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    // 3.如果缓存池中没有带有这种复用标识的cell,就创建一个带有这种复用标识的cell
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    // 4.设置cell的一些属性
    
    return cell;
    }
    
    - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    // 在这个方法中设置第section组的尾部标题
    }
    
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    // 在这个方法中设置第section组的头部标题
    }
    
    #pragma mark - UITableViewDelegate
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 当选中了某一行的时候就会调用这个方法,可以在这里进行一些操作
    }
    • Cell的重用原理:当滚动列表时,部分 UITableViewCell 会移出窗口,UITableView 会将窗口外的UITableViewCell 放入一个缓存池中,等待重用,当 UITableView 要求 dataSource 返回UITableViewCell 时,dataSource 会先查看这个缓存池,如果池中有未使用的UITableViewCell,dataSource 会用新的数据配置这个 UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象
  • UIViewController:

      UIViewController是UIKit框架中Controller部分的基础,所有界面都是基于UIViewController搭建出来的

    • 分类:

      内容型 ViewController UIViewController 基类,自定义视图
    • UITableViewController 垂直列表视图
    • UICollectionViewController 垂直和水平列表视图
    • UIActivityViewController 系统分享视图
    • UIAlertController AlertView和ActionSheet
    • UISearchController 搜索
    • UIInputViewController 自定义键盘容器
  • 容器型 ViewControll
      UINavigationController 导航控制器
    • UITabbarController 选项卡控制器
    • UIPageViewController 多页面控制器(多用于App启动闪屏)
    • UISplitViewController 分割控制器(用于iPad)
  • 生命周期:

      init 初始化
    • loadView() 自定义加载视图
    • viewDidLoad() 视图加载完成
    • viewWillLayoutSubviews() 将要subview布局
    • viewDidLayoutSubviews() 完成subview布局
    • viewWillAppear() 视图将要显示(过场动画即将开始)
    • viewDidAppear() 视图显示结束(过场动画结束)
    • viewWillDisappear() 视图将要消失
    • viewDidDisappear() 视图消失结束
    • didReceiveMemoryWarning() 内存警告(正在显示的界面不会收到)
    • dealloc 销毁

    网络编程

    • NSURLSession:

      执行顺序:

    • GET
    // 方法一
    -(void)get1
    {
    //对请求路径的说明
    //http://120.25.226.186:32812/login?username=520it&pwd=520&type=JSON
    //协议头+主机地址+接口名称+?+参数1&参数2&参数3
    //协议头(http://)+主机地址(120.25.226.186:32812)+接口名称(login)+?+参数1(username=520it)&参数2(pwd=520)&参数3(type=JSON)
    //GET请求,直接把请求参数跟在URL的后面以?隔开,多个参数之间以&符号拼接
    
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    //2.创建请求对象
    //请求对象内部默认已经包含了请求头和请求方法(GET)
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4.根据会话对象创建一个Task(发送请求)
    /*
    第一个参数:请求对象
    第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
    data:响应体信息(期望的数据)
    response:响应头信息,主要是对服务器端的描述
    error:错误信息,如果请求失败,则error有值
    */
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    if (error == nil) {
    //6.解析服务器返回的数据
    //说明:(此处返回的数据是JSON格式的,因此使用NSJSONSerialization进行反序列化处理)
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
    NSLog(@"%@",dict);
    }
    }];
    
    //5.执行任务
    [dataTask resume];
    }
    
    // 方法二
    -(void)get2
    {
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    //2.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //3.根据会话对象创建一个Task(发送请求)
    /*
    第一个参数:请求路径
    第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
    data:响应体信息(期望的数据)
    response:响应头信息,主要是对服务器端的描述
    error:错误信息,如果请求失败,则error有值
    注意:
    1)该方法内部会自动将请求路径包装成一个请求对象,该请求对象默认包含了请求头信息和请求方法(GET)
    2)如果要发送的是POST请求,则不能使用该方法
    */
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    //5.解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"%@",dict);
    
    }];
    
    //4.执行任务
    [dataTask resume];
    }
    • POST
    -(void)post
    {
    //对请求路径的说明
    //http://120.25.226.186:32812/login
    //协议头+主机地址+接口名称
    //协议头(http://)+主机地址(120.25.226.186:32812)+接口名称(login)
    //POST请求需要修改请求方法为POST,并把参数转换为二进制数据设置为请求体
    
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    
    //5.设置请求体
    request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    
    //6.根据会话对象创建一个Task(发送请求)
    /*
    第一个参数:请求对象
    第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
    data:响应体信息(期望的数据)
    response:响应头信息,主要是对服务器端的描述
    error:错误信息,如果请求失败,则error有值
    */
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    //8.解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"%@",dict);
    
    }];
    
    //7.执行任务
    [dataTask resume];
    }
    • 上传文件
    @interface ZViewController()
    @end
    
    @implementation ZViewController
    
    -(void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/iostest.php"]];
    //必须使用POST
    request.HTTPMethod = @"POST";
    //设置请求体
    request.HTTPBody = [self getDataBody];
    //设置请求
    24000
    头
    [request setValue:[NSString stringWithFormat:@"%d",[self getDataBody].length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:[self getDataBody] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    [task resume];
    }
    
    //获取请求体内容
    -(NSData *)getDataBody {
    NSMutableData *data = [NSMutableData data];
    
    NSString *top = [NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"file\"; filename=\"1.png\"\nContent-Type: image/png\n\n",boundary];
    
    NSString *bottom = [NSString stringWithFormat:@"\n--%@--\n\n",boundary];
    
    NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"]];
    
    [data appendData:[top dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:content];
    [data appendData:[bottom dataUsingEncoding:NSUTF8StringEncoding]];
    return data;
    }
    
    @end
    • 下载文件
    -(void)viewDidLoad {
    [super viewDidLoad];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7efc0a0e1ebfffaaf51f2de667c.jpg"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    //下载完成后文件位于location处,我们需要移到沙盒中
    NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [dirPath stringByAppendingPathComponent:@"1.jpg"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path isDirectory:NO]) {
    [manager removeItemAtPath:path error:nil];
    }
    
    [manager moveItemAtPath:[location path] toPath:path error:nil];
    
    }];
    
    //开始任务
    [task resume];
    }
  • 第三方框架 AFNetWorking

  • 本地存储

    • iOS 沙盒:

      iOS系统为每个应用程序创建自己的文件系统,每个应用程序只能访问自己的文件系统,不能相互通信,这个文件系统就就是沙盒,所有的非代码文件都要保存在此,例如图像、图标、声音、映像、属性列表、文本文件等,应用程序请求的数据需要通过权限检测

    • 目录:

      Documents:保存应用运行时生成的需要持久化的数据,iTunes会自动备份该目录,苹果建议将
      在应用程序中浏览到的文件数据保存在该目录下
    • Library: Preferences:保存应用程序的偏好设置,我们不应该直接在这里创建文件,而是需要通过NSUserDefault这个类来访问应用程序的偏好设置,iTunes会自动备份该文件目录下的内容,比如是否允许访问图片、是否允许访问地理位置等
    • Caches:一般存储的是缓存文件,例如图片视频等,此目录下的文件不会再应用程序退出时删除,在手机备份的时候,iTunes不会备份该目录,例如音频、视频等文件存放在其中
  • tmp:临时文件目录,在程序重新运行的时候,和开机的时候,会清空tmp文件夹
  • 获取目录的方法:
  • NSString *homePath = NSHomeDirectory();
    
    NSLog(@"homePath:%@",homePath);
    
    //2. 沙盒/Documents/
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    NSLog(@"docPath:%@",docPath);
    
    //3. 沙盒/Library/
    
    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    
    NSLog(@"libPath:%@",libPath);
    
    //3.1 沙盒/Library/Preferences
    
    //NSString *preferPath = [NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES) firstObject];
    
    //此方法获取路径是沙盒/Library/PreferencePanes并不存在这样的路径,想要访问Preferences文件夹,需要拼接路径。或者直接使用NSUserDefaults便可以在Preferences文件夹下创建plist文件。
    
    NSString *preferPath = [libPath stringByAppendingPathComponent:@"Preferences"];
    
    NSLog(@"preferPath:%@",preferPath);
    
    //3.2 沙盒/Library/Cache
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSLog(@"cachePath:%@",cachePath);
    
    //4. 沙盒/tmp
    
    NSString *tmpPath = NSTemporaryDirectory();
    
    NSLog(@"tmpPath:%@",tmpPath);
    
    //5. 打印xx.app位置
    
    NSLog(@".appPath:%@",[[NSBundle mainBundle] bundlePath]);//打印app安装包的在模拟器/手机上的位置(~users/Application文件夹下)
  • 文件和文件夹操作:

      文件夹操作:

      创建:
    NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //test文件夹
    documentsDir = [documentsDir stringByAppendingPathComponent:@"test"];
    //是否是文件夹
    BOOL isDir;
    BOOL isExit = [filemanager fileExistsAtPath:documentsDir isDirectory:&isDir];
    //文件夹是否存在
    if (!isExit || !isDir) {
    [filemanager createDirectoryAtPath:documentsDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    • 删除:
    //删除Wtdb文件夹
    NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *wtdbPath = [cachesDir stringByAppendingPathComponent:@"Wtdb"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:wtdbPath]) {
    BOOL isSuccess = [fileManager removeItemAtPath:wtdbPath error:nil];
    }
    • 移动:
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
    NSLog(@"rename success");
    }else{
    NSLog(@"rename fail");
    }
    • 重命名:
    //通过移动该文件对文件重命名
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"rename.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
    NSLog(@"rename success");
    }else{
    NSLog(@"rename fail");
    }
  • 文件操作:

      删除、移动、重命名与文件夹的操作类似,path 为文件路径
    • 复制:
    //bundle里的数据库文件复制到Caches/Wtdb文件夹下
    NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *filemanager = [NSFileManager defaultManager];
    cachesDir = [cachesDir stringByAppendingPathComponent:@"Wtdb"];
    BOOL isDir;//是否是文件夹
    BOOL exit = [filemanager fileExistsAtPath:cachesDir isDirectory:&isDir];
    //文件夹是否存在
    if (!exit || !isDir) {
    [filemanager createDirectoryAtPath:cachesDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //判断数据库文件是否存在
    NSString *wtdbPath = [cachesDir stringByAppendingPathComponent:@"wtdb.sqlite"];
    //如果文件不存在,则复制
    if (![filemanager fileExistsAtPath:wtdbPath]) {
    NSString *dbBundlePath = [[NSBundle mainBundle] pathForResource:@"wtdb" ofType:@"sqlite"];
    BOOL isSuccess = [filemanager copyItemAtPath:dbBundlePath toPath:wtdbPath error:nil];
    DLog(@"数据库文件%@", isSuccess ? @"拷贝成功" : @"拷贝失败");
    }
    • 写数据:
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSString *content=@"测试写入内容!";
    BOOL res=[content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (res) {
    NSLog(@"文件写入成功");
    }else {
    NSLog(@"文件写入失败");
    }
    • 读数据:
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    //NSData *data = [NSData dataWithContentsOfFile:testPath];
    //NSLog(@"文件读取成功: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"文件读取成功: %@",content);
    • 获取文件属性:
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];
    NSArray *keys;
    id key, value;
    keys = [fileAttributes allKeys];
    int count = [keys count];
    for (int i = 0; i < count; i++)
    {
    key = [keys objectAtIndex: i];
    value = [fileAttributes objectForKey: key];
    NSLog (@"Key: %@ for value: %@", key, value);
    }
  • NSUserDefaults:

      NSUserDefaults 是 iOS 系统提供的一个单例类,通过类方法 standardUserDefaults 可以获取NSUserDefaults 单例,NSUserDefaults 单例以 key - value 的形式存储了一系列偏好设置,key 是名称,value 是相应的数据,可以使用方法 objectForKey 和 setObject:forKey 来把对象存到相应的 plist 文件中和从 plist 文件中读取出来
    • 支持的数据类型:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL,如果需要存储 plist 文件不支持的类型,比如图片,可以先将其归档为 NSData类型,再存入 plist 文件,需要注意的是,即使对象是 NSArray 或 NSDictionary,他们存储的类型也应该是以上范围包括的
    • 存/取方法:
    // 存
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@”jack“ forKey:@"firstName"];
    [defaults setInteger:10 forKey:@"Age"];
    
    UIImage *image =[UIImage imageNamed:@"somename"];
    NSData *imageData = UIImageJPEGRepresentation(image, 100);//把image归档为NSData
    [defaults setObject:imageData forKey:@"image"];
    
    [defaults synchronize];
    
    // 取
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *firstName = [defaults objectForKey:@"firstName"]
    NSInteger age = [defaults integerForKey:@"Age"];
    
    NSData *imageData = [defaults dataForKey:@"image"];
    UIImage *image = [UIImage imageWithData:imageData];
  • 内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: