IOS development-AFNetworking network request

Source: Internet
Author: User

IOS development-AFNetworking network request
AFNetworking

What is AFN?
The full name is AFNetworking, which is an encapsulation of NSURLConnection and NSURLSession.
Although the operation efficiency is not as high as the ASI, it is easier to use than the ASI.
It is widely used in iOS development.

 

AFHTTPRequestOperationManager

Is one of the most important objects in AFN.
Encapsulated common HTTP Request Processing
GETPOST request
Parse Server Response Data

Create

AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
GETPOST request
// GET request-(AFHTTPRequestOperation *) GET :( NSString *) URLString parameters :( id) parameters success :( void (^) (AFHTTPRequestOperation * operation, id responseObject )) success failure :( void (^) (AFHTTPRequestOperation * operation, NSError * error) failure // POST request-(AFHTTPRequestOperation *) POST :( NSString *) URLString parameters :( id) parameters success :( void (^) (AFHTTPRequestOperation * operation, id responseObject) success failure :( void (^) (AFHTTPRequestOperation * operation, NSError * error) failure
File Upload
- (AFHTTPRequestOperation *)POST:(NSString *)URLString                      parameters:(id)parameters       constructingBodyWithBlock:(void (^)(id  formData))block                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
Monitoring networking status
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];[manager startMonitoring];[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    NSLog(@%d, status);}];

Tip: to monitor the network connection status, you must first call the startMonitoring method of the Singleton.

1. AFHTTPRequestOperationManager
* Encapsulation of NSURLConnection

2. AFHTTPSessionManager
* Encapsulation of NSURLSession

Parsing the data returned by the server
1. AFN can automatically parse the data returned by the server * by default, the data returned by the server is parsed as JSON. set the resolution method for the data returned by the server. 1> parse the data as JSON (default practice) * mgr. responseSerializer = [AFJSONResponseSerializer serializer]; * The responseObject type is NSDictionary or NSArray2> parse * mgr as XML. responseSerializer = [AFXMLParserResponseSerializer serializer]; * The responseObject type is NSXMLParser3> directly returning data *. This means that AFN should not parse the data returned by the server and keep the original data. * mgr. responseSerializer = [AFHTTPResponseSerializer serializer]; 3. note * The data returned by the server must be consistent with responseSerializer. 1> the server returns JSON data * AFJSONResponseSerializer * response> the server returns XML data * response * AFHTTPResponseSerializer3> the server returns other data * AFHTTPResponseSerializer
AFNetworking network request instance
# Import AFNetworking. h @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib .} -(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {[self postJSON];}-(void) getSession {// AFHTTPSessionManager encapsulation of NSURLSession AFHTTPSessionManager * mgr = [AFHTTPSessionManager manager]; [mgr GET: @ parameters: nil success: ^ (NSURLSessionDataTask * task, id responseObject) {} failure: ^ (NSURLSessionDataTask * task, NSError * error) {}];}/*** use AFN to send a POST request, and the server returns JSON data */-(void) postJSON {// AFHTTPRequestOperationManager encapsulate NSURLConnection // 1. create a request operation manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; // 2. request Parameter NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ hahaha; params [@ pwd] = @ 123; // 3. send a GET request NSString * url =@http: // localhost: 8080/MJServer/login; [mgr POST: url parameters: params success: ^ (AFHTTPRequestOperation * operation, id responseObject) {// call this block NSLog when the request is successful (@ request succeeded --- % @, responseObject);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// call this block NSLog when the request fails (@ request failed);}] ;}/ *** send a GET request using AFN, and the server returns JSON data, let AFN directly return data */-(void) getData {// 1. create a request operation manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; // statement: Do not parse the data returned by the server and directly return the data. // if the file is downloaded, the // responseObject type must be NSData mgr. responseSerializer = [AFHTTPResponseSerializer serializer]; // 2. request Parameter NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ hahaha; params [@ pwd] = @ 123; // 3. send a GET request NSString * url =@http: // localhost: 8080/MJServer/login; [mgr GET: url parameters: params success: ^ (AFHTTPRequestOperation * operation, id responseObject) {// call this block NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingMutableLeaves error: nil]; NSLog (@ % @, dict);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// call this block NSLog (@ request failed) when the request fails;}];} /*** use AFN to send a GET request. XML data returned by the server */-(void) getXML {// 1. create a request operation manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; // Declaration: if the server returns XML data, // responseObject is NSXMLParser mgr. responseSerializer = [AFXMLParserResponseSerializer serializer]; // 2. request Parameter NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ hahaha; params [@ pwd] = @ 123; params [@ type] = @ XML; // 3. send a GET request NSString * url =@http: // localhost: 8080/MJServer/login; [mgr GET: url parameters: params success: ^ (AFHTTPRequestOperation * operation, id responseObject) {// call this block NSLog when the request is successful (@ successful request -- % @, responseObject); // responseObject. delegate = self; // [responseObject parse];} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// when the request fails, call this block NSLog (@ request failed);}] ;}/ *** to send a GET request using AFN, JSON data returned by the server */-(void) getJSON {// 1. create a request operation manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager]; // declare that the server returns JSON data // mgr. responseSerializer = [AFJSONResponseSerializer serializer]; // The responseObject type is NSDictionary or NSArray // 2. request Parameter NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ hahaha; params [@ pwd] = @ 123; // 3. send a GET request NSString * url = @ http: // localhost: 8080/Server/login; [mgr GET: url parameters: params success: ^ (AFHTTPRequestOperation * operation, id responseObject) {// call this block NSLog when the request is successful (@ request succeeded --- % @, responseObject);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {// call this block NSLog when the request fails (@ request failed) ;}] ;}@ end
AFNetworking File Upload instance
# Import AFNetworking. h @ interface ViewController ()
  
   
@ Property (weak, nonatomic) IBOutlet UIImageView * imageView;-(IBAction) upload; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib .} -(void) Authorization :( NSSet *) touches withEvent :( UIEvent *) event {UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle: @ Please select the image delegate: self cancelButtonTitle: @ cancel dest RuctiveButtonTitle: nil otherButtonTitles: @ photo, @ album, nil]; [sheet showInView: self. view. window] ;}# pragma mark-UIActionSheet-(void) actionSheet :( UIActionSheet *) actionSheet clickedButtonAtIndex :( NSInteger) buttonIndex {UIImagePickerController * ipc = [[UIImagePickerController alloc] init]; // sets the proxy ipc. delegate = self; switch (buttonIndex) {case 0: {// take a photo if (! [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) return; ipc. sourceType = UIImagePickerControllerSourceTypeCamera; break;} case 1: {// album if (! [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) return; ipc. sourceType = UIImagePickerControllerSourceTypePhotoLibrary; break;} default: break;} // display controller [self presentViewController: ipc animated: YES completion: nil];} # pragma mark-UIImagePickerControllerDelegate/*** after selecting the image, call ** @ param info to include the image information */-(void) imagePickerController :( UIImagePickerController *) picker didFinishPickingMediaWithInfo :( NSDictionary *) info {// destroy the Controller [picker dismissViewControllerAnimated: YES completion: nil]; // obtain the image UIImage * image = info [watermark]; // display the image self. imageView. image = image;}-(void) upload1 {// 1. create a manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; // 2. encapsulation parameters (this dictionary can only contain non-file parameters) NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ 123; params [@ age] = @ 20; params [@ pwd] = @ 456; params [@ height] =@ 1.55; // 2. send a request NSString * url = @ http: // localhost: 8080/MJServer/upload; [mgr POST: url parameters: params constructingBodyWithBlock: ^ (id formData) {// this block will be automatically called before sending the request // you need to add the file parameter to formData in this block/** FileURL: the URL path name of the file to be uploaded: the parameter fileName used by the server to receive the file: (tell the server) the name of the uploaded file mimeType: the file type of the uploaded file */NSURL * url = [[NSBundle mainBundle] URLForResource: @ itcast withExtension: @ txt]; [formData appendPartWithFileURL: url name: @ file fileName: @test.txt mimeType: @ text/plain error: nil];/** FileData: the specific data name of the file to be uploaded: The parameter name fileName used by the server to receive the file: (tell the server) the file name Uploaded By mimeType: file Type of the uploaded file * // UIImage * image = [UIImage imageNamed: @ minion_01]; // NSData * fileData = UIImagePNGRepresentation (image); // [formData appendPartWithFileData: fileData name: @ file fileName: @haha.png mimeType: @ image/png];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSLog (@ uploaded successfully);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ upload Failed) ;}] ;}- (IBAction) upload {if (self. imageView. image = nil) return; // 1. create a manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; // 2. encapsulation parameters (this dictionary can only contain non-file parameters) NSMutableDictionary * params = [NSMutableDictionary dictionary]; params [@ username] = @ 123; params [@ age] = @ 20; params [@ pwd] = @ 456; params [@ height] =@ 1.55; // 2. send a request NSString * url = @ http: // 192.168.15.172: 8080/Server/upload; [mgr POST: url parameters: params constructingBodyWithBlock: ^ (id formData) {NSData * fileData = UIImageJPEGRepresentation (self. imageView. image, 1.0); [formData appendPartWithFileData: fileData name: @ file fileName: @haha.jpg mimeType: @ image/jpeg]; // This method is not used to set the file parameters. // [formData appendPartWithFormData: fileData name: @ file];} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSLog (@ uploaded successfully);} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ Upload Failed);}]; // file download, large files, resumable data transfer technology: Generally all HTTP servers support // file upload, large files, and resumable data transfer technology: Generally, HTTP servers do not support resumable data transfer, common technologies use Socket (TCPIP, UDP)} @ end
  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.