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: 

screen width height

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

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: 

Segue Lines

voor naar vc met storyboardId
let vc = storyboard?.instantiateViewControllerWithIdentifier("Second") as SecondViewController    presentViewController(vc, animated: true, completion: nil)

Tags: 

random int between

private int randInt(int min, int max) {

  Random rand = new Random();
  int randomNum = rand.nextInt((max - min) + 1) + min;

  return randomNum;
}

Tags: 

callback

class CallbackTest {
    var i = 5
    var callback: (Int -> ())? // NOTE: The optional callback takes an Int
    deinit { // NOTE: This is like -dealloc in Objective-C
        println("Deinit")
    }
}

var obj = CallbackTest()
obj.callback = {
    [unowned obj] // NOTE: Without this, deinit() would never be invoked!
    a in
    obj.i = a
}

Tags: 

enum

enum Shape {
    case Dot
    case Circle(radius: Double) // Require argument name!
    case Square(Double)
    case Rectangle(width: Double, height: Double) // Require argument names!
    func area() -> Double {
        switch self {
        case Dot:
            return 0
        case Circle(let r): // Assign the associated value to the constant 'r'
            return 3.14*r*r
        case Square(let l):
            return l*l
        case Rectangle(let w, let h):
            return w*h
        }
    }
}
var shape = Shape.Circle(radius: 3.0)
shape.area()//28.26
shape = Shape.Dot
shape.area()//0.0
shape = .Square(2)
shape.area()//4.0
shape = .Rectangle(width: 3, height: 4) // Argument names required
shape.area()//12.0

Tags: 

Hide status bar

add no to "View controller-based status bar appearance" in info.plist

add following to VC

override func prefersStatusBarHidden() -> Bool {
        return true
    }

Tags: 

uiswitch

mainSwitch = UISwitch(frame: CGRect(x: 100, y: 100, width: 0, height: 0))
   
    /* Adjust the off-mode tint color */
    mainSwitch.tintColor = UIColor.redColor()
    /* Adjust the on-mode tint color */
    mainSwitch.onTintColor = UIColor.brownColor()
    /* Also change the knob's tint color */
    mainSwitch.thumbTintColor = UIColor.greenColor()
   
    view.addSubview(mainSwitch)

@IBAction func soundEffectsSwitchChanged(sender: UISwitch) {
   
    if sender.on {
     
      Settings().setSoundFx(true)
   
    } else {
     
      Settings().setSoundFx(false)
    }
  }

Tags: 

uialert

var alert = UIAlertController(title: "No Internetconnection", message: "U heeft een internet connctie nodig om aankopen te kunnen doen", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Opnieuw", style: UIAlertActionStyle.Default, handler: { (paramAction:UIAlertAction!) in
     
      self.fetchCreditStoreItems()
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (paramAction:UIAlertAction!) in
     
      self.performSegueWithIdentifier("buyCreditsToHomeVC", sender: self)
    }))
    self.presentViewController(alert, animated: true, completion: nil)

met invullen
var controller:UIAlertController?
 
  override func viewDidLoad() {
    super.viewDidLoad()
   
    controller = UIAlertController(title: "Please enter your username",
      message: "This is usually 10 characters long",
      preferredStyle: .Alert)
   
    let action = UIAlertAction(title: "Next",
      style: UIAlertActionStyle.Default,
      handler: {[weak self] (paramAction:UIAlertAction!) in
       
        if let textFields = self!.controller?.textFields{
          let theTextFields = textFields as [UITextField]
          let userName = theTextFields[0].text
          println("Your username is \(userName)")
        }
       
      })
   
    controller!.addAction(action)
   
    controller!.addTextFieldWithConfigurationHandler(
      {(textField: UITextField!) in
        textField.placeholder = "XXXXXXXXXX"
      })
   
  }
 
  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.presentViewController(controller!, animated: true, completion: nil)
  }
 

simpel

  var controller:UIAlertController?
 
  override func viewDidLoad() {
    super.viewDidLoad()
   
    controller = UIAlertController(title: "Title",
      message: "Message",
      preferredStyle: .Alert)
   
    let action = UIAlertAction(title: "Done",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
      println("The Done button was tapped")
      })
   
    controller!.addAction(action)
   
  }
 
  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.presentViewController(controller!, animated: true, completion: nil)
  }

met action

controller = UIAlertController(
      title: "Choose how you would like to share this photo",
      message: "You cannot bring back a deleted photo",
      preferredStyle: .ActionSheet)
   
    let actionEmail = UIAlertAction(title: "Via email",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
        /* Send the photo via email */
      })
   
    let actionImessage = UIAlertAction(title: "Via iMessage",
      style: UIAlertActionStyle.Default,
      handler: {(paramAction:UIAlertAction!) in
        /* Send the photo via iMessage */
      })
   
    let actionDelete = UIAlertAction(title: "Delete photo",
      style: UIAlertActionStyle.Destructive,
      handler: {(paramAction:UIAlertAction!) in
        /* Delete the photo here */
      })
   
    controller!.addAction(actionEmail)
    controller!.addAction(actionImessage)
    controller!.addAction(actionDelete)

of...

var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

handle actions
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    switch action.style{
    case .Default:
        println("default")

    case .Cancel:
        println("cancel")

    case .Destructive:
        println("destructive")
    }
}))

Tags: 

attributes text with smart range

    let string = "iOS SDK" as NSString
   
    let result = NSMutableAttributedString(string: string)
   
    let attributesForFirstWord = [
      NSFontAttributeName : UIFont.boldSystemFontOfSize(60),
      NSForegroundColorAttributeName : UIColor.redColor(),
      NSBackgroundColorAttributeName : UIColor.blackColor()
    ]
   
    let shadow = NSShadow()
    shadow.shadowColor = UIColor.darkGrayColor()
    shadow.shadowOffset = CGSize(width: 4, height: 4)
   
    let attributesForSecondWord = [
      NSFontAttributeName : UIFont.boldSystemFontOfSize(60),
      NSForegroundColorAttributeName : UIColor.whiteColor(),
      NSBackgroundColorAttributeName : UIColor.redColor(),
      NSShadowAttributeName : shadow,
    ]
   
    /* Find the string "iOS" in the whole string and sets its attribute */
    result.setAttributes(attributesForFirstWord,
      range: string.rangeOfString("iOS"))
   
   
    /* Do the same thing for the string "SDK" */
    result.setAttributes(attributesForSecondWord,
      range: string.rangeOfString("SDK"))

Tags: 

Loop through subviews

for view in self.view.subviews as [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // show error
            return
        }
    }
}

Tags: 

Write/Read data to .plist file

First of all add a plist to your project in Xcode. For example “data.plist”.

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@”data.plist”]; //3

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5

[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}

1) Create a list of paths.
2) Get a path to your documents directory from the list.
3) Create a full file path.
4) Check if file exists.
5) Get a path to your plist created before in bundle directory (by Xcode).
6) Copy this plist to your documents directory.
next read data:
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//load from savedStock example int value
int value;
value = [[savedStock objectForKey:@”value”] intValue];

[savedStock release];

write data:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//here add elements to data file and write data to file
int value = 5;

[data setObject:[NSNumber numberWithInt:value] forKey:@”value”];

[data writeToFile: path atomically:YES];
[data release]

1) You must create a plist file in your Xcode project.
2) To optimize your app, better is to save all the data when application (or for example view) is closing. For instance in applicationWillTerminate. But if you are storing reeaaaally big data, sometimes it couldn’t be saved in this method, becouse the app is closing too long and the system will terminate it immediately.

Tags: 

Pages

Subscribe to hjsnips RSS