镔哥哥做项目,一般的数据请求不管他多复杂,只要自己写好了请求,那么调用永远是那么的简单,那么我介绍一下
一:需要用到第三方框架AFNetworking,直接写在工程pch头文件里就行因为经常用到它,这在网上随便下载就行,最好用cocopod来下载,这样什么都有了,cocopod是什么,我就不说,博客上面有介绍。
开始啦:
1:自定义网络请求DataRequestManager类专门管理网络用的
朋友们以下代码就可以直接复制来用了
.h文件
// DataRequestManager.h
// TestKeyBoard
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
#import <Foundation/Foundation.h>
@protocol DataRequestManagerDelegate<NSObject>
//通过代理传值到需要的地方
- (void)passValue:(id)value;
@optional
- (void)passGetValue:(id)getValue;
@end
@interface DataRequestManager : NSObject
{
AFHTTPRequestOperationManager *manager; //创建请求(iOS 6-7)
AFURLSessionManager *sessionManager; //创建请求(iOS7专用)
AFHTTPRequestOperation *operation; //创建请求管理(用于上传和下载)
}
@property (nonatomic, assign) id<DataRequestManagerDelegate> delegate;
//GET请求调用方法
- (void)methodGetWithURL:(NSString *)urlString;
//POST请求调用方法
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters;
//上传图片
- (void)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image;
@end
// DataRequestManager.m
// TestKeyBoard
//
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
//
#import "DataRequestManager.h"
#import "AFNetworking.h"
@implementation DataRequestManager
//GET请求
- (void)methodGetWithURL:(NSString *)urlString
{
//致空请求
if (manager) {
manager = nil;
}
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送GET请求
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"getSuccess: %@", responseObject);
[self.delegate passGetValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - POST Request (iOS 6-7)
//POST请求
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters
{
//致空请求
if (manager) {
manager = nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求
[manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
// NSLog(@"Success: %@", responseObject);
[self.delegate passValue: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)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image
{
//致空请求
if (manager) {
manager = nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求,添加需要发送的文件,此处为图片
[manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//添加图片,并对其进行压缩(0.0为最大压缩率,1.0为最小压缩率)
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//添加要上传的文件,此处为图片
[formData appendPartWithFileData:imageData
name:@"uploadFile"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
[self.delegate passValue: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];
}
#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];
}
@end
iOS经验1:自己写的网络数据请求 第三方框架 断点续传 上传下载
原文地址:http://blog.csdn.net/sammyieveo/article/details/41514407