swift

Singleton approach

class TestSingleton {
  static let sharedInstance = TestSingleton()
  var title = ""
  private init() {}
}

let t1 = TestSingleton.sharedInstance
t1.title = "A"
let t2 = TestSingleton.sharedInstance
t2.title = "B"

println(t1.title) // B
println(t2.title) // B

Tags: 

Extension for structure your code

class TestViewController: UIViewController {

  @IBOutlet weak var tableView: UITableView!
 
  override func viewDidLoad() {
    super.viewDidLoad()

    styleNavigationBar()
    }
}

private typealias TableViewDataSource = TestViewController
extension TableViewDataSource: UITableViewDataSource
{
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 0
  }
 
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! UITableViewCell
    return cell
  }
}

private typealias TableViewDelegate = TestViewController
extension TableViewDelegate: UITableViewDelegate
{
  func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 64.0
  }
}

private typealias ViewStylingHelper = TestViewController
private extension ViewStylingHelper
{
  func styleNavigationBar()
  {
   
  }
}

Tags: 

BezierPolygon

func BezierPolygon(numberOfSides: UInt) -> UIBezierPath {
  let path = UIBezierPath()
  let length : CGFloat = 20.0
  let center = CGPointMake(length, length)
  let radius : CGFloat = length
  var firstPoint = true
  for i in 0..<(numberOfSides - 1) {
    let theta = M_PI + Double(i) * 2.0 * M_PI / Double(numberOfSides)
            let dTheta = 2.0 * M_PI / Double(numberOfSides)
   
    var p = CGPointZero
    if firstPoint {
      p.x = center.x + radius * CGFloat(cos(theta))
      p.y = center.y + radius * CGFloat(sin(theta))
      path.moveToPoint(p)
      firstPoint = false
    }
   
    p.x = center.x + radius * CGFloat(cos(theta + dTheta))
    p.y = center.y + radius * CGFloat(sin(theta + dTheta))
    path.addLineToPoint(p)
  }
  path.closePath()
  return path
}

from Erica Sadun Playground Secrets and power tips

Tags: 

Google Analytics

in bridging header

#import "GAI.h"
#import "GAIFields.h"
#import "GAILogger.h"
#import "GAITracker.h"
#import "GAIDictionaryBuilder.h"

in appdelegate

    GAI.sharedInstance().trackUncaughtExceptions = true
    GAI.sharedInstance().dispatchInterval = 20
    GAI.sharedInstance().logger.logLevel = GAILogLevel.Verbose
    GAI.sharedInstance().trackerWithTrackingId("XX-123123123-1")

event tracker

    var tracker = GAI.sharedInstance().defaultTracker
    tracker.send(GAIDictionaryBuilder.createEventWithCategory("Button", action: "Pressed", label: "Button", value: nil).build() as [NSObject : AnyObject])

swift 2.0

        let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        let tracker = appDel.tracker //GAI.sharedInstance().defaultTracker
        let eventTracker: NSObject = GAIDictionaryBuilder.createEventWithCategory( "Item bought", action: "bought", label: "itemId", value: 1).build()
        tracker.send(eventTracker as! [NSObject:AnyObject])

Tags: 

Remove from array

var array = ["qwe","findmeTORemove","zxc"]

var foundIndex = [Int]()
var ind = 0
for a in array
{
  if a == "findmeTORemove"
  {
    foundIndex.append(ind)
   
  }
  ind++
}
array
for var i = foundIndex.count-1 ; i >= 0 ; i--
{
  array.removeAtIndex(foundIndex[i])
}


array = ["qwe","zxc"]

Tags: 

uiview shape

override func drawRect(rect: CGRect) {
   

    let context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor)
    CGContextSetFillColorWithColor(context, fillColor.CGColor)
    CGContextSetLineWidth(context, lineWidth);

    CGContextMoveToPoint(context, (self.frame.width / 2) , lineWidth)
    CGContextAddLineToPoint(context, self.frame.width - lineWidth, self.frame.height - lineWidth)
    CGContextAddLineToPoint(context, lineWidth, self.frame.height - lineWidth)
    CGContextClosePath(context)
    CGContextDrawPath(context, kCGPathFillStroke)
   
    CGContextStrokePath(context)
  
   
  }

Tags: 

twitter tweet

if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
    {
     
      var controller = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
      controller.setInitialText("Solved a Sudoku! ")
      controller.addImage(UIImage(named: "solvedImage"))
      controller.addURL(NSURL(string: "http://www.megastar-games.com"))
      controller.completionHandler = {
        (result:SLComposeViewControllerResult) in
      
        println("twit finished")
      }
      self.presentViewController(controller, animated: true, completion: nil)
    }
    else
    {
      println("twit not available")
    }

Tags: 

UIApplicationDidBecomeActiveNotification

NSNotificationCenter.defaultCenter().addObserver(self, selector: "<#selectorString#>", name: UIApplicationDidBecomeActiveNotification, object: nil)

Tags: 

Dispatch_async

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
   
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
       
    })
})

Tags: 

Dispatch_after

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
   
}

Tags: 

Dispatch_main

dispatch_async(dispatch_get_main_queue(), { () -> Void in
   
})

Tags: 

mail with MFMailComposeVC

import MessageUI

//MARK: MFMailComposeViewController
   
    func presentModalMailComposeViewController(animated: Bool) {
        if MFMailComposeViewController.canSendMail() {
            let mailComposeVC = MFMailComposeViewController()
            mailComposeVC.delegate = self
           
            mailComposeVC.setSubject(<#subject#>)
            mailComposeVC.setMessageBody(<#body#>, isHTML: true)
            mailComposeVC.setToRecipients([<#recipients#>])
           
            presentViewController(mailComposeVC, animated: animated, completion: nil)
        } else {
            UIAlertView(title: NSLocalizedString("Error", value: "Error", comment: ""), message: NSLocalizedString("Your device doesn't support Mail messaging", value: "Your device doesn't support Mail messaging", comment: ""), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", value: "OK", comment: "")).show()
        }
    }
   
    //MARK: MFMailComposeViewControllerDelegate
   
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
       
        if error != nil {
            println("Error: \(error)")
        }
       
        dismissViewControllerAnimated(true, completion: nil)
    }

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{  
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            //NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Result" message:@"Mail Sent Successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
            break;
        case MFMailComposeResultFailed:
            //NSLog(@"Result: failed");
            break;
        default:
            //NSLog(@"Result: not sent");
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}

Tags: 

enum raw

enum GameStatus: Int {
 
  case initial = 0, playing, finished
}

var a = GameStatus.initial
a.rawValue // 0

var d = GameStatus(rawValue: 1)
d!.rawValue // 1

Tags: 

fetch find Core Data

    let appDel = UIApplication.sharedApplication().delegate as AppDelegate
    let fetchRequest = NSFetchRequest(entityName: "Puzzle")
    let predicate = NSPredicate(format: "title == %@", "Best Language")
    fetchRequest.predicate = predicate
    let managedContext = appDel.managedObjectContext
    var error:NSError?
    // Execute the fetch request, and cast the results to an array of LogItem objects
    if let fetchResults = managedContext?.executeFetchRequest(fetchRequest, error: &error){
      if error != nil {
        println("error fetch request \(__FUNCTION__)")
       
      }else {
       
        println("num results \(fetchResults.count)")
       
       
      }

Tags: 

time for timer calc

    let minutes:Int = Int( Float(elapsedTime) / 60.0 )
    let hours:Int = Int( Float(elapsedTime) / 3600.0 )
    let sec:Int = Int( fmodf(Float(elapsedTime), 60.0))

    var minuteStr = "\(minutes)"
    if minutes < 10 {
      minuteStr = "0\(minutes)"
    }
    var hourStr = "\(hours)"
    if hours < 10 {
      hourStr = "0\(hours)"
    }
    var secStr = "\(sec)"
    if sec < 10 {
      secStr = "0\(sec)"
    }
   
    timeLabel.text = "\(hourStr):\(minuteStr):\(secStr)"

Tags: 

Draw Line

UIColor.brownColor().set()
  let context = UIGraphicsGetCurrentContext()
  CGContextSetLineWidth(context, 5)
  CGContextMoveToPoint(context, 50, 10)
  CGContextAddLineToPoint(context, 100, 123)
  CGContextStrokePath(context)

Tags: 

GCD

After amount of time

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

so use it as:
delay(0.4) {
    // do stuff
}

swift 3

func delay(delay:Double, closure:()->Void) {
  DispatchQueue.main.after(when: DispatchTime.now()+delay, execute: closure)
}

Tags: 

nsnotificaton

Sent(Post) Notification

NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)

Receive(Get) Notification

NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)

Remove Notification

NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)

Method of received Notification

func methodOfReceivedNotification(notification: NSNotification){
    //Action take on Notification
}

Tags: 

instantiate vc programmaticly

let secondViewController:UIViewController = UIViewController()
    self.presentViewController(secondViewController, animated: true, completion: nil)

Tags: 

CoreData: warning: Unable to load class named

1.

enter image description here

Notice that I corrected your entity name to the more appropriate singular.

2.
You should also follow the frequent recommendation to include

@objc(Show)
just above your class.

3.
Also make sure to cast the created managed object to the proper class, as the default would be just NSManagedObject.

var newShow = NSEntityDescription.insertNewObjectForEntityForName("Show",
inManagedObjectContext: context) as Show

Tags: 

location core data database

func applicationDirectoryPath() -> String {
    return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String
}

Tags: 

stateMachine

as global func/type

typealias StateMachineType = () -> Int

func makeStateMachine(maxState:Int) -> StateMachineType{
  var currrentState: Int = 0
 
  return {
   
    currrentState++
    if currrentState > maxState {
      currrentState = 0
    }
    return currrentState
  }
 
}

Tags: 

Animations in swift

Music bars moving

func animationMusicBars() {
    let r = CAReplicatorLayer()
    r.bounds = CGRect(x: 0.0, y: 0.0, width: 60.0, height: 60.0)
    r.position = CGPoint(x: 60, y: 60)
    view.layer.addSublayer(r)
   
    let bar = CALayer()
    bar.bounds = CGRect(x: 0.0, y: 0.0, width: 8.0, height: 40.0)
    bar.position = CGPoint(x: 10.0, y: 75.0)
    bar.cornerRadius = 2.0
    bar.backgroundColor = UIColor.redColor().CGColor
   
    r.addSublayer(bar)
   
    let move = CABasicAnimation(keyPath: "position.y")
    move.toValue = bar.position.y - 35.0
    move.duration = 0.5
    move.autoreverses = true
    move.repeatCount = Float.infinity
   
    bar.addAnimation(move, forKey: nil)
   
    r.instanceCount = 6
    r.instanceTransform = CATransform3DMakeTranslation(9.0, 0.0, 0.0)
    r.instanceDelay = 0.13
    r.masksToBounds = true
   
  }

Spinning Blocks

func animationSpingBlocks(){
    let r = CAReplicatorLayer()
    r.bounds = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0)
    r.cornerRadius = 10.0
    r.backgroundColor = UIColor(white: 0.0, alpha: 0.75).CGColor
    r.position = CGPoint(x: 220, y: 120)
   
    view.layer.addSublayer(r)
   
    let dot = CALayer()
    dot.bounds = CGRect(x: 0.0, y: 0.0, width: 14.0, height: 14.0)
    dot.position = CGPoint(x: 100.0, y: 40.0)
    dot.backgroundColor = UIColor(white: 0.8, alpha: 1.0).CGColor
    dot.borderColor = UIColor(white: 1.0, alpha: 1.0).CGColor
    dot.borderWidth = 1.0
    dot.cornerRadius = 2.0
   
    r.addSublayer(dot)
   
    let nrDots: Int = 15
   
    r.instanceCount = nrDots
    let angle = CGFloat(2*M_PI) / CGFloat(nrDots)
    r.instanceTransform = CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0)
   
    let duration: CFTimeInterval = 1.5
   
    let shrink = CABasicAnimation(keyPath: "transform.scale")
    shrink.fromValue = 1.0
    shrink.toValue = 0.1
    shrink.duration = duration
    shrink.repeatCount = Float.infinity
   
    dot.addAnimation(shrink, forKey: nil)
    r.instanceDelay = duration/Double(nrDots)
    dot.transform = CATransform3DMakeScale(0.01, 0.01, 0.01)
 
  }

source: http://www.ios-animations-by-emails.com/posts/2015-march#tutorial

Tags: 

tableview

UITableview

properties:

var tableviewTitles = ["item 1","item 2", "item 3","item 4","item 5","item 6"]

in viewdidload()

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

obliged data en source methods

//MARK: tableview
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableviewTitles.count
  }
 
  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
  }
  let cellIdentifier = "cell"
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
    cell.textLabel?.text = tableviewTitles[indexPath.row]
   
    return cell
   
  }

with a lot of (large) images:

extension ViewController{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return images.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.text = images[indexPath.row]
        if cache.objectForKey("\(indexPath.row)") != nil
        {
            cell.imageView?.image = cache.objectForKey("\(indexPath.row)") as! UIImage
        }
        else{
           
        }
        return cell
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if cache.objectForKey("\(indexPath.row)") != nil
        {
            cell.imageView?.image = cache.objectForKey("\(indexPath.row)") as! UIImage
        }
        else{
            cell.imageView?.image = UIImage(named: "placeholder.png")
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                if let img = UIImage(named: "\(self.images[indexPath.row]).png")
                {
                    cell.imageView?.image = img
                    self.cache.setObject(img, forKey: "\(indexPath.row)")
                }
               
            }
        }
       
       
      
    }
}

Tags: 

background color to image

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))

UIView:

let banner = UIView(frame: CGRectMake(x, y, width, height))

UIGraphicsBeginImageContext(banner.frame.size)
UIImage(named: "banner_promo")?.drawInRect(banner.bounds)
var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
banner.backgroundColor = UIColor(patternImage: image)

Tags: 

iosfonts.com

fonts info:
http://iosfonts.com

Tags: 

Animate Image in UIImageView

for countValue in 1...20
    {
     
      var strImageName : String = countValue < 10 ?  "anim_jap000\(countValue).png" : "anim_jap00\(countValue).png"
     
      var image  = UIImage(named:strImageName)
      if image != nil{
       
        imgListArray.append(image!)
      }

      let animationImages:[AnyObject] = imgListArray
      imgView.animationImages = animationImages
      imgView.animationDuration = 1.5
      imgView.animationRepeatCount = 0
      imgView.startAnimating()
      //self.addSubview(loadingImageView)

Tags: 

ScreenSize

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

general func:

func getScreenSize() ->CGRect {
   
    return UIScreen.mainScreen().bounds
   
}

func getScreenWidth() ->CGFloat {
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    return screenSize.width
   
}

func getScreenHeight() ->CGFloat {
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    return screenSize.height
}

Tags: 

static var in Objc replaced by statemachinetype in swift

typealias StateMachineType = ()->Int

func makeStateMachine(maxState:Int)->StateMachineType{
 
  var currentState:Int = 0
  return {
    currentState++
    if currentState > maxState{
      currentState = 0
    }
    return currentState
  }
}

Tags: 

Are we on screen to load image?

var imageURL: NSURL? {
    didSet{
      image = nil
      if view.window != nil { //Are we on screen?
          fetchImage()
      }
     
    }
  }

Tags: 

Pages

Subscribe to RSS - swift