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 ");
}];
}
}