Guest User

CIALBrowserViewController.m

a guest
Jun 17th, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 40.89 KB | None | 0 0
  1. //
  2. //  CIALBrowserViewController.m
  3. //  CIALBrowser
  4. //
  5. //  Created by Sylver Bruneau on 01/09/10.
  6. //  Copyright 2011 CodeIsALie. All rights reserved.
  7. //
  8.  
  9. #import "CIALBrowser.h"
  10. #import "CIALBrowserViewController.h"
  11. #import "UIWebViewAdditions.h"
  12. #import "UnpreventableUILongPressGestureRecognizer.h"
  13.  
  14. @interface CIALBrowserViewController ()
  15. - (void)addBookmark;
  16. - (void)updateLoadingStatus;
  17. - (void)longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer;
  18.  
  19. - (void)goBack:(id)sender;
  20. - (void)goForward:(id)sender;
  21. - (void)goHome:(id)sender;
  22. - (void)reloadOrStop:(id)sender;
  23. - (void)loadURL:(NSURL *)url;
  24.  
  25. - (void)dismiss:(id)sender;
  26. @end
  27.  
  28. @implementation CIALBrowserViewController
  29.  
  30. @synthesize bookmarkPopoverController = _bookmarkPopoverController;
  31. @synthesize addBookmarkPopoverController = _addBookmarkPopoverController;
  32. @synthesize actionActionSheet = _actionActionSheet;
  33. @synthesize modal = _modal;
  34. @synthesize enabledSafari = _enabledSafari;
  35.  
  36. + (CIALBrowserViewController *)modalBrowserViewControllerWithURL:(NSURL *)url
  37. {
  38.     CIALBrowserViewController *controller = [[[self alloc] initWithURL:url] autorelease];
  39.     controller.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  40.     controller.modal = YES;
  41.     return controller;
  42. }
  43.  
  44. /* DELETEME: default is nil
  45. - (id)init {
  46.     self = [super init];
  47.     if (self) {
  48.         _urlToLoad = nil;
  49.         req = nil;
  50.     }
  51.     return self;
  52. }
  53. */
  54.  
  55. - (id)initWithURL:(NSURL *)url  {
  56.     self = [super init];
  57.     if (self) {
  58.         [self setURL:url];
  59.     }
  60.     return self;
  61. }
  62.  
  63. - (void)loadView {
  64.     self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  65.     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
  66.     self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  67.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  68.         // Toolbar
  69.         toolBar = [[[UIToolbar alloc] initWithFrame:CGRectZero] autorelease];
  70.         navigationBar.tintColor = [UIColor darkGrayColor];
  71.         self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  72.         toolBar.barStyle = UIBarStyleDefault;
  73.         [toolBar sizeToFit];
  74.         toolBar.autoresizesSubviews = NO;
  75.         toolBar.frame = CGRectMake(0,
  76.                                    0,
  77.                                    self.view.frame.size.width,
  78.                                    toolBar.frame.size.height);
  79.         toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  80.        
  81.         NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:9];
  82.         UIBarButtonItem *flexibleSpaceButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
  83.                                                                                                   target:nil
  84.                                                                                                   action:nil] autorelease];
  85.         backButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserBack.png"]
  86.                                                            style:UIBarButtonItemStylePlain
  87.                                                           target:self
  88.                                                           action:@selector(goBack:)] autorelease];
  89.         forwardButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserForward.png"]
  90.                                                               style:UIBarButtonItemStylePlain
  91.                                                              target:self
  92.                                                              action:@selector(goForward:)] autorelease];
  93.         homeButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home.png"]
  94.                                                               style:UIBarButtonItemStylePlain
  95.                                                              target:self
  96.                                                              action:@selector(goHome:)] autorelease];
  97.  
  98.         UIBarButtonItem *bookmarkButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
  99.                                                                                              target:self
  100.                                                                                              action:@selector(viewBookmark:)] autorelease];
  101.         actionButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
  102.                                                                           target:self
  103.                                                                           action:@selector(actionButton:)] autorelease];
  104.        
  105.        
  106.         locationField = [[UITextField alloc] initWithFrame:CGRectMake(37,7,246,31)];
  107.         locationField.delegate = self;
  108.         locationField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  109.         locationField.textColor = [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1.0];
  110.         locationField.textAlignment = UITextAlignmentLeft;
  111.         locationField.borderStyle = UITextBorderStyleRoundedRect;
  112.         locationField.font = [UIFont fontWithName:@"Helvetica" size:15];
  113.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  114.         locationField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
  115.         locationField.clearsOnBeginEditing = NO;
  116.         locationField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  117.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  118.         locationField.keyboardType = UIKeyboardTypeURL;
  119.         locationField.returnKeyType = UIReturnKeyGo;        
  120.         locationField.clearButtonMode = UITextFieldViewModeWhileEditing;
  121.         [self.navigationItem setTitleView:locationField];
  122.         // reloadButton
  123.         stopReloadButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  124.         stopReloadButton.bounds = CGRectMake(0, 0, 26, 30);
  125.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateNormal];
  126.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateHighlighted];
  127.         stopReloadButton.showsTouchWhenHighlighted = NO;
  128.         [stopReloadButton addTarget:self action:@selector(reloadOrStop:) forControlEvents:UIControlEventTouchUpInside];
  129.         locationField.rightView = stopReloadButton;
  130.         locationField.rightViewMode = UITextFieldViewModeUnlessEditing;
  131.  
  132.         UIBarButtonItem *textFieldItem = [[[UIBarButtonItem alloc] initWithCustomView:locationField] autorelease];
  133.  
  134.         [buttons addObject:flexibleSpaceButtonItem];
  135.         [buttons addObject:backButtonItem];
  136.         [buttons addObject:flexibleSpaceButtonItem];
  137.         [buttons addObject:bookmarkButtonItem];
  138.         [buttons addObject:flexibleSpaceButtonItem];
  139.         [buttons addObject:actionButtonItem];
  140.         [buttons addObject:flexibleSpaceButtonItem];
  141.         [buttons addObject:homeButtonItem];
  142.         [buttons addObject:flexibleSpaceButtonItem];
  143.         [buttons addObject:textFieldItem];
  144.         [buttons addObject:flexibleSpaceButtonItem];
  145.         [buttons addObject:forwardButtonItem];
  146.        
  147.         /*
  148.         if (self.isModal) {
  149.             NSString *closeTitle = CIALBrowserLocalizedString(@"Close", nil);
  150.             closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:closeTitle style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss:)];
  151.             navigationItem.rightBarButtonItem = closeButtonItem;
  152.             [buttons addObject:closeButtonItem];
  153.         } else {
  154.             [buttons addObject:flexibleSpaceButtonItem];
  155.         }
  156.          */
  157.        
  158.         [toolBar setItems:buttons];
  159.         [self.view addSubview:toolBar];
  160.        
  161.         // webView
  162.         webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, toolBar.frame.size.height , self.view.frame.size.width, self.view.frame.size.height - toolBar.frame.size.height)];
  163.         webView.scalesPageToFit = YES;
  164.         webView.contentMode = UIViewContentModeScaleToFill;
  165.         webView.multipleTouchEnabled = YES;
  166.         webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  167.         [self.view addSubview:webView];
  168.         [webView release];
  169.     } else {
  170.         navigationItem = [[UINavigationItem alloc] initWithTitle:nil];
  171.         // titleView
  172.         locationField = [[UITextField alloc] initWithFrame:CGRectMake(37,7,300,31)];
  173.         locationField.delegate = self;
  174.         locationField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  175.         locationField.textColor = [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1.0];
  176.         locationField.textAlignment = UITextAlignmentLeft;
  177.         locationField.borderStyle = UITextBorderStyleRoundedRect;
  178.         locationField.font = [UIFont fontWithName:@"Helvetica" size:15];
  179.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  180.         locationField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
  181.         locationField.clearsOnBeginEditing = NO;
  182.        
  183.         locationField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  184.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  185.         locationField.keyboardType = UIKeyboardTypeURL;
  186.         locationField.returnKeyType = UIReturnKeyGo;
  187.        
  188.         locationField.clearButtonMode = UITextFieldViewModeWhileEditing;
  189.        
  190.         // reloadButton
  191.         stopReloadButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  192.         stopReloadButton.bounds = CGRectMake(0, 0, 26, 30);
  193.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateNormal];
  194.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateHighlighted];
  195.         stopReloadButton.showsTouchWhenHighlighted = NO;
  196.         [stopReloadButton addTarget:self action:@selector(reloadOrStop:) forControlEvents:UIControlEventTouchUpInside];
  197.         locationField.rightView = stopReloadButton;
  198.         locationField.rightViewMode = UITextFieldViewModeUnlessEditing;
  199.        
  200.         navigationItem.titleView = locationField;
  201.        
  202.         if (self.isModal) {
  203.             NSString *closeTitle = CIALBrowserLocalizedString(@"Close", nil);
  204.             closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:closeTitle style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss:)];
  205.             navigationItem.rightBarButtonItem = closeButtonItem;
  206.         }
  207.        
  208.         navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
  209.         self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  210.         navigationBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  211.         [navigationBar setItems:[NSArray arrayWithObject:navigationItem]];
  212.         [self.view addSubview:navigationBar];
  213.         [navigationBar release];
  214.        
  215.         // Toolbar
  216.         toolBar = [[[UIToolbar alloc] initWithFrame:CGRectZero] autorelease];
  217.         toolBar.barStyle = UIBarStyleDefault;
  218.         toolBar.tintColor = [UIColor darkGrayColor];
  219.         [toolBar sizeToFit];
  220.         toolBar.autoresizesSubviews = NO;
  221.         toolBar.frame = CGRectMake(0,
  222.                                    self.view.frame.size.height-toolBar.frame.size.height,
  223.                                    self.view.frame.size.width,
  224.                                    toolBar.frame.size.height);
  225.         toolBar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
  226.        
  227.         NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:9];
  228.         UIBarButtonItem *flexibleSpaceButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
  229.                                                                                                   target:nil
  230.                                                                                                   action:nil] autorelease];
  231.         backButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserBack.png"]
  232.                                                            style:UIBarButtonItemStylePlain
  233.                                                           target:self
  234.                                                           action:@selector(goBack:)] autorelease];
  235.         forwardButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserForward.png"]
  236.                                                               style:UIBarButtonItemStylePlain
  237.                                                              target:self
  238.                                                              action:@selector(goForward:)] autorelease];
  239.         actionButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
  240.                                                                           target:self
  241.                                                                           action:@selector(actionButton:)] autorelease];
  242.         UIBarButtonItem *bookmarkButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
  243.                                                                                              target:self
  244.                                                                                              action:@selector(viewBookmark:)] autorelease];
  245.        
  246.         [buttons addObject:flexibleSpaceButtonItem];
  247.         [buttons addObject:backButtonItem];
  248.         [buttons addObject:flexibleSpaceButtonItem];
  249.         [buttons addObject:actionButtonItem];
  250.         [buttons addObject:flexibleSpaceButtonItem];
  251.         [buttons addObject:homeButtonItem];
  252.         [buttons addObject:flexibleSpaceButtonItem];
  253.         [buttons addObject:bookmarkButtonItem];
  254.         [buttons addObject:flexibleSpaceButtonItem];
  255.         [buttons addObject:forwardButtonItem];
  256.         [buttons addObject:flexibleSpaceButtonItem];
  257.        
  258.         [toolBar setItems:buttons];
  259.         [self.view addSubview:toolBar];
  260.        
  261.         // webView
  262.         webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, navigationBar.frame.size.height , self.view.frame.size.width, self.view.frame.size.height - navigationBar.frame.size.height - toolBar.frame.size.height)];
  263.         webView.scalesPageToFit = YES;
  264.         webView.contentMode = UIViewContentModeScaleToFill;
  265.         webView.multipleTouchEnabled = YES;
  266.         webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  267.         [self.view addSubview:webView];
  268.         [webView release];
  269.     }
  270.  
  271.     // Create a long press recognizer for handling links long press
  272.     UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressRecognized:)];
  273.     longPressRecognizer.allowableMovement = 20;
  274.     longPressRecognizer.minimumPressDuration = 1.0f;
  275.     [webView addGestureRecognizer:longPressRecognizer];
  276.     [longPressRecognizer release];
  277. }
  278.  
  279. - (void)dealloc {
  280.     // Stop the spinner
  281.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  282.    
  283.     webView.delegate = nil;
  284.     [webView release],webView = nil;
  285.     [backButtonItem release],backButtonItem = nil;
  286.     [forwardButtonItem release],forwardButtonItem = nil;
  287.     [bookmarkButton release],bookmarkButton = nil;
  288.     [stopReloadButton release],stopReloadButton = nil;
  289.     [locationField release],locationField = nil;
  290.     [closeButtonItem release], closeButtonItem = nil;
  291.     [navigationBar release],navigationBar = nil;
  292.     [_urlToLoad release],_urlToLoad = nil;
  293.     [_urlToHandle release],_urlToHandle = nil;
  294.    
  295.     self.actionActionSheet = nil;
  296.    
  297.     [super dealloc];
  298. }
  299.  
  300. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  301.     // On iPad, allow any orientation
  302.     // On iPhone/iPod Touch, allow any orientation but upside down portrait
  303.     BOOL allowRotate = YES;
  304.     if ((UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) && (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))  {
  305.         allowRotate = NO;
  306.     }
  307.     if ([_longPressActionSheet isVisible]) {
  308.         allowRotate = NO;
  309.     }
  310.     return allowRotate;
  311. }
  312.  
  313. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  314.     // The height of the toolbar is changing according to orientation, resize the webview occording to this
  315.     if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
  316.         if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
  317.             webView.frame = CGRectMake(0, navigationBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - navigationBar.frame.size.height - toolBar.frame.size.height);
  318.         } else {
  319.             webView.frame = CGRectMake(0, navigationBar.frame.size.height, self.view.frame.size.height, self.view.frame.size.width - navigationBar.frame.size.height - toolBar.frame.size.height);
  320.         }
  321.     }
  322. }
  323.  
  324. #pragma mark -
  325.  
  326. - (void) viewDidLoad {
  327.     [super viewDidLoad];
  328.     self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  329.    
  330.     // Load WiHome
  331.     NSString *urlAddress = @"http://www.google.com";
  332.     NSURL *url = [NSURL URLWithString:urlAddress];
  333.    
  334.     //URL Requst Object
  335.     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
  336.    
  337.     //Load the request in the UIWebView.
  338.     [webView loadRequest:requestObj];
  339.    
  340.    
  341.     [self updateLoadingStatus];
  342.    
  343.     if (_urlToLoad) {
  344.         [self loadURL:_urlToLoad];
  345.     } else {
  346.         [locationField becomeFirstResponder];
  347.     }
  348. }
  349.  
  350. #pragma mark -
  351.  
  352. - (void)loadURL:(NSURL *)url {
  353.     if (!webView) {
  354.         [self setURL:url];
  355.         return;
  356.     }
  357.    
  358.     if (!url) return;
  359.    
  360.     locationField.text = url.absoluteString;
  361.    
  362.     [webView loadRequest:[NSURLRequest requestWithURL:url]];
  363. }
  364.  
  365. - (void)goBack:(id) sender {
  366.     [webView goBack];
  367.    
  368.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  369.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  370. }
  371.  
  372. - (void)goForward:(id) sender {
  373.     [webView goForward];
  374.    
  375.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  376.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  377. }
  378.  
  379. - (void)goHome:(id)sender {
  380.     NSURL *url = [NSURL URLWithString:@"http://google.ca/"];
  381.     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
  382.     [webView loadRequest:requestObj];
  383. }
  384.  
  385. - (void)reloadOrStop:(id) sender {
  386.     if (webView.loading)
  387.         [webView stopLoading];
  388.     else [webView reload];
  389. }
  390.  
  391. - (NSURL *)url {
  392.     NSURL *url = [NSURL URLWithString:locationField.text];
  393.     if (!url.scheme.length && locationField.text.length) url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]];
  394.     return url;
  395. }
  396.  
  397. #pragma mark -
  398. #pragma mark UITextField delegate
  399.  
  400. - (void)setURL:(NSURL *)url
  401. {
  402.     NSString *urlString = url.absoluteString;
  403.     if ([urlString length]) {
  404.         if (!url.scheme.length) {
  405.             url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
  406.         }
  407.         [_urlToLoad release];
  408.         _urlToLoad = [url copy];
  409.     }
  410. }
  411.  
  412. - (BOOL) textFieldShouldReturn:(UITextField *) textField {
  413.     NSURL *url = [NSURL URLWithString:locationField.text];
  414.    
  415.     // if user didn't enter "http", add it the the url
  416.     if (!url.scheme.length) {
  417.         url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]];
  418.     }
  419.    
  420.     [self loadURL:url];
  421.    
  422.     [locationField resignFirstResponder];
  423.    
  424.     return YES;
  425. }
  426.  
  427. #pragma mark -
  428.  
  429. - (void) updateLocationField {
  430.     NSString *location = webView.request.URL.absoluteString;
  431.     if (location.length)
  432.         locationField.text = webView.request.URL.absoluteString;
  433. }
  434.  
  435. - (void) updateLoadingStatus {
  436.     UIImage *image = nil;
  437.     if (webView.loading) {
  438.         image = [UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewStop.png"];
  439.        
  440.         [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  441.     } else {
  442.         image = [UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"];
  443.        
  444.         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  445.     }
  446.    
  447.     [stopReloadButton setImage:image forState:UIControlStateNormal];
  448.    
  449.     // update status of back/forward buttons
  450.     backButtonItem.enabled = [webView canGoBack];
  451.     forwardButtonItem.enabled = [webView canGoForward];
  452. }
  453.  
  454. #pragma mark -
  455. #pragma mark UIWebView delegate
  456.  
  457. - (BOOL)webView:(UIWebView *) sender shouldStartLoadWithRequest:(NSURLRequest *) request navigationType:(UIWebViewNavigationType) navigationType {
  458.     if ([request.URL.absoluteString isEqual:@"about:blank"])
  459.         return NO;
  460.     [req release];
  461.     req = (NSMutableURLRequest *)[request retain];
  462.    
  463.     return YES;
  464. }
  465.  
  466. - (void) webViewDidStartLoad:(UIWebView *) sender {
  467.     [self updateLoadingStatus];
  468. }
  469.  
  470. - (void) webViewDidFinishLoad:(UIWebView *) sender {
  471.     // Disable the defaut actionSheet when doing a long press
  472.     [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
  473.     [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
  474.    
  475.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  476.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  477.    
  478.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLoadingStatus) object:nil];
  479.     [self performSelector:@selector(updateLoadingStatus) withObject:nil afterDelay:1.];
  480. }
  481.  
  482. - (void) webView:(UIWebView *)sender didFailLoadWithError:(NSError *) error {
  483.     switch ([error code]) {
  484.         case kCFURLErrorCancelled :
  485.         {
  486.             // Do nothing in this case
  487.             break;
  488.         }
  489.         default:
  490.         {
  491.             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CIALBrowserLocalizedString(@"Error",@"")
  492.                                                             message:[error localizedDescription]
  493.                                                            delegate:nil
  494.                                                   cancelButtonTitle:CIALBrowserLocalizedString(@"OK",@"")
  495.                                                   otherButtonTitles:nil];
  496.             [alert show];    
  497.             [alert release];
  498.             break;
  499.         }
  500.     }
  501.    
  502.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  503.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  504.    
  505.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLoadingStatus) object:nil];
  506.     [self performSelector:@selector(updateLoadingStatus) withObject:nil afterDelay:1.];
  507. }
  508.  
  509. #pragma mark actions -
  510.  
  511. - (void)dismiss:(id)sender
  512. {
  513.     [self dismissModalViewControllerAnimated:YES];
  514. }
  515.  
  516.  
  517. #pragma mark -
  518. #pragma mark UIBarButtonItem functions
  519.  
  520. - (void)viewBookmark:(UIBarButtonItem *)button {
  521.     // Make other popover disappear
  522.     if ([self.actionActionSheet isVisible]) {
  523.         [self.actionActionSheet dismissWithClickedButtonIndex:self.actionActionSheet.cancelButtonIndex
  524.                                                      animated:YES];
  525.     }
  526.    
  527.     if ([self.addBookmarkPopoverController isPopoverVisible]) {
  528.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  529.     }
  530.  
  531.     if (printInteraction != nil) {
  532.         [printInteraction dismissAnimated:YES];
  533.         printInteraction = nil;
  534.     }
  535.  
  536.     // Create the popover or make it disappear if needed
  537.     if (self.bookmarkPopoverController.popoverVisible) {
  538.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  539.         self.bookmarkPopoverController = nil;
  540.     } else {
  541.         ViewBookmarkViewController * viewBookmarkViewController = [[[ViewBookmarkViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
  542.         viewBookmarkViewController.delegate = self;
  543.         [viewBookmarkViewController setBookmark:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]
  544.                                         url:self.url];
  545.         UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewBookmarkViewController] autorelease];
  546.         navController.navigationBar.tintColor = [UIColor darkGrayColor];
  547.         navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  548.         [navController.navigationBar setTintColor:[UIColor colorWithRed:100/255.0
  549.                                                                   green:51.0/255.0
  550.                                                                    blue:102.0/255.0
  551.                                                                   alpha:1.0]];
  552.         [navController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
  553.        
  554.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  555.             self.bookmarkPopoverController = [[[UIPopoverController alloc] initWithContentViewController:navController] autorelease];
  556.             [self.bookmarkPopoverController presentPopoverFromBarButtonItem:button
  557.                                                    permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
  558.                                                                    animated:YES];
  559.         } else {
  560.             [self presentModalViewController:navController animated:YES];
  561.         }
  562.     }
  563.  
  564. }
  565.  
  566. - (void)addBookmark {
  567.     AddBookmarkViewController * addBookmarkViewController = [[[AddBookmarkViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
  568.     [addBookmarkViewController setBookmark:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]
  569.                                        url:self.url];
  570.     addBookmarkViewController.delegate = self;
  571.     UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:addBookmarkViewController] autorelease];
  572.    
  573.     navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  574.    
  575.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  576.         self.addBookmarkPopoverController = [[[UIPopoverController alloc] initWithContentViewController:navController] autorelease];
  577.         self.addBookmarkPopoverController.popoverContentSize = CGSizeMake(320.0, 150.0);
  578.         [self.addBookmarkPopoverController presentPopoverFromBarButtonItem:actionButtonItem
  579.                                                permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
  580.                                                                animated:YES];
  581.     } else {
  582.         [self presentModalViewController:navController animated:YES];
  583.     }
  584. }
  585.  
  586. - (void)actionButton:(UIBarButtonItem *)button {
  587.     if ([self.bookmarkPopoverController isPopoverVisible]) {
  588.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  589.     }
  590.     if ([self.addBookmarkPopoverController isPopoverVisible]) {
  591.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  592.         // addBookmarkPopoverController is created by this actionSheet
  593.         // if this button is tapped, make the popover disappear and don't create the actionSheet
  594.         return;
  595.     }
  596.    
  597.     if (printInteraction != nil) {
  598.         [printInteraction dismissAnimated:YES];
  599.         printInteraction = nil;
  600.         // printInteraction is created by this actionSheet
  601.         // if this button is tapped, make it disappear and don't create the actionSheet
  602.         return;
  603.     }
  604.    
  605.     // Create the actionSheet or make it disappear if needed
  606.     if (!self.actionActionSheet) {
  607.         self.actionActionSheet = [[UIActionSheet alloc] initWithTitle:[_urlToHandle.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
  608.                                                          delegate:self
  609.                                                 cancelButtonTitle:nil
  610.                                            destructiveButtonTitle:nil
  611.                                                 otherButtonTitles:nil];
  612.         self.actionActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
  613.        
  614.         copyButtonIndex = -1;
  615.         openLinkButtonIndex = -1;
  616.         addBookmarkButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Add bookmark",nil)];
  617.        
  618.         if (self.enabledSafari) {
  619.             openWithSafariButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Open with Safari",@"")];
  620.         } else {
  621.             openWithSafariButtonIndex = -1;
  622.         }
  623.        
  624.         if ([MFMailComposeViewController canSendMail]) {
  625.             sendUrlButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Mail Link to this Page",@"")];
  626.         }
  627.        
  628.         Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");
  629.         if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable]) {
  630.             printButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Print",@"")];
  631.         } else {
  632.             printButtonIndex = -1;
  633.         }
  634.        
  635.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  636.             self.actionActionSheet.cancelButtonIndex = -1;
  637.         } else {
  638.             self.actionActionSheet.cancelButtonIndex = [_actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Cancel",@"")];
  639.         }
  640.     }
  641.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  642.         if (_actionActionSheet.visible) {
  643.             [_actionActionSheet dismissWithClickedButtonIndex:_actionActionSheet.cancelButtonIndex
  644.                                                      animated:YES];
  645.         } else {
  646.             [_actionActionSheet showFromBarButtonItem:button animated:YES];
  647.         }
  648.     } else {
  649.         [_actionActionSheet showInView:self.view];
  650.     }
  651. }
  652.  
  653. #pragma mark -
  654. #pragma mark UIActionSheet delegate
  655.  
  656. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  657.     if (copyButtonIndex == buttonIndex) {
  658.         NSLog(@"url : %@",_urlToHandle);
  659.         NSString *urlString;
  660.         if (req != nil) {
  661.             urlString = [req.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  662.         } else {
  663.             urlString = [_urlToHandle.absoluteString  stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  664.         }
  665.        
  666.         UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
  667.        
  668.         [pasteBoard setValue:urlString forPasteboardType:@"public.utf8-plain-text"];
  669.     } else if (openLinkButtonIndex == buttonIndex) {
  670.         NSLog(@"url : %@",_urlToHandle);
  671.         [self loadURL:_urlToHandle];
  672.         _urlToHandle = nil;
  673.     } else if (addBookmarkButtonIndex == buttonIndex) {
  674.         [self addBookmark];
  675.     } else if (openWithSafariButtonIndex == buttonIndex) {
  676.         [[UIApplication sharedApplication] openURL:self.url];
  677.     } else if (sendUrlButtonIndex == buttonIndex) {
  678.         MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
  679.         [mailViewController setSubject:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
  680.         [mailViewController setMessageBody:[self.url absoluteString]
  681.                                     isHTML:NO];
  682.        
  683.         mailViewController.mailComposeDelegate = self;
  684.        
  685.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  686.             mailViewController.modalPresentationStyle = UIModalPresentationPageSheet;
  687.         }
  688.        
  689.         [self presentModalViewController:mailViewController animated:YES];
  690.         [mailViewController release];
  691.     } else if (printButtonIndex == buttonIndex) {
  692.         Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");
  693.        
  694.         if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable])
  695.         {
  696.             printInteraction = [printInteractionController sharedPrintController];
  697.             printInteraction.delegate = self;
  698.            
  699.             UIPrintInfo *printInfo = [NSClassFromString(@"UIPrintInfo") printInfo];
  700.            
  701.             printInfo.duplex = UIPrintInfoDuplexLongEdge;
  702.             printInfo.outputType = UIPrintInfoOutputGeneral;
  703.             printInfo.jobName = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
  704.            
  705.             printInteraction.printInfo = printInfo;
  706.             printInteraction.showsPageRange = YES;
  707.            
  708.             UIViewPrintFormatter *formatter = [webView viewPrintFormatter];
  709.             printInteraction.printFormatter = formatter;
  710.            
  711.             [printInteraction presentFromBarButtonItem:actionButtonItem
  712.                                               animated:YES
  713.                                      completionHandler:
  714.              ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
  715.              }
  716.              ];
  717.         }
  718.     }
  719.    
  720.     if (req != nil) {
  721.         [req release];
  722.         req = nil;
  723.     }    
  724. }
  725.  
  726. - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
  727. {
  728.     if (actionSheet == _longPressActionSheet)
  729.     {
  730.         _longPressActionSheet = nil;
  731.     }
  732. }
  733.  
  734. #pragma mark -
  735. #pragma mark MFMailComposeViewController delegates
  736.  
  737. - (void)mailComposeController:(MFMailComposeViewController*)controller
  738.           didFinishWithResult:(MFMailComposeResult)result
  739.                         error:(NSError*)error {
  740.     [self dismissModalViewControllerAnimated:YES];
  741.    
  742.     NSString *mailError = nil;
  743.    
  744.     switch (result) {
  745.         case MFMailComposeResultSent:
  746.             break;
  747.         case MFMailComposeResultFailed:
  748.             mailError = CIALBrowserLocalizedString(@"Failed sending email, please try again...",@"");
  749.             break;
  750.         default:
  751.             break;
  752.     }
  753.    
  754.     if (mailError != nil) {
  755.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
  756.                                                         message:mailError
  757.                                                        delegate:nil
  758.                                               cancelButtonTitle:@"OK"
  759.                                               otherButtonTitles:nil];
  760.         [alert show];
  761.         [alert release];
  762.     }
  763. }
  764.  
  765. #pragma mark -
  766. #pragma mark UIPrintInteractionControllerDelegate
  767. - (void)printInteractionControllerDidDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController {
  768.     NSLog(@"printInteractionControllerDidDismissPrinterOptions");
  769.     printInteraction = nil;
  770. }
  771.  
  772. #pragma mark -
  773. #pragma mark UILongPressGestureRecognizer handling
  774.  
  775. - (void)longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer {
  776.     if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
  777.         CGPoint point = [gestureRecognizer locationInView:webView];
  778.        
  779.         // convert point from view to HTML coordinate system
  780.         CGSize viewSize = [webView frame].size;
  781.         CGSize windowSize = [webView windowSize];
  782.        
  783.         CGFloat f = windowSize.width / viewSize.width;
  784.         if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.) {
  785.             point.x = point.x * f;
  786.             point.y = point.y * f;
  787.         } else {
  788.             // On iOS 4 and previous, document.elementFromPoint is not taking
  789.             // offset into account, we have to handle it
  790.             CGPoint offset = [webView scrollOffset];
  791.             point.x = point.x * f + offset.x;
  792.             point.y = point.y * f + offset.y;
  793.         }
  794.                
  795.         // Load the JavaScript code from the Resources and inject it into the web page
  796.         NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"CIALBrowser" ofType:@"bundle"]];
  797.  
  798.         NSString *path = [bundle pathForResource:@"JSTools" ofType:@"js"];
  799.         NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  800.         [webView stringByEvaluatingJavaScriptFromString: jsCode];
  801.        
  802.         // get the Tags at the touch location
  803.         NSString *tags = [webView stringByEvaluatingJavaScriptFromString:
  804.                           [NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  805.        
  806.         NSString *tagsHREF = [webView stringByEvaluatingJavaScriptFromString:
  807.                               [NSString stringWithFormat:@"MyAppGetLinkHREFAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  808.        
  809.         NSString *tagsSRC = [webView stringByEvaluatingJavaScriptFromString:
  810.                              [NSString stringWithFormat:@"MyAppGetLinkSRCAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  811.         NSLog(@"tags : %@",tags);
  812.         NSLog(@"href : %@",tagsHREF);
  813.         NSLog(@"src : %@",tagsSRC);
  814.        
  815.         NSString *url = nil;
  816.         if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {
  817.             url = tagsSRC;
  818.         }
  819.         if ([tags rangeOfString:@",A,"].location != NSNotFound) {
  820.             url = tagsHREF;
  821.         }
  822.         NSLog(@"url : %@",url);
  823.        
  824.         NSArray *urlArray = [[url lowercaseString] componentsSeparatedByString:@"/"];
  825.         NSString *urlBase = nil;
  826.         if ([urlArray count] > 2) {
  827.             urlBase = [urlArray objectAtIndex:2];
  828.         }
  829.        
  830.         if ((url != nil) &&
  831.             ([url length] != 0)) {
  832.             // Release any previous request
  833.             [req release], req = nil;
  834.             // Save URL for the request
  835.             _urlToHandle = [[NSURL alloc] initWithString:url];
  836.            
  837.             // ask user what to do
  838.             _longPressActionSheet = [[UIActionSheet alloc] initWithTitle:[_urlToHandle.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
  839.                                                                 delegate:self
  840.                                                        cancelButtonTitle:nil
  841.                                                   destructiveButtonTitle:nil
  842.                                                        otherButtonTitles:nil];
  843.             _longPressActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
  844.            
  845.             openLinkButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Open",@"")];
  846.             copyButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Copy",@"")];
  847.            
  848.             if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  849.                 CGPoint touchPosition = [gestureRecognizer locationInView:webView];
  850.                 [_longPressActionSheet showFromRect:CGRectMake(touchPosition.x, touchPosition.y, 1, 1)
  851.                                              inView:webView
  852.                                            animated:YES];
  853.             } else {
  854.                 _longPressActionSheet.cancelButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Cancel",@"")];
  855.                 [_longPressActionSheet showInView:self.view];
  856.             }
  857.             [_longPressActionSheet release];
  858.         }        
  859.     }
  860. }
  861.  
  862. #pragma mark -
  863. #pragma mark Bookmark delegates
  864.  
  865. - (void)openThisURL:(NSURL *)url {
  866.     [self loadURL:url];
  867. }
  868.  
  869. - (void)dismissViewBookmMarkViewController:(ViewBookmarkViewController *)viewController {
  870.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  871.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  872.     } else {
  873.         [viewController dismissModalViewControllerAnimated:YES];
  874.     }
  875. }
  876.  
  877. #pragma mark -
  878. #pragma mark addBookmark delegates
  879.  
  880. - (void)dismissAddBookmMarkViewController:(AddBookmarkViewController *)viewController {
  881.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  882.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  883.     } else {
  884.         [viewController dismissModalViewControllerAnimated:YES];
  885.     }
  886. }
  887.  
  888. @end
Advertisement
Add Comment
Please, Sign In to add comment