Use of the AFNetworking open-source library for IOS development, iosafnetworking
Use of AFNetworking open source library for IOS development1. Introduction
Common methods for processing network requests
(1) NSURLConnection/NSURLSession
(2) ASIHttpRequest is common in earlier projects, because the author does not update
(3) AFNetworking is recommended for use in projects.
(4) Try MKNetworkKit.
2. Configure and use
2.1 Configuration
Library files are dragged into the project, including header files
# Import "AFNetworking. h"
2.2 Use2.2.1.GET request (html, json, xml)-(void) testGetRequest {NSString * urlstring = @ "http://www.baidu.com"; urlstring = @ "http://m.weather.com.cn/data/101010100.html"; urlstring = @ "http://mp.manzuo.com/china/beijing/home_2.xml "; // define AFNetworking management AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; // note: the default data is JSON, the content-type is JSON, And the responseObject is a resolution dictionary and array, no error Code =-1016 // resolution: Set the parser to the HTTP format. The downloaded file is NSData manager. responseSerializer = [AFCompoundResponseSerializer serializer]; [manager GET: urlstring parameters: nil success: ^ (AFHTTPRequestOperation * operation, id responseObject) {// important responseObject parameter, contains the downloaded data // NSLog (@ "o =%@", responseObject); NSString * str = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding]; NSLog (@ "str = % @", str);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ "error = % @", error);}];}TestGetRequest 2.2.2.POST request-(void) testPostRequest {// POST interface: // parameter 1: @ "user": @ "quiet" // parameter 2: @ "password ": @ "123" NSString * urlString = @ "http://quiet.local/testdir/login.php"; AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager]; manager. responseSerializer = [AFCompoundResponseSerializer serializer]; // parameter 1: Input address // parameter 2: Input URL request parameters. Format: Input dictionary [manager POST: urlString parameters: @ {@ "user": @ "quiet", @ "password": @ "123"} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSString * str = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding]; NSLog (@ "str = % @", str);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ "error = % @", error) ;}];}TestPostRequest 2.2.3. upload File (upload image)-(void) testUploadFile {// The NSString * urlString = @ "http://quiet.local/uploadtest/pk.php"; // The parameter name is: image: the parameter value is AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; manager. responseSerializer = [serialize serializer]; [manager POST: urlString parameters: nil constructingBodyWithBlock: ^ (id <AFMultipartFormData> formData) {NSString * path = [[NSBundle mainBundle] pathForResource: @ "daji.jpg" ofType: nil]; [formData appendPartWithFileURL: [NSURL URLWithString: path] name: @ "image" fileName: @ "666.jpg" mimeType: @" image/jpeg "error: nil];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSString * str = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding]; NSLog (@ "str = % @", str);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ "error = % @", error) ;}]; [manager POST: urlString parameters: nil constructingBodyWithBlock: ^ (id <AFMultipartFormData> formData) {// implementation: upload data to the Request body // fileName: uploaded file name // mimeType: You need to search for mime online, copy the corresponding format to NSString * path = [[NSBundle mainBundle] pathForResource: @ "daji.jpg" ofType: nil]; [formData appendPartWithFileURL: [NSURL fileURLWithPath: path] name: @ "image" fileName: @ "666.jpg" mimeType: @" image/jpeg "error: nil];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSString * str = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding]; NSLog (@ "str = % @", str);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ "error = % @", error) ;}];}TestUploadFile 2.2.4. download file-(void) testDownloadFile {NSString * urlString = @ "http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip"; // create a session management object (via default configuration) AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration]; Parameters * task = [manager Details: [NSURLRequest requestWithURL: [NSURL URLWithString: urlString] progress: nil destination: ^ NSURL * (NSURL * targetPath, NSURLResponse * response) {// return the file storage location NSString * path = [NSString stringWithFormat: @ "% @/Documents/all.zip", NSHomeDirectory ()]; NSLog (@ "% @", NSHomeDirectory (); return [NSURL fileURLWithPath: path];} completionHandler: ^ (NSURLResponse * response, NSURL * filePath, NSError * error) {NSLog (@ "download completed") ;}]; // start the task [task resume];}TestDownloadFile 2.2.5. monitoring Network Status-(void) testMonitorNetworkStatus {AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL: [NSURL URLWithString: @ "www.baidu.com"]; [manager. reachabilityManager setReachabilityStatusChangeBlock: ^ (AFNetworkReachabilityStatus status) {NSDictionary * dict =@{@ (unknown): @ "unknown", @ (unknown): @ "inaccessible", @ (unknown): @ "GPRS", @ (AFNetworkReachabilityStatusReachableViaWiFi): @ "Wifi",}; NSLog (@ "status % @", dict [@ (status)]);}]; // enable status monitoring [manager. reachabilityManager startMonitoring];}TestMonitorNetworkStatus 2.2.6. asynchronous image function (replacing SDWebImage)
Import header files
# Import "UIKit + AFNetworking. h"
-(Void) setImageWithURL :( NSURL *) url;
2.2.7. Some special request headers
BAIDU_WISE_UID = wapp_1428213381699_466;
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager];
[Manager. requestSerializer setValue: @ "wapp_1428425381699_466" forHTTPHeaderField: @ "BAIDU_WISE_UID"];