Presentation is loading. Please wait.

Presentation is loading. Please wait.

網路服務.

Similar presentations


Presentation on theme: "網路服務."— Presentation transcript:

1 網路服務

2 Web View

3 UIWebView You can display web content by embedding a UIWebView into your application Content can be... A remote or local URL An string that contains HTML Raw data & corresponding MIME type

4 UIWebView Load a URL from an NSURLRequest...
Load HTML from a string... Load from NSData... - (void) loadRequest:(NSURLRequest *)request; - (void) loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL; - (void) loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;

5 UIWebViewDelegate Is the view about to starting loading...
Has the view started loaded... Is the view done loading... Was there an error... - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; - (void)webViewDidStartLoad:(UIWebView *)webView; - (void)webViewDidFinishLoad:(UIWebView *)webView; - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;

6 UIWebViewNavigationType
enum { UIWebViewNavigationTypeLinkClicked, UIWebViewNavigationTypeFormSubmitted, UIWebViewNavigationTypeBackForward, UIWebViewNavigationTypeReload, UIWebViewNavigationTypeFormResubmitted, UIWebViewNavigationTypeOther }; typedef NSUInteger UIWebViewNavigationType;

7 NSURLRequest Class NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme. Creating Requests + requestWithURL: – initWithURL: Returns a URL request for a specified URL with default cache policy and timeout value. The default cache policy is NSURLRequestUseProtocolCachePolicy and the default timeout interval is 60 seconds.

8 NSURLRequest Class Creating Requests
+ requestWithURL:cachePolicy:timeoutInterval: – initWithURL:cachePolicy:timeoutInterval: enum { NSURLRequestUseProtocolCachePolicy = 0, NSURLRequestReloadIgnoringLocalCacheData = 1, NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4, NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, NSURLRequestReturnCacheDataElseLoad = 2, NSURLRequestReturnCacheDataDontLoad = 3, NSURLRequestReloadRevalidatingCacheData = 5 }; typedef NSUInteger NSURLRequestCachePolicy;

9 NSURLRequest Class Getting Request Properties
(NSURLRequestCachePolicy)cachePolicy (NSTimeInterval)timeoutInterval If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out. (NSURLRequestNetworkServiceType) networkServiceType (NSURL *)URL Returns the request's URL. enum{ NSURLNetworkServiceTypeDefault = 0, NSURLNetworkServiceTypeVoIP = 1 }; typedef NSUInteger NSURLRequestNetworkServiceType;

10 NSURLRequest Class Getting HTTP Request Properties
(NSDictionary *)allHTTPHeaderFields (NSData *)HTTPBody (NSString *)HTTPMethod The default HTTP method is “GET”. (BOOL)HTTPShouldHandleCookies Returns whether the default cookie handling will be used for this request. (NSString *) valueForHTTPHeaderField: (NSString *)field Returns the value of the specified HTTP header field.

11 NSMutableURLRequest Class
A subclass of NSURLRequest provided to aid developers who may find it more convenient to mutate a single request object for a series of URL load requests instead of creating an immutable NSURLRequest for each load.

12 NSMutableURLRequest Class
- (void)setHTTPMethod:(NSString *)method Sets the receiver’s HTTP request method. - (void)setHTTPBody:(NSData *)data data:This is sent as the message body of the request, as in an HTTP POST request - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field Sets the specified HTTP header field.

13 簡單瀏覽器 #import <UIKit/UIKit.h>
@interface IHViewController : UIViewController<UIWebViewDelegate> @property (weak, nonatomic) IBOutlet UITextField *urlField; @property (weak, nonatomic) IBOutlet UIWebView *webView; - (IBAction)loadURL:(id)sender; @end 拉線到ViewController

14 #import "IHViewController.h”
@interface IHViewController () @end @implementation IHViewController - (IBAction)loadURL:(id)sender { NSURL *url = [NSURL URLWithString:self.urlField.text]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; [self.urlField resignFirstResponder]; [self.webView loadRequest:req]; } -(void)webViewDidFinishLoad:(UIWebView *)webView{

15 Hyperlinks to external sites
By default, web links open in the current web view If you’d like them to open in Mobile Safari, you need to implement the following method on the view controller... - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest: (NSURLRequest *)request navigationType: (UIWebViewNavigationType) navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked) { [[UIApplication sharedApplication] openURL:request.URL]; return NO; } return YES;

16 Display local HTML file
display local content by constructing a file URL to a local resource - (IBAction)loadURL { NSURL *url; NSString *path = [[NSBundle mainBundle] url = [[NSURL alloc] initFileURLWithPath:path]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:req]; }

17 練習 Display Google web page in UIWebview
Display local HTML file (sample.html)

18 Web Services

19 Web Services Many apps call out to get or post data from a web source
Web services come in a number of flavors... SOAP XML REST XML JSON etc...

20 Parsing XML There are several XML parsing libraries for ObjC
NSXMLParser is an event driven parser It notifies its delegate about the items (elements, attributes, CDATA blocks, comments, etc...) that it encounters as it processes an XML document

21 NSXMLParser Class Initializing a Parser Object Managing Delegates
(id)initWithContentsOfURL:(NSURL *)url Initializes the receiver with the XML content referenced by the given URL. (id)initWithData:(NSData *)data Initializes the receiver with the XML contents encapsulated in a given data object. Managing Delegates (void)setDelegate:(id < NSXMLParserDelegate >) delegate (id < NSXMLParserDelegate >)delegate

22 NSXMLParser Class Parsing (BOOL)parse (void)abortParsing
Starts the event-driven parsing operation. (void)abortParsing Stops the parser object (NSError *)parserError Returns an NSError object from which you can obtain information about a parsing error.

23 NSXMLParserDelegate Protocol
- (void)parserDidStartDocument:(NSXMLParser *) parser Sent by the parser object to the delegate when it begins parsing a document. - (void)parserDidEndDocument:(NSXMLParser *) parser Sent by the parser object to the delegate when it has successfully completed parsing

24 NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict Sent by a parser object to its delegate when it encounters a start tag for a given element. elementName A string that is the name of an element (in its start tag). attributeDict A dictionary that contains any attributes associated with the element. Keys are the names of attributes, and values are attribute values.

25 NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName Sent by a parser object to its delegate when it encounters an end tag for a specific element.

26 NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string Sent by a parser object to provide its delegate with a string representing all or part of the characters of the current element. The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element.

27 NSURLConnection Class
An NSURLConnection object provides support to perform the loading of a URL request.

28 Synchronous + (NSData *) sendSynchronousRequest: (NSURLRequest *) request returningResponse: (NSURLResponse **) response error:(NSError **) error Performs a synchronous load of the specified URL request. Return Value: The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.

29 NSURLConnection Loading Data Asynchronously
+ (NSURLConnection *) connectionWithRequest: (NSURLRequest *) request delegate:(id)delegate Creates and returns an initialized URL connection and begins to load the data for the URL request. - (id)initWithRequest:(NSURLRequest *) request delegate:(id)delegate Returns an initialized URL connection and begins to load the data for the URL request.

30 NSURLConnection - (id)initWithRequest:(NSURLRequest *) request delegate:(id)delegate startImmediately: (BOOL)startImmediately startImmediately YES if the connection should being loading data immediately, otherwise NO. If you pass NO, you must schedule the connection in a run loop before starting it. - (void)start Causes the receiver to begin loading data, if it has not already

31 NSURLConnection - (void)cancel
Once this method is called, the receiver’s delegate will no longer receive any messages for this NSURLConnection.

32 NSURLConnectionDataDelegate
Delegate method - (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data Sent as a connection loads data incrementally. - (void)connectionDidFinishLoading: (NSURLConnection *)connection Sent when a connection has finished loading successfully

33 NSURLConnectionDataDelegate
Delegate method - (void)connection:(NSURLConnection *) connection didFailWithError:(NSError *)error Sent when a connection fails to load its request successfully. Once the delegate receives this message, it will receive no further messages for connection.

34 練習 howAction.do?method=doFindAllTypeX XML資料

35 xml

36 .h #import <UIKit/UIKit.h>
@interface ViewController : UIViewController <NSXMLParserDelegate,NSURLConnectionDataDelegate> @property(nonatomic,strong) NSMutableData *typeData; @end

37 .m #import "ViewController.h"
#define @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; NSString *urlStr=[NSString NSURL *url= [NSURL URLWithString:urlStr]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; [NSURLConnection connectionWithRequest:request delegate:self]; self.typeData=[[NSMutableData alloc]init]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.typeData appendData:data]; -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

38 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSStringEncoding strEncode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8); NSString *string = [[NSString alloc] initWithData:self.typeData encoding:strEncode]; NSData *newData = [string dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *parser=[[NSXMLParser alloc]initWithData:newData]; parser.delegate=self; [parser parse]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; } -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName [attributeDict

39 -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{ } -(void)parserDidEndDocument:(NSXMLParser *)parser [self.weatherData setData:nil]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; - (void)didReceiveMemoryWarning [super didReceiveMemoryWarning]; @end

40 JSON JSON 物件或陣列的 value 值可以如 下: JSON 字串可以包含陣列 Array 資料或者是物件 Object 資料
{   "orderID": 12345,   "shopperName": "John Smith",   "contents": [     {       "productID": 34,       "productName": "SuperWidget",       "quantity": 1     },     {       "productID": 56,       "productName": "WonderWidget",       "quantity": 3     }   ],   "orderCompleted": true } JSON  JSON 字串可以包含陣列 Array 資料或者是物件 Object 資料 陣列可以用 [ ] 來寫入資料 物件可以用 { } 來寫入資料 name / value 是成對的,中間透過 (:) 來區隔 物件或陣列的 value 值可以如 下: 數字 (整數或浮點數) 字串 (請用 “” 括號) 布林函數 (boolean) (true 或 false) 陣列 (請用 [ ] ) 物件 (請用 { } ) NULL

41 Parsing JSON 使用NSJSONSerialization parsing JSON
JSON must have the following properties: The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

42 Parsing JSON NSJSONSerialization類別 Creating a JSON Object
+ (id)JSONObjectWithData:(NSData *)data options: (NSJSONReadingOptions)opt error: (NSError **)error + (id)JSONObjectWithStream:(NSInputStream *)stream options: (NSJSONReadingOptions)opt error:(NSError **)error arrays and dictionaries are created as mutable objects enum { NSJSONReadingMutableContainers = (1UL << 0), NSJSONReadingMutableLeaves = (1UL << 1), NSJSONReadingAllowFragments = (1UL << 2) }; typedef NSUInteger NSJSONReadingOptions; leaf strings in the JSON object graph are created as instances of NSMutableString allow top-level objects that are not an instance of NSArray or NSDictionary.

43 Parsing JSON NSJSONSerialization類別 Creating JSON Data
+ (BOOL)isValidJSONObject:(id)obj + (NSData *)dataWithJSONObject:(id)obj options: (NSJSONWritingOptions)opt error:(NSError **)error + (NSInteger)writeJSONObject:(id)obj toStream: (NSOutputStream *) stream options: (NSJSONWritingOptions)opt error:(NSError **)error enum { NSJSONWritingPrettyPrinted = (1UL << 0) }; typedef NSUInteger NSJSONWritingOptions; JSON data should be generated with whitespace designed to make the output more readable. If this option is not set, the most compact possible JSON representation is generated.

44 練習 n.do?method=doFindAllTypeJ

45 JSON資料 [{"version":"1.4","categoryCode":"1","categoryName":"音樂","status":"success","total":"15"},{"version":"1.4","categoryCode":"2","categoryName":"戲劇","status":"success","total":"15"},{"version":"1.4","categoryCode":"3","categoryName":"舞蹈","status":"success","total":"15"},{"version":"1.4","categoryCode":"4","categoryName":"親子","status":"success","total":"15"},{"version":"1.4","categoryCode":"5","categoryName":"獨立音樂","status":"success","total":"15"},{"version":"1.4","categoryCode":"6","categoryName":"展覽","status":"success","total":"15"},{"version":"1.4","categoryCode":"7","categoryName":"講座","status":"success","total":"15"},{"version":"1.4","categoryCode":"8","categoryName":"電影","status":"success","total":"15"},{"version":"1.4","categoryCode":"11","categoryName":"綜藝","status":"success","total":"15"},{"version":"1.4","categoryCode":"13","categoryName":"競賽","status":"success","total":"15"},{"version":"1.4","categoryCode":"14","categoryName":"徵選","status":"success","total":"15"},{"version":"1.4","categoryCode":"15","categoryName":"其他","status":"success","total":"15"},{"version":"1.4","categoryCode":"16","categoryName":"未知分類","status":"success","total":"15"},{"version":"1.4","categoryCode":"17","categoryName":"演唱會","status":"success","total":"15"},{"version":"1.4","categoryCode":"19","categoryName":"研習課程","status":"success","total":"15"}]

46 NSStringEncoding strEncode =
CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8); NSString *string = [[NSString alloc] initWithData:self.typeData encoding:strEncode]; NSData *newData = [string dataUsingEncoding:NSUTF8StringEncoding]; NSError* error; NSArray* jsonAry = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableContainers error:&error]; for (int i=0; i<jsonAry.count; i++) { NSDictionary *type=[jsonAry objectAtIndex:i]; NSEnumerator *enumerator = [type keyEnumerator]; id aKey = nil; while ( (aKey = [enumerator nextObject]) != nil) { if([aKey id value = [type objectForKey:aKey]; value); } else if([aKey value);

47 Parsing Html

48 XPath Syntax Selecting Nodes nodename / // @
Selects all nodes with the name "nodename" / Selects from the root node // Selects nodes in the document from the current node that match the selection no matter where they are @ Selects attributes

49 Example <?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore> <book>   <title lang="eng">Harry Potter</title>   <price>29.99</price> </book>   <title lang="eng">Learning XML</title>   <price>39.95</price> </bookstore> Example bookstoreSelects all nodes with the name "bookstore" /bookstoreSelects the root element bookstore Note: If the path starts with a slash ( / ) it always represents an absolute path to an element! bookstore/bookSelects all book elements that are children of bookstore //bookSelects all book elements no matter where they are in the document bookstore//bookSelects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element all attributes that are named lang

50 XPath Syntax Predicates
used to find a specific node or a node that contains a specific value. embedded in square brackets. [ ]

51 <?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore> <book>   <title lang="eng">Harry Potter</title>   <price>29.99</price> </book>   <title lang="eng">Learning XML</title>   <price>39.95</price> </bookstore> /bookstore/book[1]Selects the first book element that is the child of the bookstore element. /bookstore/book[last()]Selects the last book element that is the child of the bookstore element /bookstore/book[last()-1]Selects the last but one book element that is the child of the bookstore element /bookstore/book[position()<3]Selects the first two book elements that are children of the bookstore element all the title elements that have an attribute named lang all the title elements that have an attribute named lang with a value of 'eng' /bookstore/book[price>35.00]Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00 /bookstore/book[price>35.00]/titleSelects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00

52 XPath Syntax Selecting Unknown Nodes * @* Matches any element node
Matches any attribute node

53 <?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore> <book>   <title lang="eng">Harry Potter</title>   <price>29.99</price> </book>   <title lang="eng">Learning XML</title>   <price>39.95</price> </bookstore> /bookstore/*Selects all the child nodes of the bookstore element //*Selects all elements in the document all title elements which have any attribute

54 XPath Syntax Selecting Several Paths
using the | operator in an XPath expression you can select several paths //book/title | //book/priceSelects all the title AND price elements of all book elements //title | //priceSelects all the title AND price elements in the document /bookstore/book/title | //priceSelects all the title elements of the book element of the bookstore element AND all the price elements in the document

55 Parsing HTML Using Libxml2 and Hpple 建立專案後 Adding the Hpple Code
下載壓縮檔 將以下檔案拖入專案

56 複製檔案至專案

57 加入搜尋libxml2標頭檔路徑 $(SDKROOT)/usr/include/libxml2

58 連結libxml2 lib

59 TFHpple Class + (TFHpple *) hppleWithHTMLData:(NSData *) theData encoding:(NSString *)encoding; + (TFHpple *) hppleWithHTMLData:(NSData *) theData; - (NSArray *) searchWithXPathQuery:(NSString *) xPathOrCSS;

60 TFHppleElement Class 屬性 NSString *content; NSString *tagName;
Returns this tag's innerHTML content NSString *tagName; NSDictionary *attributes; Returns tag attributes with name as key and content as value. NSArray *children; TFHppleElement *firstChild; TFHppleElement *parent;

61 TFHppleElement Class 方法 (BOOL)hasChildren; (BOOL)isTextNode;
(NSString *) objectForKey:(NSString *) theKey; Provides easy access to the content of a specific attribute (NSArray *) childrenWithTagName:(NSString *) tagName; Returns the children whose tag name equals the given string Returns an empty array if no matching child is found

62 TFHppleElement Class 方法
(TFHppleElement *) firstChildWithTagName: (NSString *)tagName; Returns the first child node whose tag name equals the given string Returns nil if no matching child is found (NSArray *) childrenWithClassName:(NSString *) className; Returns the children whose class equals the given string (TFHppleElement *) firstChildWithClassName: (NSString*)className;

63 TFHppleElement Class 方法 (TFHppleElement *) firstTextChild;
Returns the first text node from this element's children (NSString *) text; Returns the string contained by the first text node from this element's children can be used instead of firstTextChild.content

64

65 .m NSURL *tutorialsUrl = [NSURL NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl]; TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData]; NSString *tutorialsXpathQueryString = NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString]; for (TFHppleElement *element in tutorialsNodes) { NSString *title = [[element firstChild] content]; NSString *url = [element }

66 練習 台鐵時刻表 searchtype=0&searchdate=2014/12/25&fromcity=& tocity=&fromstation=1008&tostation=1015&traincla ss=2&fromtime=0000&totime=2359 xPath解析Html


Download ppt "網路服務."

Similar presentations


Ads by Google