Third-party iOS learning-AFNetworking1.3.0, iosafnetworking

Source: Internet
Author: User

Third-party iOS learning-AFNetworking1.3.0, iosafnetworking

After CocoaPods is installed, the third party AFNetworking can be integrated into the project according to the instructions for CocoaPods. For details, refer to the installation and use of third-party CocoaPods (general method) in the previous blog iOS study 46)

About AFNetworking
  • AFNetworking is a lightweight network request API library that uses many open-source libraries in iOS development.

  • Applicable to iOS and Mac OS X. It is built on NSURLSession, NSOperation, and other familiar Foundation technologies. The core code is AFHTTPSessionManager.

  • It has a good architecture, rich APIs, and modular construction methods, making it easy to use.

  • Official link http://cocoadocs.org/docsets/AFNetworking/1.3.0/

AFHTTPSessionManager

AFHTTPSessionManager is the management class of core network requests. It is used to manage GET and POST requests.

AFHTTPSessionManager Object Description and lazy loading code:

# Import "ViewController. h "// network request header file # import <AFNetworking/AFNetworking. h> @ interface ViewController () // session object used for network requests @ property (nonatomic, strong) AFHTTPSessionManager * session; @ end @ implementation ViewController // lazy loading-(AFHTTPSessionManager *) session {if (! _ Session) {_ session = [AFHTTPSessionManager]; // sets the type of data _ session supported when the request interface is returned. responseSerializer. acceptableContentTypes = [NSSet setWithObjects: @ "application/json", @ "text/json", @ "text/javascript", @ "application/x-json ", @ "text/html", nil];} return _ session;} @ end
AFNetworking for Network Monitoring

When conducting network monitoring, you should first determine whether the network monitoring is enabled. If the network monitoring is not enabled, you must first enable the monitoring.

-(Void) startMonitoring; // enable Network Monitoring-(void) stopMonitoring; // disable network monitoring

Next, determine the current network status. AFNetworking has several different network statuses.

// Several different network statuses: typedef NS_ENUM (NSInteger, AFNetworkReachabilityStatus) {AFNetworkReachabilityStatusUnknown =-1, // The current network is unknown, and the phone does not signal AFNetworkReachabilityStatusNotReachable = 0, // The current network is not connected, the mobile phone has no active traffic or WiFi AFNetworkReachabilityStatusReachableViaWWAN = 1, // mobile phone traffic network AFNetworkReachabilityStatusReachableViaWiFi = 2, // WiFi status };

Instance code:

# Response method of The pragma mark-network monitoring button-(IBAction) networkMonitoringAction :( UIButton *) sender {if (! IsOPen) {// Method for enabling network monitoring [[AFNetworkReachabilityManager sharedManager] startMonitoring]; isOPen = YES;} else {// disable network monitoring [[AFNetworkReachabilityManager sharedManager] stopMonitoring]; isOPen = NO;} // determine whether the current Wi-Fi status is 3G and the network is unavailable [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock: ^ (AFNetworkReachabilityStatus status) {switch (status) {case AFNetworkReachabilityStatusUnknown: NSLog (@ "the current network is unknown and the mobile phone has no signal"); break; case AFNetworkReachabilityStatusNotReachable: NSLog (@ "the current network is not connected, no active traffic or WiFi "); break; case when: NSLog (@" mobile phone traffic network "); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog (@" WiFi status "); break; default: break;}];}
AFNetworking GET request

AFNetworking1.3.0 does not require many classes to participate in the same GET request. Here, a AFHTTPSessionManager method is required.

Method:

-(NSURLSessionDataTask *) GET :( NSString *) URL of the URLString // get Request parameters :( id) parameters // The spliced parameter progress :( void (^) (NSProgress * _ Nonnull )) downloadProgress // download progress success :( void (^) (NSURLSessionDataTask * _ Nonnull, id _ Nullable) success // successful request failure :( void (^) (NSURLSessionDataTask * _ Nullable, NSError * _ Nonnull) failure // request failed

Instance code:

# Response method of The pragma mark-GET request-(IBAction) getRequestAction :( id) sender {[self. session GET: @ "http://api.yhouse.com/m/city/dynmiclist" // get request URL parameters: nil // spliced parameter progress: ^ (NSProgress * _ Nonnull downloadProgress) {// download progress NSLog (@ "download progress");} success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nullable responseObject) {// successful request NSLog (@ "successful request"); // process data... NSDictionary * reusltDict = responseObject [@ "data"]; NSArray * resultArray = reusltDict [@ "allCity"]; for (NSDictionary * dict in resultArray) {NSLog (@ "name = % @", dict [@ "name"]) ;}} failure: ^ (NSURLSessionDataTask * _ Nullable task, NSError * _ Nonnull error) {// request failed NSLog (@ "request failed") ;}];}
POST request of AFNetworking

The same is true for POST requests like GET requests. However, POST requests need to splice parameters. Generally, a parameter is a dictionary.

Method:

-(NSURLSessionDataTask *) POST :( NSString *) URL of the URLString // post Request parameters :( id) parameters // The spliced parameter body progress :( void (^) (NSProgress * _ Nonnull) uploadProgress // upload progress success :( void (^) (NSURLSessionDataTask * _ Nonnull, id _ Nullable )) success // request successful failure :( void (^) (NSURLSessionDataTask * _ Nullable, NSError * _ Nonnull) failure // request failed

Instance code:

# Pragma mark-POST request response method-(IBAction) postRequestAction :( id) sender {NSString * urlStr = @ "http://m.taskwedo.com/API/wedo1/wedo.php"; NSMutableDictionary * dict =@{ @ "do ": @ "pri_memberlist", @ "member_id": @ "zpHr2dsRvQQxYJxo2", @ "workspace_id": @ "ILfYpE4Dhs2gWcuQx "}. mutableCopy; [self. session POST: urlStr // post request URL parameters: dict // The spliced parameter body progress: ^ (NSProgress * _ Nonnull uploadProgress) {// upload progress NSLog (@ "Upload progress");} success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nullable responseObject) {// NSLog (@ "successful request"); NSDictionary * reusltDict = responseObject [@ "res"]; NSArray * keyArray = reusltDict. allKeys; for (NSString * key in keyArray) {NSArray * resultArray = reusltDict [key]; for (NSDictionary * dict in resultArray) {NSLog (@ "username = % @", dict [@ "username"]) ;}} failure: ^ (NSURLSessionDataTask * _ Nullable task, NSError * _ Nonnull error) {// request failed NSLog (@ "request failed") ;}];}

Note: If the URL string or body contains special or Chinese characters, AFNETWorking does not perform UTF8 transcoding. You need:

url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];commonContent = [commonContent stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

Code example:

# Response method of pragma mark-POST request 2-(IBAction) postRequest2Action :( id) sender {NSString * urlStr = @ "http://m.taskwedo.com/API/wedo1/wedo.php "; NSString * commonContent = @ "class module plan is used in Part 3. When you have accumulated a certain number of questions and answers, it is easy for you to quickly find your questions, therefore, this is not added to the question section. commonContent = [commonContent stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]; // use NSMutableDictionary * dict = [NSMutableDictionary dictionary] When the body or URL contains Chinese characters; [dict setValue: @ "" forKey: @ "address"]; [dict setValue: commonContent forKey: @ "comment"]; [dict setValue: @ "add_comment" forKey: @ "do"]; [dict setValue: @ "task" forKey: @ "kind"]; [dict setValue: @ "zpHr2dsRvQQxYJxo2" forKey: @ "member_id"]; [dict setValue: @ "forKey: @" other "]; [dict setValue: @ "55a47e79ec25e3641" forKey: @ "task_id"]; [self. session POST: urlStr parameters: dict progress: ^ (NSProgress * _ Nonnull uploadProgress) {NSLog (@ "uploaded successfully");} success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nullable responseObject) {NSLog (@ "request succeeded: % @", 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.