Showing posts with label iphone. Show all posts
Showing posts with label iphone. Show all posts

Friday, 23 May 2014

iOS Unit Testing

Challenges
  • Error 'Parse/Parse.h' file not found (Unit Testing in iOS)
    • Background: I added the following Unit Testing lines of code in appropriate sections of my RibbitTests.m file in Xcode 5 to import the view controller header file that I wanted to test.
#import "ImageViewController.h"
@property (nonatomic) ImageViewController *imageViewController;
#pragma mark - App Test Cases
- (void) testImageViewController{   XCTAssertNotNil(self.imageViewController, @"imageViewController model was not nil");}
    • Problem: Received error message 'Parse/Parse.h' file not found 
    • Solution: 
      • Deleted Parse.framework in Xcode 5 (use Apple Finder to check that there is no Parse.framework folder still in your project directory) 
      • Re-downloaded the Parse.com iOS SDK
      • Dragged the downloaded Parse.framework folder into the Frameworks directory within Xcode 5, and ensure that you tick the following boxes (noting that the initial error message you received may have been caused because when you initially installed Parse.com's SDK, you may not have also added a tick next to RibbitTests)
      • Dragged the downloaded Parse.framework folder into the Frameworks directory within Xcode 5, and ensure that you tick the following boxes (noting that the initial error message you received may have been caused because when you initially installed Parse.com's SDK, you may not have also added a tick next to RibbitTests)
Activities @ TeamTreeHouse - 

Unit Testing for iOS (using Xcode 5 IDE) with Amit Bijlani

DONE (using Ribbit iPhone App)
  • Unit Testing { 
    • Runtime errors (insufficient type testing)
    • Logic errors (insufficient scenarios)
    • Regressions (team scenario bugs)
    • XCTest.framework { write tests that a subclasses of XCTestCase }
    • XCT Assertion types
    • Running Unit Tests
      • CMD + U { Product > Tests }
      • Re-Testing { Product > Perform Action > Test Again }
      • Method Testing { Press 'Play' Button in gutter to the left of the method }
    • Navigating Unit Tests
      • Test Navigator (in the Project Navigator)
        • Running Specific Tests { Press 'Play' Button shown on right of: }
          • Test Suite
          • Test Cases
          • Test Methods
    • Creating Tests { Press + Button in bottom left corner of Test Navigator }
      • Test Classes
      • Test Targets
    • Matching Test Case Methods with corresponding Code Methods { Assistant Editor > Click Breadcrumb Navigation bar (at top right), then scroll down and Click either:
      • Test Classes
      • Test Callers { identifies other methods that call the method, including Unit Testing methods }
    • Continuous Integration 
    • Shortcuts 
      • CMD + U  { Runs Unit Test }
      • CMD + Click { Press this combination when hovering a method to toggle between the methods location in the header and implementation files } 

Monday, 12 May 2014

Post WDI - iOS Dev App (User Accounts, BaaS, Mobile Design, Parse.com Framework API, Asynchronous, Helper Methods, Git Ignore, RubyMotion)

Challenges
  • Debugged extensively trying to solve why checkmarks were appearing on currently selected cells in the table view only after clicking another different cell in the table view 
    • Solution: Incorrect method chosen when creating instance method with autocomplete, should have used didSelectRowAtIndexPath (NOT 
      didDeselectRowAtIndexPath)
Activities @ TeamTreeHouse - 

iOS Development (using Xcode 5 IDE) with Ben Jakuben

DONE Ribbit iPhone App
  • Xcode 5 Tabs for Open Files { Xcode5  > Preferences > Navigation > Double Click > Use Separate Tab }
  • View Controller Lifecycle 
    • Start App (First Time)
      1. view not exist
      2. call viewDidLoad (only called if no view controller exists in memory)
      3. call viewWillAppear 
      4. call viewDidAppear
      5. view controller appears on screen in ready state (user can view and interact)
    • Navigating Away from current ViewController
      1. call viewWillDisappear
      2. call viewDidDisappear
      3. view controller remains in memory for future use as long as memory avail
    • Start App (After First Time)
      1. skips viewDidLoad (as it already exists)
      2. call viewWillAppear
      3. call viewDidAppear
    • Typical Usage
      • viewDidLoad { use for code that only needs to run once when view first loaded (i.e. creating, loading data, config display) }
      • viewWillAppear { use to display something every time view controller displays on screen (i.e. refresh data, animation) }
  • Stack (of View Controllers) (Nav Controller maintains VC's pushed onto or pulled off the array stack above Root VC)
    • pushViewController
    • popViewController
  • Import Types (used in Header file)
    • " "   means search current project for header file
    • < >  means search certain present system paths (i.e. frameworks)
  • UITabBarController (switches between different tab areas of app) & UITabBarItem
    • selectedIndex property
    • setSelectedIndex
    • badgeValue property
  • UIAlertView { [alertView show] }
  • UITableViewCellAccessoryCheckmark (or None)
    • accessoryType 
    • Prevent Scrolling Cell Reuse { explicitly set each cell only when user corresponding to current table view row is in an array to prevent reuse of cells and incorrectly mirrored checkmarks being displayed }
  • UIImagePickerController (capturing photos and videos with either Default (presented modally) or Customer implementation type )
    • Protocols { Custom View Controller created in conformance with UIImagePickerController delegate, which in turn conforms to UINavigationController delegate protocol, so when user cancels or captures images or video the system notifies the cameras delegate of the users choice }
    • presentViewController used to display the the camera view modally
    • imagePickerControllerDidCancel { delegate method of UIImagePickerController where Custom Class that we've named 'CameraViewController' is the delegate }
    • didFinishPickingMediaWithInfo { stores image info in NSDictionary with a key }
    • UIImagePickerControllerMediaType { key method constant passed in and used to retrieve different media types stored as constants as part of Mobile Core Services Framework }
      • #import <MobileCoreServices/UTCoreTypes.h> (constant values of media types obtained)
      • kUTTypeImage { image media type from Core Foundation (CF) that needs to be converted to Next Step (NS) String counterpart type of data structure using Cast (NSString *). use @properties to store images retrieved for use throughout view controller and to set it to be stored in NSDictionary key }
    • UIImagePickerControllerMediaURL { key path method constant passed in and used to retrieve local iOS internal path as a string and stored in @property defined in header (videos not stored in NSDictionary like images are) }
    • Simulator Testing with Photo Album (the iPhone camera is not available unless testing using the device so to test within the simulator using the photo album instead perform the following actions in Xcode Simulator)
      • Hardware > Home, Open Safari in Simulator, Drag a photo to Safari browser, Click the 'Share' button, Click 'Save to Camera Roll'
    • Help Menu Keywords { camera programming topics for iOS }
  • Video Player 
    • Options on iPhone
      • Default Video Player (MPMoviePlayerController)
      • Embedded Video Player
    • #import <MediaPlayer/MediaPlayer.h>
    • Media Player Framework (MediaPlayer.framework)
      • Project > Build Phases > Link Binary Libraries
  • NSTimer 
    • scheduleTimerWithTimeInterval
  • Testing 
    • respondsToSelector (check if method exists before calling it in code block)
  • Modal Control Dfn { UI of VC requiring user input before proceed with app }
    • Modal View Controller { layer over current VC, child of current VC (i.e. UIAlertView) } 
  • NavigationController (NavC) (help navigate different sections of app screen flow)
    • Set NavC for the TableVC and TabBarC { pairs NavCs with TabBarController and used to control the Manual Segues with VC, Click VC, Menu > Embed In > Navigation Controller  }
      • popToRootViewControllerAnimated
      • Remove Default Back Button Setup by NavC { self.navigationItem.hidesBackButton = YES; }
      • Remove Tab Bar  { Add method to prepareForSegue setHideBottomBarWhenPushed before VC pushed onto the stack of the workflow 
  • Segue (With)
    • VC onto NavC { CTRL+click, Drag to ViewController(VC), select Action Segue }
    • Button to VC { CTRL+click button, Drag to VC, select Action Segue }
  • Segue (Without)
    • VC onto TableVC { access VC without Segue attached to Action, CTRL+click 'yellow icon' below VC, Drag to VC, select Manual Segue }
  • Segue (Identifier)
    • Click Segue between VC, Add "Identifier" to pass Data between VCs
    • Create method to perform segue to second view controller { -(void)___ { [self perfomSegueWithIdentifier:@"<insert identifier>" sender:self]; }
  • Linking the Prototype Cell of VC in Storyboard with Class Method (Attributes Inspector > Identifier > "Cell", to match CellIdentifier in code) 
  • @property Storage { Data Source 'Weak' for Text Fields on Sign Up and Sign In forms as dependent on life of View Controller itself }
  • IBOutlet { used for Text Fields for user input, dragged to @interface using Assistant Editor View }
  • IBAction { used for Button to submit, dragged to @interface }
  • Refactoring Code { Select code for refactoring (encapsulating into separate method to comply with DRY principle) into a new Helper method and then go to Edit > Refactor > Extract > <enter name for method> 
  • Stub { i.e. - (void)___ { } }
  • API  { Application Programming Interface to interact with sub systems and third party systems i.e. UIKit and Foundation frameworks }
  • Black Box { System designed with Interfaces (i.e. sets of methods and properties defined in publicly viewable header file) clearly defined between components }
  • Web Interface { between Front-End Black Box and Back-End (i.e. Parse.com Back-end-as-a-Service (BaaS) dynamically creates what is needed in Back-End) }
  • Parse.com Framework SDK Setup { extra Frameworks required as Dependencies by Parse Framework installed per Parse.com instructions via Project > Target (Ribbit) > Build Phases (tab) > Click “Link Binary with Libraries” }
  • Parse.com API Calls { iOS Guide, iOS API } 
    • objectWithClassName (PFObject) (creates Parse.com database table object) saveInBackground (save data to Parse.com back-end)
    • signUpInBackgroundWithBlock (PFUser) (asynchronous multi threaded approach using Block construct set up as callback mechanism with Parse.com response, receipt and processing in block with success and error handling)
    • currentUser (PFUser) (returned value is automatically Cached on device and user session logged in)
    • logOut (PFUser)
    • loginHandler block (PFUser)
    • loginWithUsernameInBackground (PFUser)
    • findObjectsInBackgroundWithBlock (PFQuery) (block that returns array of PFObjects)
    • relationForKey (PFRelation)
    • saveInBackgroundWithBlock 
    • reloadData (method to refresh the Table View data)
    • addObject
    • saveInBackground
  • Parse.com Classes { 
    • PFObject (iOS Guide > Users)
    • PFUser
    • PFRelation  (ensures Parse.com not dealing with too much Data at once. Relations are stored in Parse.com Table Object under column (property of Class) with designated Key. PFRelation has a PFQuery property to use to retrieve data linked by relation)
    • PFQuery (retrieving and viewing data 
    • PFFile (uploading files and associate them with a message PFObject that will be )
  • Uploading Files to Parse.com
    • PFFile to upload file itself
    • PFObject uploaded separately as message Object (created dynamically at Parse.com) associated with PFFile
      • Message Object 
        • Message Contents
        • Sender
        • Recipient
      • Schemaless means not req'd to specify keys existing on each PFObject, just set KV pair and back-end stores them
    • Chaining Asynchronous Calls { upload file itself and then other details if initial asynchronous call succeeded improves UX by not delaying user }
  • Deleting Files on Parse.com
    • Options
      • RESTful API's 
      • Clean Up Files (Dashboard > Settings > Clean Up Files) { deletes all files that we have uploaded that are no longer referenced by any other objects in back-end }
  • Asynchronous Indeterminant Nature (amount of Time) of calls as data not always returned in order expected. Multiple Callback Blocks must be managed. Avoid where possible by implementing DRY principle and sharing data between methods of VC's with prepareForSegue method
  • Block { ^ (<parameters defined inside parenthesise>) { curly braces with code } }
  • Helper Methods (i.e. looping mechanism to check for friends against current user)
    • Alternative is Hash or Cache for efficiency with high volume of users 
  • Shortcuts 
    • Hidden Files (show hidden files with CMD + Shift + . }
    • Indentation CMD + ]  or CMD + [
  • Git Ignore { store API keys in .plist file using this guide https://teamtreehouse.com/forum/hiding-api-credentials-in-github-for-xcode-5-projects }
  • Mobile Design

Events:
  • ATTENDED SydInMotion - Ruby & iOS development (awesome! early stage community)
    • @fluffyjack (inspiring presentation, RubyInMotion time after exams finish mid June '14)

Curiosity:

Purchases:
  • RubyMotion a personal leap of faith inspired by SydInMotion! Now I just need to buy some coding friends...

Links:

Sunday, 27 April 2014

Post WDI - iPhone App Sandbox, Data Management Persistence Mechanisms (Object Archiving, Core Data to SQLite)

iPhone Development (Xcode 5) (Cont'd)

iPhone App Sandbox and Data Management  DONE
  • Application Sandbox { restrictions (policy and technical) introduced by Apple to protect users from malicious apps harming their devices, and where all apps exist in a sandbox. violation cause for app rejection from App Store }
  • Object Archiving 
    • Object Graph { all references between interlinked web of objects in memory. used for Cocoa's Object Archiving (serialisation mechanism) where the object graph is stored to the file system and unarchived and read it back into memory to restore a session at the same point. Object Archiving Components include NSCoder object and NSCoding Protocol }
      • NSCoder { encode and decode archiving any object to NSCoding Protocol using "keyed encoding" where a key is provided for each instance var }
      • NSCoding Protocol 
      • Methods: 
        • initWithCoder { Decoding where key is provided and decoded instance var returned } 
        • encodeWithCoder { Encode all instance vars (using encodeObject:forKey, encodeInt:forKey, encodeBool:forKey, encodeDouble:forKey, encodeBytes:forKey) of object to store during archival. implemented with decision on instance vars of scalar type to encode or not encode (transient) } 
    • Archiving to File
      • archiveRootObject:toFile of NSKeyedArchiver (on applicationWillTerminate event)
    • Unarchiving from File
      • unarchiveObjectWithFile method from NSKeyedUnarchiver(on viewDidLoad event)
    • Data Storage Options
      • Library/Preferences Directory { access indirectly with NSUserDefaults API }
      • Library/Caches Directory { direct file manipulation, cache retrieved data, persists between launches, improves performance }
      • Documents Directory { direct file manipulation, main location to store, backed up when synced }
      • tmp Directory { direct file manipulation outside devices limited volatile memory without persisting between launches of app }
    • File Paths 
      • NSSearchPathForDirectoriesInDomains { Core Foundation function returns multiple directories in NSArray with NSStrings extracted with objectAtIndex }
      • stringByAppendingPathComponent { joins path fragments }
    • Interface Elements
      • Flexible Space Bar Button
  • Core Data 
    • Dfn: Object-Relational Mapping (ORM) framework (handles conversion of data to and from objects in the app and relational data in a database) providing management and persistence of in-memory object graphs comprising multi-level undo management, data validation, data consistency across independent data accessors, efficient filtering with indexing, sorting, and searching object graphs, and persistence between invocations to various data repositories 
    • Uses: wraps the SQLite database and relational database (alternative to using SQL and SQLite API directly) to perform querying and data management functions of CRUD (create, read, update, delete)
    • Alternatives to SQLite Repository 
      • Uses: Core Data features (undo support, object schema versioning) without need for relational databases
      • Binary File Format { same limits on large data sets as Object Archiving }
      • In-Memory Implementation { no persistence between app invocations }
    • Concepts of Core Data
      • Managed Object Context { subset of persistent objects used by app at a point in time and containing the object graph. Core Data notices changes to the objects and persists changes to the database when save is called }
      • Managed Object { object managed by Core Data that can be added or removed from object graph resulting in Core Data performing inserts and deletes w database. changes to attributes and relationships of managed objects results in Core Data performing update operations to database }
      • Managed Object Model { object-relational schema, description of Entities persisted via Core Data. it's a mapping between an object in Objective-C and an Entity as it will be stored as rows in a database table in SQLite }
        • Xcode Data Modelling Tool { for .xcdatamodel files }
      • Entity 
        • Dfn: model of managed object containing only parts of object that Core Data will be persisting
        • Model Types:
          • Object Attributes { for persisting }
          • Relationships and Other Entities { stored to form a persistent object graph }
      • Persistent Stack { parts of Core Data that interact with a data repository like SQLite }
    • Core Data Application Template 
      • Dfn: boilerplate code that contains additional properties and actions to allow the Core Data application to interact with the managed object context through its application delegate 
      • Features:
        • @dynamic construct { tells compiler missing property getters and setters in implementation file will be provided by superclass NSManagedObject at runtime } 
        • managedObjectContext property { Core Data managed object context for passing to controllers subview in the app window upon applicationDidFinishLaunching }
      • CRUD (Create, Read, Update, Delete)
        • insertNewObjectForEntityForName:inManagedObjectContext method of NSEntityDescription { Create. arguments include name of Entity NSString from managed object model, and reference to managed object context }
        • NSFetchRequest instance in viewDidLoad method { Fetch. with NSEntityDescription to specify type of Entity to fetch, returns NSMutableArray of managed objects
        • hasChanges used by managed object context to report any changes to managed objects that were tracked and save in the applicationWillTerminate method 
        • deleteObject method of NSManagedObjectContext is passed managed object to delete
        • Note: NSUInteger vs NSNumber (scalar integer vs actual object)
Curiosity:



Links:

Post WDI - iPhone Storing App Preferences

iPhone Development (Xcode 5) (Cont'd)

iPhone Storing App Preferences   DONE
  • Application Preferences (aka Settings, User Defaults, User Preferences, Options)
    • Overall preference system where apps customise for users
  • Application Preferences System { low-level tasks of persisting preferences to iPhone with app preferences separate and backed up  
  • Design Principles
    • Opinionated Software { limit app preferences with an opinion on best ways to accomplish tasks serves larger market } 
    • Implicit (In-App) Preference Exposure { based on user actions using the app and returning to last state of app upon reuse }
    • Explicit Preference Exposure using Apples Settings Application { single location to customise iPhone Settings Bundle, but UI is limited }
    • Alternatively { customized toolbar with limited frequently used items and a 'more' button }
    • Examples { API access, streamline w default inputs saved to reduce user taps }
  • Utility App Template { contain info icon that animates a transition to a flipside view for setting app preferences when tapped }
  • Settings Bundle Template { generated from Resources group in sidebar it creates a Root.plist file editable in Property List Editor, which controls appearance of the app in the settings bundle where preferences may be set and retrieved from the preferences database and grouped. types may be edited (i.e. PSTextFieldSpecifier changed to PSMultiValueSpecifier). note that multiple PList files may be created (i.e. About, etc) }
  • Reading and Writing User Defaults
    • NSUserDefaults API { singleton pattern (only one instance object of class stored) class used to store app preferences as key/value pairs }
    • viewWillDissappear event { persist in saving key values when view disappears  (i.e. on/off state and levels as constants) using setBool and setFloat methods of standardUserDefaults method  associated with NSUserDefault singleton API. preferences stored in PList file (XML property list file) }
    • viewDidLoad event { read and use preferences when view appears upon application launch using floatForKey and boolForKey methods of NSUserDefaults API. set the preferences with a Helper Method setValuesFromPreferences, and cover the initial case with default settings using a dictionary of default preference keys and values to the registerDefaults method. Array Title String properties and Array of UITextFields setup by reading preferences current value from NSUserDefaults, and used for storage and editing. Store preferences into user defaults database using Utility Template App 'done' action instance }
  • In-App Preferences
    • FlipSideViewController (to implement table view Delegate and Data Source Protocols instead of using TableViewController) for Utility Template App (with Flipside View) 
      • Preferences Stored and Edited { added as subviews of table cells content view }
Links:

Post WDI - iPhone Multiview Navigation-Based Apps (Table View Categories)

iPhone Development (Xcode 5) (Cont'd)

iPhone Multiview Navigation-Based Apps (with Table Views)    DONE
  • Table Views { toolset to display list of cells onscreen by Category and Sub Category, they respond to touch events and allowing users to scroll up and down, with each single cell structured to contain multiple pieces of info, and cells broken into sections of info clusters }
    • Types
      • Plain (aka Index Tables) { lack visual separation of sections of grouped tables
      • Grouped 
    • Implementation
      • UITableView { instance creates table view }
        • Methods:
        • accessoryType ("disclosure indicator" array. touching reveals details)
      • UITableViewController { subclass instance handles interactions with table view and conforms to req'd protocols }
      • UITableViewDataSource Protocol { provide data for table to display } 
        • Methods: 
        • numberOfSectionsInTableView (qty table sections)
        • tableView:tableViewNumberOfRowsInSection (qty rows in each section)
      • UITableViewDelegate Protocol { creating cells in table and react to user selection }
        • Methods:
        • tableView:titleForHeaderInSection (string title section no.)
        • tableView:cellForRowAtIndexPath (returns UITableViewCell object for table section and row)
        • tableView:didSelectRowAtIndexPath { react to row touch event from user using indexPath instance }
      • NSIndexPath { communicates row and section info (IndexPath for incoming objects in table methods with accessors IndexPath.section and IndexPath.row }
        • Methods:
        • UILabel object { textLabel, setText }
    • Memory Management
      • Reuse cells no longer req'd to generate current display instance of allocation across all table cells
  • Navigation Controller { allow user to drill down multiple views of data }
  • Navigation Controller Stack { new views appear when view controllers are instantiated and pushed onto the navigation controller stack or to go back the navigation controller pops the current view off the stack to unload it and previous view moves to top of stack and becomes active }
  • Apple Navigation-Base Application Template
    • Preparation
      • UINavigationController { instance of Root View Controller and subclass of UITableViewController. It is a navigation controller that provides functionality to push and pop other controllers }
        • Properties: { title property }
      • UINavigationBar { horizontal navigation bar with UI elements to navigate views }
      • UINavigationItem { used to display title in navigation bar }
Links:

Friday, 25 April 2014

Post WDI - iPhone Multiview App Architecture (Multiple-View Controllers, Toolbars)

iPhone Development (Xcode 5) (Cont'd)

iPhone Multiview Apps (with Toolbar) (manually created)   DONE
  • UIViewController { load and swap multiple @class subviews (separate controller structure) with UIView instance method insertSubView:atIndex. use default controller to clear current view (i.e. clearView ), remove inactive subviews  where superview property is tested to be nil using removeFromSuperView for individual or simultaneous views }
  • UIToolbar and UIBarButtonItem { overlayed floating subview index to switch views based on event action (i.e. Touch Up Inside) }


iPhone Multiview Apps (with Tab Bar) (expedited method)   DONE
  • UITabBar and UITabBarController (not the Apple default tab bar)
    • UITabBarControllerDelegate Protocol has all optional methods 
    • appplicationDidFinishLaunching method to add tabBarViewController instance
    • floatValue of NSString class provides floating point numbers from user input returning 0.0 for incorrect input allowing valid calculation always
    • viewWillAppear method used as hook to only update view just before displayed onscreen when we have access to all objects

Events Upcoming
    • ATTENDED - MyBirthdayApp, 28th Apr 2014
    • ATTENDED - Sydney MongoDB Meetup, 6pm, 29 Apr 2014 (MongoDB Australia, 2-12 Foveaux St Surry Hills)
    • ATTENDED - Entrepreneurs of 2025 - (Start Presenting To Groups) - 6:30pm 30 Apr 2014 (Level 1 99 York St) - Organiser and Host (Cyril Sansano) Beware: Nobody turned up except for me despite 11ppl RSVP'ing!!!
    • ATTENDED  - GA Launch Party - 6-9pm, Fri 2 May 2014 GA Sydney (York St), 56-58 York St