網路服務檔案

教育部資通訊軟體創新人才推升推廣計畫
iOS智慧裝置軟體設計
網路服務
明新科技大學 資訊工程系 彭亦暄
iOS
Web View
智
慧
裝
置
軟
體
設
計
2
彭
亦
暄
、
江
佩
穎
UIWebView
You can display web content by embedding a
UIWebView into your application
Content can be...
iOS
• A remote or local URL
• An string that contains HTML
• Raw data & corresponding MIME type
智
慧
裝
置
軟
體
設
計
3
彭
亦
暄
UIWebView
Load a URL from an NSURLRequest...
- (void) loadRequest:(NSURLRequest *)request;
Load HTML from a string...
- (void) loadHTMLString:(NSString *)string
baseURL:(NSURL *)baseURL;
iOS
Load from NSData...
智
慧
裝
置
軟
體
設
計
- (void) loadData:(NSData *)data
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName
baseURL:(NSURL *)baseURL;
4
彭
亦
暄
UIWebViewDelegate
Is the view about to starting loading...
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
Has the view started loaded...
iOS
- (void)webViewDidStartLoad:(UIWebView *)webView;
Is the view done loading...
- (void)webViewDidFinishLoad:(UIWebView *)webView;
Was there an error...
- (void)webView:(UIWebView *)webView
didFailLoadWithError:(NSError *)error;
5
智
慧
裝
置
軟
體
設
計
彭
亦
暄
UIWebViewNavigationType
iOS
enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;
智
慧
裝
置
軟
體
設
計
6
彭
亦
暄
NSURLRequest Class
NSURLRequest objects represent a URL load request
in a manner independent of protocol and URL scheme.
Creating Requests
• 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.
7
iOS
+ requestWithURL:
– initWithURL:
智
慧
裝
置
軟
體
設
計
彭
亦
暄
NSURLRequest Class
Creating Requests
+ requestWithURL:cachePolicy:timeoutInterval:
– initWithURL:cachePolicy:timeoutInterval:
iOS
enum
{
NSURLRequestUseProtocolCachePolicy = 0,
NSURLRequestReloadIgnoringLocalCacheData = 1,
NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4,
NSURLRequestReloadIgnoringCacheData =
NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReturnCacheDataElseLoad = 2,
NSURLRequestReturnCacheDataDontLoad = 3,
NSURLRequestReloadRevalidatingCacheData = 5
};
typedef NSUInteger NSURLRequestCachePolicy;
智
慧
裝
置
軟
體
設
計
8
彭
亦
暄
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.
iOS
(NSURLRequestNetworkServiceType) networkServiceType
(NSURL *)URL
智
• Returns the request's URL.
慧
裝
置
軟
體
設
計
enum{
NSURLNetworkServiceTypeDefault = 0,
NSURLNetworkServiceTypeVoIP = 1
}; typedef NSUInteger NSURLRequestNetworkServiceType;
9
彭
亦
暄
NSURLRequest Class
Getting HTTP Request Properties
(NSDictionary *)allHTTPHeaderFields
(NSData *)HTTPBody
(NSString *)HTTPMethod
• The default HTTP method is “GET”.
• 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.
10
iOS
 (BOOL)HTTPShouldHandleCookies
智
慧
裝
置
軟
體
設
計
彭
亦
暄
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.
iOS
智
慧
裝
置
軟
體
設
計
11
彭
亦
暄
NSMutableURLRequest Class
- (void)setHTTPMethod:(NSString *)method
• Sets the receiver’s HTTP request method.
- (void)setHTTPBody:(NSData *)data
iOS
• 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.
12
彭
亦
暄
簡單瀏覽器
#import <UIKit/UIKit.h>
@interface IHViewController :
UIViewController<UIWebViewDelegate>
iOS
@property (weak, nonatomic) IBOutlet
UITextField *urlField;
@property (weak, nonatomic) IBOutlet
UIWebView *webView;
智
慧
裝
置
軟
體
設
計
- (IBAction)loadURL:(id)sender;
@end
拉線到ViewController
13
彭
亦
暄
iOS
#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{
置
NSLog(@"網頁載入完成");
軟
體
}
設
計
@end
彭
亦
暄
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...
iOS
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:
(NSURLRequest *)request navigationType: (UIWebViewNavigationType)
navigationType { 智
慧
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
裝
置
[[UIApplication sharedApplication] openURL:request.URL];
軟
return NO;
體
設
}
計
return YES;
彭
}
亦
15
暄
Display local HTML file
display local content by constructing a file URL to a local
resource
iOS
- (IBAction)loadURL {
NSURL *url;
NSString *path = [[NSBundle mainBundle] pathForResource:@”sample"
ofType:@"html"];
url = [[NSURL alloc] initFileURLWithPath:path];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:req];
}
智
慧
裝
置
軟
體
設
計
16
彭
亦
暄
練習
Display Google web page in UIWebview
Display local HTML file (sample.html)
iOS
智
慧
裝
置
軟
體
設
計
17
彭
亦
暄
iOS
Web Services
智
慧
裝
置
軟
體
設
計
18
彭
亦
暄
、
江
佩
穎
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...
iOS
•
•
•
•
智
慧
裝
置
軟
體
設
計
19
彭
亦
暄
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
iOS
智
慧
裝
置
軟
體
設
計
20
彭
亦
暄
NSXMLParser Class
Initializing a Parser Object
 (id)initWithContentsOfURL:(NSURL *)url
• Initializes the receiver with the XML content referenced by the
given URL.
 (id)initWithData:(NSData *)data
Managing Delegates
(void)setDelegate:(id < NSXMLParserDelegate >) delegate
(id < NSXMLParserDelegate >)delegate
21
iOS
• Initializes the receiver with the XML contents encapsulated in a
given data object.
智
慧
裝
置
軟
體
設
計
彭
亦
暄
NSXMLParser Class
Parsing
(BOOL)parse
• Starts the event-driven parsing operation.
(void)abortParsing
• Stops the parser object
iOS
(NSError *)parserError
• Returns an NSError object from which you can obtain
information about a parsing error.
智
慧
裝
置
軟
體
設
計
22
彭
亦
暄
NSXMLParserDelegate Protocol
- (void)parserDidStartDocument:(NSXMLParser *) parser
• Sent by the parser object to the delegate when it begins parsing a
document.
- (void)parserDidEndDocument:(NSXMLParser *) parser
iOS
• Sent by the parser object to the delegate when it has successfully
completed parsing
智
慧
裝
置
軟
體
設
計
23
彭
亦
暄
NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
iOS
• Sent by a parser object to its delegate when it encounters a start tag for a
given element.
• elementName
智
慧
裝
attributeDict
置
• A dictionary that contains any attributes associated with the element. Keys 軟
體
are the names of attributes, and values are attribute values.
設
計
• A string that is the name of an element (in its start tag).
•
24
彭
亦
暄
NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
iOS
• Sent by a parser object to its delegate when it encounters
an end tag for a specific element.
智
慧
裝
置
軟
體
設
計
25
彭
亦
暄
NSXMLParserDelegate Protocol
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
iOS
• 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.
智
慧
裝
置
軟
體
設
計
26
彭
亦
暄
NSURLConnection Class
An NSURLConnection object provides support to
perform the loading of a URL request.
iOS
智
慧
裝
置
軟
體
設
計
27
彭
亦
暄
Synchronous
+ (NSData *) sendSynchronousRequest:
(NSURLRequest *) request returningResponse:
(NSURLResponse **) response error:(NSError **)
error
28
iOS
• 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.
智
慧
裝
置
軟
體
設
計
彭
亦
暄
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.
iOS
• - (id)initWithRequest:(NSURLRequest *) request
delegate:(id)delegate
• Returns an initialized URL connection and begins to load
the data for the URL request.
29
智
慧
裝
置
軟
體
設
計
彭
亦
暄
NSURLConnection
- (id)initWithRequest:(NSURLRequest *) request
delegate:(id)delegate startImmediately:
(BOOL)startImmediately
• startImmediately
- (void)start
• Causes the receiver to begin loading data, if it has not
already
30
iOS
• 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.
智
慧
裝
置
軟
體
設
計
彭
亦
暄
NSURLConnection
- (void)cancel
• Once this method is called, the receiver’s delegate will
no longer receive any messages for this
NSURLConnection.
iOS
智
慧
裝
置
軟
體
設
計
31
彭
亦
暄
NSURLConnectionDataDelegate
Delegate method
- (void)connection:(NSURLConnection *)
connection didReceiveData:(NSData *)data
• Sent as a connection loads data incrementally.
iOS
- (void)connectionDidFinishLoading:
(NSURLConnection *)connection
• Sent when a connection has finished loading successfully
32
智
慧
裝
置
軟
體
設
計
彭
亦
暄
NSURLConnectionDataDelegate
Delegate method
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
iOS
• Sent when a connection fails to load its request
successfully.
• Once the delegate receives this message, it will receive
no further messages for connection.
智
慧
裝
置
軟
體
設
計
33
彭
亦
暄
練習
http://cloud.culture.tw/frontsite/trans/SearchS
howAction.do?method=doFindAllTypeX
XML資料
iOS
智
慧
裝
置
軟
體
設
計
34
彭
亦
暄
xml
iOS
智
慧
裝
置
軟
體
設
計
35
彭
亦
暄
.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<NSXMLParserDelegate,NSURLConnectionDataDelegate>
@property(nonatomic,strong) NSMutableData *typeData;
iOS
@end
智
慧
裝
置
軟
體
設
計
36
彭
亦
暄
.m
iOS
#import "ViewController.h"
#define hostUrl
@"http://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindAllTypeX"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlStr=[NSString stringWithFormat:@"%@",hostUrl];
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
{
NSLog(@"%@",error);
}
37
智
慧
裝
置
軟
體
設
計
彭
亦
暄
-(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];
}
iOS
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"Info"])
NSLog(@"%@ %@",[attributeDict objectForKey:@"categoryName"],
[attributeDict objectForKey:@"categoryCode"]);
智
慧
裝
置
軟
體
設
計
彭
亦
暄
iOS
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"%@",string);
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
[self.weatherData setData:nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void)didReceiveMemoryWarning
{
智
[super didReceiveMemoryWarning];
慧
裝
}
@end
置
軟
體
設
計
彭
亦
暄
JSON
JSON
{
物件或陣列的 value 值可以如
下:
NULL
iOS
"orderID": 12345,
 JSON 字串可以包含陣列 Array "shopperName": "John Smith",
"shopperEmail": "[email protected]",
資料或者是物件 Object 資料
"contents": [
陣列可以用 [ ] 來寫入資料
{
物件可以用 { } 來寫入資料
"productID": 34,
• name / value 是成對的,中間透過
"productName": "SuperWidget",
(:) 來區隔
"quantity": 1
},
{
"productID": 56,
智
數字 (整數或浮點數)
慧
"productName": "WonderWidget",
裝
字串 (請用 “” 括號)
"quantity": 3
置
布林函數 (boolean) (true 或 false) }
軟
],
陣列 (請用 [ ] )
體
"orderCompleted": true
設
物件 (請用 { } )
計
}
彭
亦
暄
Parsing JSON
使用NSJSONSerialization parsing JSON
JSON must have the following properties:
41
iOS
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.
智
慧
裝
置
軟
體
設
計
彭
亦
暄
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
iOS
arrays and dictionaries are created as mutable objects
enum {
NSJSONReadingMutableContainers = (1UL << 0),
智
慧
leaf strings in the JSON object graph are created as instances of NSMutableString
裝
NSJSONReadingMutableLeaves = (1UL << 1),
置
NSJSONReadingAllowFragments = (1UL << 2)
軟
體
};
allow top-level objects that are not an instance of NSArray or NSDictionary.
設
typedef NSUInteger NSJSONReadingOptions;
計
42
彭
亦
暄
Parsing JSON
NSJSONSerialization類別
iOS
 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.
43
彭
亦
暄
練習
http://cloud.culture.tw/frontsite/trans/SearchShowActio
n.do?method=doFindAllTypeJ
iOS
智
慧
裝
置
軟
體
設
計
44
彭
亦
暄
JSON資料
45
iOS
[{"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
iOS
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 isEqual:@"categoryCode"]){
id value = [type objectForKey:aKey];
NSLog(@"Code: %@", value);
}
else if([aKey isEqual:@"categoryName"])
{
id value = [type objectForKey:aKey];
NSLog(@"Name: %@", value);
}
}
}
智
慧
裝
置
軟
體
設
計
彭
亦
暄
Parsing Html
47
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
http://www.w3schools.com/XPath/xpath_syntax.asp
48
iOS
//
智
慧
裝
置
軟
體
設
計
彭
亦
暄
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
Example
iOS
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
彭
//@langSelects all attributes that are named lang
49
亦
暄
XPath Syntax
Predicates
used to find a specific node or a node that contains
a specific value.
embedded in square brackets.
[ ]
iOS
智
慧
裝
置
軟
體
設
計
50
彭
亦
暄
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</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
iOS
/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
裝
//title[@lang]Selects all the title elements that have an attribute named lang
置
//title[@lang='eng']Selects 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
51
暄
XPath Syntax
Selecting Unknown Nodes
*
• Matches any element node
@*
• Matches any attribute node
iOS
智
慧
裝
置
軟
體
設
計
52
彭
亦
暄
iOS
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
智
慧
裝
/bookstore/*Selects all the child nodes of the bookstore element
置
//*Selects all elements in the document
軟
體
//title[@*]Selects all title elements which have any attribute
設
計
53
彭
亦
暄
XPath Syntax
Selecting Several Paths
using the | operator in an XPath expression you can
select several paths
54
iOS
//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
智
慧
裝
置
軟
體
設
計
彭
亦
暄
Parsing HTML
Using Libxml2 and Hpple
建立專案後
Adding the Hpple Code
• 下載壓縮檔 https://github.com/topfunky/hpple
• 將以下檔案拖入專案
iOS
智
慧
裝
置
軟
體
設
計
55
彭
亦
暄
複製檔案至專案
iOS
智
慧
裝
置
軟
體
設
計
56
彭
亦
暄
加入搜尋libxml2標頭檔路徑
iOS
$(SDKROOT)/usr/include/libxml2
智
慧
裝
置
軟
體
設
計
57
彭
亦
暄
連結libxml2 lib
iOS
智
慧
裝
置
軟
體
設
計
58
彭
亦
暄
TFHpple Class
+ (TFHpple *) hppleWithHTMLData:(NSData *)
theData encoding:(NSString *)encoding;
iOS
+ (TFHpple *) hppleWithHTMLData:(NSData *)
theData;
智
慧
裝
置
軟
體
設
計
- (NSArray *) searchWithXPathQuery:(NSString *)
xPathOrCSS;
59
彭
亦
暄
TFHppleElement Class
屬性
NSString *content;
• Returns this tag's innerHTML content
NSString *tagName;
NSDictionary *attributes;
iOS
• Returns tag attributes with name as key and content as
value.
智
慧
裝
置
軟
體
設
計
NSArray *children;
TFHppleElement *firstChild;
TFHppleElement *parent;
60
彭
亦
暄
TFHppleElement Class
方法
(BOOL)hasChildren;
(BOOL)isTextNode;
(NSString *) objectForKey:(NSString *) theKey;
• Provides easy access to the content of a specific attribute
iOS
(NSArray *) childrenWithTagName:(NSString *)
tagName;
智
慧
裝
置
軟
體
設
計
• Returns the children whose tag name equals the given
string
• Returns an empty array if no matching child is found
61
彭
亦
暄
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
iOS
(NSArray *) childrenWithClassName:(NSString *)
className;
智
慧
裝
置
軟
體
設
計
• Returns the children whose class equals the given string
(TFHppleElement *) firstChildWithClassName:
(NSString*)className;
62
彭
亦
暄
TFHppleElement Class
方法
(TFHppleElement *) firstTextChild;
• Returns the first text node from this
element's children
iOS
(NSString *) text;
• Returns the string contained by the first
text node from this element's children
• can be used instead of
firstTextChild.content
智
慧
裝
置
軟
體
設
計
63
彭
亦
暄
iOS
智
慧
裝
置
軟
體
設
計
64
彭
亦
暄
.m
iOS
NSURL *tutorialsUrl = [NSURL URLWithString:@"http://localhost/web.php"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
NSString *tutorialsXpathQueryString =
@"//div[@class='content-wrapper']/ul/li/a";
NSArray *tutorialsNodes = [tutorialsParser
searchWithXPathQuery:tutorialsXpathQueryString];
for (TFHppleElement *element in tutorialsNodes)
智
{
慧
NSString *title = [[element firstChild] content];
裝
置
NSString *url = [element objectForKey:@"href"];
軟
NSLog(@"%@,%@",title,url);
體
設
}
計
65
彭
亦
暄
練習
iOS
台鐵時刻表
http://twtraffic.tra.gov.tw/twrail/SearchResult.aspx?
searchtype=0&searchdate=2014/12/25&fromcity=&
tocity=&fromstation=1008&tostation=1015&traincla
ss=2&fromtime=0000&totime=2359
xPath解析Html
智
慧
裝
置
軟
體
設
計
66
彭
亦
暄