IOS http(上傳和下載)

來源:互聯網
上載者:User

標籤:檔案路徑   不能   err   res   loaddata   omd   usr   url   download   

 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(上傳和下載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.