#import "MainViewController.h"#import "Video.h"#define kBaseURL @"http://192.168.3.252/~apple"@interface MainViewController ()
@property (strong, nonatomic) NSArray *dataList;@property (weak, nonatomic) UITableView *tableView;@end@implementation MainViewController
/*
In network application development,
1. Data is loaded synchronously to ensure that you can read
2. images, audios, and videos are asynchronously loaded. You can gradually see multimedia information without blocking the use of the main thread.
*/
# Pragma mark instantiation view-(void) loadView {self. view = [[UIView alloc] initWithFrame: [UIScreen mainScreen]. applicationFrame]; // 1 tableview CGRect frame = self. view. bounds; UITableView * tableView = [[UITableView alloc] initWithFrame: CGRectMake (0, 0, frame. size. width, frame. size. height-44) style: UITableViewStylePlain]; // 1) data source [tableView setDataSource: self]; // 2) proxy [tableView setDelegate: self]; //) set table height [TableView setRowHeight: 80]; [self. view addSubview: tableView]; self. tableView = tableView; // toolBar UIToolbar * toolBar = [[UIToolbar alloc] initWithFrame: CGRectMake (0, tableView. bounds. size. height, 320, 44)]; [self. view addSubview: toolBar]; // Add the toolbar button UIBarButtonItem * item1 = [[UIBarButtonItem alloc] initWithTitle: @ "load json" style: UIBarButtonItemStyleDone target: self action: @ selector (loadJson)]; UIBarButtonItem * item2 = [[UIBarButtonItem alloc] initWithTitle: @ "load xml" style: UIBarButtonItemStyleDone target: self action: @ selector (loadXML)]; UIBarButtonItem * item3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: Custom target: nil action: nil]; [toolBar setItems: @ [item3, item1, item3, item2, item3]; # The pragma mark-uitableview data source method is required for the two methods under uitableview. -(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. dataList. count;} // this method is called once for each filled row. All rows on the interface are filled ., -(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {// query reusable Cells Using the recharged identifier static NSString * ID = @ "MyCell "; UITableViewCell * cell = [tableView metadata: ID]; if (cell = nil) {cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: ID];} // set the Video * v = self. dataList [indexPath. row]; cell. TextLabel. text = v. name; cell. detailTextLabel. text = v. teacher; // attach an image // 1) attach a network image synchronously. the synchronous method assumes that these commands cannot be executed until they are completed. // Note: Do not use the synchronous method to load images when developing network applications. Otherwise, the user experience will be seriously affected. // NSString * imagePath = [NSString stringWithFormat: @ "% @", kBaseURL, v. imageURL]; // NSURL * imageUrl = [NSURL URLWithString: imagePath]; // NSData * imageData = [NSData dataWithContentsOfURL: imageUrl]; // UIImage * image = [UIImage imageWithData: imageData]; // 2) asynchronously load the network image // the network connection itself has an asynchronous command sendAsync // [cell. imageView setImage: image]; // if the cached image does not exist if (v. cacheImage = Nil) {// use the default image placeholder to ensure that there is an image and that there is a place. UIImage * image = [UIImage imageNamed: @ "user_default.png"]; [cell. imageView setImage: image]; // use the default image placeholder // enable the asynchronous connection to load the image. After loading, refresh the corresponding table to [self loadImageAsyncWithIndexPath: indexPath];} else {[cell. imageView setImage: v. cacheImage];} // [self loadImageAsyncWithUrl: imageUrl imageView: cell. imageView]; return cell ;}# pragma mark asynchronously loads network images // because uitableview is reusable, to avoid data conflicts caused by quick and frequent table refresh, you cannot directly pass uiimageview into an Asynchronous Method // The correct solution is to pass the indexpath of the table row into the asynchronous method. After the image is loaded, the specified row is refreshed directly. -(Void) loadImageAsyncWithIndexPath :( NSIndexPath *) indexPath {Video * v = self. dataList [indexPath. row]; // retrieve the NSString * imagePath = [NSString stringWithFormat: @ "% @", kBaseURL, v. imageURL]; NSURL * imageUrl = [NSURL URLWithString: imagePath]; // NSLog (@ "% @", url, imageView ); // 1 request NSURLRequest * request = [NSURLRequest requestWithURL: imageUrl]; // 2 connection sendasync asynchronous request [NSURLConnecti On sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * error) {// UIImage * image = [UIImage imageWithData: data]; // [imageView setImage: image]; // Save the network data to the cached image. V. cacheImage = [UIImage imageWithData: data]; // refresh the table [self. tableView reloadRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationLeft] ;}# pragma mark processes json data-(void) handlerJSONData :( NSData *) data {// [] in the json file represents a data. // Deserialization of json data/* serialization: converts an nsboject into a sequence of data for transmission over the Internet. Deserialization: generate the desired object based on the data obtained on the network. * // The second parameter is the parsing method. Generally, NSJSONReadingAllowFragments NSArray * array = [NSJSONSerialization JSONObjectWithData: data options: Unknown error: nil]; NSLog (@ "% @", array); // data in nsarray format after json parsing. // Tip: If you develop a network application, you can save the deserialized objects to the sandbox for future development and use. NSArray * docs = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString * path = [docs [0] stringByAppendingPathComponent: @ "json. plist "]; [array writeToFile: path atomically: YES]; // write the data in the array to jspns in the sandbox. in plist. // Assign NSMutableArray * arrayM = [NSMutableArray array] to the data list; for (NSDictionary * dict in array) {Video * video = [[Video alloc] init]; // assign video [video setValuesForKeysWithDictionary: dict]; [arrayM addObject: video];} self. dataList = arrayM; // refresh the table [self. tableView reloadData]; NSLog (@ "% @", arrayM ); // This statement will call description in video and descriptionWithLocale} In nsarray + log # pragma mark to load json-(void) loadJson {NS Log (@ "load json"); // load data from the web server NSString * str = @ "http://www.baidu.com? Format = json "; // This is a mess. // Note: NSData has a synchronization method, but in actual development, do not use the secondary method // you cannot specify the timeout when using the NSData synchronization method. If the server connection is abnormal, the user experience will be affected. // NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: str]; // resume NSURL * url = [NSURL URLWithString: str]; // create NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: Required timeoutInterval: 2.0f]; // create a NSURLConnect synchronization method to load data NSURLResponse * response = nil; NSError * error = nil; // synchronously load data NSData * data = [NSURLConnection sendSynchro NousRequest: request returningResponse: & response error: & error]; // if (data! = Nil) {// the following two sentences are meaningless and only used for tracking debugging. NSString * result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", result); // when processing network data, do not convert NSData to nsstring. [Self handlerJSONData: data];} else if (data = nil & error = nil) {NSLog (@ "NULL data ");} else {NSLog (@ "% @", error. localizedDescription) ;}# pragma mark load xml-(void) loadXML {NSLog (@ "load xml") ;}//-(void) viewDidLoad // {// [super viewDidLoad]; //} @ end