iOS Programming UIWebView 2,iosuiwebview

來源:互聯網
上載者:User

iOS Programming UIWebView 2,iosuiwebview

iOS Programming  UIWebView

1 Instances of UIWebView render web content.

UIWebView可以顯示web content。

In fact, the Safari application on your device uses a UIWebView to render its web content.

事實上,Safari application 用了一個UIWebView 顯示它的web content。

In this part of the chapter, you will create a view controller whose view is an instance of UIWebView.

When one of the items is selected from the table view of courses, you will push the web view's controller onto the navigation stack and have it load the URL string stored in the NSDictionary.

當item的一個從table view of courses 被選中,你push the  web view的controller 到navigation stack,讓它載入儲存在NSDictionary中得URL。

Create a new NSObject subclass and name it BNRWebViewController. In BNRWebViewController.h, add a property and change the superclass to UIViewController:

@interface BNRWebViewController : UIViewController

@property (nonatomic) NSURL *URL;

@end

 

In BNRWebViewController.m, write the following implementation.

- (void)loadView

{

UIWebView *webView = [[UIWebView alloc] init];

webView.scalesPageToFit = YES;

self.view = webView;

}

- (void)setURL:(NSURL *)URL

{

_URL = URL;

if (_URL) {

NSURLRequest *req = [NSURLRequest requestWithURL:_URL];

[(UIWebView *)self.view  loadRequest:req];

}

}

@end

 

In BNRCoursesViewController.h, add a new property to hang on to an instance of BNRWebViewController.

@class BNRWebViewController;

@interface BNRCoursesViewController : UITableViewController

@property (nonatomic) BNRWebViewController *webViewController;

@end

In BNRAppDelegate.m, import the header for BNRWebViewController, create an instance of

BNRWebViewController, and set it as the BNRWebViewController of the BNRCoursesViewController.

#import "BNRWebViewController.h"

 

BNRWebViewController *wvc = [[BNRWebViewController alloc] init];

cvc.webViewController = wvc;

 

In BNRCoursesViewController.m, import the header files for BNRWebViewController and then implement tableView:didSelectRowAtIndexPath: to configure and push the webViewController onto the navigation stack when a row is tapped.

實現tableView:didSelectRowAtIndexPath來配置和推送webViewController到navigation stack 當row 被點擊時。

#import "BNRWebViewController.h"

- (void)tableView:(UITableView *)tableView

didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NSDictionary *course = self.courses[indexPath.row];

NSURL *URL = [NSURL URLWithString:course[@"url"]];

self.webViewController.title = course[@"title"];

self.webViewController.URL = URL;

[self.navigationController pushViewController:self.webViewController  animated:YES];

}

2 Credentials資格

When you try to access a web service, it will sometimes respond with an authentication challenge, which means "Who the heck are you?" You then need to send a username and password (a credential) before the server will send its genuine response.

當你嘗試access  a web service,它有時候響應一個authentication challenge 意思是說:"你到底是誰

"。在server 發送本來的響應之前,你需要發送一個username and password(a credential).

 

When the challenge is received, the NSURLSession delegate is asked to authenticate that challenge, and the delegate will respond by supplying a username and password.

當authentication challenge 被收到後,NSURLSession delegate 被要求認authenticate that challenge,這個delegate 將會通過提供一個username 和password來響應。

Open BNRCoursesViewController.m and update fetchFeed to hit a secure Big Nerd Ranch courses web service.

 

NSString *requestString =

@"https://bookapi.bignerdranch.com/private/courses.json";

The NSURLSession now needs its delegate to be set upon creation. Update initWithStyle: to set the delegate of the session.

NSURLSession 現在需要知道它的delegate來設定創造。

_session = [NSURLSession sessionWithConfiguration:config

delegate:self delegateQueue:nil];

 

Then update the class extension in BNRCoursesViewController.m to conform to the NSURLSessionDataDelegate protocol.

 

@interface BNRCoursesViewController () <NSURLSessionDataDelegate>

 

To authorize this request, you will need to implement the authentication challenge delegate method.

為了authorize 這個request,你需要實現authentication challenge delegate method.

This method will supply a block that you can call, passing in the credentials as an argument.

這個方法會提供了一個你要調用的block,傳遞一個credentials 作為參數。

In BNRCoursesViewController.m implement the NSURLSessionDataDelegate method to handle the authentication challenge.

- (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);

}

 

The completion handler takes in two arguments.

The first argument is the type of credentials you are supplying.

第一個參數是你要提供的credentials的類型。

Since you are supplying a username and password, the type of authentication is NSURLSessionAuthChallengeUseCredential.

因為你要提供username 和password,authentication 的類型是NSURLSessionAuthChallengeUseCredential。

The second argument is the credentials themselves, an instance of NSURLCredential, which is created with the username, password, and an enumeration specifying how long these credentials should be valid for.

第二個參數是credentials 自身,一個NSURLCredential 執行個體,將建立username ,password和一個enumeration 指明這些credentials 將有效多長時間。

3 The Request Body 請求體

When NSURLSessionTask talks to a web server, it uses the HTTP protocol. This protocol says that any data you send or receive must follow the HTTP specification.

當NSURLSessionTask 與一個web server,它使用HTTP protocol.這個協議說你要發送或接受的任何資料需要遵守HTTP specification.

NSURLRequest has a number of methods that allow you to specify a piece of the request and then properly format it for you.

NSURLRequest有許多方法允許你指定請求的一個片段然後恰當的format 。

Any service request has three parts: a request-line, the HTTP headers, and the HTTP body, which is optional.

任何service request 有三個部分:request-line,HTTP headers 和HTTP body 。

The request-line (which Apple calls a status line) is the first line of the request and tells the server what the client is trying to do.

request-ling(apple 稱為status line) 是請求的第一行,告訴server ,client打算做什麼。

In this request, the client is trying to GET the resource at  /courses.json. (It also specifies the HTTP specification version that the data is in.)

在這個請求裡client 打算get 資源在/courses.json。

While there are a number of supported HTTP methods, you most commonly see GET and POST. The default of NSURLRequest, GET, indicates that the client wants something from the server. The thing that it wants is called the Request-URI (/courses.json).

Today, we also use the Request-URI to specify a service that the server implements.

現在我們仍然用Request-URI來指明server 實現指定的service.

For example, in this chapter, you accessed the courses service, supplied parameters to it, and were returned a JSON document.

You are still GETting something, but the server is more clever in interpreting what you are asking for.

你仍然在GETting something,但是server 將會更聰明在interperting .

In addition to getting things from a server, you can send it information. For example, many web servers allow you to upload photos. A client application would pass the image data to the server through a service request.

另外一種情況是你想發送給server一些東西。

In this situation, you use the HTTP method POST, which indicates to the server that you are including the optional HTTP body.

在這種情況下,你使用HTTP 方法POST ,這就indicates  to the server 你將including 可選擇的HTTP body.

The body of a request is data you can include with the request – typically XML, JSON, or Base-64 encoded data.

request body 是你能包括的請求資料:XML,JSON,或者Base-64 encoded data.

When the request has a body, it must also have the Content-Length header.

當request 有body時,它必須有content-length header。

Handily enough,NSURLRequest will compute the size of the body and add this header for you.

方便的是,NSURLRequest 將會計算body 的大小並把為你添加這個header.

 

NSURL *someURL = [NSURL URLWithString:@"http://www.photos.com/upload"];

UIImage *image = [self profilePicture];

NSData *data = UIImagePNGRepresentation(image);

 

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:someURL

cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:90];

// This adds the HTTP body data and automatically sets the Content-Length header

req.HTTPBody = data;

// This changes the HTTP Method in the request-line

req.HTTPMethod = @"POST";

// If you wanted to set the Content-Length programmatically...

[req setValue:[NSString stringWithFormat:@"%d", data.length]

forHTTPHeaderField:@"Content-Length"];

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.