你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS開發之網絡開發工具

IOS開發之網絡開發工具

編輯:IOS開發綜合

IOS開發之網絡開發工具

做移動端開發 經常會涉及到幾個模塊:1、網絡檢測 2、網絡請求get和post請求 3、文件上傳 4、文件下載 5、斷點續傳

現在將這些一一分享給大家 ,也歡迎大家一起學習和討論 本例子采用AFNetWorking框架

網絡檢測:


#pragma mark - Reachability Management (iOS 6-7)


//網絡監聽(用於檢測網絡是否可以鏈接。此方法最好放於AppDelegate中,可以使程序打開便開始檢測網絡)
- (void)reachabilityManager
{
//打開網絡監聽
[manager.reachabilityManager startMonitoring];

//監聽網絡變化
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {

//當網絡不可用(無網絡或請求延時)
case AFNetworkReachabilityStatusNotReachable:
break;

//當為手機蜂窩數據網和WiFi時
case AFNetworkReachabilityStatusReachableViaWiFi:
case AFNetworkReachabilityStatusReachableViaWWAN:
break;

//其它情況
default:
break;
}
}];

//停止網絡監聽(若需要一直檢測網絡狀態,可以不停止,使其一直運行)
[manager.reachabilityManager stopMonitoring];
}


Get請求數據:

#pragma mark - GET Request (iOS 6-7)


//GET請求
- (void)methodGet
{
//致空請求
if (manager) {
manager = nil;
}

//創建請求
manager = [AFHTTPRequestOperationManager manager];

//設置請求的解析器為AFHTTPResponseSerializer(用於直接解析數據NSData),默認為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送GET請求
[manager GET:@"接口地址" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", responseObject);

//請求成功(當解析器為AFHTTPResponseSerializer時)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//請求失敗
NSLog(@"Error: %@", error);
}];

}

POST請求:

#pragma mark - POST Request (iOS 6-7)


//POST請求
- (void)methodPost
{
//致空請求
if (manager) {
manager = nil;
}

//添加參數
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};

//創建請求
manager = [AFHTTPRequestOperationManager manager];

//設置請求的解析器為AFHTTPResponseSerializer(用於直接解析數據NSData),默認為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送POST請求
[manager POST:@"接口地址" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", 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)methodUpload
{
//致空請求
if (manager) {
manager = nil;
}

//添加參數
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};

//創建請求
manager = [AFHTTPRequestOperationManager manager];

//設置請求的解析器為AFHTTPResponseSerializer(用於直接解析數據NSData),默認為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送POST請求,添加需要發送的文件,此處為圖片
[manager POST:@"接口地址" parameters:parameters constructingBodyWithBlock:^(id formData) {

//添加圖片,並對其進行壓縮(0.0為最大壓縮率,1.0為最小壓縮率)
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"圖片名字(注意後綴名)"], 1.0);

//添加要上傳的文件,此處為圖片
[formData appendPartWithFileData:imageData name:@"服務器放圖片的參數名(Key)" fileName:@"圖片名字" mimeType:@"文件類型(此處為圖片格式,如image/jpeg)"];

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

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", 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];

}

IOS7特性特有上傳和下載:



#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];

}

源碼下載地址:http://download.csdn.net/detail/wangliang198901/7935199




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