A detailed explanation of iOS common network request method

Source: Internet
Author: User
Tags json static class

The advantages of this common network request method are:

This method can be called by both 1.get and post
2. The Uiviewcontroller class can be invoked directly with the self pointer (because this method is written in the Uiviewcontroller category), and the other class simply generates a pointer with [Uiviewcontroller new] to make a network request
3. Only need to pass in three parameters
4. Code logic simple and easy to understand
5. Based on AFNetworking3.1.0

Related code:

Create a class that inherits from Afhttpsessionmanager, named Afappdotnetapiclient

The code is as follows Copy Code

AFAppDotNetAPIClient.h

#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
@interface Afappdotnetapiclient:afhttpsessionmanager

To create a method declaration for a single instance class
+ (instancetype) sharedclient;

@end

Afappdotnetapiclient.m

#import "AFAppDotNetAPIClient.h"

@implementation Afappdotnetapiclient

method implementation for creating a single instance class
+ (Instancetype) sharedclient{
Initializes a static class pointer
Static Afappdotnetapiclient *sharedclient;
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
Sharedclient = [Afappdotnetapiclient new];

Afnetworking Request header information Related settings
Sharedclient.requestserializer = [Afjsonrequestserializer serializer];
[Sharedclient.requestserializer setvalue:@ "Application/json;charset=utf-8" forhttpheaderfield:@ "Content-Type"];

Afnetworking The parameter correlation settings obtained
Sharedclient.responseserializer = [Afjsonresponseserializer serializer];
SharedClient.responseSerializer.acceptableContentTypes = [Nsset setwithobjects:@ "Application/json", @ "Text/json", @ "Text/html", @ "Text/javascript", nil];
SSL-related Settings
Sharedclient.securitypolicy = [Afsecuritypolicy policywithpinningmode:afsslpinningmodenone];
});

return sharedclient;
}
@end

The network request method written in the Uiviewcontroller category:

The code is as follows Copy Code

-(Nsurlsessiondatatask *) Defaultrequestwithurl: (NSString *) URL withparameters: (nsdictionary *) Parameters WithMethod : (NSString *) method Withblock: (void (^) (nsdictionary *dict, Nserror *error)) block
{
Default printing of incoming arguments
#ifdef DEBUG
NSLog (@ "Common method =%@", method);//get or post
NSLog (@ "Common URL =%@", url);/The requested URL
NSLog (@ "Common parameters =%@", parameters);/Incoming arguments
#endif

To determine whether a get or post method is invoked in Afnetworking according to the method string
if ([Method isequaltostring:@ ' Get "]) {//is used in AFNetworking3.1.0, the new progress progress block is added
return [[Afappdotnetapiclient sharedclient] Get:url parameters:parameters progress:^ (nsprogress * _Nonnull DownloadProgress) {

} success:^ (Nsurlsessiondatatask * _nonnull task, id _nullable JSON) {
#ifdef DEBUG
NSLog (@ "common get JSON =%@", JSON);//print acquired JSON
#endif

Nsdictionary *dict = json;//directly back to the dictionary for easy use

if (block) {
Block (dict, nil);
}
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
Returns an empty dictionary and Nserror pointer if an error is requested
if (block) {
Block ([Nsdictionary dictionary], error);//This is a bit of a pit, because, for example, I want to judge whether a request succeeds based on a field, and I have an empty dictionary @{},
According to a key fetch value:[@{} objectforkey:@ "ErrorCode"],
Then determine if the string's Intvalue equals 0:[[@{} objectforkey:@ "ErrorCode"] intvalue] = = 0 is returned 1.
I think the solution is to change from the server side, the return of the field key with Issuccess,value is the string true or false can be resolved,
But this can only know that success or failure can not be based on ErrorCode code for other operations, because ErrorCode can be 0, 1, 2, 3, and so on.
}

Determine if the error is null from the pointer level, and print the error if it is not empty
if (Error) {
NSLog (@ "%@", error);
}
}];
}

Post related code
return [[Afappdotnetapiclient sharedclient]post:url parameters:parameters progress:^ (nsprogress * _Nonnull uploadprogress) {

} success:^ (Nsurlsessiondatatask * _nonnull task, id _nullable JSON) {
#ifdef DEBUG
NSLog (@ "common post json =%@", JSON);//print acquired JSON
#endif

Nsdictionary *dict = json;//directly back to the dictionary for easy use

if (block) {
Block (dict, nil);
}
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
Returns an empty dictionary and Nserror pointer if an error is requested
if (block) {
Block ([Nsdictionary dictionary], error);
}

Determine if the error is null from the pointer level, and print the error if it is not empty
if (Error) {
NSLog (@ "%@", error);
}
}];

The return value is temporarily unavailable and does not need to create a variable to receive; The self pointer passed in is not used so this method is highly portable.
}

-(void) Request
{
Test Network Request method
1. The use of the Web site I have previously caught, the API is written in PHP, the server is very stable, I often used for testing, but also for testing
2.get parameter start and end pass unsigned integer
Nsdictionary *parameters = @{
@ "type": @ "List",
@ "City": @ "2",
@ "lid": @ "31",
@ "SortBy": @ "1",
@ "Start": @ "0",
@ "End": @ "3"
};

[Self defaultrequestwithurl:@ "/api.php" withparameters:parameters withmethod:@ "Get" withblock:^ (NSDictionary *dict, Nserror *error) {

}];
}

Additional upload method for multiple maps, also based on AFNetworking3.1.0, and the above method is similar so do not add detailed comments:

The code is as follows Copy Code

-(void) Startmultipartuploadtaskwithurl: (NSString *) URL
Imagesarray: (Nsarray *) images
Parameterofimages: (NSString *) parameter
Parametersdict: (nsdictionary *) parameters
Compressionratio: (float) ratio
Succeedblock: (void (^) (nsdictionary *dict)) Succeedblock
Failedblock: (void (^) (nserror *error)) failedblock{
if (Images.count = = 0) {
NSLog (@ "Picture array count is zero");
Return
}
for (int i = 0; i < Images.count; i++) {
if (![ Images[i] Iskindofclass:[uiimage class]) {
NSLog (the%d element in the @ "images is not a UIImage object", i+1);
}
}

Afhttpsessionmanager *manager = [Afhttpsessionmanager manager];

[Manager Post:url Parameters:parameters constructingbodywithblock:^ (id<afmultipartformdata> _Nonnull formData ) {
int i = 0;
Generate picture names based on current system time
NSDate *date = [NSDate Date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[Formatter setdateformat:@ "yyyy year mm month DD Day"];
NSString *datestring = [Formatter stringfromdate:date];

For (UIImage *image in images) {
NSString *filename = [NSString stringwithformat:@ "%@%d.png", datestring,i];
NSData *imagedata;
if (ratio > 0.0f && ratio < 1.0f) {
ImageData = uiimagejpegrepresentation (image, ratio);
}else{
ImageData = uiimagejpegrepresentation (image, 1.0f);
}
[FormData appendpartwithfiledata:imagedata name:parameter filename:filename mimetype:@ "Image/jpg/png/jpeg"];
}
} progress:^ (Nsprogress * _nonnull uploadprogress) {

} success:^ (Nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
Nsdictionary *dict = [Nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingmutablecontainers Error:nil];

NSLog (@ "common post json =%@", dict);

Succeedblock (DICT);
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
if (Error) {
Failedblock (Error);

NSLog (@ "%@", error);
}
}];
}

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.