Network requests in IOS
For network requests that use NSURLConnection, it is best to define a class method. In the main thread, you can directly call a class method to obtain the requested network data. // construct a class method-request network + (void) requestData :( NSString *) urlStr httpMethod :( NSString *) method params :( NSMutableDictionary *) params comletionHandle :( void (^) (id result) block {// 1. construct URL urlStr = [BASE_URL stringByAppendingString: urlStr]; NSURL * url = [NSURL URLWithString: urlStr]; // 2. request construct NSMutableURLRequest * request = [NSMutableURLRequest requestWithU RL: url]; request. timeoutInterval = 60; request. HTTPMethod = method; // determine the request method if ([method isinclutostring: @ "GET"]) {// concatenate NSMutableString * paramsStr = [[NSMutableString alloc] initWithString: @"? "]; // Splicing style // splicing URL ---" https://api.weibo.com/2/statuses/home_timeline.json? Access_token = 2.00SllYeF568jxC1082c39bc40 _ Vqyg & username = aaa & pass = bbb // The parameter dictionary for (int I = 0; I <params. count; I ++) {NSString * key = params. allKeys [I]; NSString * value = params [key]; // Start splicing = [paramsStr appendFormat: @ "% = % @", key, value]; // splice & Symbol // The last one is no longer concatenated with & Symbol if (I <params. count-1) {[paramsStr appendFormat: @ "&"] ;}// obtain the spliced URL (splice the main URL with the spliced URL to obtain the complete URL) request. URL = [NSURL URLWithString: [urlStr stringByAppendingString: paramsStr];} else if ([method isinclutostring: @ "POST"]) {// Add the parameter to the Request body. NSMutableString * paramsStr = [[NSMutableString alloc] initWithString: @ ""]; for (int I = 0; I <params. count; I ++) {NSString * key = params. allKeys [I]; NSString * value = params [key]; // Start splicing [paramsStr appendFormat: @ "% @=%@", key, value]; if (I <params. count-1) {[paramsStr appendFormat: @ "&"] ;}/// add to the Request body // convert the string to data NSData * data = [paramsStr dataUsingEncoding: NSUTF8StringEncoding]; request. HTTPBody = data;} // 3. start request network NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [NSURLConnection failed: request queue: queue completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if (connectionError) {NSLog (@ "error ---- % @", connectionError); return;} // data retrieved successfully // start parsing data id result = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil]; // The returned data is dispatch_async (dispatch_get_main_queue (), ^ {block (result) ;});}];}