IOS开发之网络开发工具
IOS开发之网络开发工具
做移动端开发 经常会涉及到几个模块:1、网络检测 2、网络请求get和post请求 3、文件上传 4、文件下载 5、断点续传
现在将这些一一分享给大家 ,也欢迎大家一起学习和讨论 本例子采用AFNetWorking框架
网络检测:
#pragma mark - Reachability Management (iOS 6-7)
//网络监听(用于检测网络是否可以链接。此方法最好放于AppDelegate中,可以使程序打开便开始检测网络)
- (void)reachabilityManager
{
//打开网络监听
[manager.reachabilityManager startMonitoring];
//监听网络变化
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
//当网络不可用(无网络或请求延时)
case AFNetworkReachabilityStatusNotReachable:
break;
//当为手机蜂窝数据网和WiFi时
case AFNetworkReachabilityStatusReachableViaWiFi:
case AFNetworkReachabilityStatusReachableViaWWAN:
break;
//其它情况
default:
break;
}
}];
//停止网络监听(若需要一直检测网络状态,可以不停止,使其一直运行)
[manager.reachabilityManager stopMonitoring];
}
Get请求数据:
#pragma mark - GET Request (iOS 6-7)
//GET请求
- (void)methodGet
{
//致空请求
if (manager) {
manager = nil;
}
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送GET请求
[manager GET:@"接口地址" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
POST请求:
#pragma mark - POST Request (iOS 6-7)
//POST请求
- (void)methodPost
{
//致空请求
if (manager) {
manager = nil;
}
//添加参数
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求
[manager POST:@"接口地址" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
上传:
#pragma mark - Upload Request (iOS 6-7)
//上传(以表单方式上传,以图片为例)
- (void)methodUpload
{
//致空请求
if (manager) {
manager = nil;
}
//添加参数
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求,添加需要发送的文件,此处为图片
[manager POST:@"接口地址" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//添加图片,并对其进行压缩(0.0为最大压缩率,1.0为最小压缩率)
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"图片名字(注意后缀名)"], 1.0);
//添加要上传的文件,此处为图片
[formData appendPartWithFileData:imageData name:@"服务器放图片的参数名(Key)" fileName:@"图片名字" mimeType:@"文件类型(此处为图片格式,如image/jpeg)"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
下载:
#pragma mark - Download Request (iOS 6-7)
//下载
- (void)methodDownload
{
//下载进度条
UIProgressView *downProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
downProgressView.center = CGPointMake(self.view.center.x, 220);
downProgressView.progress = 0;
downProgressView.progressTintColor = [UIColor blueColor];
downProgressView.trackTintColor = [UIColor grayColor];
[self.view addSubview:downProgressView];
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
//方法一
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *cachesDirectory = [paths objectAtIndex:0];
// NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"文件名"];
//方法二
NSString *filePath = [NSString stringWithFormat:@"%@/Documents/文件名(注意后缀名)", NSHomeDirectory()];
//打印文件保存的路径
NSLog(@"%@",filePath);
//创建请求管理
operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]]];
//添加下载请求(获取服务器的输出流)
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
//设置下载进度条
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//显示下载进度
CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
[downProgressView setProgress:progress animated:YES];
}];
//请求管理判断请求结果
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
NSLog(@"Finish and Download to: %@", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@",error);
}];
}
断点续传:
#pragma mark - Download Management (iOS 6-7)
//开始下载(断点续传)
- (void)downloadStart
{
[self methodDownload];
[operation start];
}
//暂停下载(断点续传)
- (void)downloadPause
{
[operation pause];
}
//继续下载(断点续传)
- (void)downloadResume
{
[operation resume];
}
IOS7特性特有上传和下载:
#pragma mark - Upload Request (iOS 7 only)
//上传(iOS7专用)
- (void)methodUploadFor7
{
//致空请求
if (sessionManager) {
sessionManager = nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"上传地址"]];
//添加上传的文件
NSURL *filePath = [NSURL fileURLWithPath:@"本地文件地址"];
//发送上传请求
NSURLSessionUploadTask *uploadTask = [sessionManager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
//请求失败
NSLog(@"Error: %@", error);
} else {
//请求成功
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
//开始上传
[uploadTask resume];
}
#pragma mark - Download Request (iOS 7 only)
//下载(iOS7专用)
- (void)methodDownloadFor7
{
//致空请求
if (sessionManager) {
sessionManager = nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]];
//发送下载请求
NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
NSURL *filePath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [filePath URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//下载完成
NSLog(@"Finish and Download to: %@", filePath);
}];
//开始下载
[downloadTask resume];
}
源码下载地址:http://download.csdn.net/detail/wangliang198901/7935199
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。