objective-C delegates for webview AND alertviews


We have learned quite a lot about delegates, using generics (for delegates such as UIWebController) and when one can avoid using the generics (for such as AlertViews) while getting callbacks.

We continue to simply amend the tablecontroller (not that it shows any data from the api call) over which we overlaid our webview. The webview now demonstrates javascript/objective-c interworking – per various webposts I found and copied.

samplesTaskListTableViewController.m

  
//
//  samplesTaskListTableViewController.m
//  Microsoft Tasks
//
//  Created by Brandon Werner on 3/4/14.
//  Copyright (c) 2014 Microsoft. All rights reserved.
//

#import "samplesTaskListTableViewController.h"
#import "samplesTaskItem.h"
#import "sampleAddTaskItemViewController.h"
#import "samplesWebAPIConnector.h"
#import "ADALiOS/ADAuthenticationContext.h"

@interface samplesTaskListTableViewController ()

@property NSMutableArray *taskItems;
@property ADAuthenticationContext *authContext;

@end

@implementation samplesTaskListTableViewController

-(void)loadData {
    
    // Load data from the webservice
    [samplesWebAPIConnector getTaskList:^(NSArray *tasks, NSError* error) {
       
        self.webView.delegate = self;
        if (error != nil)
        {
            dispatch_async(dispatch_get_main_queue(),^ {
                NSString *htmlString = @"<html><body><h3><script>";
                htmlString = [htmlString stringByAppendingString: @"window.location=\"callmycode: OK to Try Again! &"];
               // htmlString = [htmlString stringByAppendingString:error.localizedDescription];
                htmlString = [htmlString stringByAppendingString:@"\""];
                htmlString = [htmlString stringByAppendingString:@"</script></h3></body></html>"];

                [self.webView loadHTMLString:htmlString baseURL:nil];
            });
        }
        else
        {
            self.taskItems = (NSMutableArray*)tasks;
            
            // Refresh main thread since we are async
            dispatch_async(dispatch_get_main_queue(), ^{
      //          [self.tableView reloadData];
                NSString *fullURL = @"https://ssoportal.rapmlsqa.com/SPInitiatedSSOHandler.aspx/BARS/6?wa=wsignin1.0&wtrealm=http://tablet.com/&wreply=http%3A%2F%2Fm.rapmlsqa.com%2FSPHandler.aspx%3FMls%3DBARS";
                NSURL *url = [NSURL URLWithString:fullURL];
                NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
                
                NSArray *cookiesForDomain = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"https://ssoportal.rapmlsqa.com/"]];
                
                NSMutableString *cookieStringToSet      = [[NSMutableString alloc] init];
                for (NSHTTPCookie *cookie in cookiesForDomain) {
                    [cookieStringToSet appendFormat:@"%@=%@;", cookie.name, cookie.value];
                }
                
                if (cookieStringToSet.length) {
                    [requestObj setValue:cookieStringToSet forHTTPHeaderField:@"Cookie"];
                }
                [_webView loadRequest:requestObj];

            });
        }
    }];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *URL = [request URL];
    if ([[URL scheme] isEqualToString:@"callmycode"]) {
        NSString *urlString = [[request URL] absoluteString];
        NSArray *urlParts = [urlString componentsSeparatedByString:@":"];
        //check to see if we just got the scheme
        if ([urlParts count] > 1) {
            NSArray *parameters = [[urlParts objectAtIndex:1] componentsSeparatedByString:@"&"];
            NSString *methodName = [[parameters objectAtIndex:0]stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
            NSString *variableName = [[parameters objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
            
            NSString *message = [NSString stringWithFormat:@"%@%@", methodName, variableName];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:message delegate: self cancelButtonTitle: nil otherButtonTitles: @"OK",nil, nil];
            [alert show];
        }
    } else {
        NSString *requestURL = [[request.URL absoluteString] lowercaseString];
    
        // Stop at the end URL.
        if ( [requestURL hasPrefix:@"https://ssoportal.rapmlsqa.com/ssologon"] )
        {
            [samplesWebAPIConnector signOut];
            [self loadData];
            return NO;
        }
    }
    return YES;
}

- (IBAction)pressedLogout:(id)sender {
    
    [samplesWebAPIConnector signOut];
    [self.taskItems removeAllObjects];
    
    // Refresh main thread since we are async
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
    
    [self loadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 //   [samplesWebAPIConnector signOut];
    self.refreshControl = [[UIRefreshControl alloc] init];
    
    [self.refreshControl addTarget:self action:@selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
    
    [self setRefreshControl:self.refreshControl];
    
    self.taskItems = [[NSMutableArray alloc] init];
    [self loadData];
    
}

-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
    // Refresh table here...
    [self.taskItems removeAllObjects];
    [self.tableView reloadData];
    [self loadData];
    [self.refreshControl endRefreshing];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.taskItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskPrototypeCell" forIndexPath:indexPath];
    
    samplesTaskItem *taskItem = [self.taskItems objectAtIndex:indexPath.row];
    cell.textLabel.text = taskItem.itemName;
    
    if (taskItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    samplesTaskItem *tappedItem = [self.taskItems objectAtIndex:indexPath.row];
    tappedItem.completed = !tappedItem.completed;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        [alertView dismissWithClickedButtonIndex:0 animated:NO];
        [samplesWebAPIConnector signOut];
        [self loadData];
    }
}

@end

Advertisements

About home_pw@msn.com

Computer Programmer who often does network administration with focus on security servers. Very strong in Microsoft Azure cloud!
This entry was posted in AAD. Bookmark the permalink.