AFNetworking 是 iOS 一個使用很方便的網絡開發框架。今天我們就簡單介紹如何在我們的項目中使用它。
1、從官網下載最新的AFNetworking代碼。
2、將AFNetWorking和UIKit+AFNetworking文件夾導入項目
3、添加類庫 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
4、在使用的地方導入
#import AFNetworking.h
#import UIKit+AFNetworking.h
5、網絡url訪問測試。
NSString *URLTmp = @http://www.coneboy.com;
NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//轉碼成UTF-8 否則可能會出現錯誤
URLTmp = URLTmp1;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@Success: %@, operation.responseString);
NSString *requestTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
//系統自帶JSON解析
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@success:%@,resultDic);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@Failure: %@, error);
//[SVProgressHUD dismissWithError:@提交失敗,請重試];
}];
[operation start];
6、如何獲取一張網絡圖片
NSString *url = @http://www.uimaker.com/uploads/allimg/111101/1_111101085050_3.jpg;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, 150.0f, 200.0f, 200.0f)];
[imageView setImageWithURL:[NSURL URLWithString:url]];
[self.view addSubview:imageView];