iOS網絡編程使用代理方法 , 簡化請求和響應
//在此之前要遵守協議<NSURLConnectionDataDelegate>import "ViewController.h"
import "Cricl.h"
@interface ViewController (){ UITextField _textField; UIProgressView _progressView; UILabel _label; UIButton _button; Cricl cricl; long long _totalLength; NSMutableData _data; UIImageView imageOne; UIImageView imageTwo; UIImageView imageThree; UIButton buttonpause; BOOL num; NSTimer *timer; } @end
@implementation ViewController
(void)viewDidLoad { cricl = [[Cricl alloc]initWithFrame:CGRectMake(70,130, 375, 100)]; cricl.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0];
imageOne = [[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 160, 120)]; [self.view addSubview:imageOne]; imageTwo = [[UIImageView alloc]initWithFrame:CGRectMake(195, 300, 160, 120)]; [self.view addSubview:imageTwo]; imageThree = [[UIImageView alloc]init];
[self.view addSubview:cricl]; [super viewDidLoad]; [self layout];//頁面布局 }
-(void)layout{ self.view.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1]; //地址欄 _textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 355, 25)]; _textField.borderStyle = UITextBorderStyleRoundedRect;//文本框邊框樣式(圓弧) _textField.text = @"http://i-7.vcimg.com/trim/f7a6fc6ebf36475798dd3bf726288d5988839/trim.jpg"; [self.view addSubview:_textField];
_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 110, 80, 25)];
// _label.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0.6]; _label.text = @"正在下載"; _label.font = [UIFont fontWithName:@"Arial" size:20]; [self.view addSubview:_label];
_progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(30, 400, 335, 25)];
// [self.view addSubview:_progressView];
_button.layer.backgroundColor = [UIColor blackColor].CGColor;
_button = [[UIButton alloc]initWithFrame:CGRectMake(10, 500, 355, 25)];
[_button setTitle:@"下載" forState:UIControlStateNormal];
_button.backgroundColor = [UIColor colorWithRed:0.8 green:0.5 blue:0.7 alpha:0.6];
[_button addTarget:self action:@selector(choose) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
buttonpause = [[UIButton alloc]initWithFrame:CGRectMake(20, 600, 60, 25)];
buttonpause.backgroundColor = [UIColor colorWithRed:0.8 green:0.5 blue:0.7 alpha:0.6];
[buttonpause setTitle:@"暫停" forState:UIControlStateNormal];
[buttonpause addTarget:self action:@selector(okpause) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonpause];
}
pragma mark 更新進度條
-(void)updateProgress{ if(_data.length == _totalLength){ _label.text = @"下載完成"; } else{ _label.text = @"正在下載"; } cricl.value = (float)_data.length/_totalLength2M_PI; }
pragma mark 發送數據請求
-(void)choose{ NSLog(@"下載中..."); NSString *urlStr; if(num){ urlStr= @"http://i-7.vcimg.com/trim/867a1fe997bf3baeebbd223ae9aecdc8142598/trim.jpg"; } else{ urlStr=@"http://i-7.vcimg.com/trim/f7a6fc6ebf36475798dd3bf726288d5988839/trim.jpg"; } //對于url中的中文是無法解析的,需要進行url編碼 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSetURLQueryAllow]
//創建url鏈接 NSURL url = [NSURL URLWithString:urlStr]; //創建請求request NSURLRequest request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f]; //創建鏈接 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; //啟動連接 [connection start];
}
pragma mark -開始代理方法
pragma mark -開始響應
-(void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response{ NSLog(@"接收響應"); _data = [[NSMutableData alloc]init]; //初始化,設置進度條進度 cricl.value = 0; //處理響應 NSLog(@"%@",response); //通過響應頭中的content-Length取得整個響應的總長度 NSHTTPURLResponse httpResponse = (NSHTTPURLResponse )response; NSDictionary *HeaderFields = [httpResponse allHeaderFields]; NSLog(@"%@",HeaderFields);
_totalLength = [HeaderFields[@"Content-Length"] longLongValue];
// NSLog(@"%lld",_totalLength);
}
pragma mark 接收響應數據
-(void)connection:(NSURLConnection )connection didReceiveData:(NSData )data{ NSLog(@"接收響應數據"); [_data appendData:data]; //更新進度條 [self updateProgress]; }
pragma mark 數據接收完成
-(void)connectionDidFinishLoading:(NSURLConnection )connection{ NSLog(@"數據接收完成"); //數據接收完保存文件(注意蘋果官方要求:下載數據智能保存到緩存目錄) NSString path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSLog(@"%@",path); path=[path stringByAppendingPathComponent:@"下載圖片01.jpg"]; //保存下載內容 [_data writeToFile:path atomically:YES]; if(num){ imageOne.image = [UIImage imageWithData:_data]; num = NO; } else{ imageTwo.image = [UIImage imageWithData:_data]; num = YES;
}
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(convert) userInfo:nil repeats:YES];
}
pragma mark 請求失敗
-(void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{ NSLog(@"請求失敗:%@",error); } -(void)okpause{ [timer invalidate]; timer = nil; } -(void)convert{ NSDate *date = [[NSDate alloc]init]; imageThree.image = imageOne.image; imageOne.image = imageTwo.image; imageTwo.image = imageThree.image; NSLog(@"%@",date);
}
import "Cricl.h"
@implementation Cricl
- (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [self drawArc:context]; }
-(void)setValue:(float)value{ _value = value; [self setNeedsDisplay]; }
-(void)drawArc:(CGContextRef)context{ CGContextMoveToPoint(context, 220/2.0, 100/2.0); [[UIColor redColor]set]; CGContextAddArc(context, 220/2.0, 100/2.0, 100/2.0, 0, _value, 0); CGContextDrawPath(context, kCGPathFillStroke); }
@end
//簡化請求和響應
import "ViewController.h"
@interface ViewController (){ UILabel _label; UIButton _button; UITextField _field; long long _totalLength; UIImageView imageOne; UIImageView *imageTwo; BOOL num; }
@end
@implementation ViewController
(void)viewDidLoad { [super viewDidLoad]; [self layout]; } -(void)layout{ imageOne =[[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 100, 100)]; [self.view addSubview:imageOne];
imageTwo = [[UIImageView alloc]initWithFrame:CGRectMake(150, 300, 100, 100)]; [self.view addSubview:imageTwo];
_field = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 355, 25)];
_field.borderStyle = UITextBorderStyleRoundedRect;
_field.text = @"http://5.26923.com/download/pic/000/328/ba80a24af0d5aba07e1461eca71f9502.jpg";
[self.view addSubview:_field];
_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 90, 100, 25)];
_label.text = @"圖片";
[self.view addSubview:_label];
_button = [[UIButton alloc]initWithFrame:CGRectMake(10,500, 355, 25)];
_button.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:0.6];
[_button setTitle:@"正在下載" forState:UIControlStateNormal];
[_button addTarget:self action:@selector(sendRequst) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
} -(void)sendRequst{ //發送網址,并將其轉換成utf8網絡字節序 NSString urlStr = _field.text; NSLog(@"xxxx%@",urlStr); urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //連接與網絡 NSURL url = [NSURL URLWithString:urlStr]; //發送請求和網絡 NSURLRequest request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f]; //同步所表示文件原件的發送必須到達才可執行下一步,異步可以進行后臺 //發送異步請求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse response, NSData data, NSError connectionError) { NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSLog(@"%@",path);
path = [path stringByAppendingPathComponent:@"圖片01.jpg"];
[data writeToFile:path atomically:YES];
NSLog(@"%i",num);
if(num){
imageOne.image = [UIImage imageWithData:data];
num = NO;
}else{
imageTwo.image = [UIImage imageWithData:data];
num= YES;
}
}];
}
</pre>