[IOS multithreading & Network, ios Multithreading
A. Basic AFN knowledge1. Concept
- AFNetworking
- Encapsulation of NSURLConnection
- The running efficiency is not as high as the ASI (because the ASI is based on CFNetwork), but it is easy to use.
- AFN supports ARC
B. Basic Request usage1. basic use (1) header file AFNetworking. h (2) manager class: AFHTTPRequestOperationManager (3) Send GET requests using the "GET" method, and send POST requests using the "POST" method (4) Send parameters using the dictionary (5) block Processing request succeeded/failed
1/** send GET/POST Request */2-(void) sendNormalRequest {3 // 1. CREATE request manager 4 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; 5 6 // 2. set parameter 7 NSMutableDictionary * param = [NSMutableDictionary dictionary]; 8 param [@ "user"] = @ "tom"; 9 param [@ "password"] = @ "123 "; 10 11 // 3. send request 12 // 3.1 GET request 13 // [manager GET: @ "http: // 192.168.0.21: 8080/MyTestServer/login" parameters: param success: ^ (AFHTTPRequestOperation * operation, id responseObject) {14 // NSLog (@ "successful request"); 15 // NSLog (@ "% @", responseObject ); 16 //} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {17 // NSLog (@ "request failed"); 18 // NSLog (@ "% @", error); 19 //}]; 20 21 // 3.2 POST request 22 [manager POST: @ "http: // 192.168.0.21: 8080/MyTestServer/login" parameters: param success: ^ (AFHTTPRequestOperation * operation, id responseObject) {23 NSLog (@ "request succeeded"); 24 NSLog (@ "% @", responseObject); 25} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {26 NSLog (@ "request failed"); 27 NSLog (@ "% @", error); 28}]; 29}
2. To facilitate viewing of the Chinese data returned by the server, add a category to the array and dictionary to support Chinese
1 # import <Foundation/Foundation. h> 2 3 @ implementation NSDictionary (Log) 4 5/** local display */6-(NSString *) descriptionWithLocale :( id) locale {7 NSMutableString * str = [NSMutableString string]; 8 9 [str appendString: @ "{\ n"]; 10 11 // traverse dictionary 12 [self enumerateKeysAndObjectsUsingBlock: ^ (id key, id obj, BOOL * stop) {13 [str appendFormat: @ "\ t % =%@, \ n", key, obj]; 14}]; 15 16 [str appendString: @ "}"]; 17 18 // retrieve the last "," 19 nsange range = [str rangeOfString: @ "," options: NSBackwardsSearch]; 20 [str deleteCharactersInRange: range]; 21 22 return str; 23} 24 25 @ end26 27 @ implementation NSArray (Log) 28 29-(NSString *) descriptionWithLocale :( id) locale {30 NSMutableString * str = [NSMutableString string]; 31 32 [str appendString: @ "[\ n"]; 33 34 // traverse all elements of the array 35 [self enumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop) {36 [str appendFormat: @ "% @, \ n", obj]; 37}]; 38 39 [str appendString: @ "]"]; 40 41 return str; 42} 43 44 @ end
3. parse the returned json data
- AFHTTPRequestOperationManager automatically identifies and parses the returned data by setting the serializer.
- Json Parsing is used by default. You do not need to set the serializer.
- Json is automatically converted into a dictionary or array output.
1/** return json data */2-(void) getJson {3 // 1. CREATE request manager 4 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; 5 6 // set serializer 7 // [manager setResponseSerializer: [AFJSONResponseSerializer serializer]; // The default value is 8 9 // 2. set the parameter 10 NSMutableDictionary * param = [NSMutableDictionary dictionary]; 11 param [@ "type"] = @ "json"; 12 13 // 3. send request 14 [manager GET: @ "http: // 192.168.0.21: 8080/MyTestServer/video" parameters: param success: ^ (AFHTTPRequestOperation * operation, id responseObject) {15 NSLog (@ "request succeeded"); 16 NSLog (@ "returned data type: % @", [responseObject class]); 17 NSLog (@ "% @", responseObject); 18} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {19 NSLog (@ "request failed"); 20 NSLog (@ "% @", error ); 21}]; 22}
Output:
03:34:14. 817 AFNBasicDemo [1889: 192783]
Request successful
03:34:14. 817 AFNBasicDemo [1889: 192783]
The returned data type is
:__ NSCFDictionary
03:34:14. 818 AFNBasicDemo [1889: 192783] {
Videos = [
{
Name =
Dragon trainer
1,
Video = videos/1. MP4,
Length = 16
Seconds
,
Image = images/[20150124-180852-0]. PNG
},
...4. the xml data returned for parsing is set to use the xml serializer, or the xml data can be automatically converted to a dictionary or array. If the xml serializer is not set, the returned data will fail to be processed.
1/** return xml data */2-(void) getXml {3 // 1. create a request manager 4 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; 5 6 // set the serializer 7 [manager setResponseSerializer: [AFXMLParserResponseSerializer serializer]; 8 9 // 2. set the parameter 10 NSMutableDictionary * param = [NSMutableDictionary dictionary]; 11 param [@ "type"] = @ "xml"; 12 13 14 // 3. send 15 _ weak typeof (self) vc = self; 16 [manager GET: @ "http: // 192.168.0.21: 8080/MyTestServer/video" parameters: param success: ^ (AFHTTPRequestOperation * operation, id responseObject) {17 NSLog (@ "request succeeded"); 18 NSLog (@ "returned data type: % @", [responseObject class]); 19 20 NSXMLParser * parser = (NSXMLParser *) responseObject; 21 parser. delegate = vc; 22 [parser parse]; 23} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {24 NSLog (@ "request failed "); 25 NSLog (@ "% @", error); 26}]; 27}
C. File Download/upload1. File Download
- It is also a simple request
- However, there is no listening function like ASI.
1-(void) downloadFile {2 // 1. CREATE request manager 3 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; 4 5 // set serializer 6 [manager setResponseSerializer: [AFHTTPResponseSerializer serializer]; // use binary data for serialization 7 8 // 3. send request 9 [manager GET: @ "http: // 192.168.0.21: 8080/MyTestServer/images/images.zip" parameters: nil success: ^ (AFHTTPRequestOperation * operation, id responseObject) {10 11 NSLog (@ "request succeeded"); 12 NSLog (@ "returned data type: % @", [responseObject class]); 13 14 NSString * cachePath = [Export (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 15 NSString * filePath = [cachePath stringByAppendingPathComponent: @ "download.zip"]; 16 NSData * data = (NSData *) responseObject; 17 [data writeToFile: filePath atomically: YES]; 18 19} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {20 NSLog (@ "request failed"); 21 NSLog (@ "% @", error); 22}]; 23}
2. File Upload
- POST request with formData
- To distinguish between common parameters and file parameters, it is impossible to upload file data in common parameters.
- Files are assigned values in the block parameter.
(1) converting a file into binary data (2) merging file Parameters
1/** Upload File */2-(void) uploadFile {3 // 1. CREATE request manager 4 AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager]; 5 6 // 2. set parameter 7 NSMutableDictionary * param = [NSMutableDictionary dictionary]; 8 param [@ "user"] = @ "uploader"; 9 10 // 3. set 11 NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "M2.jpg" ofType: nil]; 12 NSData * fileData = [NSData dataWithContentsOfFile: filePath]; 13 14 // 4. upload File 15__ weak typeof (fileData) uploadData = fileData; 16 17 [manager POST: @ "http: // 192.168.0.21: 8080/MyTestServer/upload" parameters: param constructingBodyWithBlock: ^ (id <AFMultipartFormData> formData) {18 19 // concatenate file data 20 [formData appendPartWithFileData: uploadData name: @ "uploadedFile" fileName: @ "my_pic.jpg" mimeType: @ "image/jpg"]; 21 22} success: ^ (AFHTTPRequestOperation * operation, id responseObject) {23 NSLog (@ "uploaded successfully ---- % @", responseObject ); 24} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {25 NSLog (@ "Upload Failed ---- % @", error); 26}]; 27}
D. Network Status MonitoringAFNetworkReachabilityManager (1) create a network monitoring manager (2) Set monitoring network status changes (3) enable monitoring (4) you can also take the initiative to obtain the network status
1-(IBAction) monitorNetwork :( UIButton *) sender {2 // 1. create a network status monitoring manager 3 AFNetworkReachabilityManager * manager = [AFNetworkReachabilityManager sharedManager]; 4 5 // 2. network status change event (passive detection) 6 [manager setReachabilityStatusChangeBlock: ^ (AFNetworkReachabilityStatus status) {7 switch (status) {8 case AFNetworkReachabilityStatusUnknown: 9 NSLog (@ "convert to Unknown network"); 10 break; 11 case when: 12 NSLog (@ "convert to mobile network"); 13 break; 14 case AFNetworkReachabilityStatusReachableViaWiFi: 15 NSLog (@ "converted to WIFI network"); 16 break; 17 case AFNetworkReachabilityStatusNotReachable: 18 NSLog (@ "converted to no network"); 19 break; 20 21 default: 22 break; 23} 24}]; 25 26 // enable monitoring 27 [manager startMonitoring]; 28 29 // actively detect 30 if ([manager isReachable]) {31 NSLog (@ ""); 32} else if ([manager isReachableViaWiFi]) {33 NSLog (@ ""); 34} else if ([manager isReachableViaWWAN]) {35 NSLog (@ "Internet access via mobile phone now"); 36} else {37 NSLog (@ "No network now "); 38} 39}