AFNetworking是一個輕量級的iOS網絡通訊類庫。它創建在NSURLConnection和NSOperation等類庫的基礎上,讓不少網絡通訊功能的實現變得十分簡單。它支持HTTP請求和基於REST的網絡服務(包括GET、POST、 PUT、DELETE等)。支持ARC。php
Github地址:https://github.com/AFNetworking/AFNetworkinghtml
//
// MJViewController.m
// 03.AFN演練
//
// Created by apple on 14-4-30.
// Copyright (c) 2014年 itcast. All rights reserved.
//
#import "MJViewController.h"
#import "AFNetworking.h"
@interface MJViewController ()
@end
@implementation MJViewController
/**
要使用常規的AFN網絡訪問
1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
全部的網絡請求,均有manager發起
2. 須要注意的是,默認提交請求的數據是二進制的,返回格式是JSON
1> 若是提交數據是JSON的,須要將請求格式設置爲AFJSONRequestSerializer
2> 若是返回格式不是JSON的,
3. 請求格式
AFHTTPRequestSerializer 二進制格式
AFJSONRequestSerializer JSON
AFPropertyListRequestSerializer PList(是一種特殊的XML,解析起來相對容易)
4. 返回格式
AFHTTPResponseSerializer 二進制格式
AFJSONResponseSerializer JSON
AFXMLParserResponseSerializer XML,只能返回XMLParser,還須要本身經過代理方法解析
AFXMLDocumentResponseSerializer (Mac OS X)
AFPropertyListResponseSerializer PList
AFImageResponseSerializer Image
AFCompoundResponseSerializer 組合
*/
- (void)viewDidLoad
{
[super viewDidLoad];
[self reach];
}
#pragma mark - 演練
#pragma mark - 檢測網絡鏈接
- (void)reach
{
/**
AFNetworkReachabilityStatusUnknown = -1, // 未知
AFNetworkReachabilityStatusNotReachable = 0, // 無鏈接
AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花錢
AFNetworkReachabilityStatusReachableViaWiFi = 2, // 局域網絡,不花錢
*/git
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
// 檢測網絡鏈接的單例,網絡變化時的回調方法
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"%d", status);
}];
}
程序員
- (void)sessionDownload
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
NSString *urlString = @"http://localhost/itcast/videos/01.C語言-語法預覽.mp4";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
// 指定下載文件保存的路徑
// NSLog(@"%@ %@", targetPath, response.suggestedFilename);
// 將下載文件保存在緩存路徑中
NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
// URLWithString返回的是網絡的URL,若是使用本地URL,須要注意
NSURL *fileURL1 = [NSURL URLWithString:path];
NSURL *fileURL = [NSURL fileURLWithPath:path];
NSLog(@"== %@ |||| %@", fileURL1, fileURL);
return fileURL;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"%@ %@", filePath, error);
}];
[task resume];
}github
- (void)postJSON
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *dict = @{@"name": @"zhangsan"};
NSDictionary *dict1 = @{@"name": @"wangwu"};
NSArray *array = @[dict, dict1];
// 設置請求格式
manager.requestSerializer = [AFJSONRequestSerializer serializer];
// 設置返回格式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
}json
- (void)postUpload1
{
// 本地上傳給服務器時,沒有肯定的URL,很差用MD5的方式處理
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil];
// 要上傳保存在服務器中的名稱
// 使用時間來做爲文件名 2014-04-30 14:20:57.png
// 讓不一樣的用戶信息,保存在不一樣目錄中
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 設置日期格式
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *fileName = [formatter stringFromDate:[NSDate date]];
[formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"OK");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error");
}];
}
緩存
- (void)postUpload
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// AFHTTPResponseSerializer就是正常的HTTP請求響應結果:NSData
// 當請求的返回數據不是JSON,XML,PList,UIImage以外,使用AFHTTPResponseSerializer
// 例如返回一個html,text...
//
// 實際上就是AFN沒有對響應數據作任何處理的狀況
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// formData是遵照了AFMultipartFormData的對象
[manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 將本地的文件上傳至服務器
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil];
[formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"完成 %@", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"錯誤 %@", error.localizedDescription);
}];
}
#pragma mark - JSON
- (void)XMLData
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// 返回的數據格式是XML
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
NSDictionary *dict = @{@"format": @"xml"};
// 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情
[manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 若是結果是XML,一樣須要使用6個代理方法解析,或者使用第三方庫
// 第三方庫第三方框架,效率低,內存泄漏
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
}
服務器
- (void)JSONData
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// 本來須要拼接get訪問URL ? & =
NSDictionary *dict = @{@"format": @"json"};
// 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情
[manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
// 提問:NSURLConnection異步方法回調,是在子線程
// 獲得回調以後,一般更新UI,是在主線程
NSLog(@"%@", [NSThread currentThread]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
}
網絡
- (void)postLogin
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// 本來須要拼接get訪問URL ? & =
NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};
// 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情
[manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
// 提問:NSURLConnection異步方法回調,是在子線程
// 獲得回調以後,一般更新UI,是在主線程
NSLog(@"%@", [NSThread currentThread]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
}
session
- (void)getLogin{ AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 本來須要拼接get訪問URL ? & = NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"}; // 網絡訪問是異步的,回調是主線程的,所以程序員不用管在主線程更新UI的事情 [manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); // 提問:NSURLConnection異步方法回調,是在子線程 // 獲得回調以後,一般更新UI,是在主線程 NSLog(@"%@", [NSThread currentThread]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];}@end