Request processing for iOS elearning------6 JSON Format data

Source: Internet
Author: User

#import "MainViewController.h" #import "Video.h" #define Kbaseurl @ "Http://192.168.3.252/~apple" @interface Mainviewcontroller () <uitableviewdatasource, uitableviewdelegate> @property (Strong, nonatomic) NSArray * DataList, @property (weak, nonatomic) UITableView *tableview; @end @implementation Mainviewcontroller
</pre><p class= "P1" >/*</p><p class= "P2" ><span class= "S1" > </span> In the development of network application, </p><p class= "P2" ><span class= "S1" > 1 </span> data is synchronously loaded, can guarantee the user to see </p> <p class= "P2" ><span class= "S1" > 2 </span> image, audio, video is loaded asynchronously. Can ensure that the main thread without blocking the use of the premise, users can gradually see the multimedia information. </p><p class= "P1" > */</p><pre code_snippet_id= "412158" Snippet_file_name= "blog_20140630 _1_3481337 "name=" code "class=" OBJC "> #pragma mark materialized View-(void) loadview{self.view = [[UIView alloc]initwithframe:[u    Iscreen 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) Agent [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 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:uibarbuttonsystemitemflexiblespace    Target:nil Action:nil]; [ToolBar setitems:@[item3, Item1, Item3, ITEM2, Item3]];} #pragma the Mark-uitableview data source method is necessary for UITableView the following two methods are required. -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{return Self.dataList.count;} This method is called once for each row that is populated. Know that all the lines on the interface are filled. ,-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath{//Use the refillable identifier to query for reusable cells static nsstring *id = @ "MyCell";        UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];    if (cell = = nil) {cell = [[UITableViewCell alloc]initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:id];        }//Set cell contents Video *v = Self.datalist[indexpath.row];    Cell.textLabel.text = V.name;    Cell.detailTextLabel.text = V.teacher;    Load picture//1) synchronously load the network picture, the synchronization method for these instructions will not be executed until the command is completed. Note: When developing a network app, do not use the Sync method to load the picture, otherwise it will seriously affect the user experience//nsstring *imagepath = [NSString stringwithformat:@ "%@%@", Kbaseurl, v.imageurl];//Nsurl *imageurl = [Nsurl urlwithstring:imagepath];//nsdata *imagedata = [NSData DataWithContentsOfUR l:imageurl];//UIImage *image = [UIImage imagewithdata:imagedata];//////2] asynchronously Load network Pictures///////////Network connections themselves have asynchronous commands Sendasyn    c//[Cell.imageview Setimage:image];        If the cached image does not exist if (v.cacheimage = = nil) {//Use the default image placeholder, you can guarantee 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//To open an asynchronous connection to load the image, since loading is complete, you need to refresh the corresponding table navigation [self loadimageasyncwithindexpath:indexpath];    }else {[Cell.imageview setimage:v.cacheimage];    }//[self Loadimageasyncwithurl:imageurl ImageView:cell.imageView]; return cell;} #pragma mark asynchronously loads the network picture//Because UITableView is reusable, in order to avoid the user to quickly and frequently refresh the table, resulting in data conflicts, can not be directly uiimageview into the asynchronous method// The correct workaround is to pass the indexpath of the table row into the Async method, and after loading the finished image, refresh the specified row directly. -(void) Loadimageasyncwithindexpath: (Nsindexpath *) indexpath{Video *v = Self.datalist[indexpath.row];//Remove the row currently being populated N    sstring *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 [Nsurlconnection sendasynchronousrequest:request Queue:[nsoperationqueue Mainqueue] completionhandler:^ (Nsurlresponse *response, NsdatA *data, Nserror *error) {//uiimage *image = [UIImage imagewithdata:data];        [ImageView Setimage:image];        Saves network data to a cached image.        V.cacheimage = [UIImage imagewithdata:data];    Refresh table [Self.tableview Reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationleft]; }];}    #pragma mark handles the JSON data-(void) Handlerjsondata: (NSData *) data{the [] representation of a data in a//json file.     Deserialize JSON data/* Serialization: Convert a Nsboject to serial data for transmission over the Internet.     Deserialization: Reverses the data obtained on the network to the object we need. *////The second parameter is a parsing method, generally with nsjsonreadingallowfragments nsarray *array = [nsjsonserialization jsonobjectwithdata:data options        : Nsjsonreadingallowfragments Error:nil];  NSLog (@ "%@", array);        JSON parsing is data in nsarray format.    Tip: If you are developing a network application, you can save the deserialized object to the sandbox for later development.    Nsarray *docs = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *path = [docs[0]stringbyappendingpathcomponent:@ "Json.plist"]; [Array Writetofile:path atomically:yes]; Put the array insideThe data is written to the jspn.plist in the sandbox.    Assigning a value to a data list nsmutablearray *arraym = [Nsmutablearray array];        For (nsdictionary *dict in array) {video *video = [[Video Alloc]init];        Assign a value to video [video Setvaluesforkeyswithdictionary:dict];    [Arraym Addobject:video];    } self.datalist = Arraym;        Refresh table [Self.tableview Reloaddata];  NSLog (@ "%@", Arraym); This will call the video inside the description and Nsarray+log inside the Descriptionwithlocale} #pragma mark load json-(void) loadjson{NSLog (@ "load    JSON ");  Load data from the Web server nsstring *str = @ "Http://www.baidu.com?format=json";    This is a doodle.//Hint: NSData itself has a synchronous method, but in the actual development, do not use the secondary method//When using the NSData synchronization method, cannot specify the time-out period, if the server connection is not normal, will affect the user experience.    NSData *data = [NSData datawithcontentsofurl:[nsurl urlwithstring:str];    CV nsurl Nsurl *url = [Nsurl urlwithstring:str]; Establish nsurlrequest nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:    Nsurlrequestuseprotocolcachepolicy timeoutinterval:2.0f]; Build Nsurlconnect synchronization method to load data nsurlrEsponse *response = nil;    Nserror *error = nil; Synchronous load Data NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&    ERROR];        Error handling if (data! = nil) {//The following two sentences themselves have little meaning and are used only for tracking debugging.        NSString *result = [[NSString alloc]initwithdata:data encoding:nsutf8stringencoding];                NSLog (@ "%@", result);        Do not convert NSData to nsstring while processing network data.    [Self handlerjsondata:data];    }else if (data = = Nil && error = = nil) {NSLog (@ "null data");    }else {NSLog (@ "%@", error.localizeddescription); }} #pragma mark loaded xml-(void) loadxml{NSLog (@ "load xml");} -(void) viewdidload//{//[Super viewdidload];//} @end

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.