码迷,mamicode.com
首页 > 其他好文 > 详细

UI_18 图片异步下载、KVO

时间:2015-09-08 23:48:32      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:

一、异步下载图片ImageViewDownloader

     图?下载是iOS开发中常?的功能,但系统并未提供图?下载类。 为了便于后续使?,可以将图?下载封装到?个类?? (ImageDownloader)

     新建SingleViewApplication,使用默认的Storyboard,向其中添加一个Button一个ImageView并关联属性、添加事件。点击Button实现异步下载并显示图片。AsynImageDownloader类封装了下载图片的方法。

使用代理进行AsynImageDownloader与ViewController中的传值(UIImage)

AsynImageDownloaderDelegate.h

#import <Foundation/Foundation.h>
@class UIImage;
@class AsynImageDownloader;

@protocol AsynImageDownloaderDelegate <NSObject>

- (
void)AsynImageDownloader:(AsynImageDownloader *)downloader isLoading:(UIImage *)image;

@end


封装图片下载的方法

AsynImageDownloader.h

#import <Foundation/Foundation.h>
#import
"AsynImageDownloaderDelegate.h"

@interface AsynImageDownloader : NSObject<NSURLConnectionDataDelegate>

@property (nonatomic, assign) id<AsynImageDownloaderDelegate> delegate;

@property (nonatomic, retain) NSURLConnection *connection;

- (
instancetype)initWithImageURL:(NSString *)imageURL;


@end


AsynImageDownloader.m

#import "AsynImageDownloader.h"
#import
<UIKit/UIKit.h>

@interface AsynImageDownloader ()
@property (nonatomic, retain) NSMutableData *receiveData;
@end

@implementation AsynImageDownloader

- (
instancetype)initWithImageURL:(NSString *)imageURL
{
   
self = [super init];
   
if (self) {
       
//1.URL
       
NSURL *url = [NSURL URLWithString:imageURL];
       
//2.request
       
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
       
//3.connection OBJ
       
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    }
   
return self;
}

- (
void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   
self.receiveData = [NSMutableData data];
}

- (
void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [
_receiveData appendData:data];
   
UIImage *image = [UIImage imageWithData:_receiveData];
   
if ([_delegate respondsToSelector:@selector(AsynImageDownloader:isLoading:)]) {
        [
_delegate AsynImageDownloader:self isLoading:image];
    }
}


@end


创建对象并显示图片,遵守协议、设置代理

ViewController.m

#import "ViewController.h"

#import "AsynImageDownloader.h"
#import
"AsynImageDownloaderDelegate.h"

#define kPicURL @"http://image.zcool.com.cn/56/13/1308200901454.jpg"

@interface ViewController ()<NSURLConnectionDataDelegate, AsynImageDownloaderDelegate>
@property (nonatomic, retain) NSMutableData *receiveData;

@property (retain, nonatomic) IBOutlet UIImageView *imgView;

- (
IBAction)asynDownloaderPic:(UIButton *)sender;
@end

@implementation ViewController

- (
void)viewDidLoad {
    [
super viewDidLoad];
   
// Do any additional setup after loading the view, typically from a nib.
}

- (
void)didReceiveMemoryWarning {
    [
super didReceiveMemoryWarning];
   
// Dispose of any resources that can be recreated.
}

#pragma mark -- AsynImageDownloaderDelegate --
- (void)AsynImageDownloader:(AsynImageDownloader *)downloader isLoading:(UIImage *)image
{
   
self.imgView.image = image;
}

#pragma mark -- 异步下载图片 --

- (IBAction)asynDownloadPic:(UIButton *)sender {

    AsynImageDownloader *downloader = [[AsynImageDownload alloc] initWithImageURL:kPicURL];

    downloader.delegate = self;
}

- (
void)dealloc {
    [
_imgView release];
    [
super dealloc];
}

@end


二、KVO(Key-Value-Observer 键值观察者)

1、KVO简介

     KVO是观察者设计模式的?种具体实现

     在 Cocoa 的模型-视图-控制器 (Model-view-controller)架构里,控制器负责让视图和模型同步。这一共有两步:当 model 对象改变的时候,视图应该随之改变以反映模型的变化;当用户和控制器交互的时候,模型也应该做出相应的改变。

     KVO 能帮助我们让视图和模型保持同步。控制器可以观察视图依赖的属性变化。MVC中M与C通信,M发?变化通知C。其中M是被 观察者,C是观察者。

     KVO触发机制:?个对象(观察者),监测另?对象(被观察者)的某属性是否发?变化,若被监测的属性发?的更改,会触发观察者的?个?法(?法名固定,类似代理?法)

KVO详细介绍及使用:http://objccn.io/issue-7-3/

2、KVO使?步骤

1、注册观察者(为被观察者指定观察者以及被观察属性)

2、实现回调?法

3、触发回调?法(被观察属性发?更改)

4、移除观察者

3、使用示例

示例一

     给Person类的name属性添加观察者。name发?变化 时,让self.view的背景颜?随机改变。界面包含一个UITextField、一个UIButton。使用SingleViewApplication创建,在Storyboard中添加控件

YFPerson.h

#import <Foundation/Foundation.h>

@interface YFPerson : NSObject

@property (nonatomic, retain) NSString *name;

@end

ViewController.m

#import "ViewController.h"
#import
"YFPerson.h"

@interface ViewController ()
@property (nonatomic, retain) YFPerson *person;
@property (retain, nonatomic) IBOutlet UITextField *textField;

- (
IBAction)didClickButton:(UIButton *)sender;
@end

@implementation ViewController

- (
void)viewDidLoad {
    [
super viewDidLoad];
   
   
self.person = [[YFPerson alloc] init];
   
//1.注册观察者(为被观察者_person添加一个观察者self并设置其观察的属性)
    [
_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    [
_person release];
   
   
// Do any additional setup after loading the view, typically from a nib.
}

- (
IBAction)didClickButton:(UIButton *)sender {
   
   
//3.1改变Person.name
   
_person.name = _textField.text;
   
}
//3.2被观察者属性改变触发以下方法
//2.实现回调方法
- (
void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   
NSLog(@"被观察者的路径:%@",keyPath);
   
NSLog(@"被观察者:%@", object);                    //object为被观察者
   
NSLog(@"被监测的属性所有状态下的值:%@", change);     //change {kind=1; new=""; old="<null>"}
   
NSLog(@"在注册观察者时,context的值:%@", context);  //context
   
   
//判断新值和旧值
   
if (![change[@"new"]isEqualToString:change[@"old"]]) {
       
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
    }
   
}

- (
void)dealloc {
   
//4.移除观察者
    [
_person removeObserver:self forKeyPath:@"name" context:nil];
    [
_textField release];
    [
super dealloc];
}

@end

示例二

KVO监测Model图?下载

https://github.com/zooyf/KVO-Monitoring-Model-Picture-Download



附,第三方框架

文件下载

如果文件比较小,下载方式会比较多

直接用NSData的+ (id)dataWithContentsOfURL:(NSURL *)url;

利用NSURLConnection发送一个HTTP请求去下载

如果是下载图片,还可以利用SDWebImage框架

文件压缩解压框架

第三方解压缩框架——SSZipArchive

下载地址:https://github.com/samsoffes/ssziparchive

注意:需要引入libz.dylib框架 

// Unzipping

NSString *zipPath = @"path_to_your_zip_file";

NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";

[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];

// Zipping

NSString *zippedPath = @"path_where_you_want_the_file_created";

NSArray *inputPaths = [NSArray arrayWithObjects:

                       [[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"jpg"],

                       [[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"]

                       nil];

[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];

部分文件的MIMEType


UI_18 图片异步下载、KVO

标签:

原文地址:http://my.oschina.net/zooyf/blog/503528

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!