Chapter WebServices and UIWebView

Source: Internet
Author: User

Chapter WebServices and UIWebView

1. Usually, fetch data from a Web server using four handy classes:nsurl, Nsurlrequest, Nsurlsessiontask, and Nsurlsession . Each of these classes have an important role in communicating with a Web server:

An Nsurl instance contains, the location of a Web application in URL format. For many Web services, the URL is composed of the base address, the Web application you is communicating with, and a NY arguments that is being passed.

An Nsurlrequest instance holds all the data necessary to communicate with a Web server. This includes an Nsurl object as well as a caching policy, a limit on how long you'll give the Web server to respond, an D Additional data passed through the HTTP protocol. (Nsmutableurlrequest is the mutable subclass of Nsurlrequest.)

An Nsurlsessiontask instance encapsulates the lifetime of a single request. It tracks the state of the request and have methods to cancel, suspend, and resume the request. Tasks would always be subclasses of Nsurlsessiontask, specifically Nsurlsessiondatatask, Nsurlsessionuploadtask, or NSURLS Essiondownloadtask.

An Nsurlsession instance acts as a factory for data transfer tasks. It's a configurable container that can set common properties on the tasks it creates. Some examples include header fields, all requests should has or whether requests work over cellular connections. Nsurlsession also have a rich delegate model that can provide information on the status of a given task and handle Authenti Cation challenges, for example.

2. The purpose of the nsurlsession is a bit hazier. Nsurlsession ' s job is to create tasks of a similar nature. For example, if your application had a set of requests so all required the same header fields, you could configure the N Surlsession with these additional header fields. Similarly, if a set of requests should not connect over cellular networks, then an nsurlsession could is configured to not Allow cellular access. These shared behaviors and attributes is then configured on the tasks the session creates. Tasks is always created in the suspended state, so calling resume on the task would start the Web service request.

#import <UIKit/UIKit.h>#import"BNRWebViewController.h"@ Interface*Webviewcontroller; @end
#import "BNRCoursesViewController.h"#import "TableViewCell.h"@interfaceBnrcoursesviewcontroller () <NSURLSessionDataDelegate>@property (nonatomic) nsurlsession*session; @property (nonatomic, copy) Nsarray*courses;@end@implementationBnrcoursesviewcontroller#pragmaMark-life cycle-(Instancetype) Initwithstyle: (uitableviewstyle) style{ Self=[Super Initwithstyle:style]; if(self) {self.navigationItem.title=@"BNR Courses"; Nsurlsessionconfiguration*config =[Nsurlsessionconfiguration defaultsessionconfiguration]; _session=[Nsurlsession sessionwithconfiguration:configDelegate: Self delegatequeue:nil];            [Self fetchfeed]; }    returnSelf ;}-(void) viewdidload{[Super Viewdidload]; //[Self.tableview Registerclass:[uitableviewcell class] forcellreuseidentifier:@ "UITableViewCell"];uinib *nib = [uinib nibwithnibname:@"Tableviewcell"Bundle:nil]; [Self.tableview registernib:nib Forcellreuseidentifier:@"Tableviewcell"];}#pragmamark-uitableviewdatasource-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{returnSelf.courses.count;}-(uitableviewcell*) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{Tableviewcell*cell = [TableView dequeuereusablecellwithidentifier:@"Tableviewcell"Forindexpath:indexpath]; Nsdictionary*course =Self.courses[indexpath.row]; Cell.courseTitleLabel.text= course[@"title"]; Nsarray*upcoming = course[@"upcoming"]; if(upcoming) {NSString*startdate = [Upcoming firstobject][@"start_date"]; NSString*instructors = [Upcoming firstobject][@"Instructors"]; Cell.upcomingLabel.text= [NSString stringWithFormat:@"%@  %@", StartDate, instructors]; }    returncell;}-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{nsdictionary*course =Self.courses[indexpath.row]; Nsurl*url = [Nsurl urlwithstring:course[@"URL"]]; Self.webViewController.url=URL; Self.webViewController.title= course[@"title"]; [Self.navigationcontroller PushViewController:self.webViewController animated:yes];}#pragmaMark-request to Server-(void) fetchfeed{NSString*requeststring =@"Https://bookapi.bignerdranch.com/private/courses.json"; Nsurl*url =[Nsurl urlwithstring:requeststring]; Nsurlrequest*req =[Nsurlrequest Requestwithurl:url]; Nsurlsessiondatatask*datatask =[self.session datataskwithrequest:req Completionhandler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {Nsdictionary*jsonobject = [nsjsonserialization jsonobjectwithdata:data options:0Error:nil]; Self.courses= jsonobject[@"Courses"]; Dispatch_async (Dispatch_get_main_queue (),^{[Self.tableview reloaddata];                                                     });    }]; [Datatask resume];}#pragmamark-nsurlsessiondatadelegate-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didreceivechallenge: ( Nsurlauthenticationchallenge *) Challenge Completionhandler: (void(^) (Nsurlsessionauthchallengedisposition, Nsurlcredential *)) completionhandler{nsurlcredential*cred = [Nsurlcredential credentialwithuser:@"Bignerdranch"Password@"Achievenerdvana"Persistence:nsurlcredentialpersistenceforsession]; Completionhandler (nsurlsessionauthchallengeusecredential, cred);}@end

Chapter WebServices and UIWebView

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.