AFNetworking請(qǐng)求各種類型的數(shù)據(jù)備忘筆記?
AFNetworking是一個(gè)輕量級(jí)的iOS網(wǎng)絡(luò)通信類庫(kù)咧织。它建立在NSURLConnection和NSOperation等類庫(kù)的基礎(chǔ)上备燃,讓很多網(wǎng)絡(luò)通信功能的實(shí)現(xiàn)變得十分簡(jiǎn)單。它支持HTTP請(qǐng)求和基于REST的網(wǎng)絡(luò)服務(wù)(包括GET剧蹂、POST、 PUT、DELETE等)题造。支持ARC鹦赎。Github地址:https://github.com/AFNetworking/AFNetworking?
```
1.? ? //??
2.? ? //? MJViewController.m??
3.? ? //? 03.AFN演練?
?4.? ? //??
5.? ? //? Created by apple on 14-4-30.??
6.? ? //? Copyright (c) 2014年 itcast. All rights reserved.??
7.? ? //??
8.? ??
? 9.? ? #import "MJViewController.h"? 10.? #import "AFNetworking.h"??
11.? ??
?12.? @interface MJViewController ()?
?13.? ??
?14.? @end??
15.? ??
?16.? @implementation MJViewController?
?17.? /**?
18.? ? 要使用常規(guī)的AFN網(wǎng)絡(luò)訪問(wèn)?
19.? ??
?20.? ? 1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];?
21.? ?
?22.? ? ? 所有的網(wǎng)絡(luò)請(qǐng)求,均有manager發(fā)起?
23.? ?
?24.? ? 2. 需要注意的是,默認(rèn)提交請(qǐng)求的數(shù)據(jù)是二進(jìn)制的,返回格式是JSON?
25.? ??
?26.? ? ? 1> 如果提交數(shù)據(jù)是JSON的,需要將請(qǐng)求格式設(shè)置為AFJSONRequestSerializer 27.? ? ? 2> 如果返回格式不是JSON的,?
28. ?
?? 29.? ? 3. 請(qǐng)求格式 30.? ?
?31.? ? ? ? AFHTTPRequestSerializer? ? ? ? ? ? 二進(jìn)制格式?
32.? ? ? ? AFJSONRequestSerializer? ? ? ? ? ? JSON?
33.? ? ? ? AFPropertyListRequestSerializer? ? PList(是一種特殊的XML,解析起來(lái)相對(duì)容易)?
34.? ??
?35.? ? 4. 返回格式?
36.? ??
?37.? ? ? ? AFHTTPResponseSerializer? ? ? ? ? 二進(jìn)制格式?
38.? ? ? ? AFJSONResponseSerializer? ? ? ? ? JSON?
39.? ? ? ? AFXMLParserResponseSerializer? ? ? XML,只能返回XMLParser,還需要自己通過(guò)代理方法解析?
40.? ? ? ? AFXMLDocumentResponseSerializer (Mac OS X)?
41.? ? ? ? AFPropertyListResponseSerializer? Plist?
42.? ? ? ? AFImageResponseSerializer? ? ? ? ? Image?
43.? ? ? ? AFCompoundResponseSerializer? ? ? 組合?
44.? ? */? 45.? ? 46.? - (void)viewDidLoad??
47.? {? 48.? ? ? [super viewDidLoad];?
?49.? ? ? ??
?50.? ? ? [self reach];? 51.? }??
52.? ? 53.? #pragma mark - 演練??
54.? #pragma mark - 檢測(cè)網(wǎng)絡(luò)連接??
55.? - (void)reach? 5
6.? {? 57.? ? ? /**?
58.? ? ? ? AFNetworkReachabilityStatusUnknown? ? ? ? ? = -1,? // 未知
?59.? ? ? ? AFNetworkReachabilityStatusNotReachable? ? = 0,? // 無(wú)連接?
60.? ? ? ? AFNetworkReachabilityStatusReachableViaWWAN = 1,? // 3G 花錢(qián)?
61.? ? ? ? AFNetworkReachabilityStatusReachableViaWiFi = 2,? // 局域網(wǎng)絡(luò),不花錢(qián) 62.? ? ? ? */?
?63.? ? ? // 如果要檢測(cè)網(wǎng)絡(luò)狀態(tài)的變化,必須用檢測(cè)管理器的單例的startMonitoring? 64.? ? ? [[AFNetworkReachabilityManager sharedManager] startMonitoring];??
65.? ? ? ??
?66.? ? ? // 檢測(cè)網(wǎng)絡(luò)連接的單例,網(wǎng)絡(luò)變化時(shí)的回調(diào)方法??
67.? ? ? [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {?
?68.? ? ? ? ? NSLog(@"%d", status);??
69.? ? ? }];??
70.? }??
71.? ??
?72.? #pragma mark - Session 下載??
73.? - (void)sessionDownload??
74.? {?
?75.? ? ? NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];??
76.? ? ? AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];??
77.? ? ? ?
?78.? ? ? NSString *urlString = @"http://localhost/itcast/videos/01.C語(yǔ)言-語(yǔ)法預(yù)覽.mp4";??
79.? ? ? urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];??
80.? ? ??
? 81.? ? ? NSURL *url = [NSURL URLWithString:urlString];??
82.? ? ? NSURLRequest *request = [NSURLRequest requestWithURL:url];??
83.? ? ? ??
?84.? ? ? NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {??
85.? ? ? ? ? // 指定下載文件保存的路徑??
86.? //? ? ? ? NSLog(@"%@ %@", targetPath, response.suggestedFilename);??
87.? ? ? ? ? // 將下載文件保存在緩存路徑中??
88.? ? ? ? ? NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];??
89.? ? ? ? ? NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];??
90.? ? ? ? ? ?
?91.? ? ? ? ? // URLWithString返回的是網(wǎng)絡(luò)的URL,如果使用本地URL,需要注意??
92.? ? ? ? ? NSURL *fileURL1 = [NSURL URLWithString:path];?
?93.? ? ? ? ? NSURL *fileURL = [NSURL fileURLWithPath:path];?
?94.? ? ? ? ? ?
?95.? ? ? ? ? NSLog(@"== %@ |||| %@", fileURL1, fileURL);??
96.? ? ? ? ? ?
?97.? ? ? ? ? return fileURL;?
?98.? ? ? } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {??
99.? ? ? ? ? NSLog(@"%@ %@", filePath, error);? 100.? ? ? }];??
101.? ? ? ?
?102.? ? ? [task resume];??
103.? }??
104.? ?
?105.? #pragma mark - POST JSON??
106.? - (void)postJSON??
107.? {??
108.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];?
?109.? ? ? ??
110.? ? ? NSDictionary *dict = @{@"name": @"zhangsan"};??
111.? ? ? NSDictionary *dict1 = @{@"name": @"wangwu"};??
112.? ? ? NSArray *array = @[dict, dict1];??
113.? ? ? // 設(shè)置請(qǐng)求格式
?114.? ? ? manager.requestSerializer = [AFJSONRequestSerializer serializer];? 115.? ? ? // 設(shè)置返回格式??
116.? ? ? manager.responseSerializer = [AFHTTPResponseSerializer serializer];? 117.? ? ? ??
118.? ? ? [manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) {??
119.? ? ? ? ? NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];??
120.? ? ? ? ? ??
121.? ? ? ? ? NSLog(@"%@", result);??
122.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {??
123.? ? ? ? ? ??
124.? ? ? }];??
125.? ? ? ??
126.? }??
127.? ??
128.? #pragma mark - 隨機(jī)文件名上傳??
129.? - (void)postUpload1??
130.? {??
131.? ? ? // 本地上傳給服務(wù)器時(shí),沒(méi)有確定的URL,不好用MD5的方式處理??
132.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];??
133.? ? ? manager.responseSerializer = [AFHTTPResponseSerializer serializer];? 134.? ? ? ??
135.? ? ? [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(idformData) {??
136.? ? ? ? ? ??
137.? ? ? ? ? NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil];??
138.? ? ? ? ? ??
139.? ? ? ? ? // 要上傳保存在服務(wù)器中的名稱??
140.? ? ? ? ? // 使用時(shí)間來(lái)作為文件名 2014-04-30 14:20:57.png??
141.? ? ? ? ? // 讓不同的用戶信息,保存在不同目錄中??
142.? ? ? ? ? NSDateFormatter *formatter = [[NSDateFormatter alloc] init];??
143.? ? ? ? ? // 設(shè)置日期格式??
144.? ? ? ? ? formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";??
145.? ? ? ? ? NSString *fileName = [formatter stringFromDate:[NSDate date]];? 146.? ? ? ? ? ??
147.? ? ? ? ? [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL];??
148.? ? ? ? ? ??
149.? ? ? } success:^(AFHTTPRequestOperation *operation, id responseObject) {? 150.? ? ? ? ? NSLog(@"OK");??
151.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {??
152.? ? ? ? ? NSLog(@"error");??
153.? ? ? }];??
154.? }??
155.? ??
156.? #pragma mark - POST上傳??
157.? - (void)postUpload??
158.? {??
159.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];??
160.? ? ? // AFHTTPResponseSerializer就是正常的HTTP請(qǐng)求響應(yīng)結(jié)果:NSData??
161.? ? ? // 當(dāng)請(qǐng)求的返回?cái)?shù)據(jù)不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer??
162.? ? ? // 例如返回一個(gè)html,text...??
163.? ? ? //??
164.? ? ? // 實(shí)際上就是AFN沒(méi)有對(duì)響應(yīng)數(shù)據(jù)做任何處理的情況??
165.? ? ? manager.responseSerializer = [AFHTTPResponseSerializer serializer];? 166.? ? ? ??
167.? ? ? // formData是遵守了AFMultipartFormData的對(duì)象??
168.? ? ? [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(idformData) {
169.
170.? ? ? ? ? // 將本地的文件上傳至服務(wù)器
171.? ? ? ? ? NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"頭像1.png" withExtension:nil];
172.
173.? ? ? ? ? [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
174.? ? ? } success:^(AFHTTPRequestOperation *operation, id responseObject) {
175.? ? ? ? ? NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
176.
177.? ? ? ? ? NSLog(@"完成 %@", result);
178.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
179.? ? ? ? ? NSLog(@"錯(cuò)誤 %@", error.localizedDescription);
180.? ? ? }];
181.? }
182.
183.? #pragma mark - JSON
184.? - (void)XMLData
185.? {
186.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
187.
188.? ? ? // 返回的數(shù)據(jù)格式是XML
189.? ? ? manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
190.
191.? ? ? NSDictionary *dict = @{@"format": @"xml"};
192.
193.? ? ? // 網(wǎng)絡(luò)訪問(wèn)是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
194.? ? ? [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
195.
196.? ? ? ? ? // 如果結(jié)果是XML,同樣需要使用6個(gè)代理方法解析,或者使用第三方庫(kù)
197.? ? ? ? ? // 第三方庫(kù)第三方框架,效率低,內(nèi)存泄漏
198.? ? ? ? ? NSLog(@"%@", responseObject);
199.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
200.? ? ? ? ? NSLog(@"%@", error);
201.? ? ? }];
202.? }
203.
204.? #pragma mark - JSON
205.? - (void)JSONData
206.? {
207.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
208.
209.? ? ? // 原本需要拼接get訪問(wèn)URL ? & =
210.? ? ? NSDictionary *dict = @{@"format": @"json"};
211.
212.? ? ? // 網(wǎng)絡(luò)訪問(wèn)是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
213.? ? ? [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
214.? ? ? ? ? NSLog(@"%@", responseObject);
215.? ? ? ? ? // 提問(wèn):NSURLConnection異步方法回調(diào),是在子線程
216.? ? ? ? ? // 得到回調(diào)之后,通常更新UI,是在主線程
217.? ? ? ? ? NSLog(@"%@", [NSThread currentThread]);
218.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
219.? ? ? ? ? NSLog(@"%@", error);
220.? ? ? }];
221.? }
222.
223.? #pragma mark - POST登錄
224.? - (void)postLogin
225.? {
226.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
227.
228.? ? ? // 原本需要拼接get訪問(wèn)URL ? & =
229.? ? ? NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};
230.
231.? ? ? // 網(wǎng)絡(luò)訪問(wèn)是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
232.? ? ? [manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
233.? ? ? ? ? NSLog(@"%@", responseObject);
234.? ? ? ? ? // 提問(wèn):NSURLConnection異步方法回調(diào),是在子線程
235.? ? ? ? ? // 得到回調(diào)之后,通常更新UI,是在主線程
236.? ? ? ? ? NSLog(@"%@", [NSThread currentThread]);
237.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
238.? ? ? ? ? NSLog(@"%@", error);
239.? ? ? }];
240.? }
241.
242.? #pragma mark - GET登錄
243.? - (void)getLogin
244.? {
245.? ? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
246.
247.? ? ? // 原本需要拼接get訪問(wèn)URL ? & =
248.? ? ? NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};
249.
250.? ? ? // 網(wǎng)絡(luò)訪問(wèn)是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
251.? ? ? [manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
252.? ? ? ? ? NSLog(@"%@", responseObject);
253.? ? ? ? ? // 提問(wèn):NSURLConnection異步方法回調(diào),是在子線程
254.? ? ? ? ? // 得到回調(diào)之后,通常更新UI,是在主線程
255.? ? ? ? ? NSLog(@"%@", [NSThread currentThread]);
256.? ? ? } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
257.? ? ? ? ? NSLog(@"%@", error);
258.? ? ? }];
259.? }
260.```
@end