您的位置:首页 > 理论基础 > 计算机网络

封装网络请求,下载,上传功能

2015-07-21 10:20 387 查看
对于网络数据请求每个人都能想出很多自己的方法,使用第三方,自己封装苹果自带的,不管哪家的,自己学会就是自己的拉 废话少说 上码

//
//  ConnectionUtil.h
//  BlocksConnectionDemo
//
//  Created by junxinWang on 15-5-29.
//  Copyright (c) 2015年 junxinWang. All rights reserved.
//

#import <Foundation/Foundation.h>
typedef enum requestMethod {
RequestMethodGet,
RequestMethodPost
}RequestMethod;
typedef enum downloadType {
downloadImage,
downloadMove
}DownLoadType;
typedef enum uploadType {
uploadImage,
uploadMove
}UpLoadType;
typedef void (^POSTRequest) (id objc);
typedef void (^DownLoad) (id objc);
typedef void (^UpLoad) (id objc);
typedef void (^Progress) (float progress);
typedef void (^Error) (NSError *error);
@interface ConnectionUtil : NSObject
+ (ConnectionUtil *)sharconn;
@property (nonatomic, strong) NSData *data;
@property (nonatomic, strong) NSDictionary *paramDIc;
@property (nonatomic) RequestMethod requestMethod;//请求方式
@property (nonatomic) DownLoadType downloadtype;//下载的类型
@property (nonatomic) UpLoadType uploadtype;//上传类型
@property (nonatomic, copy) POSTRequest postConn;
@property (nonatomic, copy) DownLoad download;
@property (nonatomic, copy) UpLoad   upload;
@property (nonatomic, copy) Progress postPro;
@property (nonatomic, copy) Error error;

+ (void)connection:(POSTRequest)postConn postConnError:(Error)error;
+ (void)connectionDown:(DownLoad)download downError:(Error)error;
+ (void)connectionUpload:(UpLoad)upload uploaError:(Error)error;
+ (void)downloadProgress:(Progress)postPro error:(Error)error;

- (void)startConn:(NSString *)url requestMedth:(RequestMethod)type param:(NSDictionary *)param;

- (void)downLoadConn:(NSString *)url;
- (void)uploadConn:(NSString *)url uploadtype:(UpLoadType)uploadtype  param:(NSDictionary *)param;
- (void)stopConn;
@end


//
//  ConnectionUtil.m
//  BlocksConnectionDemo
//
//  Created by junxinWang on 15-5-29.
//  Copyright (c) 2015年 junxinWang. All rights reserved.
//

#import "ConnectionUtil.h"
#import <UIKit/UIKit.h>
@interface ConnectionUtil ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,NSURLSessionDownloadDelegate>
@property (nonatomic, retain)  NSURLConnection *connection;//连接对象
@property (nonatomic, strong) NSURLSession *urlsession;//普通回话
@property (nonatomic, strong) NSURLSession *backgroundSession;//后台回话
@property (nonatomic, strong) NSURLSessionDownloadTask *sessionDownloadTask;//下载队列
@property (nonatomic,strong)NSURLSessionDownloadTask *backgroundTask;//后台下载队列
@property (nonatomic, strong) NSData *partiaData;//下载局部数据
@property (nonatomic, strong) NSOutputStream *outputStream;
@property (nonatomic, copy) NSString *urlpath;
@end

@implementation ConnectionUtil
static ConnectionUtil *connhelp = nil;
+ (ConnectionUtil *)sharconn {
static dispatch_once_t oneTonke;
dispatch_once(&oneTonke, ^{
connhelp = [[self alloc] init];
});
return connhelp;
}

- (void)startConn:(NSString *)url requestMedth:(RequestMethod)type param:(NSDictionary *)param{
self.paramDIc = param;
NSURL *urlconn = [NSURL URLWithString:[self getStringWithUrl:url]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlconn];

if (RequestMethodPost == type) {
[request setHTTPBody:[self postBody]];
[request setHTTPMethod:@"POST"];
}
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
// [conn start];

}
- (void)stopConn {
[self.connection cancel];
}
- (NSString *)getStringWithUrl:(NSString *)str {
switch (self.requestMethod) {
case RequestMethodPost:
return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
break;
case RequestMethodGet:
return str;
default:
break;
}
}

//获取post请求 请求体
- (NSData *)postBody {
return [[self appedData] dataUsingEncoding:NSUTF8StringEncoding];
}
//将字典中的参数拼接成字符串
- (NSString *)appedData {
NSMutableString *urlstr = [NSMutableString stringWithCapacity:1];
for (NSString *key in self.paramDIc) {
NSString *value = self.paramDIc[key];
[urlstr appendFormat:@"&%@=%@",key,value];
}
//剔除第一个&符
[urlstr deleteCharactersInRange:NSMakeRange(0, 1)];
return urlstr;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"链接服务器...");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//    NSString *String =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.data = data;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

if(self.postConn){
id obj = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
self.postConn(obj);
}

}

//请求数据失败触发 网络中断 服务器未开
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (self.error) {
self.error(error);
}
}

+ (void)connection:(POSTRequest)postConn postConnError:(Error)error{
connhelp.postConn = postConn;
connhelp.error = error;
}

- (NSData *)data {
if(!_data){
self.data = [NSData data];
}
return _data;
}
- (NSDictionary *)paramDIc {
if (!_paramDIc) {
self.paramDIc = [NSDictionary dictionary];
}
return _paramDIc;
}
- (void)uploadConn:(NSString *)url uploadtype:(UpLoadType)uploadtype  param:(NSDictionary *)param;
{
NSData *imageData = UIImageJPEGRepresentation([param valueForKey:@"image"], 0.6);

NSString *boundary = @"0xKhTmLbOuNdArY";
NSString *filename = [NSString stringWithFormat:@"9.jpg"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
NSURL *upurl = [NSURL URLWithString:url];
//2 Request -put 默认是get
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:upurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];
request.HTTPMethod  = @"POST";
/**
*  设置网络请求验证方
*/
//1授权字符串
// NSString *authStr = @"admin:123456";
//2Base64的编码 避免在网络上一明文传输
//iOS中,仅对nsdata的数据类型提供base64编码
//    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
//    NSString *encodeStr = [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
//    NSString *authValue = [NSString stringWithFormat:@"Basic %@",encodeStr];

//[request setValue:authValue forHTTPHeaderField:@"Content-Type"];
//3Session

// 4 Create object to put content into...
//拼接from表单 加载上传数据
NSMutableData *body = [NSMutableData data];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// 定义上传图片的类型
//  [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//__block NSString *stringForText = @"Hola";

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//4uploadTask

// NSData *imgeData = UIImageJPEGRepresentation([param valueForKey:@"image"], 0.75);

//NSData *imgeData = [NSJSONSerialization dataWithJSONObject:[param valueForKey:@"upfile"] options:NSJSONWritingPrettyPrinted error:nil];
//应用block的请求方式
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

//上传完成后 data参数转成string就是服务器返回的内容
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(self.upload){
if(error){
self.error(error);
}else{
self.upload(str);}
}
// NSLog(@"ok%@",str);
}];
//开始上传
[uploadTask resume];
}
+ (void)connectionUpload:(UpLoad)upload uploaError:(Error)error {
connhelp.upload = upload;
connhelp.error = error;
}
#pragma mark - 如果我们需要利用NSURLSession进行数据传输我们需要:
/**

*  创建一个NSURLSessionConfiguration,用于创建NSSession时设置工作模式(3种)

*  (1)一般模式(default):工作模式类似于原来的NSURLConnection,可以使用缓存的Cache,Cookie,鉴权。

*  (2)及时模式(ephemeral):不使用缓存的Cache,Cookie,鉴权。

*  (3)后台模式(background):在后台完成上传下载,创建Configuration对象的时候需要给一个NSString的ID用于追踪完成工作的Session是哪一个

*/

- (void)downLoadConn:(NSString *)url  {

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

//    NSURLCache *myCache = [[NSURLCache alloc] initWithMemoryCapacity: 16384 diskCapacity: 268435456 diskPath: fileName];

/**

*  @网络设置:参考NSURLConnection中的设置项

*  两种创建方法(目前不太懂什么区别)

*  (1)就是根据刚才创建的Configuration创建一个Session,系统默认创建一个新的OperationQueue处理Session的消息

*  (2)可以设定回调的delegate(注意这个回调delegate会被强引用),并且可以设定delegate在哪个OperationQueue回调,如果我们将其

*     设置为[NSOperationQueue mainQueue]就能在主线程进行回调非常的方便

*/

//NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
//sessionConfiguration.URLCache = myCache;
// sessionConfiguration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
self.urlsession = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//NSString *str =[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *urlconn = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:urlconn];

/**

*  NSURLSessionUploadTask:上传用的Task,传完以后不会再下载返回结果;

*  NSURLSessionDownloadTask:下载用的Task;

*  NSURLSessionDataTask:可以上传内容,上传完成后再进行下载。

*/
self.sessionDownloadTask = [self.urlsession downloadTaskWithRequest:request];

[_sessionDownloadTask resume];

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
//下载成功后,文件是保存在一个临时目录的,需要开发者自己考到放置该文件的目录

NSURL *destination = [self createDirectoryForDownloadItemFromURL:location];
BOOL success = [self copyTempFileAtURL:location toDestination:destination];

if (success) {
if (self.download) {
if (downloadTask.error) {
self.error(downloadTask.error);
}else {
self.download(downloadTask);
}

}
}else {
NSLog(@"文件保存错误");
}
self.sessionDownloadTask = nil;
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

if (self.postPro) {
if (downloadTask.error) {
self.error(downloadTask.error);
}else{
CGFloat progress = ((float)totalBytesWritten) / totalBytesExpectedToWrite;
self.postPro(progress);
}
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
+ (void)downloadProgress:(Progress)postPro error:(Error)error {
connhelp.postPro = postPro;
connhelp.error = error;
}
+ (void)connectionDown:(DownLoad)download downError:(Error)error {
connhelp.download = download;
connhelp.error = error;
}
//创建文件本地保存目录
-(NSURL *)createDirectoryForDownloadItemFromURL:(NSURL *)location
{
NSString *newpath;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsDirectory = urls[0];

NSString *tmpstr = [location absoluteString];
if (self.downloadtype == downloadImage) {
newpath = [tmpstr stringByReplacingCharactersInRange:NSMakeRange(tmpstr.length-4, 4) withString:@".jpg"];
}else if(self.downloadtype == downloadMove){
newpath = [tmpstr stringByReplacingCharactersInRange:NSMakeRange(tmpstr.length-4, 4) withString:@".mp4"];
}

NSLog(@"%@",newpath);
NSURL *url2 = [NSURL URLWithString:newpath];
return  [documentsDirectory URLByAppendingPathComponent:[url2 lastPathComponent]];
}
//把文件拷贝到指定路径
-(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination  {
NSError *error;
NSFileManager *filemanager = [NSFileManager defaultManager];
[filemanager removeItemAtURL:destination error:nil];

// NSURL *url =[NSURL URLWithString:tmpstr];
[filemanager copyItemAtURL:location toURL:destination error:nil];
if (error == nil) {
NSLog(@"转移成功");
return true;
}else {
NSLog(@"%@",error);
return false;
}
}
- (NSString *)getCachesImagePath {

//获取caches文件夹路径
NSString *filepath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
//获取MP3文件夹的路径
NSString *newpath = [filepath stringByAppendingPathComponent:@"Images"];
//3判断文件夹是否存在
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:@"newpath"]) {
//没有的话创建文件夹
BOOL isSuccess =  [manager createDirectoryAtPath:newpath withIntermediateDirectories:YES attributes:nil error:nil];
if (isSuccess) {
// NSLog(@"images创建成功");
}else{
//  NSLog(@"images创建失败");
}
}
return newpath;
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: