0918-网络 Cell (只需要掌握SDWebImage用法)
SDWebImage三方框架99%都用 比 AFNNetworking三方框架好多了 ASI停止更新了
工作中只需要掌握SDWebImage AFN网络框架
----------
以下了解即可
以后用框架AFN网络+SDWebImage图片下载 就可以了 通过学习苹果原生的NSURLConnection 以后学习AFN网络框架
自定义NSOperation在大型项目中才用到 为每个Cell异步下载图片
【以下仅仅面试看 了解几个框架
】
--------------------------------------------------
自定义NSOperation在大型项目中才用到 为每个Cell异步下载图片
SDWebImage三方框架99%都用 比 AFNNetworking三方框架好多了 ASI停止更新了
------------------
127.0.0.1 或者 localhost 或者路由器分配的ip地址 (真机测试用这个)
// HMViewController.m
// 01-基本的HTTP请求
#import "HMViewController.h"
#import "MBProgressHUD+MJ.h"
@interface HMViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
- (IBAction)login;
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (IBAction)login {
// 1.用户名
NSString *usernameText = self.username.text;
if (usernameText.length == 0) {
[MBProgressHUD showError:@"请输入用户名"];
return;
}
// 2.密码
NSString *pwdText = self.pwd.text;
if (pwdText.length == 0) {
[MBProgressHUD showError:@"请输入密码"];
return;
}
/**
接口文档:定义描述服务器端的请求接口
1> 请求路径URL:客户端应该请求哪个路径
* http://localhost:8080/MJServer/login
2> 请求参数:客户端要发给服务器的数据
* username - 用户名
* pwd - 密码
3> 请求结果:服务器会返回什么东西给客户端
*/
// 3.发送用户名和密码给服务器(走HTTP协议)
// 创建一个URL : 请求路径
NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText, pwdText];
NSURL *url = [NSURL URLWithString:urlStr];
// 创建一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 发送一个同步请求(在主线程发送请求)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"%@", data);
}
@end
------------------
字典不能存放nil
牵扯到网络一般比较复杂
-----------
这个了解即可
面试前回顾即可
cell怎么防止一个URL重复下载思路
// HMAppsViewController.m
// 01-cell图片下载 知道思路即可
#import "HMAppsViewController.h"
#import "HMApp.h"
@interface HMAppsViewController ()
/**
* 所有的应用数据
*/
@property (nonatomic, strong) NSMutableArray *apps;
/**
* 存放所有下载操作的队列
*/
@property (nonatomic, strong) NSOperationQueue *queue;
/**
* 存放所有的下载操作(url是key,operation对象是value)
*/
@property (nonatomic, strong) NSMutableDictionary *operations;
/**
* 存放所有下载完的图片
*/
@property (nonatomic, strong) NSMutableDictionary *images;
@end
@implementation HMAppsViewController
#pragma mark - 懒加载
- (NSMutableArray *)apps
{
if (!_apps) {
// 1.加载plist
NSString *file = [[NSBundle mainBundle] pathForResource:@"apps" ofType:@"plist"];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
// 2.字典 --> 模型
NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
HMApp *app = [HMApp appWithDict:dict];
[appArray addObject:app];
}
// 3.赋值
self.apps = appArray;
// _apps = appArray;
}
return _apps;
}
- (NSOperationQueue *)queue
{
if (!_queue) {
self.queue = [[NSOperationQueue alloc] init];
}
return _queue;
}
- (NSMutableDictionary *)operations
{
if (!_operations) {
self.operations = [[NSMutableDictionary alloc] init];
}
return _operations;
}
- (NSMutableDictionary *)images
{
if (!_images) {
self.images = [[NSMutableDictionary alloc] init];
}
return _images;
}
#pragma mark - 初始化方法
- (void)viewDidLoad
{
[super viewDidLoad];
// 这里仅仅是block对self进行了引用,self对block没有任何引用
[UIView animateWithDuration:2.0 animations:^{
self.view.frame = CGRectMake(0, 0, 100, 100);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// 移除所有的下载操作缓存
[self.queue cancelAllOperations];
[self.operations removeAllObjects];
// 移除所有的图片缓存
[self.images removeAllObjects];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.apps.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
// 取出模型
HMApp *app = self.apps[indexPath.row];
// 设置基本信息
cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download;
// 先从images缓存中取出图片url对应的UIImage
UIImage *image = self.images[app.icon];
if (image) { // 说明图片已经下载成功过(成功缓存)
cell.imageView.image = image;
} else { // 说明图片并未下载成功过(并未缓存过)
// 显示占位图片
cell.imageView.image = [UIImage imageNamed:@"placeholder"];
// 下载图片
[self download:app.icon indexPath:indexPath];
}
return cell;
}
/**
* 下载图片
*
* @param imageUrl 图片的url
*/
- (void)download:(NSString *)imageUrl indexPath:(NSIndexPath *)indexPath
{
// 取出当前图片url对应的下载操作(operation对象)
NSBlockOperation *operation = self.operations[imageUrl];
if (operation) return;
// 创建操作,下载图片
// HMAppsViewController * == typeof(self)
// int age = 20;
// typeof(age) age2 = 10; // int age2 = 10;
// typeof(100) age3 = 30; // int age3 = 30;
__weak typeof(self) appsVc = self;
operation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url]; // 下载
UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage
// 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// 存放图片到字典中
if (image) {
appsVc.images[imageUrl] = image;
}
// 从字典中移除下载操作 (防止operations越来越大,保证下载失败后,能重新下载)
[appsVc.operations removeObjectForKey:imageUrl];
// 刷新表格
[appsVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
}];
// 添加操作到队列中
[self.queue addOperation:operation];
// 添加到字典中 (这句代码为了解决重复下载)
self.operations[imageUrl] = operation;
}
/**
* 1.会阻塞主线程 - 影响用户体验
* 2.重复下载 - 浪费流量,浪费时间,影响用户体验
* // 保证:1张图片只下载1次
*/
/**
* 当用户开始拖拽表格时调用
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 暂停下载
[self.queue setSuspended:YES];
}
/**
* 当用户停止拖拽表格时调用
*/
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// 恢复下载
[self.queue setSuspended:NO];
}
@end
有沙盒缓存代码 面试时了解即可

// // HMAppsViewController.m // 01-cell图片下载 #define HMAppImageFile(url) [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]] #import "HMAppsViewController.h" #import "HMApp.h" @interface HMAppsViewController () /** * 所有的应用数据 */ @property (nonatomic, strong) NSMutableArray *apps; /** * 存放所有下载操作的队列 */ @property (nonatomic, strong) NSOperationQueue *queue; /** * 存放所有的下载操作(url是key,operation对象是value) */ @property (nonatomic, strong) NSMutableDictionary *operations; /** * 存放所有下载完的图片 */ @property (nonatomic, strong) NSMutableDictionary *images; @end @implementation HMAppsViewController #pragma mark - 懒加载 - (NSMutableArray *)apps { if (!_apps) { // 1.加载plist NSString *file = [[NSBundle mainBundle] pathForResource:@"apps" ofType:@"plist"]; NSArray *dictArray = [NSArray arrayWithContentsOfFile:file]; // 2.字典 --> 模型 NSMutableArray *appArray = [NSMutableArray array]; for (NSDictionary *dict in dictArray) { HMApp *app = [HMApp appWithDict:dict]; [appArray addObject:app]; } // 3.赋值 self.apps = appArray; // _apps = appArray; } return _apps; } - (NSOperationQueue *)queue { if (!_queue) { self.queue = [[NSOperationQueue alloc] init]; } return _queue; } - (NSMutableDictionary *)operations { if (!_operations) { self.operations = [[NSMutableDictionary alloc] init]; } return _operations; } - (NSMutableDictionary *)images { if (!_images) { self.images = [[NSMutableDictionary alloc] init]; } return _images; } #pragma mark - 初始化方法 - (void)viewDidLoad { [super viewDidLoad]; // 这里仅仅是block对self进行了引用,self对block没有任何引用 [UIView animateWithDuration:2.0 animations:^{ self.view.frame = CGRectMake(0, 0, 100, 100); }]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // 移除所有的下载操作缓存 [self.queue cancelAllOperations]; [self.operations removeAllObjects]; // 移除所有的图片缓存 [self.images removeAllObjects]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.apps.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"app"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } // 取出模型 HMApp *app = self.apps[indexPath.row]; // 设置基本信息 cell.textLabel.text = app.name; cell.detailTextLabel.text = app.download; // 先从images缓存中取出图片url对应的UIImage UIImage *image = self.images[app.icon]; if (image) { // 说明图片已经下载成功过(成功缓存) cell.imageView.image = image; } else { // 说明图片并未下载成功过(并未缓存过) // 获得caches的路径, 拼接文件路径 NSString *file = HMAppImageFile(app.icon); // 先从沙盒中取出图片 NSData *data = [NSData dataWithContentsOfFile:file]; if (data) { // 沙盒中存在这个文件 cell.imageView.image = [UIImage imageWithData:data]; } else { // 沙盒中不存在这个文件 // 显示占位图片 cell.imageView.image = [UIImage imageNamed:@"placeholder"]; // 下载图片 [self download:app.icon indexPath:indexPath]; } } return cell; } /** * 下载图片 * * @param imageUrl 图片的url */ - (void)download:(NSString *)imageUrl indexPath:(NSIndexPath *)indexPath { // 取出当前图片url对应的下载操作(operation对象) NSBlockOperation *operation = self.operations[imageUrl]; if (operation) return; // 创建操作,下载图片 __weak typeof(self) appsVc = self; operation = [NSBlockOperation blockOperationWithBlock:^{ NSURL *url = [NSURL URLWithString:imageUrl]; NSData *data = [NSData dataWithContentsOfURL:url]; // 下载 UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage // 回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // 存放图片到字典中 if (image) { appsVc.images[imageUrl] = image; #warning 将图片存入沙盒中 // UIImage --> NSData --> File(文件) NSData *data = UIImagePNGRepresentation(image); // 获得caches的路径, 拼接文件路径 // NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[imageUrl lastPathComponent]]; [data writeToFile:HMAppImageFile(imageUrl) atomically:YES]; // UIImageJPEGRepresentation(<#UIImage *image#>, 1.0) } // 从字典中移除下载操作 (防止operations越来越大,保证下载失败后,能重新下载) [appsVc.operations removeObjectForKey:imageUrl]; // 刷新表格 [appsVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; }]; }]; // 添加操作到队列中 [self.queue addOperation:operation]; // 添加到字典中 (这句代码为了解决重复下载) self.operations[imageUrl] = operation; } /** * 当用户开始拖拽表格时调用 */ - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { // 暂停下载 [self.queue setSuspended:YES]; } /** * 当用户停止拖拽表格时调用 */ - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { // 恢复下载 [self.queue setSuspended:NO]; } @end
图片放到caches里
-----------------
了解即可
自定义Operation封装完整的下载操作 代替block写法 如果觉得麻烦 也可以直接用NSBlockOperation 但是建议还是用自定义Operation 这样代码简洁一些
自定义operation被添加到队列里 队列会自动调用自定义operation中的main方法
- (void)download:(NSString *)imageUrl indexPath:(NSIndexPath *)indexPath { // 取出当前图片url对应的下载操作(operation对象) HMDownloadOperation *operation = self.operations[imageUrl]; if (operation) return; // 创建操作,下载图片 operation = [[HMDownloadOperation alloc] init]; operation.imageUrl = imageUrl; operation.indexPath = indexPath; // 设置代理 operation.delegate = self; // 添加操作到队列中 [self.queue addOperation:operation]; // 添加到字典中 (这句代码为了解决重复下载) self.operations[imageUrl] = operation; }
// HMDownloadOperation.m #import "HMDownloadOperation.h" @implementation HMDownloadOperation - (void)main { @autoreleasepool { if (self.isCancelled) return; NSURL *url = [NSURL URLWithString:self.imageUrl]; NSData *data = [NSData dataWithContentsOfURL:url]; // 下载 UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage if (self.isCancelled) return; // 回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)]) { [self.delegate downloadOperation:self didFinishDownload:image]; } }]; } } @end
// HMDownloadOperation.h #import <Foundation/Foundation.h> @class HMDownloadOperation; @protocol HMDownloadOperationDelegate <NSObject> @optional - (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image; @end @interface HMDownloadOperation : NSOperation @property (nonatomic, copy) NSString *imageUrl; @property (nonatomic, strong) NSIndexPath *indexPath; @property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate; @end
特殊注意:main里面需要加上@autoreleasepool{
}
自定义Operation HMDownloadOperation 继承 NSOperation 当添加operation被添加到队列里 就会自动调用 - (void)main 所以重写 main函数 main函数里都必须要写 自己开线程 自己释放对象 @autoreleasepool { if(self.isCancelled) return; //是否被cancel了 下载操作 if(self.isCancelled) return; 回到主线程 通知主线程操作 } [queue cancelAllOperation] 正在执行的operation不会停止 已经执行的operatin已经执行完毕 自动被queue释放了
--------------------------
默认 ios程序不能播放gif图片 SDWebImage可以做到自动播放 基于ImageIO框架 SDWebImage其实是有很多分类 github里下载第三方框架 SDWebImage/SDWebImage文件夹 拖到自己项目中就可以了 不用看example了 使用这个分类
SDWebImage默认缓存时长 1week
SDImageCache.h里有
SDImageCache.h里有
----------
-----------------------
内存警告处理
内存警告清理缓存图片 和 清理内存中的图片 用SDWebImage很好
Appdelegate.m里 通过applicationDidReceiveMemoryWarning
Appdelegate.m里 通过applicationDidReceiveMemoryWarning