IOS Programming Web Services and UIWebView, iosuiwebview

Source: Internet
Author: User

IOS Programming Web Services and UIWebView, iosuiwebview

IOS Programming Web Services and UIWebView

The work is divided into two parts. the first is connecting to and collecting data from a web service and using that data to create model objects. the second part is using the UIWebView class to display web content.

The work is divided into two parts: First, connection and mobile data from a web service and use the data to create model objects. The second part is to use the UIWebView class to display web content.

Nerdfeed object digoal

1 Web Services

Your web browser uses the HTTP protocol to communicate with a web server.

Your web browser communicates with a web server over HTTP.

In the simplest interaction, the browser sends a request to the server specifying a URL.

The simplest way is to send a request to the server of the specified url.

The server responds by sending back the requested page (typically HTML and images), which the browser formats and displays.

The browser returns the format and display of the page browser returned to the request.

In more complex interactions, browser requests include other parameters, like form data. The server processes these parameters and returns a customized, or dynamic, web page.

You can write a client application for iOS that leverages the HTTP infrastructure to talk to a web-enabled server. the server side of this application is a web service. your client application and the web service can exchange requests and responses via HTTP.

Because the HTTP protocol does not care what data it transports, these exchanges can contain complex data.

Because HTTP protocol does not care about what data it transmits, these exchanges may contain complex data.

This data is typically in JSON (JavaScript Object Notation) or XML format.

The data is generally JSON (JavaScript Object Notation) or XML format.

If you control the web server as well as the client, you can use any format you like; if not, you have to build your application to use whatever the server supports.

If you can control the web server like a client, you can use the format you like. If not, you must build your application based on server support.

2 Starting the Nerdfeed application

 

(1) Create a new Empty Application for the iPad Device Family. Name this application Nerdfeed

(2) Create a new NSObject subclass and

Name it BNRCoursesViewController. In BNRCoursesViewController. h, change the superclass to UITableViewController.

@ Interface BNRCoursesViewController: UITableViewController

In BNRCoursesViewController. m, write stubs for the required data source methods so that you can

Build and run as you go through this exercise.

-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section

{
Return 0;

}

-(UITableViewCell *) tableView :( UITableView *) tableView

CellForRowAtIndexPath :( NSIndexPath *) indexPath

{
Return nil;

}

 

In BNRAppDelegate. m, create an instance of BNRCoursesViewController and set it as the root view controller of a navigation controller. Make that navigation controller the root view controller of the window.

# Import "BNRCoursesViewController. h"

 

BNRCoursesViewController * cvc =
[[BNRCoursesViewController alloc] initWithStyle: UITableViewStylePlain];

UINavigationController * masterNav =
[[UINavigationController alloc] initWithRootViewController: cvc];

Self. window. rootViewController = masterNav;

 

3 NSURL, NSURLRequest, NSURLSession, and

NSURLSessionTask

 

(1) An NSURL instance contains the location of a web application in URL format.

An NSURL instance uses the URL format to contain the location of a web application.

For processing web services, the URL will be composed of the base address, the web application you are communicating with, and any arguments that are being passed.

For many web services, the URL is based on the basic address, the web application you communicate with and any transmitted parameters.

(2) An NSURLRequest instance holds all the data necessary to communicate with a web server.

The NSURLRequest instance maintains all the necessary data to communicate with the wb server.

This includes des an NSURL object as well as a caching policy, a limit on how long you will give the web server to respond, and additional data passed through the HTTP protocol.

This includes an NSURL object, a caching policy, the time limit for your web server response and additional data transmitted over HTTP.

(3) An NSURLSessionTask instance encapsulates the lifetime of a single request.

The NSURLSessionTask instance provides an overview of the lifecycle of a single request.

It tracks the state of the request and has methods to cancel, suspend, and resume the request.

It tracks the request status. There are methods such as cancel, suspend, and resume request.

Tasks will always be subclasses of NSURLSessionTask, specifically NSURLSessionDataTask, NSURLSessionUploadTask, or NSURLSessionDownloadTask.

Tasks is always a subclass of NSURLSessionTask, including NSURLSessionDataTask, NSURLSessionUploadTask, and NSURLSessionDownloadTask.

(4) An NSURLSession instance acts as a factory for data transfer tasks.

The NSURLSession instance is like a data transfer tasks factory.

It is a writable able container that can set common properties on the tasks it creates.

It is a configurable container that can set the public attributes of the tasks it creates.

Some examples include header fields that all requests shoshould have or whether requests work over cellular connections.

Some examples include whether all request headers fields or requests are cellular connections.

4 Formatting URLs and requests format URL and request

The form of a web service request varies depending on who implements the web service; there are no set-in-stone rules when it comes to web services.

The form of the web service request depends on who implements the web service and changes. When you encounter web services, there are no specific rules.

You will need to find the documentation for the web service to know how to format a request.

You need to know how to format a request for the web service documentation.

As long as a client application sends the server what it wants, you have a working exchange.

As long as the client application sends the desired message to the server, you can work.

 

Http://bookapi.bignerdranch.com/courses.json

That the base URL is bookapi.bignerdranch.com

The web application is located

Courses on that server's filesystem, followed by the data format (json) you need CT the response in.

The base url is bookapi.bignerdranch.com. The web application is located in the filesystem courses of the server, followed by the data format you expect to respond.

Web service requests come in all sorts of formats, depending on what the creator of that web service is trying to accomplish.

Web service requests can be in various formats, depending on what the web application Creator wants to accomplish.

The courses web service, where each piece of information the web server needs to honor a request is broken up into arguments supplied as path components, is somewhat common.

Each segment of information required by this web server is divided into parameters as a request and becomes a component of the path.

This participant ular web service call says, "Return all of the courses in a json format ."

This special web service call indicates that all courses are returned in json format.

Another common web service format looks like this:

Another common web service format is

Http://baseURL.com/serviceName? ArgumentX = valueX & argumentY = valueY

 

For example, you might imagine that you cocould specify the month and year for which you wanted a list of the courses having a URL like this:

Http://bookapi.bignerdranch.com/courses.json? Year = 2014 & month = 11

You will need to make a string "URL-safe." For example, space characters and quotes are not allowed in URLs; They must be replaced with escape-sequences.

You need a string URL-safe. For example, spaces and references are not in the URL. You must replace it with escape-sequences.

NSString * search = @ "Play some \" Abba \"";

NSString * escaped =

[Search stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

// Escaped is now "Play % 20 some % 20% 22 Abba % 22"

If you need to un-escape a percent-escaped string, NSString has the method:

If you want to un-escape a percent-escaped string, you can use:

-(NSString *) stringByRemovingPercentEncoding;

When the request to the Big Nerd Ranch courses feed is processed, the server will return JSON data that contains the list of courses.

When the request is processed, the server returns json data.

5 Working with NSURLSession

NSURLSession refers both to a specific class as well as a name for a collection of classes that form an API for network requests.

NSURLSession can be a special class or a container class that forms the network request api.

The book will refer to the class as just NSURLSession, or an instance thereof, and the API as the NSURLSession API.

In BNRCoursesViewController. m add a property to the class extension to hold onto an instance of NSURLSession.

@ Interface BNRCoursesViewController ()

@ Property (nonatomic) NSURLSession * session;

@ End

Then override initWithStyle: to create the NSURLSession object.

-(Instancetype) initWithStyle :( UITableViewStyle) style

{
Self = [super initWithStyle: style]; if (self ){

Self. navigationItem. title = @ "BNR Courses ";

NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];

_ Session = [NSURLSession sessionWithConfiguration: config

DelegateQueue: nil];

Delegate: nil

}

Return self ;}

 

In BNRCoursesViewController. m, implement the fetchFeed method to create an NSURLRequest that connects to bookapi.bignerdranch.com and asks for the list of courses.

Then, use the NSURLSession to create an NSURLSessionDataTask that transfers this request to the server.

-(Void) fetchFeed

{
NSString * requestString =

@ "Http://bookapi.bignerdranch.com/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 ){

NSString * json = [[NSString alloc] initWithData: data

NSLog (@ "% @", json) ;}];

[DataTask resume];}

 

NSURLSession's job is to create tasks of a similar nature.

NSURLSession is used to create a naturally similar task.

For example, if your application had a set of requests that all required the same header fields, you cocould configure the NSURLSession with these additional header fields. similarly, if a set of requests shocould not connect over cellular networks, then an NSURLSession cocould be configured to not allow cellular access. these shared behaviors and attributes are then configured on the tasks that the session creates.

For example, your application has some requests and they have the same header fields. You can configure the NSURLSession with these additional header fields. These common representations and attributes can be configured on the tasks created by the session.

A project may have multiple instances of NSURLSession

A project may have multiple NSURLSession variables.

By giving the session a request and a completion block to call when the request finishes, it will return an instance of NSURLSessionTask.

When a request is called by a given session and a completion block, it returns an NSURLSessionTask when the request is complete.

Since Nerdfeed is requesting data from a web service, the type of task will be an NSURLSessionDataTask.

Because Nerdfeed requests data from a web service, the task type is NSURLSessionDataTask.

Tasks are always created in the suspended state, so calling resume on the task will start the web service request.

The task is always created in the suincluded State. Therefore, call resume to start the web service request on this task.

Kick off the exchange whenever the BNRCoursesViewController is created.

Start exchange after BNRCoursesViewController is created.

In BNRCoursesViewController. m, update initWithStyle :.

 

[Self fetchFeed];

 

6 JSON data

7. Parsing JSON data

Apple has a built-in class for parsing JSON data, NSJSONSerialization.

Apple has a built-in class for parsing JSON data, NSJSONSerialization.

You can hand this class a bunch of JSON data and it will create instances of NSDictionary for every JSON object, NSArray for every JSON array, NSString for every JSON string, and NSNumber for every JSON number.

You can use this class to process JSON data. It will create NSDictionary for every JSON object, NSArray for every JSON array, NSString for every JSON string, and NSNumber for every JSON number.

 

In BNRCoursesViewController. m, modify the NSURLSessionDataTask completion handler to use the NSJSONSerialization class to convert the raw JSON data into the basic objects.

NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData: data options: 0

NSLog (@ "% @", jsonObject );

In BNRCoursesViewController. m, add a new property to the class extension to hang on to that array, which is an array of NSDictionary objects that describe each course.

@ Property (nonatomic, copy) NSArray * courses;

 

Then, in the same file, change the implementation of the NSURLSessionDataTask completion handler:

 

Self. courses = jsonObject [@ "courses"];

NSLog (@ "% @", self. courses );

 

Now, still in BNRCoursesViewController. m, update the data source methods so that each of the course titles are shown in the table. you will also want to override viewDidLoad to register the table view cell class.

 

-(Void) viewDidLoad

{
[Super viewDidLoad];

[Self. tableView registerClass: [UITableViewCell class] forCellReuseIdentifier: @ "UITableViewCell"];

}

 

-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section

{
Return 0;

Return [self. courses count];}

 

-(UITableViewCell *) tableView :( UITableView *) tableView

CellForRowAtIndexPath :( NSIndexPath *) indexPath

{
Return nil; UITableViewCell * cell =

[TableView dequeueReusableCellWithIdentifier: @ "UITableViewCell" forIndexPath: indexPath];

NSDictionary * course = self. courses [indexPath. row]; cell. textLabel. text = course [@ "title"];

Return cell ;}

7 The main thread

Modern iOS devices have multi-core processors that enable the devices to run multiple chunks of code concurrently.

Currently, iOS devices have multiple core processors, allowing devices to run multiple lines of code simultaneously.

Fittingly, this is referred to as concurrency, and each chunk of code runs on a separate thread.

This becomes concurrency, and each piece of code runs in a separate thread.

So far in this book, all of our code has been running on the main thread.

So far, all our code has run in main thread.

The main thread is sometimes referred to as the UI (user interface) thread, as any code that modifies the UI has to run on the main thread.

The main thread is sometimes used as the UI thread because any code that modifies the UI runs in the main thread.

When the web service completes, you need to reload the table view data.

After the web service is complete, you need to load table view data.

By default, NSURLSessionDataTask runs the completion handler on a background thread.

By default, NSURLSessionDataTask fully competion handler is on the background thread.

You need a way to force code to run on the main thread in order to reload the table view, and you can do that easily using the dispatch_async function.

You need to force the code to run in the main thread. In order to load the table view, you can do this easily by using the dispatch_async function.

In BNRCoursesViewController. m, update the completion handler to reload the table view data on the main thread.

Dispatch_async (dispatch_get_main_queue (), ^ {[self. tableView reloadData];

});

 

 

 

 

 

 

 

 

Related Article

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.