iOS Programming Web Services and UIWebView,iosuiwebview

來源:互聯網
上載者: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.

工作分為兩部分,第一,串連和行動數據從一個web service 並使用這些資料建立model objects。第二部分是使用UIWebView 類展示web content .

Nerdfeed object diagram

1 Web Services

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

你的網頁瀏覽器通過HTTP協議與一個web server 交流。

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

最簡單的方式是瀏覽器發送一個請求到指定url 的伺服器。

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

瀏覽器響應通過返回給請求的頁面瀏覽器的格式和顯示。

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.

因為HTTP protocol不關心它傳送的資料是什麼,這些exchanges 可能包含複雜的資料。

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

這些資料一般是JSON(JavaScript Object Notation)或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.

如果你能像client 一樣能控制web server,你可以使用你喜歡的格式。如果不是,你必須構建你的應用基於server支援的。

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.

NSURL執行個體用URL格式包含了一個web application的位置。

For many 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.

對於很多web services,URL 由基礎地址,你交流的web application和被傳送的任何參數。

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

NSURLRequest執行個體保持了所有與wb server 交流的任何必要的資料。

This includes 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.

這包括一個NSURL對象,一個caching策略,你給web server 響應的時間限制和通過HTTP協議傳送的附加的資料。

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

NSURLSessionTask執行個體概況了單個request的生命週期。

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

它跟蹤了request 的狀態。並有方法cancel,suspend ,resume request。

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

tasks總是NSURLSessionTask的子類,有NSURLSessionDataTask,NSURLSessionUploadTask,NSURLSessionDownloadTask。

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

NSURLSession執行個體就像是一個data transfer tasks的工廠。

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

它是一個可配置的容器,能設定它建立的task的 公用屬性。

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

一些例子包括所有request的header fields 或者request 工作是否cellular 串連。

4 Formatting URLs and requests格式化URL和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.

web service request 的form 依賴於誰實現了web service 而變化。當遇到web services時沒有特定的規則。

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

你需要為web service 的文檔來知道怎樣 format 一個request.

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

只要client application 給server 發送了他想要的,你就可以工作了。

 

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

that the base URL is bookapi.bignerdranch.com

the web application is located at

courses on that server's filesystem, followed by the data format (json) you expect the response in.

base url 是bookapi.bignerdranch.com,web application 坐落在server的filesystem的courses,緊跟著是你期望響應的資料格式。

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請求可以是各種格式,取決於web application 的創造者想完成什麼。

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.

這種web server 需要的每個資訊片段作為一個request 被分割成參數成為path 組成部分是 很普遍的。

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

這個特殊的web service call 說返回所有的courses 用json 格式。

Another common web service format looks like this:

另一個普遍的web service 格式是

http://baseURL.com/serviceName?argumentX=valueX&argumentY=valueY

 

for example, you might imagine that you could 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.

你需要一個string URL-safe .例如空格和引用不在URL裡。你必須用escape-sequences 取代。

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

NSString *escaped =

[search stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

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

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

如果你想un-escape 一個percent-escaped string ,你可以用:

- (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.

當request 經過處理,server 將返回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 既可以一個特殊的類,也可以指那些形成了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的工作就是建立一個自然相近的任務。

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

例如,你的應用有一些requests,他們有相同的header fields,你可以配置在NSURLSession與這些額外的header fields。這些共同的表現和屬效能夠配置到session 建立的tasks上。

A project may have multiple instances of NSURLSession

一個project可能有多個NSURLSession 變數。

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

通過給定session 一個請求和一個completion block 去調用當request 完成時,它將返回一個NSURLSessionTask.

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

由於Nerdfeed 從一個web service 請求資料,task的類型是NSURLSessionDataTask。

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

任務總是建立為suspended 狀態,所以調用resume 在這個任務上講開始web service request。

Kick off the exchange whenever the BNRCoursesViewController is created.

在BNRCoursesViewController建立後開始exchange。

 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 有一個內建的類為解析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.

你能用這個類處理JSON data,它將建立NSDictionary 為每個JSON object,NSArray 為每個JSON array,NSString為每個JSON string,NSNumber 為每個JSON number。

 

In BNRCoursesViewController.m, modify the NSURLSessionDataTask completion handler to use the NSJSONSerialization class to convert the raw JSON data into the basic foundation 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.

現在的iOS設別都有多個核心處理器,這樣能夠讓裝置同時運行多行代碼。

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

這被成為concurrency,每塊代碼運行在分開的線程裡。

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

到目前為止,我們所有的代碼運行在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.

主線程有時也被成為UI thread,因為任何修改UI的代碼都運行在main thread 裡。

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

當web service 完成後,你需要載入table view資料。

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

預設情況下,NSURLSessionDataTask完全competion handler 在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.

你需要一種方式強迫代碼運行在main thread 為了載入table view ,你可以輕鬆的完成這些,通過dispatch_async 函數。

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];

});

 

 

 

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.