iOS經驗1:自己寫的網路資料請求 第三方架構 斷點續傳 上傳下載
鑌哥哥做項目,一般的資料請求不管他多複雜,只要自己寫好了請求,那麼調用永遠是那麼的簡單,那麼我介紹一下
一:需要用到第三方架構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 = [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 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
工程完美,自己複製可用