自己寫的網絡數據請求 第三方框架 斷點續傳 上傳下載

一:需要用到第三方框架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


.m文件

//  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 = [AFHTTPRequestOperationManagermanager];

    //設置請求的解析器爲AFHTTPResponseSerializer(用於直接解析數據NSData),默認爲AFJSONResponseSerializer(用於解析JSON

//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //發送GET請求

    [manager GET:urlStringparameters:nilsuccess:^(AFHTTPRequestOperation *operation,id responseObject) {

        //請求成功(當解析器爲AFJSONResponseSerializer時)

        NSLog(@"getSuccess: %@", responseObject);

        [self.delegatepassGetValue: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 = [AFHTTPRequestOperationManagermanager];

    //設置請求的解析器爲AFHTTPResponseSerializer(用於直接解析數據NSData),默認爲AFJSONResponseSerializer(用於解析JSON

    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //發送POST請求

    [manager POST:urlStringparameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {

        

        //請求成功(當解析器爲AFJSONResponseSerializer時)

//        NSLog(@"Success: %@", responseObject);

        [self.delegatepassValue: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 = [AFHTTPRequestOperationManagermanager];

    

    //設置請求的解析器爲AFHTTPResponseSerializer(用於直接解析數據NSData),默認爲AFJSONResponseSerializer(用於解析JSON

    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    //發送POST請求,添加需要發送的文件,此處爲圖片

    [manager POST:urlStringparameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        

        //添加圖片,並對其進行壓縮(0.0爲最大壓縮率,1.0爲最小壓縮率)

        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

        NSDateFormatter *formatter = [[NSDateFormatteralloc] init];

        // 設置時間格式

        formatter.dateFormat = @"yyyyMMddHHmmss";

        NSString *str = [formatter stringFromDate:[NSDate date]];

        NSString *fileName = [NSStringstringWithFormat:@"%@.png", str];

        //添加要上傳的文件,此處爲圖片

        [formData appendPartWithFileData:imageData

                                    name:@"uploadFile"

                                fileName:fileName

                                mimeType:@"image/jpeg"];


    } success:^(AFHTTPRequestOperation *operation,id responseObject) {

        

        //請求成功(當解析器爲AFJSONResponseSerializer時)

        NSLog(@"Success: %@", responseObject);

        [self.delegatepassValue: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

{

    [selfmethodDownload];

    [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 = [[AFURLSessionManageralloc] initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];

    

    //添加請求接口

    NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"上傳地址"]];

    

    //添加上傳的文件

    NSURL *filePath = [NSURLfileURLWithPath:@"本地文件地址"];

    

    //發送上傳請求

    NSURLSessionUploadTask *uploadTask = [sessionManageruploadTaskWithRequest:request fromFile:filePath progress:nilcompletionHandler:^(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 = [[AFURLSessionManageralloc] initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];

    

    //添加請求接口

    NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"下載地址"]];

    

    //發送下載請求

    NSURLSessionDownloadTask *downloadTask = [sessionManagerdownloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {

        

        //設置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夾中。關於如何獲取文件路徑,請自行搜索相關資料)

        NSURL *filePath = [NSURLfileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)firstObject]];

        

        return [filePathURLByAppendingPathComponent:[response suggestedFilename]];

        

    } completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error) {

        

        //下載完成

        NSLog(@"Finish and Download to: %@", filePath);

    }];

    

    //開始下載

    [downloadTask resume];

}


@end


工程完美,自己複製可用
發佈了9 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章