Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Wednesday, 7 May 2014

Post WDI - iOS Dev App (Web View, Custom Classes, Date Formatting, Dynamic Binding, Super, Self, Segue, View Controller Stack)


Activities @ TeamTreeHouse - 

iOS Development (using Xcode 5 IDE) with Amit Bijlani (Cont'd)

DONE Building API Reader (Table View) iPhone App
  • @synthesise { replace setter and getter methods in .m file associated with @property instance variables in .h file }
  • @interface declaration { NSString *title; } (optional in latest Xcode!)
  • Scoping instance variables { only visible in Class declared within unless use getters and setters }
  • Setter method (in .h) { - (void) setTitle:(NSString *)title; }
  • Getter method (in .h) { - (NSString *) title; }
  • Setter method implementation (in .m, returns instance so use *) { - (void) setTitle:(NSString *)_title { title = _title; }
  • Getter method implementation (in .m) { - (NSString *) title { return title; } }
  • Primitive Type (i.e. int) declaration { @property (nonatomic) int views  } (not require 'strong'/'weak', etc)
  • Legibility Alternative for Primitive Type (Boolean) { 
.m@property (nonatomic) BOOL unread;
// alternative@property (nonatomic, getter = isUnread) BOOL unread; 

ViewControllerif (blogPost.isUnread) {   NSLog(@"%@", @"hi");}
  • Custom Class instance variable setter access approaches {
    • Dot Notation { NSString *string = blogPost.title; }
    • Convenience Constructor { NSString *string = [blogPost title]; } 
    • Set Method { [blogPost setTitle:@"my title"]; }
  • Self 
    • directly accesses Setter and Getters of the instance variable in @interface
    • allows multiple instance vars to refer to a particular instance of a Class
    • where Class has Parent Class like NSObject, the instance of a Class ('self') needs to refer to the Parent from which it inherits properties and methods (using 'super')
  • Super { refers to Parent Class within implementation }
    • i.e. self = [super init]; // self refers to particular instance of the Class. calls Super/Parent Class to use its methods (i.e. init, dealloc, etc) to initialise instance of Custom Class
  • Customer Class { benefits in that code is more maintainable than with say NSDictionary for data }
  • Dedicated Initializers { responsible to initialize new instances of Class with data, ensures that when a Custom Class is initialized, it must have a title for example }
    • init (NSString, etc)
    • initWithObjects (NSArray, NSDictionary)
    • i.e. - (id) initWithTitle:(NSString *)someTitle;
  • Convenience Constructors { Class methods (i.e. + sign in Help) that performs Alloc and Init in one step and returns an instance }
    • alloc init
    • arrayWithObjects
    • i.e. + (id) blogPostWithTitle:(NSString *)someTitle;  // 'someTitle' passed as argument with this Class method (uses + sign)
  • id { general purpose data type that follows Dynamic Binding Design Pattern where Class of an Instance is not specified immediately (i.e. only definition created in Controller, but it is Bound at Runtime when run app which causes the Object to become a specific type like NSString). it can create instance of any Class and not always know return type. not required to use asterix * (i.e. id *myObject) to indicate instance when specifying 'id', as this is already implied }
  • Dynamic Binding { see above }
  • Display Images from JSON URL { NSURL (i.e. URLWithString) downloaded as UIData (i.e. dataWithContentsOfURL) object (binary), parsed to convert to UIImage object (i.e. imageWithData), and set to the UIImageView (i.e. imageView) }
  • Debugging Malformed and Erroneous Data { i.e. JSON with empty fields ( if ( [blogPost.thumbnail isKindOfClass:[NSString class]] ) { // only display if not NSNull ) }
  • Concatenating Data { [NSString stringWithFormat:@"%@ %@", blogPost.author, blogPost.date]; }
  • Custom Date Styles with NSDateFormatterStyle {
NSDATE *today = [[NSDate alloc] init]; // or use convenience constructor [NSDate date]

NSLog@“%@“, today); // prints today’s date
// NSDate Object stores in ‘seconds’ from Jan 1 2001 until today (represented internally). where 60 sec/min, 60 min/hour, 24 hr/day
NSTimeInterval secondsPerDay = 60 * 60 * 24; // typedef double used with the Date object
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay]; // add time to now NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-secondsPerDay]; // minus seconds per day
// create instance of NSDateFormatter NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@“EE MMM, dd”];(see Help Menu "Date Formatting Guide > Date Formatters > Fixed Formats (depends on iOS version)http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

// pass date object *today through date formatter and output a string NSString *todayString = [dateFormatter stringFromDate:today];
  • URL open in Default Browser
NSURL *url = [NSURL URLWithString:@"http://www.lukeschoen.com"]; UIApplication *application = [UIApplication sharedApplication]; // retrieves shared instance of singleton application object UIApplicationMain (see Support Files > main.m)[application openURL:url]; // call UIApplicationMain's method 'openURL'
  • Navigation Controller { manages presentation of hierarchy of data in app. manages multiple View Controllers and navigation between them. Navigation Controller has following elements:
      • Nav Bar (back button, title)
      • View (custom content)
      • Toobar (optional)
    • View Hierarchy
      • Stack of View Controllers { LIFO (Last In First Out) }
        • viewControllers (NSArray)
      • rootViewController
    • Stack Manipulation
      • Push (View Controller) on Stack (point to same View Controller unless there is a Modal View Controller)
        • Properties set
          • topViewController
          • visibleViewController (points to last one pushed onto the Stack)
  • Link ViewControllers in Storyboard { click Cell, press CTRL and Drag, select say 'push' (push View Controller on the Stack by creating a Segue aka Scene between the View Controllers) }
  • Link & Intercept Segue Event with Code { click Segue (connection between View Controllers), Attributes Inspector > Storyboard Segue > Identifier > "___" (i.e. showBlogPost) }
.h
@property (strong, nonatomic) IBOutlet UIWebView *detailView;@property (strong, nonatomic) NSURL *blogPostURL;
.m (of Master View Controller)

// check 'identifier' given to the segue in the storyboard.    // prepareForSegue is part of UIViewController- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {   NSLog(@"%@",segue.identifier);
// use BlogPost Custom Class (on event where segue for DetailView is fired). DetailViewController (segue object) has @properties 'detailView' and 'blogPostURL' defined if ([[segue identifier] isEqualToString:@"showBlogPost"]) {  // access blogpost object from blogposts array that was selected from Table View       NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];   BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row]; [segue.destinationViewController setBlogPostURL:blogPost.url];

.m (of Detail/Web View Controller)
- (void)viewDidLoad {    [super viewDidLoad];// below refers to @property blogPostURL that was set in Master View Controller to prepare segue and show URL details associated with list itemNSURLRequest *urlRequest = [NSURLRequest requestWithURL:self.blogPostURL]; 
  • WebView { subclass of UIView, uses WebKit rendering engine to display webpages }
  • UIWebView { control dragged to Storyboard and instantiated in code to load webpage by clicking the UIWebView in Assistant Editor, pressing CTRL and dragging the UIWebView from Storyboard to section of code in @interface }
  • Embed WebView and Display Common DetailView (in viewDidLoad method)
NSURL *url = [NSURL URLWithString:@"http://www.lukeschoen.com"]; // create instance of url request    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; [self.detailView loadRequest:urlRequest]; // load default webpage using @property detailView

Links:

Purchases:

Saturday, 3 May 2014

Post WDI - iOS Development App (Master-Detail Table View, JSON, API, Mutable, Memory Management)

Activities @ TeamTreeHouse - 

iOS Development (using Xcode 5 IDE) with Amit Bijlani (Cont'd)

DONE Building API Reader (Table View) iPhone App
  • Table View (List) with Master-Detail App
    • Manual
    • Master-Detail Template
  • UIApplication { single instance, only allowed one UIApplication object for a single app. watches for Events and Routes to appropriate targets }
  • AppDelegate
    • Dfn: capability to Intercept Events at an App level so can Add Custom code. all apps have it to hook into UIApplication (app lifecycle). responsible to ensure app has a Window 
    • .h { defines lifecycle of app }
    • .m { implementation of .h containing methods }
  • UIWindow object { coordinates presentation of Views on screen. hosting Views and working with UIApplication object to deliver Events to Views and View Controller }
  • View Controller object { manages presentation of app Content on screen, including Single MainView (property) and its Collection of Sub Views  i.e. self.view (where View is property of ViewController) }
  • UIViewController class { base class for all ViewController objects, provides Default functionality for Views' ability to load, display, respond, etc }
  • View object { draws Content in designated Rect area and Responds to Events in that area }
  • Controls { specialised Views responsible for implementing interface objects (i.e. buttons, text fields, toggle switches) }
  • Data { ways to store data in app (i.e. Core Data, etc) }
  • Storyboard (defines flow between ViewControllers)
    • MasterViewController { inherits from UITableViewController and UIViewController as displays List of TableView UITableView with Rows(UITableViewCells) attributes and behaviour and where tap event shows DetailViewController }
    • DetailViewController  { inherits from UIViewController as displays Single View Text from Table View Cell }
    • Scene { ViewControllers }
    • Segue {  connection between Scenes of type UIStoryboardSegue (arrow Transition between each View Controller). it has Properties: identifier, sourceViewController, destinationViewController }
      • identifier { read-only shown in View. accessed in code with method prepareForSegue. use Method notation (instead of Dot Notation) when dealing with 'read-only' info as indicated in Help }
      • prepareForSegue { intercepts Segue once it is triggered and takes two args }
        • Segue param { contains info about Segue }
        • sender { originator of Segue }
(UIStoryboardSegue *)segue sender:(id)sender
  • Shortcuts
    • Double-Click - Zoom in/out of Storyboard canvas 
    • CMD+N - New File
  • UITableViewController { is declared in NSObjCRuntime.h (according to hover+CMD+Click) and implements two Protocols. It contains a @property 'tableView' of type UITableView which implements the two Protocols }
    • UITableViewDataSource { defines what is displayed in Table View. it mediates between Table View and Data }
    • UITableViewDelegate { defines how Data displayed with Methods to configure Table Views (i.e. row heights, section headers/footers, tap event or editing actions) }
@property (nonatomic, retain) UITableView *tableView;

  • indexPath { object with two Properties (Section, and Row in that Section) }
  • Memory Management
    • No Table View Cell Reuse { alloc and init new table view cell for each row to be displayed in table view. slow with large quantities of rows in the array to be alloc'ed }
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    • Efficient Reuse of Table View Cells { allows table view to efficiently manage cells with each one having an identifier in storyboard so when table view cell scrolls beyond screen the table view re-marks it for reuse and recycles it on new row }
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

  • NSDictionary 
    • objectForKey { type 'id' is generic data type (any Object) }
    • valueForKey { always expects String }
// declaration for key value pair NSDictionary *blogPost1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"Blogpost1", @"title", @"Luke Schoen", @"author", nil]; 
// ALTERNATIVE convenience constructor for NSDictionary NSDictionary *blogPost1 = [NSDictionary dictionaryWithObjectsAndKeys:@"Blogpost1", @"title",@"Luke Schoen", @"author", nil];



  • SubTitles { Storyboard > Change Type (of TableViewCell) in Attribute Inspector > subTitle }
  • UITableViewCell Properties:
    • textLabel
    • detailTextLabel
  • Mutable 
    • Memory Inefficency { performance overhead when want to modify Contents of object, mem alloc needs to change and find mem space for additional Content }
    • NSMutableArray (subclass of NSArray)
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:0]; // if capacity 0, use below NSMutableArray *titles = [NSMutableArray array]; // memory alloc minimal to hold pointer to array [titles addObject:@“My Book”]; // add object to array. mem dynamically alloc. array size grows [titles insertObject:@“abc” atIndex:0];  [titles removeLastObject]; [titles removeObjectAtIndex:0]; 
    • NSMutableDictionary (subclass of NSDictionary)
      • Declare with Memory Capacity
NSMutableDictionary *book = [NSMutableDictionary dictionary]; [book setObject:@“My Book”, forKey:@”title”]; [book setObject:@“Luke Schoen”, forKey:@”author"]; [book removeObjectForKey:@“title”]; [book removeAllObjects]; // removes all objects from a dictionary
    • NSMutableString (subclass of NSString) 
NSMutableString *string = [NSMutableString string];[string appendString:@"Title: My Book"];[string appendString:@"Author: Luke Schoen"];[string insertString:@" -- " atIndex:10]; 
  • Immutable { cannot be modified } 
    • Memory Efficient { when variable for object alloc, mem req'd known (knows qty objects and kind of objects. pass around without need to modify }
    • NSArray
  • JSON Parsing (JavaScript Object Notation)
// create NSURL class object (convenience class to breakdown url) 
// download the data (NSData object stream from JSON)   
NSURL *movieURL = [NSURL URLWithString:@"http://www.omdbapi.com/?s=Terminator"]; 
// parse data  
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL]; 
// declare pointer in memory 
NSError *error = nil; 
// deserialise data into JSON object format to stored in dictionary 
// pass pointer reference to NSError so value can be modified by the method it is being passed to (otherwise just passing by value and can only read 
// i.e. &__ means value can be modified by the method 
// i.e. ___ means just passing its value and it can only read your object NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@", dataDictionary);
self.
moviePosts = [dataDictionary objectForKey:@"Search”];

// extract 'title' from NSDictionary and set
cell.textLabel.text = [moviePost valueForKey:@"Title"];
cell.detailTextLabel.text = [
moviePost valueForKey:@"Year"];


Events Upcoming
    • ATTENDED - RORO Syd Dev Hub - 6:30pm 6th May 2014 (Level 15, 2 Market St)
    • UNABLE - RORO USer Group - 7pm 13th May 2014 (Trinity Bar, 505 Crown St Surry Hills)
    • UNABLE - Sydney Drupal Meetup - 7pm, 15th May 2014 (Level 5, 48 Pirrama Rd)

Sunday, 30 March 2014

Post WDI - Node.js, Mocha, REPL, Dev Tools, Jade

Challenges
  • Node.js App 
  • Unable to view sub-directories after deploy to Heroku app:
    •  Tested - Procfile, Script Start (in Package.json), Foreman
  • Unable to remove error message that echos when running local Node.js server (tried creating a favicon.ico image and placing in main project directory, public folder, and the module folder indicated with no win)
    • Error: ENOENT, open '/Users/ ... / ... / <project_name> /portfolio/node_modules/express/node_modules/connect/node_modules/static-favicon/../public/favicon.ico'
  • Unable to overcome errors that appear when Testing in later Git Branch called 'Streams' (which includes pushes containing Express Module Sessions). Previous Branch without these Testing errors is 'Mongo', now cloned and progressing with 'Mocha2'. 
    • ~/Documents/ <project_directory>/ ✗ streams ∴ 
    • Error: Error setting TTL index on collection : sessions
    • TypeError: Object Error: Cannot determine state of server has no method 'isCompatible'
  • RIP Rohan Ramsay

  • Unit 5 - Phase 2 - Setting Priorities for Development - DONE
  • Unit 6 - Phase 3 - Concept Definition - DONE 
  • Unit 7 - Phase 4 - Product Dev & Feasibility Assessment - DONE 
  • Assignment 1 - DONE


Activities @ Lynda - 

Up and Running with Evernote for Mac - DONE

Node.js Essential Training with Joseph LeBlanc - DONE
  • Node.js(Modules, Require, Exports, Event Loops and Callbacks, Blocking vs Non-Blocking Environment, HTTP Module, RESTful, NPM Commands, Express Module and Framework,  Dependencies, Jade Templating Engine, Module Getters and Setters, Module Caching and Function Scopes, Reusable Modules with Module.Exports, Handling and Modifying Large Datasets with GET and PUT Requests Returning JSON, Creating Middleware to Modify HTTP Response Headers, Configuration for Unit Testing with Mocha, Should, and Supertest by Decoupling Seed Data and Server from App)
  • Node Package Manager (NPM)
  • Jade Templating Engine
  • Bootstrap 
  • Chrome Postman Plugin (HTTP Requests)
  • Unit Testing (Mocha, Should, Supertest)
  • Istanbul Code Coverage
  • Foreman (Heroku Deployment)
  • REPL (Read Eval Print Loop for interactive Node.js code debugging)
    • Created Custom REPL Gaining Control of App (Command-Line Interface interacting with Node.js App and Inspecting Data in Real-Time, Built Custom Prompt, GET and PUT Actions without HTTP Interface with Equiv. Results)
  • Optimise Module Cool!!
    • Handed Command-Line Arguments passed to Node.js App (Code Written to Accept Command-Line Args, Used Optimist to Return Data as an Object  with Properties and Values at the Cmd-Line instead of as an Array for easier Look-up)
  • Building Command-Line Tools 
    • Package.JSON Bin Scripts, Hashbangs in Server.js so Shell feeds whole Server.js with Node, NPM Link for symbolic link to path of project
  • Links

MongoDB via Mongoose Connection -  DONE
  • Node.js, MongoDB, npm install (save dependencies), Mongo Lab, Mongoose to create schema data for chainable queries, Postman (Chrome Extension), Querying collections in MongoDB database and handling responses, route handling, Jade framework to render template Views, Connect-Mongo middleware to tie Express sessions with MongoDB by parsing cookies 


Activities @ Book Reading

Javascript The Good Parts - DONE


Activities @ Code School

Discover DevTools - DONE


Activities - General
  • TeamTreehouse - Using (Use my basic account) MUST USE PERKS!!!
  • Amazon Web Services - Pending (Use Voucher by June 2014!)
  • General Assembly Courses - Pending (Use Vouchers)
  • Web Host - Pending (continue with Uber or change to Anchor?)

Events Upcoming
  • ATTENDed - ROROSyd Dev Hub - 6:30pm Tues 1 Apr 2014 (2 Market St Syd) 
  • ATTENDed - Codium - State Library of New South Wales, Macquarie Street
  • ATTENDed - M&G Prep Workshop with Tarun - 10am-1pm 12 Apr 2014 (Fishburners)
  • ATTENDed - M&G Graduates - 6:30-9pm 14 Apr 2014 (Mezzanine Level, 56-58 York St)
    • Business Card
Curiosity