So you got past the intro and learned about the health store and how we need authorization from the user in order to have read and write access to certain properties. Now that the user trusts your app, let’s learn how to interact with the health store. 1. HKObjects and the health store Before we get into reading and writing, let’s get to know HKObjects. Here is the class tree: As you can see, HKObjectType inherits directly from NSObject. You can basically have 2 types of HKObjects; HKCharacteristic and HKSample -Type. HKCharacteristicType doesn’t change over time whereas HKSampleType does change, such as calories consumed, calories burnt, Glucose levels etc. Let’s… Read More
Continue ReadingHealthKit for iOS8: Part 1
Intro: What it’s for? HealthKit is a framework that allows you to store health data to a persistent store on the users device. We will begin with an app from Part 1 but we will take some detours that are important to understand so bare with me. The first steps are: – Create a tab bar application in Swift for iPhone Only – Rename First and Second view controllers to Profile and Journal and make them UITableViewControllers – In Capabilities turn on HealthKit HealthKit, (HK), requires permissions to access the health store since most of this data is considered confidential. So to do this, move over to the AppDelegate.swift.… Read More
Continue ReadingSwift Closures Quick Reference: Part 3
Now let’s write our own closure! func fetchMostRecentDataOfQuantityType(quantityType: HKQuantityType, withCompletion completion: ((mostRecentQuantity:HKQuantity?, error:NSError?) -> ())? ) { let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) [timeSortDescriptor], resultsHandler: { (query:HKSampleQuery!, results:[AnyObject]!, error:NSError?) -> Void in let query = HKSampleQuery(sampleType: quantityType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor]) { query, results, error in if completion != nil && error != nil { completion!(mostRecentQuantity: nil, error: error) return; } let resultsArray = results as NSArray? var quantitySample: HKQuantitySample? = resultsArray?.firstObject as HKQuantitySample? var quantity: HKQuantity? = quantitySample?.quantity if completion != nil { completion!(mostRecentQuantity: quantity, error: error) } } self.healthStore?.executeQuery(query) } Notice we declare a function that takes a quantityType parameter and a completion parameter. The… Read More
Continue Reading
HealthKit for iOS8: Part 4
Ok so the Journal view controller was quite simple. Let’s take another quick break by looking at an even simpler view controller, the FoodPicker: import Foundation import UIKit import HealthKit class FoodPickerViewController: UITableViewController { var selectedFoodItem: FoodItem? let FoodPickerViewControllerTableViewCellIdentifier:NSString = “cell” let FoodPickerViewControllerUnwindSegueIdentifier:NSString = “FoodPickerViewControllerUnwindSegueIdentifier” var foodItems: NSArray = NSArray() var energyFormatter: NSEnergyFormatter { var energyFormatter: NSEnergyFormatter? var onceToken: dispatch_once_t = 0 dispatch_once(&onceToken, { energyFormatter = NSEnergyFormatter() energyFormatter?.unitStyle = NSFormattingUnitStyle.Long energyFormatter?.forFoodEnergyUse = true energyFormatter?.numberFormatter.maximumFractionDigits = 2 }) return energyFormatter! } var healthStore:HKHealthStore? } Here we are looking at imports, subclassing UITableViewController and property declarations. Our first property is selectedFoodItem, which will be set to whatever value the user selects from… Read More
Continue ReadingSwift Closures Quick Reference: Part 2
Let’s analyze some useful applications of closures in everyday code! Ok so let’s take a look at a real life function that uses a closure. A typical closure is a completion handler. A completion handler is a parameter, just like any other, that is passed into a function as a closure. When that code gets executed, the completion handler gets filled. Then your function will use the value of that completion handler to do something useful. Here are some typical uses of closures in API’s. The typical one is UIView.animateWithDuration. Open Xcode and start writing UIView.anim… and it will autocomplete for you with this: UIView.animateWithDuration(<duration: NSTimeInterval>, animations: <() -> Void()… Read More
Continue ReadingSwift Closures Quick Reference: Part 1
Blocks/Closures are confusing! They’re confusing because its a bit abstract. Most tutorials cover how a block is declared and used. Sometimes blocks or closures can me even more confusing… A block is a bunch of code wrapped up in a {}. You can 2 either of 2 things with them: A. You can assign that block of code to a variable. (this is where completionHandlers, also a confusing concept, fit in) B. You can use that block of code directly Let’s take a look at assigning it to something. No doubt you have seen a construct like: var someName = “Mars” or var hisAge = 39 This would be considered hardcoding… Read More
Continue ReadingSwift is Confusing: Classes, Structures, Designated Initializers, Instance Methods, Type Methods, Functions, Methods, Convenience Initializers & External Parameter Names
Class vs Structs Both: Store values, initialize, subscripts, extensible & protocol Class can inherit, de-initialize, reference counting & typecast Functions vs Methods Methods are FUNCTIONS INSIDE A CLASS Functions can be inside or OUTSIDE A CLASS! Cannot use functionName(param1,param2) to call a function declared inside a class {} Methods: It is implicitly passed the object for which it was called It is able to operate on data that is contained within the class Instance Methods vs Type Methods (Instance Method vs Class Methods I think) Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for… Read More
Continue Reading
Swift Optionals Quick Reference
Optionals confuse me so I wrote this post and hope it can be of some help. OPTIONALS Takeaway #1: Optionals are used to declare a variable but are not assigned a value at start Takeaway #2: Optionals contain a Some or None value, they DONT contain a String or Array or whatever else. Takeaway #3: Therefore we MUST unwrap the value of an Optional to see what the prize is 🙂 In other words, to access its value! Takeaway #4: DECLARATION OPTIONS A) Using the following syntax: var someVar? – You will mostly use this… B) Using “var someVar!” <Implicitly unwrapped> – Unfortunately UIKit & other Apple frameworks will use a lot of… Read More
Continue ReadingWhy, oh Why, did Apple take away ARC just to give us Optionals!?
I’m having trouble understanding optionals so here is a shot at explaining them. 🙂 var thisIsAnInt: Int Simple, this is an Int variable declaration. var couldBeAnInt: Int? This on the other hand is an optional variable declaration. This optional declaration doesn’t mean: “this is an int, which is optional”. It reads more like: This is an OPTIONAL variable. It’s a type of variable in and of itself. Its NOT NECESSARILY an Int. It just may or may NOT contain an Int”. Woah! Ok so what is it for and when do you use it. Well that part seems simple enough: If that variable can or could or may be nil… Read More
Continue ReadingiOS : Swift : Blocks = Closures
I’ve never really liked blocks in ObjC. When Swift came out it made things more complicated for me because I’ve never really liked C either. Finally when I had to deal with closures in Swift, well that’s just gonna piss a lot of people off! After a few days reviewing tons of material online, and I mean TONS! I came to understand this: The only C-like exposure I had prior to ObjC was a little PHP. So that allows me to understand a function, which is the equivalent of a method in ObjC: DECLARING func sayHello( ) { println(“Hello World”) } CALLING sayHello( ) RESULT Hello World Even… Read More
Continue ReadingiOS7 Custom Transitions
iOS7 Series –Custom Transitions There is a hierarchy of actors you need to visualize here. It goes a little something like: A TransitioningDelegate An AnimatedTransitioning A ContextTransitioning The VC you start out with and that will call the transition will adopt the first protocol, the TransitioningDelegate Protocol. The purpose of doing so is to obtain the authority to manage the entire transition process. You will then create a Transitioning class which we can call the Transition Manager. This class will adopt the AnimatedTransitioning protocol. The purpose of this protocol is to animate the transition. The Transition Manager class receives all the necessary information from the Transitioning Context (a protocol adopted… Read More
Continue ReadingBusiness of iOS Apps
I keep reading articles or watching videos of iOS businesses who made it and they share their wisdom of the Common 10 Mistakes iOS developers make. Guess what? Most of those mistakes, although they are worded as developer concepts, they are really business concepts. Common Mistakes: Don’t need a marketing guy. Don’t need a business guy. Don’t need a business perspective. Usually worded as, I thought I would get rich quick, or Im looking for a one hit wonder, or Im a great programmer and I thought that was enough. Well guess what, if you are going to sell something and make more than 99c for it, its gonna need… Read More
Continue Reading
Fetching data from an iOS app – The new NSURLSession API
Ok, this is gonna be short, I promise! 🙂 Do you remember those apps you’ve got stored away or the ones you are working on that fetch data from the web with a NSURLConnection? Time to update them, here’s how. Basically you have a method that calls a web fetch and is somehow signaled to use that received data to refresh a UI. If you used NSURLConnection sendAsynchronousRequest:, you have the issue that it blocks the main thread. It does carry out requests asynchronously from each other, but each request does indeed block the main thread since it is carried out in the main queue. Alternatively, you can use a… Read More
Continue ReadingCreating a Menu in SpriteKit
Cocos2d has a easy to use CCMenu object to which you add CCMenuItems. In SpriteKit however, you are back to UIKit objects. This doesn’t not mean its more complicated, its just different :-). You will need to create a UIControl such as a button or you can use SpriteKit’s SKNode to create the visual object onscreen: SKLabelNode* someNode = [SKLabelNode labelNodeWithFontNamed:@”Chalkduster”]; [someNode setText:@”Play Game”]; [someNode setPosition:CGPointMake(CGRectGetMidX(self.frame)+5,CGRectGetMidY(self.frame)-40)]; [self addChild: someNode]; Now you simply connect the object action to some event like so: for (UITouch *touch in touches) { CGPoint location = [touch locationInNode:self]; if ([someNode containsPoint:location]) { SKTransition* present = [SKTransition revealWithDirection:SKTransitionDirectionDown duration:1]; GameScene* gameScene = [[GameScene alloc] initWithSize:CGSizeMake(1024, 768)]; [self.scene.view… Read More
Continue ReadingSwift Tutorial II
Ok so in the first tutorial we covered let, which is the keyword for defining constants. let thisBeAConstant = 3.141 Now we are going to cover variables, which use the var keyword like so: var thisVariable = time Notice 2 things about Swift: 1) We don’t use ; at the end of a line. That’s just weird 🙂 2) We don’t have to specify the type. The type is inferred by whatever value you pass in, so: var someString = “this is a string” var someInteger = 5 So Swift is kinda smart. Now let’s meet some old friends “Hao jiu bu juan” ARRAYS var energies = [“solar”, “wind”, “fossil”, “this is a… Read More
Continue ReadingFirst SWIFT Tutorial ever! :-)
let is used for assigning constants whereas var is used for creating variables. ie: let salute: Character = “Hey there…” let everyone: Character = “Swift World” var saluteEveryone = salute + everyone saluteEveryone = saluteEveryone + “!”
Continue ReadingComment Coding – Coding for Visual Learners
I’ve mentioned this in my online courses as well as classroom courses and its usually overlooked. I think its an important design technique for those of us who are Visual Learners. What’s a Visual Learner? Many people, prime examples are asian students, are great at math because they are quick to grasp abstract tasks. They can read a sentence or paragraph and understand everything the first time. Not me! I’m the kind of person that has to read concepts 10 times over and still have trouble applying it. I need visual representations of concepts in order to understand them. As a matter of fact, I review iOS and Cocos2D books and… Read More
Continue ReadingCreating a simple UICollectionView in iOS
Steps 1) Create Master-Detail Application & Replace the MasterViewController First we want to create a Master-Detail Application just because it sets up a Master-Detail relationship even though thats the first thing we are going to break :). So go ahead and create a new project in XCode4 based on a Master-Detail Application type. Use ARC, Storyboards and CoreData because we will use CoreData to store information. Your storyboard should look like this: Now select the Master scene until its highlighted in blue and delete it with the Delete key. We simply replace it by dragging in a UICollectionViewController onto the storyboard in its place. This places a UICollectionViewController scene with… Read More
Continue ReadingiOS7 – UIKit Dynamics
iOS7 Series – UIKit Dynamics Incorporating UIKitDynamics into your app is pretty simple! The great thing about it is that you really get the most bang for your buck because the end result has a really big WOW Factor which is certain to impress your users. Let’s take a quick conceptual drive around UIKitDynamics. First we adopt the protocol into the ViewController which will implement UIKitDynamics, why? Well because the objects which will be animated in the end will have to send back a lot of signals like “Hey, I collided with a boundary” or “hey I just hit somebody else and I was going this fast, in this… Read More
Continue ReadingiOS Smarties :)
Everyone loves Smarties! And much the same way Smarties Candies make you smarter… today we are talking about Code Snippets that make you….er Smarter! More than a source of cut/paste Objective C source code, this is meant to be a quick reference. As such, some of these will be incomplete and I will be filling them up as I go along. 1) UIAlertView UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle:@”No hay farmacias” message:@”Favor cambie sus parámetros” delegate:self cancelButtonTitle:@”Cancelar” otherButtonTitles:@”Ok”, nil]; [internetAlert show]; 2) NSNotification //1. Register as observer of notifications in viewDidLoad [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@”TestNotification” object:nil]; //2. NSNotifCtr CLEANUP in viewDidUnload [[NSNotificationCenter defaultCenter] removeObserver:self]; //4. Post notif to NSNotif in… Read More
Continue ReadingFirst Google Glass App – Part 8 – Hello Glass!
Jumping right in, let’s create a Glass GDK project from scratch: Create New Android Project Configure GDK Imports Code qwe To create a new project…See our Part 1 of the tutorial. Make sure to configure the Glass GDK Sneak Peek Manually if it didn’t get configured by Android Studio or Eclipse on set up. As it turns out, even if you create a project setting GDK as the Compile for API, it doesn’t get created as such. You must double check in your build.gradle file (CAREFUL, there are 2 such files. You need to modify your inner most gradle file) and make sure it looks something like this: And you… Read More
Continue ReadingiOS7 Sprite Kit for Game Design for iPhone & iPad
iOS 7 Series – Sprite Kit Welcome to iOS7 and to start off, I want to kick things off with SpriteKit. Although it deals with video games, many companies are using iOS apps as a marketing tactic to engage their users in an effort to promote their products. SpriteKit is the most prominent feature in iOS7 so we’re going to take a quick tour. Go ahead and create a New Project in XCode5 and select the SpriteKit template (the bottom right icon): Click next and fill in your project data. Once you are in the main XCode window notice we have the following files in the Project Navigator: 1) AppDelegate… Read More
Continue ReadingFirst Google Glass App – Part 7 – Bridge to Glass App GDK Development
Before jumping into Glass dev, let’s understand how to create a Hello World project in Android Studio (AS) and run it on our device. Create New Project Get to know the guts Add Imports Add Code Tweak guts Run on Device Create New Project When you select New Project from the File Menu, you get this Wizard screen: Fill in the Application Name in a natural language and the Module Name without spaces. Make sure to select API 15 for Minimum and Target SDK but Glass Development Kit Sneak Peek for Compile with. Click Next and in the next screen just leave everything as is (the launch icon selector screen).… Read More
Continue ReadingFirst Android App – Part 6
My First Android App Now we are going to receive the input of this message and use the button to send it. To do so, edit your Button declaration to look like this: <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/button_send” android:onClick=”sendMessage” /> We are simply telling it to respond to the onClick button action by calling the sendMessage method. So we must declare this method in code, of course. Open your MainActivity.java file and add the following: /** Called when the user clicks the Send button */ public void sendMessage(View view) { // Do something in response to button } We are declaring a public method that returns void, is called sendMessage and… Read More
Continue ReadingGlass Development Mirror API – Part 4 – Where to start after setting up!
So you have Glass and you want to develop apps for it? You already have an IDE such as Eclipse or Android Studio to code your apps in, you know all about adb and Droid@Screen to view your Glass screen on your computer screen! Well you do have options, before jumping into your typical Hello World Glass app. As with other platforms like iOS, you have the option of native apps and web based services apps. This last option is basically an app that runs on a server(s) and interacts directly with your device (be it Glass or iDevice) by sending it information. Native – GDK – Apps These are… Read More
Continue ReadingHow to create an app – Not programmatically
A fellow coder asked: “How does one go about developing an app from scratch? Where does one start?” My response follows: Some will say its a matter of style and you have to find your own. And eventually you will, after a lot of copy-paste programming. I started in 2009 and my first app was a copy-paste of a few different projects. All the app did was connect to the Internet, download XML and parse it into a uilabel. Then I decided to look into more complex app samples. So I downloaded a few from Apple. In particular I remember iPhoneCoreDataRecipes. In hindsight, it was too complex for a beginner… Read More
Continue ReadingObjC Programming
The Big Picture ObjC is OOP which means objects send messages to other objects. Before getting into messages, let’s define objects. Objects. This is very diverse. An object can be a string, a number, a Boolean, an integer, an array, a dictionary or even one you create yourself. There are any types of objects but let’s start at the root object. The root object is called NSObject. You’ll see references to it in code but you’ll hardly ever use it directly. This is called the root object because it’s the starting point of any object. It’s like Adam and Eve rolled into one and ANY other kind of object in… Read More
Continue ReadingStatic Libraries in iOS – Video Tutorial
Libraries is another one of those rather obscure topics for newbie programmers, kinda like Blocks and Delegates/Protocols. Think of libraries as just that, a resource you can use which doesn’t belong to you. A loaner 🙂 NOTE: If you need a nice tutorial on Blocks or Delegates, check out: Video Tutorial: Objective-C Blocks Video Tutorial: Objective-C Protocols and Delegates Ok back to our tutorial! Well a library is a piece of code that you can use (by importing it into your projects) but its not yours, so you can’t really do what you want to that piece of code, except use its functionality. In this tutorial we will create our… Read More
Continue ReadingCommand line prompts
ls ping netstat open locate sqlite sudo nano /etc/apache2/httpd.conf Computers are amazing! We all love telling them what to do. It’s like having you’re own personal assistant. And while adding calendar appointments, editing presentations and browsing web pages is very sophisticated nowadays, command prompt shells are so much more appealing, to me anyway. I remember the first time I used a command prompt was in my uncle’s Apple IIe back in San Francisco. Who didn’t love making printout loops using * to draw shapes and spell words…or since we are geeks, draw a big heart on the screen. I also remember computer class back at school at EIS. The 10… Read More
Continue ReadingFirst Android App – Part 5
My First Android App Android is based on Java much like iOS is based on ObjectiveC. If you are coming from an iOS background, itll be a bit jarring at first. Even though ObjC “comes from” C, C formats are a bit different. So I thought Id start with that first. ObjC: [myObject methodForDoingThis:someParameter]; is a method call which refers to this declared method: -(void)methodForDoingThis: (id)someParameter{ //1. Take the passed in parameter //2. Do something to with that parameter value //3. Call some other method… //4. Or if this were a method that returned an object instead of void //4. Return a new object value } C: myObject.methodForDoingThis(someParameter); is… Read More
Continue ReadingGoogle Glass – Part 2 – Pros & Cons
In the first review I covered basically what Glass is and what its not, what it can & can’t do. Now on to usability! PROS (IMHO) The biggest advantage in my opinion, is being able to interact with information without having to look down like a zombie. Or more importantly, not just the fact that we all look like zombies throughout the day, constantly checking our phones. Because of course some will argue we are “Glassholes” or look like morons wearing these glasses. But if you’re a true techie, you don’t care how something looks, you care about what it can do. Its very comfortable to be able to get… Read More
Continue ReadingOAuth & PKI for Dummies
I’ve been programming for a few years and I’ve heard of PKI and OAuth for a while. I’ve read about it in SSL certificates for servers and even installed certificates. I’ve signed many apps with certificates and I’ve granted access to many others for Facebook or Twitter interaction. I’ve looked around for definitions or explanations lately and came up empty handed. So I’ve put together this article to not only explain it but to try and make sure I DO understand as much as I think I do and point out the parts I DONT! What OAuth is and what isn’t! It’s not a login replacement. Logging into apps is… Read More
Continue ReadingGoogle Glass & Android Series for Developers & Users
So I’ve gotten a little carried away with the Glass-Android thing. My posts are as disorganized as my thoughts, so I thought I’d organize my posts a bit. Here is the set of posts for Android & Glass Development as of Feb 15th, 2014: Google Glass Review – Part 1 – 什么 (shen me = what = what Glass is & isn’t) Google Glass Review – Part 2 – Pros & Cons Develop apps for Google Glass – Part 3 – Setting up! Glass Development Mirror API – Part 4 – Where to start after setting up First Android App – Part 5 First Android App – Part 6 First Google… Read More
Continue ReadingGoogle Glass Review – Part 1- 什么
I got my Glass a little late…but here is my review! What they are? You might think the answer is obvious, but its not. Its a wearable computer but its not a full blown computer. Does that make it less of a computer? Not really, unless you consider ipads and iphones less than a computer because you can’t do ALL the things you can normally do on a full blown laptop. What can you do with them? Since we already mentioned you can’t do everything you can on a full blown computer, let’s talk about what we CAN DO! Out of the box, Glass comes with a few commands such… Read More
Continue ReadingDevelop apps for Google Glass – Part 3 – Setting up!
If you have experience in Android (Java) development, this will be even easier. What you’ll need: Google Glass – to test your apps on Eclipse or Android Studio for coding Android SDK 15 & Glass Development Kit Sneak Peek (GDK) Configure adb Glass Well you either borrow a pair or get your own, but you will need Google Glass to test your apps. The reason being that there is no Glass emulator as there is for Android as of yet. Eclipse or Android Studio Eclipse is the most widely known IDE for Android programming but its worth getting to know Android Studio, the new IDE for developing on Android &… Read More
Continue ReadingBlocks & Completion Handlers
Think of blocks as c functions: (return type)functionName(input1, input2) { input1 + input2 } and you call it like this: return type = functionName (1,2) Blocks are similar: NSInteger (^mathOperation)(NSInteger x, NSInteger y) = ^NSInteger(NSInteger x,NSInteger y){ return x + y; }; You call it like this: NSInteger sum = mathOperation(1,2); Now imagine how cool it is to, instead of just passing a value to a method (like saying: here is a value, evaluate it), you can pass a whole method to it (like saying: here is something else to do!). Or better yet, here do this but only when you finish doing that! Like, load the users posts or tweets after you finish authenticating him!… Read More
Continue ReadingCreating Reactive Cocoa Xcode project
Earlier I posted an article on using RAC. It was a plain vanilla example of using RAC. While I AM working on a second post with more useful examples, I wanted to go over how to ADD RAC to a project. First, you must have ruby installed. This means, go to Terminal and type in: which ruby This is what I get: …../.rvm/rubies/ruby-2.1.0/bin/ruby Important to note here that if you don’t have that rvm bit, you might still have ruby. RVM stands for Ruby Version Manager and for what little I know about ruby, its one of the managers available for ruby but there are others. If… Read More
Continue ReadingReactive Cocoa in 3 simple steps!
If you made it through installing ReactiveCocoa, via Cocoapods, which required you to have ruby, update it and install Cocoapods and CLT, then you’re already ahead! So here is RAC. RAC is used when you need to be notified of something important in your app; completed download, some long asynchronous task like data fetching, parsing or image processing is complete or to update UI such as a completed form produces an active Submit button or an incomplete field yields a red warning sign to the user. How does RAC work? You basically create signals for events you are interested in (like the ones mentioned above) and then you tie those… Read More
Continue Reading