Graduation

Well, after 4 years at LeTourneau University, I have achieved my end goal. I graduated Summa Cum Laude with a Bachelor degree in Computer Science and Mathematics and another Bachelor degree in Chemistry. I have spent four fabulous years at LeTourneau. I am thrilled to have finished my time at LeTourneau, and I am excited to begin a great job.  I want to thank my friends and classmates who have been a great source of friendship and support. I also want to thank my professors and the staff of LeTourneau for their tremendous investment in my life. They have been a blessing and an inspiration to me. 

Lessons From iOS: UISplitViewController

UISplitViewController is one of the fundamental view controllers for the iPad, but using it for the first time can present a challenge. A good example of a split view controller is the mail application. The sidebar(or popover in portrait) on the left lists emails or mailboxes. the main panel on the right shows the content of an email. There are a number of moving pieces that need to fit together. Typically the UISplitViewController contains two UINavigationViewControllers. The view controllers are referenced are UINavigationViewControllers.  The first navigation view controller is called the master view.  The master view usually has a table view controller as its root view controller and appears as sidebar in landscape and a popover in portrait. The second view controller is referred to as the detail view controller. The detail view is typically visible either as a main panel in landscape or as full screen view in portrait.

So usually there is one UISplitViewController, two UINavigationViewControllers, one UITableViewController, and one custom view controller.
To avoid ambiguity I will refer to them as the split controller, detail nav, master nav, master controller, and detail controller to refer respectively to each of these views.

The general preference of the Cocoa frameworks is to delegate rather than to subclass. Chance are there is nothing special about either of your nav views or the master controller so these can be delegated to another object. The same could be done with the UISplitViewController, but if you keep delegating everything further back then your either going to end up with an application delegate that is monstrous, or you have view controllers that are acting as delegates for views they are unrelated to, or you create an object to act as delegate for a collection of things. Since the split controller is all about holding other views it made sense to to subclass UISplitViewController and make the subclass act as the delegate for the views and controllers it contains.

Using this design the split controller adopts the UINavigationController delegate to support the detail nav (master nav is usually static). It will need to support UITableViewDelegate and UITableViewDataSource to support selecting elements from the master controller. It will also need to support UISplitViewController and UIPopoverController delegates(The first to support orientation changes and the latter to present the master view in portrait orientation). If your detail view has a custom delegate, the split controller most also adopt it.

A very natural use of UISplitViewController is to list a collection of items briefly in the master controller and display the object at length in the detail view (Like the Mail or notes app). Another design pattern is to use it as an alternative graphical representation of a tab bar. Instead of listing the tabs along the bottom, the tabs can be listed along the side inside the master controller. In this case the detail controller is not one controller, but one of a collection of controllers.  

There are a number of moving peaces that all need to work together to produce a functioning split controller. The first step is to tie everything together. Somewhere outside the split controller class it needs to have its splitView delegate and its popover delegate set to itself. After that is handled all the rest of the heavy lifting is done inside the split controller class. During my experimentation I found that in order to prevent strange bugs it was necessary to retain the popover controller and the button that presents the popover view.  

@interface LETUSplitController ()

@property (nonatomic, readwrite) UINavigationController * detailNav;
@property (nonatomic, strong) UIBarButtonItem *splitViewButton;
@property UIPopoverController * splitPopover;

@end

There are four key methods to handle the split view behavior. The first is setting delegates and settings. This is easily done inside the viewDidLoad method.

-(void)viewDidLoad
{
  //set the master nav delegates and title
  UITableViewController * masterView = (id)[self.viewControllers[0] topViewController];
  masterView.title = @"myTitle";
  masterView.tableView.delegate = self;
  masterView.tableView.dataSource = self;

  //Set the detail nav delegate
  self.detailNav = self.viewControllers[1];
  self.detailNav.delegate = self;
  
  //set a couple of settings
  masterView.clearsSelectionOnViewWillAppear = NO;
  masterView.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
  
  //do your extra stuff here
}

The next step is to configure the splitViewController delegate methods. These methods are responsible for handling the orientation changes and presenting the popover and the button.  

- (void)splitViewController:(UISplitViewController*)splitController 
willHideViewController:(UIViewController *)viewController 
withBarButtonItem:(UIBarButtonItem *)barButtonItem
forPopoverController:(UIPopoverController *)popoverController
{
  barButtonItem.title = @"myTitle";
  [[[self.viewControllers[1] topViewController] navigationItem] setLeftBarButtonItem:barButtonItem animated:YES];
  self.splitViewButton = barButtonItem;
  self.splitPopover = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController
     willShowViewController:(UIViewController *)viewController
  invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
  [[[self.viewControllers[1] topViewController] navigationItem] setLeftBarButtonItem:nil animated:YES];
  self.splitViewButton = nil;
  self.splitPopover = nil;
}

The next step is to respond to the user selecting an item from the the mater view. For whatever reason the button likes to disappear after a selection so I just re-inserted it after each selection.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
  
  //use the cell to decide what to do. l\Load a new detail view or update the current one
  
  [self.splitPopover dismissPopoverAnimated:YES];
  [[[self.viewControllers[1] topViewController] navigationItem] setLeftBarButtonItem:self.splitViewButton animated:YES];
}

The last step is to handle all of he data source methods for the master view. This is just standard TableViewController stuff.  I had a deuce of a time getting all the moving pieces to work together. What I present here should be the bear bones essentials required to get it all to work. If you have troubles drop me a comment and maybe I can help you. Also let me know if you have questions or problems.

A quick tutorial

I was sitting in algorithms class the other morning. My professor is the chair of the computer science department. He mentioned that the Dean of the school of the engineering Department wanted to learn mobile Application Development. A few days later I was able to give a give a quick intro lesson to the Dean. It's always exciting to show new people how to develop applications. And it's good to have a reputation as someone who knows what he is doing.

Lessons From iOS: HTTP authentication

I recently became the maintainer of a universal iOS application. The application was designed and built by a student at LeTourneau University. The App is called iLETU. It is a shortcut to the dozens of student related websites and resources that a LeTourneau Student might need to access. One of the most convenient features of the app is an automatic login to a number of student websites. Each of the five websites accessible from the app via auto login require different login methods. After spending time reading the devDocs, searching Stack Overflow, and trying out a few ideas in XCode I think I finally understand how to do HTTP basic authentication on iOS and OS X.

The secret to HTTP basic authentication using cocoa is knowing NSURL and the related classes. 

  • NSURL
  • NSURLRequest/NSMutableURLRequest
  • NSURLConnection
  • NSURLCredential
  • NSURLCredentialStorage
  • NSURLProtectionSpace
  • UIWebView/WebView/NIWebController etc.

If your project actually wants to display web content to the user the no brainier solution is to use Apple's UIWebView(Or WebView if you are on a Mac). For the iLETU app some basic navigation was also necessary so I used NIWebController, a handy view controller for web views from the nimbus framework that adds a toolbar to the basic WebView.

Webviews load data from a NSURLRequest object. NSURLRequests provide basic information for requesting a URL: timeout, HTTP fields, etc. Websites are requested via HTTP GET requests. Most forms on websites are submitted via a HTTP POST request.

But the real magic comes from NSURLConnection. In the words of the devDocs, "An NSURLConnection object provides support to perform the loading of a URL request." If you want to load some a URL in the background without displaying it you would use NSURLConnection. The real power of the NSURLConnection is in the method

+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate

The NSURLConnectionDelegate protocol has methods for responding to successful connections, fatal errors, and authentication challenges. If you are trying to access data Protected by HTTP basic authentication this is how Cocoa does it. At this point an example should bring some clarity.  

//basic HTTP authentication
NSURL *url = [NSURL URLWithString: urlString];
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:url
                                  cachePolicy:NSURLRequestReloadIgnoringCacheData
                              timeoutInterval:12];
[self.webView openRequest:request];
(void)[NSURLConnection connectionWithRequest:request delegate:self];

This creates a URL. From the URL a URLRequest is created. The URLRequest is then loaded in the web view. The Request is also used to make a URLConnection. We don't really use the connection, but we need to receive notifications about authentication so we set the delegate. There are only two methods we need from the delegate.

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{   
    NSURLCredential * cred = [NSURLCredential credentialWithUser:@"username"
                                                        password:@"password"
                                                     persistence:NSURLCredentialPersistenceForSession];
    [[NSURLCredentialStorage sharedCredentialStorage]setCredential:cred forProtectionSpace:[challenge protectionSpace]];
    
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
    return YES;
}

Whenever there is an authentication challenge a credential is added to the credential storage. You also tell the connection to use the credential storage.

Python is awesome

I present for your consideration the following problem given a preorder and inorder transversal of a tree construct the postorder traversal

Consider the following tree

     D
    / \
   /   \
  B     F
 / \   / \
A   C E   G
  • prefix: DBACFEG
  • infix: ABCDEFG
  • postfix: ACBEGFD

The goal is to generate the postfix representation from the first two. When you look at the problem for a little bit you should be able to find some clues to start. First look at the sections of the prefix and infix

 M  L   R
 D BAC FEG

  L  M  R
 ABC D EFG

So the first place to start is to find the root of the tree and the left and right branches. The root is the first element of the prefix representation(D). The root is the identical element in the infix notation(D). The left branch is the elements to the left of the root in the infix notation(ABC). The left branch in the prefix notation is the elements starting just to the right of the root and are the same size as the infix(BAC). The right branch of the tree is the elements to the right of the root in infix notation(EFG). The right branch is the same number of elements beginning after the left branch in the prefix notation(FEG).

Once the root and branches are identified only two parts remain. The branches and roots must be rearranged into postfix notation. The left and right branches must be parsed into postfix notation. The most reasonable way to parse each of the branches recursively.

The code for the algorithm is listed in python3 below:

def postfix(prefix,infix):
	# Base case
	if(prefix==""):
		return ""
	
	# Find the root
	root = prefix[0];
	index = infix.find(root)
	
	# recursively parse the left branch
	left=postfix(prefix[1:1+index],infix[:index])
	# recursively parse the right branch
	right=postfix(prefix[1+index:],infix[index+1:])
	#assign the root to middle
	middle=root	
	
	# put it all together
	return left+right+middle
For comparison the code in C is listed here:
#include <string.h>
#include <stdio.h>

int MAX_LENGTH = 26;

void substring(char const * original, char * result,int start, int stop);
void postfix(char const * prefix, char const * infix, char * postfix);


//replaces array splice in Python
void substring(char const * original, char * result,int start, int stop)
{
    strncpy(result, &original[start], stop-start);
    result[stop-start]='\0';
}


void postfix(char const * pre, char const * in, char * post)
{
    //handels base cases for C
    if(strlen(pre) ==0)
    {
        return;
    }
    else if (strlen(pre)==1)
    {
        strcpy(post,pre);
        return;
    }
    
	char root = pre[0];
    
    //index = inorder.find(root)
	int index;
	for(int i = 0; i < strlen(in);++i)
	{
        if(in[i]==root)
        {
            index = i;
        }
	}
    
    char leftPrefix[MAX_LENGTH];
    char rightPrefix[MAX_LENGTH];
    char leftInfix[MAX_LENGTH];
    char rightInfix[MAX_LENGTH];
    char leftPostfix[MAX_LENGTH];
    char rightPostfix[MAX_LENGTH];

    //preorder[1:1+index]
    substring(pre,leftPrefix,1,1+index);
    //inorder[:index]
    substring(in,leftInfix,0,index);
    
    //preorder[1+index:]
    substring(pre,rightPrefix,1+index,(int)strlen(pre));
    //inorder[index+1:]
    substring(in,rightInfix,index+1,(int)strlen(in));
    
    
    char left[MAX_LENGTH];
    char right[MAX_LENGTH];
	
	
    //left=postfix(prefix[1:1+index],infix[:index])
    postfix(leftPrefix,leftInfix,leftPostfix);
    sprintf(left, "%s",leftPostfix);
    //right=postfix(prefix[1+index:],infix[index+1:])
    postfix(rightPrefix,rightInfix,rightPostfix);
    sprintf(right, "%s",rightPostfix);
    //middle=root	
    char middle[3];
	sprintf(middle,"%c", root);
    //return left+right+middle
	sprintf(post,"%s%s%s", left, right, middle);
}

The difference is shocking. The Python code is elegant compact and readable. The C code is long, clunky, and was a pain to debug. The Python array splice notation is powerful and compact. The String object in Python make it easy to copy strings and substrings. The ability to return strings is another phenomenal advantage over the C approach. I found the problem fascinating and the relative results in each language insightful. I hope someone else finds this interesting.