1. 程式人生 > >IOS http(上傳和下載)

IOS http(上傳和下載)

fig pla nil style span atof port use userinfo

HttpTool.h

技術分享
#import <Foundation/Foundation.h>

typedef void (^HttpToolProgressBlock)(CGFloat progress);
typedef void (^HttpToolCompletionBlock)(NSError *error);



@interface HttpTool : NSObject

-(void)uploadData:(NSData *)data
              url:(NSURL *)url
    progressBlock : (HttpToolProgressBlock)progressBlock
            completion:(HttpToolCompletionBlock) completionBlock;

/** 下載數據 */ -(void)downLoadFromURL:(NSURL *)url progressBlock : (HttpToolProgressBlock)progressBlock completion:(HttpToolCompletionBlock) completionBlock; -(NSString *)fileSavePath:(NSString *)fileName; @end
View Code 技術分享
#import "HttpTool.h"

#define kTimeOut 5.0


@interface HttpTool()<NSURLSessionDownloadDelegate,NSURLSessionTaskDelegate>{

    
//下載 HttpToolProgressBlock _dowloadProgressBlock; HttpToolCompletionBlock _downladCompletionBlock; NSURL *_downloadURL; //上傳 HttpToolProgressBlock _uploadProgressBlock; HttpToolCompletionBlock _uploadCompletionBlock; } @end @implementation HttpTool #pragma mark - 上傳 -(void
)uploadData:(NSData *)data url:(NSURL *)url progressBlock:(HttpToolProgressBlock)progressBlock completion:(HttpToolCompletionBlock)completionBlock{ NSAssert(data != nil, @"上傳數據不能為空"); NSAssert(url != nil, @"上傳文件路徑不能為空"); _uploadProgressBlock = progressBlock; _uploadCompletionBlock = completionBlock; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kTimeOut]; request.HTTPMethod = @"PUT"; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; //NSURLSessionDownloadDelegate NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; //定義下載操作 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data]; [uploadTask resume]; } #pragma mark - 上傳代理 #pragma mark - 上傳進度 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ if (_uploadProgressBlock) { CGFloat progress = (CGFloat) totalBytesSent / totalBytesExpectedToSend; _uploadProgressBlock(progress); } } #pragma mark - 上傳完成 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ if (_uploadCompletionBlock) { _uploadCompletionBlock(error); _uploadProgressBlock = nil; _uploadCompletionBlock = nil; } } #pragma mark - 下載 -(void)downLoadFromURL:(NSURL *)url progressBlock:(HttpToolProgressBlock)progressBlock completion:(HttpToolCompletionBlock)completionBlock{ NSAssert(url != nil, @"下載URL不能傳空"); _downloadURL = url; _dowloadProgressBlock = progressBlock; _downladCompletionBlock = completionBlock; NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kTimeOut]; //session 大多數使用單例即可 NSURLResponse *response = nil; //發達同步請求 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; //NSLog(@"%lld",response.expectedContentLength); if (response.expectedContentLength <= 0) { if (_downladCompletionBlock) { NSError *error =[NSError errorWithDomain:@"文件不存在" code:404 userInfo:nil]; _downladCompletionBlock(error); //清除block _downladCompletionBlock = nil; _dowloadProgressBlock = nil; } return; } NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; //NSURLSessionDownloadDelegate NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; //定義下載操作 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request]; [downloadTask resume]; } #pragma mark -NSURLSessionDownloadDelegate #pragma mark 下載完成 -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ //圖片保存在沙盒的Doucument下 NSString *fileSavePath = [self fileSavePath:[_downloadURL lastPathComponent]]; //文件管理 NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager copyItemAtURL:location toURL:[NSURL fileURLWithPath:fileSavePath] error:nil]; if (_downladCompletionBlock) { //通知下載成功,沒有沒有錯誤 _downladCompletionBlock(nil); //清空block _downladCompletionBlock = nil; _dowloadProgressBlock = nil; } } #pragma mark 下載進度 -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ if (_dowloadProgressBlock) { //已寫數據字節數除以總字節數就是下載進度 CGFloat progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite; _dowloadProgressBlock(progress); } } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{ } #pragma mark -傳一個文件名,返回一個在沙盒Document下的文件路徑 -(NSString *)fileSavePath:(NSString *)fileName{ NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; //圖片保存在沙盒的Doucument下 return [document stringByAppendingPathComponent:fileName]; } @end
View Code

IOS http(上傳和下載)