SlideShare uma empresa Scribd logo
1 de 58
iPhone SDK


   UIWebView Tips
iPhone SDK




24/7 twenty-four seven
http://d.hatena.ne.jp/KishikawaKatsumi/
iPhone SDK




•     touch   •Subway Map
•LDR touch    •MyWebClip
•             •
•LCD Clock    •
iPhone SDK

http://github.com/kishikawakatsumi

•hatena-touch     •DescriptionBuilder
•ldr-touch        •TiledLayerView
•tv-listings      •UICCalendarPicker
•MapKit-Route-Directions
•FlipCardNavigationView
•PhotoFlipCardView
iPhone SDK


   UIWebView Tips
iPhone SDK

              UIWebView Tips
•                      •UI     UIWebView

•data URI scheme       •
•UIWebView
•JavaScript
•JavaScript
•JavaScript
iPhone SDK



•*.js
•
iPhone SDK
                     (1)

NSBundle *mainBundle = [NSBundle mainBundle];

NSString *path =
[mainBundle pathForResource:@"index.html"
              ofType:nil
           inDirectory:@"html"];

NSURL *fileURL = [NSURL fileURLWithPath:path];

[webView loadRequest:
 [NSURLRequest requestWithURL:fileURL]];
iPhone SDK
                        (2)

NSBundle *mainBundle = [NSBundle mainBundle];

NSString *path =
[mainBundle pathForResource:@"index.html"
              ofType:nil
           inDirectory:@"html"];
NSString *htmlContents =
[NSString stringWithContentsOfURL:fileURL
                encoding:NSUTF8StringEncoding
                  error:nil];

[webView
 loadHTMLString: htmlContents baseURL:path];
iPhone SDK



*.js
iPhone SDK
iPhone SDK
              OK

<script type="text/javascript" src="json2.js"></script>




NSString *path =
[[NSBundle mainBundle]
 pathForResource:@"index" ofType:@"html"];

[webView loadRequest:
 [NSURLRequest
  requestWithURL:[NSURL fileURLWithPath:path]]];
iPhone SDK
*.js
iPhone SDK


             Make Rule
iPhone SDK
iPhone SDK
iPhone SDK
iPhone SDK




NSString *path =
[mainBundle pathForResource:@"index.html"
              ofType:nil
           inDirectory:@"html"];
iPhone SDK




<img src="img/menu_line.png" width="260" height="1">
iPhone SDK


•
•                HTML
iPhone SDK

      data URI scheme

•    HTML
iPhone SDK
data URI scheme

<p>This is a data encoded image.</p>
<img src="data:image/jpeg;base64,/9j/
4AAQSkZJRgABAQEAYABgAAD/
2wBDAAEBAQEBAQEBAQEBAQEBAQICAQEBAQMCA
gICAwMEBAMDAwMEBAYFBAQFBAMDBQcFBQYGBg
YGBAUHBwcGBwYGBg
... +0lShKd4r3XzOLlePTXToYYHOc4w3C9WjTrzj
T5rcqlJKztdWTtZ9e5+p9FFFfsB8gf/2Q==" />
iPhone SDK

UIWebView
iPhone SDK

webView.opaque = NO;
webView.backgroundColor = [UIColor clearColor];


<style type="text/css">
    body {
         background-color: transparent;
    }
</style>
iPhone SDK

  JavaScript
iPhone SDK
JavaScript

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.title =
     [webView
      stringByEvaluatingJavaScriptFromString:@"document.title"];
}
iPhone SDK

JavaScript
iPhone SDK
in JavaScript

document.location = "app::" + "function::" + param1 + "::" + param2;




app::function::param1::param2
URL

               iPhone SDK
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {


   NSString *requestString = [[request URL] absoluteString];

   NSArray *params = [requestString componentsSeparatedByString:@"::"];


   if ([params count] > 1 &&

   
       [[params objectAtIndex:0] isEqualToString:@"app"]) {

   
       if([[params objectAtIndex:1] isEqualToString:@"function"]) {


   
     
    NSLog([params objectAtIndex:2]); // param1

   
     
    NSLog([params objectAtIndex:3]); // param2

   
     
    // Call your method in Objective-C method using the above...

   
     }

   
     return NO;

   }


   return YES; // Return YES to make sure regular navigation works as expected.
}
iPhone SDK
<script type="text/javascript">
 separator = "::";
 var directionsService = new google.maps.DirectionsService();

 function route(request) {
   directionsService.route(request, function(response, status) {
     if (status == google.maps.DirectionsStatus.OK) {
       document.location = "directions-v3" + separator + "route" +
separator + JSON.stringify(response);
     }
   });
 }
</script>
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
   NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));



                   iPhone SDK
     NSString *requestString = [[request URL] absoluteString];
     NSArray *params = [requestString componentsSeparatedByString:@"::"];

    NSString *function = [params objectAtIndex:0];

   if ([params count] > 1 && [function isEqualToString:@"directions-v3"]) {
       NSString *param1 = [params objectAtIndex:1];
       if([param1 isEqualToString:@"route"]) {
           NSString *param2 = [params objectAtIndex:2];
           id JSONValue = [[param2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
JSONValue];
           if (!JSONValue) {
               if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didFailWithMessage:)]) {
                   [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didFailWithMessage:param2];
               }
           } else {
               if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didGetObject:)]) {
                   [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didGetObject:JSONValue];
               }
           }
       }
       return NO;
   }


    return YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
   NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));



                   iPhone SDK
     NSString *requestString = [[request URL] absoluteString];
     NSArray *params = [requestString componentsSeparatedByString:@"::"];

    NSString *function = [params objectAtIndex:0];

   if ([params count] > 1 && [function isEqualToString:@"directions-v3"]) {
       NSString *param1 = [params objectAtIndex:1];
       if([param1 isEqualToString:@"route"]) {
           NSString *param2 = [params objectAtIndex:2];
           id JSONValue = [[param2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
JSONValue];
           if (!JSONValue) {
               if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didFailWithMessage:)]) {
                   [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didFailWithMessage:param2];
               }
           } else {
               if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didGetObject:)]) {
                   [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didGetObject:JSONValue];
               }
           }
       }
       return NO;
   }
                                  URL

    return YES;                 JSON
}
iPhone SDK

•      API (Google Maps API      )




              MapKit-Route-Directions
iPhone SDK

JavaScript
iPhone SDK
@interface UIWebView (JavaScriptDebug)
- (void)webView:(UIWebView *)sender
runJavaScriptAlertPanelWithMessage:(NSString *)message
            initiatedByFrame:(WebFrame *)frame;
@end

@implementation UIWebView (JavaScriptDebug)

- (void)webView:(UIWebView *)sender
runJavaScriptAlertPanelWithMessage:(NSString *)message
            initiatedByFrame:(WebFrame *)frame {
   NSLog(@"alert: %@", message);
}

@end


alert(item["name"]);
iPhone SDK


•        alert
•Unpublished API
iPhone SDK

    UI        UIWebView

•        HTML + CSS +JavaScript
iPhone SDK
iPhone SDK
•
iPhone SDK



•
•
•
•
•
iPhone SDK
<div id="tag_price" class="float_l">${price}</div>

<div id="tag_info" class="float_r"><img src="img/menu_tag_info.png" alt="Info"
width="76" height="39"></div></div><div id="menu"><div class="text">$
{comment}</div>

<div class="bar"><img src="img/menu_line.png" width="260" height="1"></
div>
<div class="text">
<span class="blue">    </span> ${advantage}
</div>
<div class="bar"><img src="img/menu_line.png" width="260" height="1"></
div>
<div class="text">
<span class="blue">    </span> ${spec}
iPhone SDK
- (void)viewDidLoad {
   [super viewDidLoad];


          self.title = [NSString stringWithUTF8String:"       "];

        NSBundle *mainBundle = [NSBundle mainBundle];
        NSString *path = [mainBundle pathForResource:@"index.html" ofType:nil inDirectory:@"html"];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        NSString *htmlContents = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${photo}" withString:@"photo.jpg"];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${name}" withString:[NSString stringWithUTF8String:"USB
    USB                 "]];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${price}" withString:[NSString stringWithUTF8String:"
    
      950   "]];
   htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${comment}" withString:[NSString
stringWithUTF8String:"ReadyBoost                        USB                 "]];
   htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${advantage}" withString:[NSString
stringWithUTF8String:"Windows      Vista ReadyBoost    "]];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${spec}" withString:[NSString stringWithUTF8String:"<br>
                    USB        Ver.2.0   <br>              USB A      <br>            DC 5V"]];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${size}" withString:[NSString stringWithUTF8String:"2 GB "]];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${color}" withString:[NSString stringWithUTF8String:"        "]];
        htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${count}" withString:[NSString stringWithUTF8String:"1      "]];
        [web loadHTMLString:htmlContents baseURL:fileURL];
}
iPhone SDK
iPhone SDK
iPhone SDK
CSS
<style type="text/css">
body {
   -webkit-user-select: none;
   -webkit-touch-callout: none;
}
</style>



JavaScript
<script type="text/javascript">
function OnLoad() {
  document.documentElement.style.webkitTouchCallout = "none";
  document.documentElement.style.webkitUserSelect = "none";
}
</script>
</head>
<body onload="OnLoad()">
iPhone SDK
iPhone SDK
iPhone SDK
CSS
-webkit-tap-highlight-color:rgba(163,215,112,0.70);
iPhone SDK
iPhone SDK

#import <Foundation/Foundation.h>

@interface FilteredWebCache : NSURLCache
{
}

@end
iPhone SDK
#import "FilteredWebCache.h"
#import "FilterManager.h"

@implementation FilteredWebCache

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
   NSURL *URL = [request URL];
   BOOL blockURL = [[FilterManager sharedFilterManager] shouldBlockURL:URL];
   if (blockURL) {
       LOG(@"!%@! was blocked.", URL);
       NSURLResponse *response = [[NSURLResponse alloc] initWithURL:URL
                                       MIMEType:@"text/plain"
                              expectedContentLength:1
                                  textEncodingName:nil];

      NSCachedURLResponse *cachedResponse =
      [[NSCachedURLResponse alloc] initWithResponse:response
                             data:[NSData dataWithBytes:" " length:1]];

      [super storeCachedResponse:cachedResponse forRequest:request];

      [cachedResponse release];
      [response release];
    }
    return [super cachedResponseForRequest:request];
}
iPhone SDK
- (void)viewDidLoad {
   [super viewDidLoad];

    NSArray *paths =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentDirectory = [paths objectAtIndex:0];

    NSString *path = [documentDirectory stringByAppendingPathComponent:@"cache.dat"];

  NSUInteger discCapacity = 10 * 1024 * 1024;
  NSUInteger memoryCapacity = 512 * 1024;

  FilteredWebCache *cache =
  [[FilteredWebCache alloc] initWithMemoryCapacity:memoryCapacity
                         diskCapacity:discCapacity diskPath:path];
  [NSURLCache setSharedURLCache:cache];
  [cache release];
iPhone SDK


•
iPhone SDK
iPhone SDK
http*://zedo.com*
http*://zencudo.co.uk*
http*://zmedia.com*
*/a.aspx?Zone*
*/a.thefreedictionary.*
*/adjs.php?*
*/ads.pl?*
*/ad.gif?*
*/ad1.jpg
*/adx2.js
http://*.images-amazon.com/*
http://*.ad.adlantis.jp/*
http://*.adlantis.jp/*.js*"
iPhone SDK
for (id whiteURL in whiteList) {
   NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF like[c] %@", whiteURL];
   if ([predicate evaluateWithObject:[URL absoluteString]]) {
       [loadedURLsOfCurrentPage addObject:URL];
       return NO;
   }
}




[@"SELF like[c] http://*.ad.adlantis.jp/*"
 evaluateWithObject:@"http://suiheiliebe.blog52.fc2.com/"]
iPhone SDK
iPhone SDK
NSPredicate *regex =
 [NSPredicate predicateWithFormat:
   @"SELF MATCHES 'https?://[a-zA-Z0-9/.?_+~=%:;!#-]+'"];
if ([regex evaluateWithObject:source]) {

Mais conteúdo relacionado

Mais procurados

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document ObjectArti Parab Academics
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2borkweb
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentationScott Messinger
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy stepsprince Loffar
 
Introduction to Parse backend for mobile developers
Introduction to Parse backend for mobile developersIntroduction to Parse backend for mobile developers
Introduction to Parse backend for mobile developersGrigor Yeghiazaryan
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
20131108 cs query by howard
20131108 cs query by howard20131108 cs query by howard
20131108 cs query by howardLearningTech
 

Mais procurados (20)

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Java script
Java scriptJava script
Java script
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
Java Script
Java ScriptJava Script
Java Script
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
Introduction to Parse backend for mobile developers
Introduction to Parse backend for mobile developersIntroduction to Parse backend for mobile developers
Introduction to Parse backend for mobile developers
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
20131108 cs query by howard
20131108 cs query by howard20131108 cs query by howard
20131108 cs query by howard
 

Semelhante a UIWebView Tips

I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)Katsumi Kishikawa
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Satoshi Asano
 
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III) Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III) Mobivery
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Filippo Matteo Riggio
 
PhoneGap_Javakuche0612
PhoneGap_Javakuche0612PhoneGap_Javakuche0612
PhoneGap_Javakuche0612Yuhei Miyazato
 
125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용NAVER D2
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Sarp Erdag
 
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014Fábio Pimentel
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordovaAyman Mahfouz
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the AirAvitoTech
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjCLin Luxiang
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platformsAyush Sharma
 
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Saulo Arruda
 

Semelhante a UIWebView Tips (20)

I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III) Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
 
iOS 7 SDK特訓班
iOS 7 SDK特訓班iOS 7 SDK特訓班
iOS 7 SDK特訓班
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
 
PhoneGap_Javakuche0612
PhoneGap_Javakuche0612PhoneGap_Javakuche0612
PhoneGap_Javakuche0612
 
125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용125 고성능 web view-deview 2013 발표 자료_공유용
125 고성능 web view-deview 2013 발표 자료_공유용
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
 
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordova
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
 

UIWebView Tips

  • 1. iPhone SDK UIWebView Tips
  • 2. iPhone SDK 24/7 twenty-four seven http://d.hatena.ne.jp/KishikawaKatsumi/
  • 3. iPhone SDK • touch •Subway Map •LDR touch •MyWebClip • • •LCD Clock •
  • 4. iPhone SDK http://github.com/kishikawakatsumi •hatena-touch •DescriptionBuilder •ldr-touch •TiledLayerView •tv-listings •UICCalendarPicker •MapKit-Route-Directions •FlipCardNavigationView •PhotoFlipCardView
  • 5. iPhone SDK UIWebView Tips
  • 6. iPhone SDK UIWebView Tips • •UI UIWebView •data URI scheme • •UIWebView •JavaScript •JavaScript •JavaScript
  • 8. iPhone SDK (1) NSBundle *mainBundle = [NSBundle mainBundle]; NSString *path = [mainBundle pathForResource:@"index.html" ofType:nil inDirectory:@"html"]; NSURL *fileURL = [NSURL fileURLWithPath:path]; [webView loadRequest: [NSURLRequest requestWithURL:fileURL]];
  • 9. iPhone SDK (2) NSBundle *mainBundle = [NSBundle mainBundle]; NSString *path = [mainBundle pathForResource:@"index.html" ofType:nil inDirectory:@"html"]; NSString *htmlContents = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil]; [webView loadHTMLString: htmlContents baseURL:path];
  • 12. iPhone SDK OK <script type="text/javascript" src="json2.js"></script> NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; [webView loadRequest: [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
  • 14. iPhone SDK Make Rule
  • 18. iPhone SDK NSString *path = [mainBundle pathForResource:@"index.html" ofType:nil inDirectory:@"html"];
  • 19. iPhone SDK <img src="img/menu_line.png" width="260" height="1">
  • 21. iPhone SDK data URI scheme • HTML
  • 22. iPhone SDK data URI scheme <p>This is a data encoded image.</p> <img src="data:image/jpeg;base64,/9j/ 4AAQSkZJRgABAQEAYABgAAD/ 2wBDAAEBAQEBAQEBAQEBAQEBAQICAQEBAQMCA gICAwMEBAMDAwMEBAYFBAQFBAMDBQcFBQYGBg YGBAUHBwcGBwYGBg ... +0lShKd4r3XzOLlePTXToYYHOc4w3C9WjTrzj T5rcqlJKztdWTtZ9e5+p9FFFfsB8gf/2Q==" />
  • 24. iPhone SDK webView.opaque = NO; webView.backgroundColor = [UIColor clearColor]; <style type="text/css"> body { background-color: transparent; } </style>
  • 25. iPhone SDK JavaScript
  • 26. iPhone SDK JavaScript - (void)webViewDidFinishLoad:(UIWebView *)webView { self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"]; }
  • 28. iPhone SDK in JavaScript document.location = "app::" + "function::" + param1 + "::" + param2; app::function::param1::param2
  • 29. URL iPhone SDK - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestString = [[request URL] absoluteString]; NSArray *params = [requestString componentsSeparatedByString:@"::"]; if ([params count] > 1 && [[params objectAtIndex:0] isEqualToString:@"app"]) { if([[params objectAtIndex:1] isEqualToString:@"function"]) { NSLog([params objectAtIndex:2]); // param1 NSLog([params objectAtIndex:3]); // param2 // Call your method in Objective-C method using the above... } return NO; } return YES; // Return YES to make sure regular navigation works as expected. }
  • 30. iPhone SDK <script type="text/javascript"> separator = "::"; var directionsService = new google.maps.DirectionsService(); function route(request) { directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { document.location = "directions-v3" + separator + "route" + separator + JSON.stringify(response); } }); } </script>
  • 31. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); iPhone SDK NSString *requestString = [[request URL] absoluteString]; NSArray *params = [requestString componentsSeparatedByString:@"::"]; NSString *function = [params objectAtIndex:0]; if ([params count] > 1 && [function isEqualToString:@"directions-v3"]) { NSString *param1 = [params objectAtIndex:1]; if([param1 isEqualToString:@"route"]) { NSString *param2 = [params objectAtIndex:2]; id JSONValue = [[param2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] JSONValue]; if (!JSONValue) { if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didFailWithMessage:)]) { [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didFailWithMessage:param2]; } } else { if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didGetObject:)]) { [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didGetObject:JSONValue]; } } } return NO; } return YES; }
  • 32. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); iPhone SDK NSString *requestString = [[request URL] absoluteString]; NSArray *params = [requestString componentsSeparatedByString:@"::"]; NSString *function = [params objectAtIndex:0]; if ([params count] > 1 && [function isEqualToString:@"directions-v3"]) { NSString *param1 = [params objectAtIndex:1]; if([param1 isEqualToString:@"route"]) { NSString *param2 = [params objectAtIndex:2]; id JSONValue = [[param2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] JSONValue]; if (!JSONValue) { if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didFailWithMessage:)]) { [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didFailWithMessage:param2]; } } else { if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didGetObject:)]) { [(id<UICGoogleMapsAPIDelegate>)delegate goolgeMapsAPI:self didGetObject:JSONValue]; } } } return NO; } URL return YES; JSON }
  • 33. iPhone SDK • API (Google Maps API ) MapKit-Route-Directions
  • 35. iPhone SDK @interface UIWebView (JavaScriptDebug) - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame; @end @implementation UIWebView (JavaScriptDebug) - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame { NSLog(@"alert: %@", message); } @end alert(item["name"]);
  • 36. iPhone SDK • alert •Unpublished API
  • 37. iPhone SDK UI UIWebView • HTML + CSS +JavaScript
  • 41. iPhone SDK <div id="tag_price" class="float_l">${price}</div> <div id="tag_info" class="float_r"><img src="img/menu_tag_info.png" alt="Info" width="76" height="39"></div></div><div id="menu"><div class="text">$ {comment}</div> <div class="bar"><img src="img/menu_line.png" width="260" height="1"></ div> <div class="text"> <span class="blue"> </span> ${advantage} </div> <div class="bar"><img src="img/menu_line.png" width="260" height="1"></ div> <div class="text"> <span class="blue"> </span> ${spec}
  • 42. iPhone SDK - (void)viewDidLoad { [super viewDidLoad]; self.title = [NSString stringWithUTF8String:" "]; NSBundle *mainBundle = [NSBundle mainBundle]; NSString *path = [mainBundle pathForResource:@"index.html" ofType:nil inDirectory:@"html"]; NSURL *fileURL = [NSURL fileURLWithPath:path]; NSString *htmlContents = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${photo}" withString:@"photo.jpg"]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${name}" withString:[NSString stringWithUTF8String:"USB USB "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${price}" withString:[NSString stringWithUTF8String:" 950 "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${comment}" withString:[NSString stringWithUTF8String:"ReadyBoost USB "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${advantage}" withString:[NSString stringWithUTF8String:"Windows Vista ReadyBoost "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${spec}" withString:[NSString stringWithUTF8String:"<br> USB Ver.2.0 <br> USB A <br> DC 5V"]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${size}" withString:[NSString stringWithUTF8String:"2 GB "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${color}" withString:[NSString stringWithUTF8String:" "]]; htmlContents = [htmlContents stringByReplacingOccurrencesOfString:@"${count}" withString:[NSString stringWithUTF8String:"1 "]]; [web loadHTMLString:htmlContents baseURL:fileURL]; }
  • 45. iPhone SDK CSS <style type="text/css"> body { -webkit-user-select: none; -webkit-touch-callout: none; } </style> JavaScript <script type="text/javascript"> function OnLoad() { document.documentElement.style.webkitTouchCallout = "none"; document.documentElement.style.webkitUserSelect = "none"; } </script> </head> <body onload="OnLoad()">
  • 50. iPhone SDK #import <Foundation/Foundation.h> @interface FilteredWebCache : NSURLCache { } @end
  • 51. iPhone SDK #import "FilteredWebCache.h" #import "FilterManager.h" @implementation FilteredWebCache - (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request { NSURL *URL = [request URL]; BOOL blockURL = [[FilterManager sharedFilterManager] shouldBlockURL:URL]; if (blockURL) { LOG(@"!%@! was blocked.", URL); NSURLResponse *response = [[NSURLResponse alloc] initWithURL:URL MIMEType:@"text/plain" expectedContentLength:1 textEncodingName:nil]; NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:[NSData dataWithBytes:" " length:1]]; [super storeCachedResponse:cachedResponse forRequest:request]; [cachedResponse release]; [response release]; } return [super cachedResponseForRequest:request]; }
  • 52. iPhone SDK - (void)viewDidLoad { [super viewDidLoad]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString *path = [documentDirectory stringByAppendingPathComponent:@"cache.dat"]; NSUInteger discCapacity = 10 * 1024 * 1024; NSUInteger memoryCapacity = 512 * 1024; FilteredWebCache *cache = [[FilteredWebCache alloc] initWithMemoryCapacity:memoryCapacity diskCapacity:discCapacity diskPath:path]; [NSURLCache setSharedURLCache:cache]; [cache release];
  • 56. iPhone SDK for (id whiteURL in whiteList) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[c] %@", whiteURL]; if ([predicate evaluateWithObject:[URL absoluteString]]) { [loadedURLsOfCurrentPage addObject:URL]; return NO; } } [@"SELF like[c] http://*.ad.adlantis.jp/*" evaluateWithObject:@"http://suiheiliebe.blog52.fc2.com/"]
  • 58. iPhone SDK NSPredicate *regex = [NSPredicate predicateWithFormat: @"SELF MATCHES 'https?://[a-zA-Z0-9/.?_+~=%:;!#-]+'"]; if ([regex evaluateWithObject:source]) {

Notas do Editor