Sails js 2

Sailsjs for backend rest api

==
help with salsas:

  • Google Groups: sails.js
  • IRC: #sailsjs
  • Stack Overflow (using tag sails.js)

==
instal

mac:
nodejs.org
download pkg
(
/usr/local/bin/node
/usr/local/bin/npm
add to $PATH
/usr/local/bin
)

(sudo) npm install sails –global

==
setup first project
sails new firstApp

move to folder
cd firstApp

to start sails:
sails lift

generate new model via blueprint engine
sails generate api user

then question about migrate on sails lift
choose alter in non Prod env
change firstApp/config/model.js

module.exports.models = {
migrate: 'alter'
};

http://localhost:1337/user
first results
in json response []

localhost:1337/user/create?name=HJSnips
results in

[
 
  {
    "name": "HJSnips",
    "createdAt": "2016-03-30T07:30:39.555Z",
    "updatedAt": "2016-03-30T07:30:39.555Z",
    "id": 1
  }
]

==
use Sails built-in integration
with websockets and Socket.io

create
firstApp/assets/js/test.js

io.socket.get('/user', function (users){ console.log(users);});
io.socket.on('user', function (message) {
console.log("Got message: ", message);
});

==
policies
firstApp/config/policies.js
module.exports.policies = {
'UserController': {
'create': ['sessionAuth']
}
};

==
static assets
npm install sails-generate-static --save

sails generate static

sails lift
now when adding content to assets Grunt will create routes files in .tmp

== css assets
to use css in html via grunt make sure:

<!--STYLES-->
<!--STYLES END-->

are in!

<head>
<title>New Sails App</title>
<!-- Viewport mobile tag for sensible mobile support -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
   
<!--STYLES-->
<!--STYLES END-->
</head>

<html>
<body>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<!--TEMPLATES-->
<!--TEMPLATES END-->
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>


</html>

Calc days between dates

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Tags: 

App without Storyboard

iOS 14

  • remove main story board from files
  • from => info remove 'main storyboard file base name'
  • then drill down in scene manifest to remove main item 0 main file name and remove

adjust code in sceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = ViewController()
        window.makeKeyAndVisible()
        self.window = window
    }
...

Project > Targets > Deployment Info

empty "Main Interface"

Remove Reference in Info.plist

Open your Info.plist

    • Click the arrow at the leftmost of Application Scene Manifest (UIApplicationSceneManifest) key to expand
      Click the arrow at the leftmost of Scene Configuration (UISceneConfigurations) key to expand
      Click the arrow at the leftmost of Application Session Role (UIWindowSceneSessionRoleApplication) key to expand
      Click the arrow at the leftmost of First Item (Item 0) key to expand
      Remove the key Storyboard Name (UISceneStoryboardFile)
  • From IOS 13

    Not in appDelegate anymore...
    in SceneDelegate:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
            guard let windowScene = (scene as? UIWindowScene) else { return }
            window = UIWindow(windowScene: windowScene)
            window?.rootViewController = MockupIntroVC()
            window?.backgroundColor = .systemBackground // optional
            window?.makeKeyAndVisible()
        }

    AppDelegate

    var window: UIWindow?

      func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        if let window = window {
          window.backgroundColor = UIColor.whiteColor()
          window.rootViewController = ViewController()
          window.makeKeyAndVisible()
        }
        return true
      }

    ViewController

    class ViewController: UIViewController {

      var button :UIButton!
     

      override func viewDidLoad() {
        super.viewDidLoad()
       
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = .redColor()
        setupLayout()
      }
     

      func setupLayout()
      {
        if button == nil
        {
          self.view.addSubview(createButton(self))
          }
      }

      func buttonPressed(sender:UIButton)
      {
        showNewViewController(SecondViewController())
      }
      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        print("\(__FUNCTION__)")
      }

      deinit
      {
        print("\(__FUNCTION__) v1")
      }

    }

    // General funcs for demo purposes
    func createButton(vc:UIViewController)->UIButton
    {
      let button:UIButton
      button = UIButton(frame: CGRectMake(0,0,123,123))
      button.backgroundColor = .yellowColor()
      button.addTarget(vc, action: "buttonPressed:", forControlEvents: .TouchUpInside)
      button.setTitle("Button", forState: .Normal)
      return button
    }

    func showNewViewController(vc:UIViewController)
    {
      UIApplication.sharedApplication().keyWindow!.rootViewController = vc.self

    }

    SecondViewController

    class SecondViewController: UIViewController {

      var button :UIButton!
      override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = .blueColor()
        setupLayout()
          }

      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
      }


      func setupLayout()
      {
        if button == nil
        {
          self.view.addSubview(createButton(self))
        }
      }
     
      func buttonPressed(sender:UIButton)
      {
        showNewViewController(ViewController())
      }
      deinit
      {
        print("\(__FUNCTION__) v2")
      }
    }

    Tags: 

    find top viewcontroller

    extension UIApplication {
      class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
          return topViewController(nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
          if let selected = tab.selectedViewController {
            return topViewController(selected)
          }
        }
        if let presented = base?.presentedViewController {
          return topViewController(presented)
        }
        return base
      }
    }

    and use like

    if let topvc = UIApplication.topViewController()
              {
                if topvc is HomeVC
                {
                  let vc = topvc as! HomeVC
                  vc.updateGcmMessageButton()
                }
              }

    Tags: 

    find in array times, Slow in build functionality...

    Consider this

    func getCell(x:Int, y:Int) -> GameBoardCell?{
        let start1 = NSDate()
        if let r = gameBoardCells.indexOf({$0.xPos == x && $0.yPos == y})
        {
          let end1 = NSDate()
          let timeInterval: Double = end1.timeIntervalSinceDate(start1)
          print("Time to evaluate problem1: \(timeInterval)")
          //return gameBoardCells[i]
        }
       
       
        let start2 = NSDate()
        let result = gameBoardCells.filter ({$0.xPos == x && $0.yPos == y})
        if result.count > 0
        {
          let end2 = NSDate()
          let timeInterval2: Double = end2.timeIntervalSinceDate(start2)
          print("Time to evaluate problem2: \(timeInterval2) count \(result.count)")
         
          //return result.first
        }
       
       
        let start3 = NSDate()
        for c in gameBoardCells
        {
          if(c.xPos == x && c.yPos == y)
          {
            let end3 = NSDate()
            let timeInterval3: Double = end3.timeIntervalSinceDate(start3)
            print("Time to evaluate problem3: \(timeInterval3)")
            return c
          }
        }
        return nil
      }

    in the beginning with small array
    Time to evaluate problem1: 0.000268995761871338
    Time to evaluate problem2: 0.000285029411315918 count 1
    Time to evaluate problem3: 0.000150978565216064

    results with large array
    Time to evaluate problem1: 3.80277633666992e-05
    Time to evaluate problem2: 0.000289022922515869 count 1
    Time to evaluate problem3: 2.3961067199707e-05

    So Old school looping is quicker than using the build in functionality

    Tags: 

    Elapsed Time

    let start1 = NSDate()
    //.. Do Something ..
    let end1 = NSDate()
    let timeInterval: Double = end1.timeIntervalSinceDate(start1)
    print("Elapsed Time: \(timeInterval)")

    Tags: 

    Sweet Loops

    for section in sections {
        var foundTheMagicalRow = false
        for row in rows {
            if row.isMagical {
                foundTheMagicalRow = true
                break
            }
        }
        if foundTheMagicalRow {
            //We found the magical row!
            //No need to continue looping through our sections now.
            break
        }
    }

    is the same as:
    sectionLoop: for section in sections {
        rowLoop: for row in rows {
            if row.isMagical {
                break sectionLoop
            }
        }
    }

    from:
    http://krakendev.io/

    Tags: 

    Razor Snips

    Send to Action Controller from checkbox

    @Html.CheckBox("FilterOnDates", new { OnChange = "document.forms[0].submit();" })

    Tags: 

    Screen grabbing

    //Grab the screen image to file
    if ( key == ' ' ) {
      ofImage image;  //Declare image object

      //Grab contents of the screen
      image.grabScreen( 0, 0, ofGetWidth(), ofGetHeight() ); 

      image.saveImage( "screen.png" );  //Save image
    }

    Tags: 

    hpp to .h in Xcode

    The behavior can be changed quite easily by renaming the file ___FILEBASENAME___.hpp to ___FILEBASENAME___.h in this folder:

    /Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File\ Templates/Source/C++\ File.xctemplate/WithHeader
    Also you have to change all occurences of "hpp" to "h" in both template files in this folder.

    Tags: 

    Record crashes

    General func

    func exceptionHandler(exception : NSException) {
      let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
     

        defaults.setObject(exception.debugDescription , forKey: "exception")
        defaults.synchronize()
      print("exc: \(exception)")
      print("exc call stack: \(exception.callStackSymbols)")
    }

    in didFinishLaunchingWithOptions

    NSSetUncaughtExceptionHandler(exceptionHandler)
        if NSUserDefaults.standardUserDefaults().objectForKey("exception") != nil
        { .. }

    create crash for example with

    let array = NSArray()
    let elem = array.objectAtIndex(99)

    Tags: 

    Inheritance with didSet

    class A:UIView
    {
      var b:Int
     
      override init(frame: CGRect) {
        b = 1
        super.init(frame: frame)
      }

      required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
      }
     
      func bla()
      {
       
      }

    }

    class B:A  {

      override var b:Int
      {
        didSet
        {
          print("b \(b)")
        }
      }

      func bcd()
      {
       
      }
     
      override func bla()
      {
       
      }

    }

    Tags: 

    Reachability

    swift 2.0

     
    public class ReachabilityToConnection {
        class func isConnectedToNetwork() -> Bool {
          var zeroAddress = sockaddr_in()
          zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
          zeroAddress.sin_family = sa_family_t(AF_INET)
          let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
          }
          var flags = SCNetworkReachabilityFlags()
          if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
          }
          let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
          let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
          return (isReachable && !needsConnection)
        }
    }

    Tags: 

    find in array and delte

      if let foundIndex = find(self.friends!, friend) {

             //remove the item at the found index
             self.friends!.removeAtIndex(foundIndex)

        }


    swift 2.0
    if let foundIndex = bombsOnScreen.indexOf( bomb) {
            bombsOnScreen.removeAtIndex(foundIndex)
          }

    find in array and delte

      if let foundIndex = find(self.friends!, friend)
    {

             //remove the item at the found index
             self.friends!.removeAtIndex(foundIndex)

    }

    swift 2.0

    if let foundIndex = bombsOnScreen.indexOf( bomb)
    {
            bombsOnScreen.removeAtIndex(foundIndex)
    }

    Tags: 

    Delegate pattern

    delegation pattern

    protocol ClassDelegate: class{
      func b1Pressed()
     
    }


    class Class: UIView
    {

      weak var delegate: ClassDelegate?
    ...
    func b1action(sender:UIButton)
      {
        self.delegate?. b1Pressed()
      }


    class ViewController: UIViewController, ClassDelegate {

      override func viewDidLoad() {
        super.viewDidLoad()
        let class = Class(frame: CGRectMake(0, 0, 234, 234))
        menu.delegate = self
    ...

      }

    ...
      func b1Pressed() {
        println("clc")
      }
    ...

    Tags: 

    Audio in ViewController

    import Foundation
    import AVFoundation
    import UIKit

    class AudioPlayerHelper {
     
      static func setupAudioPlayerWithFile(file: String, type:String)-> AVAudioPlayer?
      {
       
        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        let url = NSURL.fileURLWithPath(path!)
        do{
          let audioplayer = try AVAudioPlayer(contentsOfURL: url)
          return audioplayer
        }
        catch{
          return nil
        }
      
       
      }
    }

    import UIKit
    import AVFoundation

    class ViewController: UIViewController {

      var click = AVAudioPlayer()
      var whistle = AVAudioPlayer()
     
      override func viewDidLoad() {
        super.viewDidLoad()
      
        whistle = AudioPlayerHelper.setupAudioPlayerWithFile("whistle", type: "wav")
        click = AudioPlayerHelper.setupAudioPlayerWithFile("click", type: "wav")
       
      }

      @IBAction func clickpressed(sender: UIButton) {
        click.play()
      }

      @IBAction func whistlePressed(sender: UIButton) {
        whistle.play()
      }
    }

    in swift 4
    import AVFoundation
    class ViewController: UIViewController {

        var buttonSoundEffect: AVAudioPlayer?
       
        override func viewDidLoad() {
            super.viewDidLoad()
           
            let path = Bundle.main.path(forResource: "button.mp3", ofType:nil)!
            let url = URL(fileURLWithPath: path)
           
            do {
                buttonSoundEffect = try AVAudioPlayer(contentsOf: url)
                buttonSoundEffect?.prepareToPlay()
            } catch {
                // couldn't load file :(
            }
        }

        @IBAction func buttonpressed(_ sender: UIButton) {
           
            buttonSoundEffect?.play()
        }
       
    }

    Tags: 

    Color Hex to Decimal and Decimal to Hex

    func colorCodeDecimalToHex(red:Int, green: Int, blue: Int) ->String
    {
      var result = ""
     
      if red >= 0 && green >= 0 && blue >= 0 &&
      red <= 255 && green <= 255 && blue <= 255
      {
        result = "0x"
        result += NSString(format:"%2X", red) as String
        result += NSString(format:"%2X", green) as String
        result += NSString(format:"%2X", blue) as String
        return result.stringByReplacingOccurrencesOfString(" ", withString: "0")
       
      }
     
      return result
    }

    func colorCodeHexToRGB(hexString: String)-> String
    {
      var result = ""
      var input = hexString.stringByReplacingOccurrencesOfString("0x", withString: "") as NSString
     
      var red = UInt8(strtoul(input.substringWithRange(NSRange(location: 0, length: 2)), nil, 16))
      var green = UInt8(strtoul(input.substringWithRange(NSRange(location: 2, length: 2)), nil, 16))
        var blue = UInt8(strtoul(input.substringWithRange(NSRange(location: 4, length: 2)), nil, 16))
     
      result = "\(red) \(green) \(blue)"
      return result
    }

    var a = colorCodeDecimalToHex(117, 186, 40) //"0x75BA28"
    var b = colorCodeHexToRGB("0x75BA28")//"117 186 40"

    Tags: 

    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: 

    Pages

    Subscribe to hjsnips RSS