Skip to content

Instantly share code, notes, and snippets.

@pythonicrubyist
Last active August 29, 2015 14:16
Show Gist options
  • Save pythonicrubyist/4019e059786ccccf3df7 to your computer and use it in GitHub Desktop.
Save pythonicrubyist/4019e059786ccccf3df7 to your computer and use it in GitHub Desktop.
IOS developments with Swift
// Actions are method invocations from View to View Controller.
// Outlets are method invocations from View Controller to view.
// Initial Setup for ViewControllers
// ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work.
// ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
// ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
// ViewWill/DidDisappear - Same idea as WillAppear.
// ViewDidUnload/ViewDidDispose - In Objective C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.
// Displaying date
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE hh:mm:ss a z"
println(formatter.stringFromDate(date))
// Generating random integers
let lower : UInt32 = 1
let upper : UInt32 = 6
let randomNumber = arc4random_uniform(upper - lower) + lower
return Int(randomNumber)
// Adding UI elements using code
class ViewController: UIViewController {
var count = 0
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Creating a label using code only.
var label = UILabel()
label.frame = CGRectMake(150, 150, 60, 60)
label.text = "0"
self.view.addSubview(label)
self.label = label
// Creating a button using code only.
var button = UIButton()
button.frame = CGRectMake(150, 250, 60, 60)
button.setTitle("Click", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(button)
// Assigning an action to the target.
button.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside)
}
func incrementCount(){
self.count++
self.label.text = "\(self.count)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// Image Picker
let nextController = UIImagePickerController()
self.presentViewController(nextController, animated: true , completion: nil)
// Activity
let image = UIImage()
let nextController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.presentViewController(nextController, animated: true, completion: nil)
// Alerts
let nextController = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {action in self.dismissViewControllerAnimated(true, completion: nil)}
nextController.addAction(okAction)
self.presentViewController(nextController, animated: true, completion: nil)
// Navigating to a dirfferent controller using code
// Get the NextViewController
var controller: NextViewController
controller = self.storyboard?.instantiateViewControllerWithIdentifier("NextViewController") as! NextViewController
// Set the two values to random numbers from 1 to 6
controller.firstValue = self.randomNextValue()
controller.secondValue = self.randomNextValue()
// Present the view Controller
self.presentViewController(controller, animated: true, completion: nil)
// Navigating to a dirfferent controller using segues:
performSegueWithIdentifier("segueID", sender: self) // this line can be done using only Storyboard as well.
func prepareForSegue(_ segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "rollDice" {
let controller = segue.destinationViewController as! SECONDViewController
controller.firstValue = self.firstValue
controller.secondValue = self.secondValue
}
}
// Delegate Pattern
// A Delegate is an object that executes a set of functions on behalf of another object.
// the ability to resue views without needing to subclass or modify them, is an important goal of Swift. Wiew classes should be used as is
// A protocol is a list of functions a deligate needs to implement.
// Basic TabelView
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let favoriteThings = [
"Raindrops on roses",
"Whiskers on kittens",
"Bright copper kettles",
"Warm woolen mittens"
]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.favoriteThings.count
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
return nil
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// In attributes inspector, incrase the count of "Cell Prototype" to 1.
// Then click on the profotype cell and set ites identifier to "FavoriteThingCell"
let cell = tableView.dequeueReusableCellWithIdentifier("FavoriteThingCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = favoriteThings[indexPath.row]
return cell
}
}
// Add a Start Over Button
// Set the class of each of the story nodes to “ViewController”
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start Over", style: UIBarButtonItemStyle.Plain, target: self, action: "startOver")
}
func startOver(){
if let navigationController = self.navigationController {
navigationController.popToRootViewControllerAnimated(true)
}
}
}
// ViewControllers are deinitialized when they slide off the screen to the right.
// Add a Start Over Button
// Set the class of each of the story nodes to “ViewController”
class ViewController: UIViewController {
deinit(){
println("VC deallocated...")
}
}
// Connecting to Web services
/* 1 - Define constants */
let BASE_URL = "https://api.flickr.com/services/rest/"
let METHOD_NAME = "flickr.galleries.getPhotos"
let API_KEY = "ENTER_YOUR_API_KEY_HERE"
let GALLERY_ID = "5704-72157622566655097"
let EXTRAS = "url_m"
let DATA_FORMAT = "json"
let NO_JSON_CALLBACK = "1"
/* 2 - API method arguments */
let methodArguments = [
"method": METHOD_NAME,
"api_key": API_KEY,
"gallery_id": GALLERY_ID,
"extras": EXTRAS,
"format": DATA_FORMAT,
"nojsoncallback": NO_JSON_CALLBACK]
/* 3 - Initialize session and url */
let session = NSURLSession.sharedSession()
let urlString = BASE_URL + escapedParameters(methodArguments)
let url = NSURL(string: urlString)!
let request = NSURLRequest(URL: url)
/* 4 - Initialize task for getting data */
let task = session.dataTaskWithRequest(request) { data, response, downloadError in
if let error = downloadError {
println("Error occured: \(error)")
} else {
var parsingError: NSError? = nil
let parsedResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as NSDictionary
println(parsedResult)
}
})
task.resume()
// Five stages of apps in iOS:
// 1. Active: This is the state of the app that is actively controlling the screen.
// 2. Background: This is the state of apps that are actively running, but are not on screen. Consider the Maps app, giving directions while you check your email. Or a music app, playing audio while you look up something on the map.
// 3. Not Running: The state of apps that have never been started, for instance.
// 4. Inactive: This is the state of an app that was running, until the user taps the home button, or receives a phone call.
// 5. Suspended. This is the state of apps that could be running in the background, but have no work to do.
// Persisting User Data in IOS:
// Storing a value in NSUserDefaults
NSUserDefaults.standardUserDefaults().defaults.setFloat(22.5 forKey: “myValue”)
// Retrieving a value from NSUserDefaults
let value = NSUserDefaults.standardUserDefaults().floatForKey(“myValue”)
// Building the path for a file in the Documents directory
let filename = "usersVoice.wav"
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let pathArray = [dirPath, filename]
let fileURL = NSURL.fileURLWithPathComponents(pathArray)!
// Checking to see if a file exists
if NSFileManager.defaultManager().fileExistsAtPath(audioFileURL().path!) {
shouldSegueToSoundPlayer = true
}
/ Persistance with CoreData
// Try to get a reference to the context
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext!
println("context has changes to save: \(context.hasChanges)")
// Using properties:
var sharedContext: NSManagedObjectContext {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
return delegate.managedObjectContext!
}
let fetchRequest = NSFetchRequest(entityName: "Person")
let results = sharedContext.executeFetchRequest(fetchRequest, error: error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment