你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> iOS經驗1:自己寫的網絡數據請求 第三方框架 斷點續傳 上傳下載

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

編輯:關於IOS

镔哥哥做項目,一般的數據請求不管他多復雜,只要自己寫好了請求,那麼調用永遠是那麼的簡單,那麼我介紹一下

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

@protocol DataRequestManagerDelegate

//通過代理傳值到需要的地方

- (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 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 = [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 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

工程完美,自己復制可用

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved