Network encapsulation Based on AFNetworking3.0, afnetworking3.0

Source: Internet
Author: User

Network encapsulation Based on AFNetworking3.0, afnetworking3.0

1. Create a header file named HTTPMethod.

2. Import the AFNetworking header file (download the latest version on github ):

# Import "AFNetworking. h"

3. Declare the class method in the. h file:

// Parameter explanation: (1) urlString is the URL you want to request (2) bodyDic is the parameter for POST requests (3) dataBlock is the block for data callback after successful data requests

+ (Void) getDataByString :( NSString *) urlString BodyDic :( NSDictionary *) bodyDic WithDataBlock :( void (^) (id data) dataBlock;

4. Implementation of the method:

+ (Void) getDataByString :( NSString *) urlString BodyDic :( NSDictionary *) bodyDic WithDataBlock :( void (^) (id) dataBlock

{

// (1). Transcoding of strings

UrlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet characterSetWithCharactersInString: urlString];

// (2). Create a manager object (session)

AFHTTPSessionManager * manager = [AFHTTPSessionManager];

// (3). Set the allowed request category

Manager. responseSerializer. acceptableContentTypes = [NSSet setWithObjects: @ "text/plain", @ "text/json", @ "application/json", @ "text/javascript ", @ "text/html", @ "application/javascript", @ "text/js", nil];

// (4). Start the request

If (! BodyDic ){

// If bodyDic is empty, execute the get request.

[Manager GET: urlString parameters: nil success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nonnull responseObject ){

DataBlock (responseObject );

} Failure: ^ (NSURLSessionDataTask * _ Nullable task, NSError * _ Nonnull error ){

NSLog (@ "request failed ");

}];

}

Else

{

[Manager POST: urlString parameters: bodyDic success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nonnull responseObject ){

DataBlock (responseObject );

} Failure: ^ (NSURLSessionDataTask * _ Nullable task, NSError * _ Nonnull error ){

NSLog (@ "request failed ");

}];

}

}

 

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.