swift

Mutating Core Data object

Problem: How to mutate a fetched CD object in child views


import SwiftUI import CoreData struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], animation: .default) var items: FetchedResults<Item> var body: some View { NavigationView { List { ForEach(items) { item in NavigationLink { ItemDetail(item: item) } label: { Text("itemview1 at \(item.timestamp!, formatter: itemFormatter) name: \((item.name ?? "").isEmpty ? "": item.name! )") } } .onDelete(perform: deleteItems) } .toolbar { #if os(iOS) ToolbarItem(placement: .navigationBarTrailing) { EditButton() } #endif ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } Text("Select an item") } } private func addItem() { withAnimation { let newItem = Item(context: viewContext) newItem.timestamp = Date() do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } private func deleteItems(offsets: IndexSet) { withAnimation { offsets.map { items[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } } private let itemFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium return formatter }() struct ItemDetail: View { @ObservedObject var item: Item @State var name: String = "" var body: some View { Form { TextField("Enter name", text: $name ).onChange(of: name) { newValue in item.name = name } Button("Submit") { // nav back } Spacer() NavigationLink { ItemDetail(item: item) } label: { Text("itemview1 at \(item.timestamp!, formatter: itemFormatter) name: \((item.name ?? "").isEmpty ? "": item.name! )") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) } }

Dynamic UIFont

example by demo

UIFont

.largeTitle, .title1, .title2, .title3, .headline, .subheadline, .body, .footnote, .caption1, .caption2, .callout

Large (Default)

| Style | Weight | Size (points)
| ---------- | :------: | --------------: |
Large Title | Regular | 34
Title 1 | Regular | 28
Title 2 | Regular | 22
Title 3 | Regular | 20
Headline | Semi-Bold | 17
Body |Regular | 17
Callout | Regular | 16
Subhead | Regular |15
Footnote | Regular | 13
Caption 1 | Regular | 12
Caption 2 | Regular | 11

let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true 

apple doc
article with examples

Tags: 

Swift App from Terminal

ObjC article by chris eidhof

// Run any SwiftUI view as a Mac app.

import Cocoa
import SwiftUI

NSApplication.shared.run {
    VStack {
        Text("Hello, World")
            .padding()
            .background(Capsule().fill(Color.blue))
            .padding()
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)

}

extension NSApplication {
    public func run<V: View>(@ViewBuilder view: () -> V) {
        let appDelegate = AppDelegate(view())
        NSApp.setActivationPolicy(.regular)
        mainMenu = customMenu
        delegate = appDelegate
        run()
    }
}

// Inspired by https://www.cocoawithlove.com/2010/09/minimalist-cocoa-programming.html

extension NSApplication {
    var customMenu: NSMenu {
        let appMenu = NSMenuItem()
        appMenu.submenu = NSMenu()
        let appName = ProcessInfo.processInfo.processName
        appMenu.submenu?.addItem(NSMenuItem(title: "About \(appName)", action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: ""))
        appMenu.submenu?.addItem(NSMenuItem.separator())
        let services = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
        self.servicesMenu = NSMenu()
        services.submenu = self.servicesMenu
        appMenu.submenu?.addItem(services)
        appMenu.submenu?.addItem(NSMenuItem.separator())
        appMenu.submenu?.addItem(NSMenuItem(title: "Hide \(appName)", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h"))
        let hideOthers = NSMenuItem(title: "Hide Others", action: #selector(NSApplication.hideOtherApplications(_:)), keyEquivalent: "h")
        hideOthers.keyEquivalentModifierMask = [.command, .option]
        appMenu.submenu?.addItem(hideOthers)
        appMenu.submenu?.addItem(NSMenuItem(title: "Show All", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: ""))
        appMenu.submenu?.addItem(NSMenuItem.separator())
        appMenu.submenu?.addItem(NSMenuItem(title: "Quit \(appName)", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

        let windowMenu = NSMenuItem()
        windowMenu.submenu = NSMenu(title: "Window")
        windowMenu.submenu?.addItem(NSMenuItem(title: "Minmize", action: #selector(NSWindow.miniaturize(_:)), keyEquivalent: "m"))
        windowMenu.submenu?.addItem(NSMenuItem(title: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: ""))
        windowMenu.submenu?.addItem(NSMenuItem.separator())
        windowMenu.submenu?.addItem(NSMenuItem(title: "Show All", action: #selector(NSApplication.arrangeInFront(_:)), keyEquivalent: "m"))

        let mainMenu = NSMenu(title: "Main Menu")
        mainMenu.addItem(appMenu)
        mainMenu.addItem(windowMenu)
        return mainMenu
    }
}

class AppDelegate<V: View>: NSObject, NSApplicationDelegate, NSWindowDelegate {
    init(_ contentView: V) {
        self.contentView = contentView

    }
    var window: NSWindow!
    var hostingView: NSView?
    var contentView: V

    func applicationDidFinishLaunching(_ notification: Notification) {
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        hostingView = NSHostingView(rootView: contentView)
        window.contentView = hostingView
        window.makeKeyAndOrderFront(nil)
        window.delegate = self
        NSApp.activate(ignoringOtherApps: true)
    }
}

Operationqueue urlsession

let group = DispatchGroup()
for _ in 0...999 {
    group.enter()
    URLSession.shared.dataTask(with: …) { _, _, _ in
        …
        group.leave()
    }.resume()
}
group.wait()

Navigation link button makes master detail setup on iPad

.navigationViewStyle(StackNavigationViewStyle()) does the trick...

NavigationView {
        Text("Hello world!")
    }
    .navigationViewStyle(StackNavigationViewStyle())

SwiftUI small techniques

do after 1 seconds

@State var reloadCount = 0
...
body
---
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  self.reloadCount += 1
}

Bool

var isBoolean = false
...
isBoolean.toggle()

SwiftUI Elements

Text

Text("Hello World!")

Text("Hello World")
    .font(.largeTitle)
    .foregroundColor(Color.green)
    .lineSpacing(50)
    .lineLimit(nil)
    .padding()

multiline

Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse est leo, vehicula eu eleifend non, auctor ut arcu")
      .lineLimit(nil).padding()
struct ContentView: View {
    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }()

    var now = Date()
    var body: some View {
        Text("Now is the Date: \(now, formatter: Self.dateFormatter)")
    }
}

Text with background

Text("Hello World").color(.red).font(.largeTitle).background(Image(systemName: "photo").resizable().frame(width: 100, height: 100))

Images

sytem icon images

Image(systemName: "photo")
            .foregroundColor(.red)
            .font(.largeTitle)
Image(systemName: "star").resizable().aspectRatio(contentMode: .fill).padding(.bottom)

cast from UIImage to Image

if let image = UIImage(named: "test.png") {
  Image(uiImage: image)
}

Stacks

HStack, VStack, ZStack with styling:

VStack (alignment: .leading, spacing: 20){
    Text("Hello")
    Divider()
    Text("World")
}

on top of each other:

ZStack() {
    Image("hello_world")
    Text("Hello World")
        .font(.largeTitle)
        .background(Color.black)
        .foregroundColor(.white)
}

Input

Toggle

@State var isShowing = true //state

Toggle(isOn: $isShowing) {
    Text("Hello World")
}.padding()

Button

struct ContentView : View {
  var body: some View {

    Button(action: {
        self.buttonPress()
      }, label: {
          Text("TickTock").color(.white)
      }).frame(minWidth: 0, maxWidth: .infinity)
        .padding(20)
        .background(Color.blue)
  }

  private func buttonPress() {
    print("tick tock")
  }

}

(new!) to next view with presentation button

struct NextView: View {
  var body: some View {
    Text("NextView")
  }
}

struct ContentView : View {
  var body: some View {

    PresentationButton(Text("Navigate to another View"), destination: NextView())
  }
}

tableview

//
//  TableViewController.swift
//  SwipeActions
//
//  An exercise file for iOS Development Tips Weekly
//  by Steven Lipton (C)2018, All rights reserved
//  For videos go to http://bit.ly/TipsLinkedInLearning
//  For code go to http://bit.ly/AppPieGithub
//

import UIKit

class TableViewController: UITableViewController {

    let rowCount = 12
   
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let greenAction = UIContextualAction(style: .normal, title: "Green") { (action, view, actionPerformed) in
            self.setCell(color: .green, at: indexPath)
        }
        greenAction.backgroundColor = .green
       
        let blueAction = UIContextualAction(style: .normal, title: "Blue") { (action, view, actionPerformed) in
            self.setCell(color: .blue, at: indexPath)
        }
        blueAction.backgroundColor = .blue
       
        return UISwipeActionsConfiguration(actions: [greenAction,blueAction])
    }
   
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let greenAction = UIContextualAction(style: .normal, title: "Green") { (action, view, actionPerformed) in
            self.setCell(color: .green, at: indexPath)
        }
        greenAction.backgroundColor = .green
       
        let blueAction = UIContextualAction(style: .normal, title: "Blue") { (action, view, actionPerformed) in
            self.setCell(color: .blue, at: indexPath)
        }
        blueAction.backgroundColor = .blue
       
        return UISwipeActionsConfiguration(actions: [blueAction,greenAction])
    }
   
    //A simple example of what you can do in the cell
    func setCell(color:UIColor, at indexPath: IndexPath){
       
        // I can change external things
        self.view.backgroundColor = color
        // Or more likely change something related to this cell specifically.
        let cell = tableView.cellForRow(at: indexPath )
        cell?.backgroundColor = color
    }
   
   
    //Your standard Table Delegate and Data Source methods
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rowCount
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = String(format:"Row #%i",indexPath.row + 1)
        cell.textLabel?.font = UIFont(name: "GillSans-Bold", size: 26)
        return cell
    }
   
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Sample Action Table"
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

Long method

func async(_ runner: @escaping @autoclosure () ->())
{
    DispatchQueue.global(qos: .default).async {
        runner()
    }
}

func longMethod() {
    for _ in 1...2 {
        sleep(5)
    }
    print("run like a boss")
}
async(longMethod())

Tags: 

Readfile Rxswift

let disposebag = DisposeBag()
 
  enum FileReadError: Error {
    case fileNotFound, unreadable, encodingFailed
  }
 
  func loadText(from filename: String) -> Single<String> {
    return Single.create {
      single in
      let disposable = Disposables.create()
     
      guard let path = Bundle.main.path(forResource: filename, ofType: "txt") else {
        single(.error(FileReadError.fileNotFound))
        return disposable
      }
      guard let data =  FileManager.default.contents(atPath: path) else {
        single(.error(FileReadError.unreadable))
        return disposable
      }
      guard let contents = String(data: data, encoding: .utf8) else {
        single(.error(FileReadError.encodingFailed))
        return disposable
      }
      single(.success(contents))
     
      return disposable
    }
  }
  loadText(from: "filename")
    .subscribe{
      switch $0 {
      case .success(let string):
        print(string)
      case .error(let descript):
        print(descript)
     
      }
  }
    .disposed(by: disposebag)

Tags: 

playground network request

do not forget:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

    func getAll(completion: @escaping (GetResourcesRequest<ResourceType>)->Void)
    {
        let dataTask = URLSession.shared.dataTask(with: resourceURL) {

            data , _, _ in
            //print("datatask \(data) b \(b) c \(c)")
            guard let jsonData = data else {
                completion(.failure)
                return
            }
            do {
                let resources = try JSONDecoder().decode([ResourceType].self, from: jsonData)
                completion(.success(resources ))
            }
            catch {
                completion(.failure)
            }
        }
        dataTask.resume()
    }

Tags: 

Array copy clone

//Protocal that copyable class should conform
protocol Copying {
    init(original: Self)
}

//Concrete class extension
extension Copying {
    func copy() -> Self {
        return Self.init(original: self)
    }
}

//Array extension for elements conforms the Copying protocol
extension Array where Element: Copying {
    func clone() -> Array {
        var copiedArray = Array<Element>()
        for element in self {
            copiedArray.append(element.copy())
        }
        return copiedArray
    }
}

//Simple Swift class that uses the Copying protocol
final class MyClass: Copying {
    let id: Int
    let name: String
   
    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
   
    required init(original: MyClass) {
        id = original.id
        name = original.name
    }
}

//Array cloning
let objects = [MyClass]()
//fill objects array with elements
let clonedObjects = objects.clone()

Tags: 

shake animations

func shakeByRotateView(view:UIView){
    let shake:CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shake.duration = 0.12
    shake.repeatCount = Float.infinity
    shake.autoreverses = true
   
    shake.fromValue = NSNumber(value: 0.05*Double.pi)
    shake.toValue = NSNumber(value: -0.05*Double.pi)
    view.layer.add(shake, forKey: "lineRotation")
}

func shakeView(view:UIView){
    let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 2
    shake.autoreverses = true
   
    var from_point:CGPoint = CGPoint(x:view.center.x - 5,y: view.center.y)
    var from_value:NSValue = NSValue(cgPoint: from_point)
   
    var to_point:CGPoint = CGPoint(x:view.center.x + 5,y: view.center.y)
    var to_value:NSValue = NSValue(cgPoint: to_point)
   
    shake.fromValue = from_value
    shake.toValue = to_value
    view.layer.add(shake, forKey: "position")
}

Tags: 

Codable Decodable

enum PlanetState:String, CodingKey {
    case UnLocked = "unlocked"
    case Locked = "locked"
    case Completed = "completed"
    case Tutorial = "tutorial"
    case ComingSoon = "comingsoon"
}


class Planet: Codable
{
    var state:PlanetState
    var order:Int
    var planetBrev:String
    var bought:Bool
    var collectableGold:Int
   
    enum CodingKeys: String, CodingKey
    {
        case state      = "state"
        case order      = "order"
        case planetBrev = "planetBrev"
        case bought     = "bought"
        case collectableGold = "collectableGold"
    }
   
    init(state: PlanetState, order: Int, planetBrev:String, bought: Bool, collectableGold:Int = -1)
    {
        self.state = state
        self.order = order
        self.planetBrev = planetBrev
        self.bought = bought
        self.collectableGold = collectableGold
    }
   
    required init(from decoder: Decoder) throws {
       
        let values = try decoder.container(keyedBy: CodingKeys.self)
        self.state = (try PlanetState(rawValue: values.decode(String.self, forKey: CodingKeys.state)))!
        self.order = try values.decode(Int.self, forKey: CodingKeys.order)
        self.planetBrev = try values.decode(String.self, forKey: CodingKeys.planetBrev)
        self.bought = try values.decode(Bool.self, forKey: CodingKeys.bought)
        self.collectableGold = try values.decode(Int.self, forKey: CodingKeys.collectableGold)
    }
   
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try? container.encode(self.state.stringValue, forKey: CodingKeys.state)
        try? container.encode(self.order, forKey: CodingKeys.order)
        try? container.encode(self.planetBrev, forKey: CodingKeys.planetBrev)
        try? container.encode(self.bought, forKey: CodingKeys.bought)
        try? container.encode(self.collectableGold, forKey: CodingKeys.collectableGold)
    }
}

load
do {
   let planet = try decoder.decode(Planet.self, from: pData)
   HLog.info(function: #function, message: "planet \(planet.planetBrev) \(planet.collectableGold)")
   self.planets.append(planet)
} catch {
    print("error \(error)")
}

save to default for example
if let jsonData = try? encoder.encode(planet)
            {
                defaults.set(jsonData, forKey: "\(Constants.kQuarkPlanetSave)\(planet.planetBrev)")
                HLog.info(function: #function, message: "defaults did save data \(planet.planetBrev)")
                savedPlanets.append(planet.planetBrev)
            }

class Excercise: Encodable,Decodable {
    var date:Date
    var remarks:[String]
   
    init(date:Date,remarks:[String]) {
        self.date = date
        self.remarks = remarks
    }
 
}

let x = Excercise(date:Date(),remarks:["avc","def"])
let encoder = JSONEncoder()
let jsonData = try encoder.encode(x)
String(data: jsonData, encoding: .utf8)!//"{"date":531262938.28764498,"remarks":["avc","def"]}"
let decoder = JSONDecoder()
let decoded = try decoder.decode(Excercise.self, from: jsonData)
decoded.date//"Nov 1, 2017 at 10:01 PM"
decoded.remarks//["avc", "def"]
type(of: decoded)//Excercise.Type

Tags: 

UILabel outlined / stroked text

class StrokedLabel: UILabel {
   
    var strockedText: String = "" {
        willSet(newValue) {
            let strokeTextAttributes = [
                NSAttributedStringKey(rawValue: NSAttributedStringKey.strokeColor.rawValue) : UIColor.black,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor.white,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.strokeWidth.rawValue) : -4.0,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.boldSystemFont(ofSize: 30)
                ] as [NSAttributedStringKey : Any]?
           
            let customizedText = NSAttributedString(string: newValue
                , attributes: strokeTextAttributes)
           
           
           
            attributedText = customizedText
        }
    }
}

Tags: 

Path Finding

import GameplayKit

let graph = GKGraph()


let nodeA = GKGraphNode()
let nodeB = GKGraphNode()
let nodeC = GKGraphNode()
let nodeD = GKGraphNode()
let nodeE = GKGraphNode()


graph.addNodes([nodeA,nodeB,nodeC,nodeD,nodeE])
nodeA.addConnectionsToNodes([nodeB,nodeD], bidirectional: true)
nodeB.addConnectionsToNodes( [nodeD], bidirectional: true)
nodeC.addConnectionsToNodes( [nodeE], bidirectional: false)
nodeD.addConnectionsToNodes( [nodeC], bidirectional: false)
let path:[GKGraphNode] = graph.findPathFromNode(nodeA, toNode: nodeE)

Tags: 

Server side Swift

Kitura

mkdir serverside
cd serverside/
mkdir server
cd server
docker run -itv $(pwd):/projects --name projects -w /projects -p 8089:8089 -p 8090:8090 -p 5984:5984 twostraws/server-side-swift /bin/bash
docker start projects
docker attach projects
root@c661e0faa890:/projects# mkdir project1
root@c661e0faa890:/projects# cd project1/
root@c661e0faa890:/projects/project1# swift package init --type executable
root@c661e0faa890:/projects/project1# swift build
root@c661e0faa890:/projects/project1# .build/debug/project1
Hello, world!

change package to:
let package = Package(
name: "project1",
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1)
]
)

swift build
swift package generate-xcodeproj

docker ps - shows a list of running containers
docker ps -a shows list all projects

docker start #NAME PROJ#
docker attach #NAME#
ctrl-p ctrl-q to get back to local terminal without stopping
docker start -i #NAME#

Vapor

Use & adjust Post template.
change in fluent.json
"driver":"memory" into "driver":"sqlite"

create
sqlite.json
insert
{
"path":"pokemonDB.sqlite"
}

in config+Setup
change setupPreparations into desired Pokemon class

private func setupPreparations() throws {
        preparations.append(Post.self)
        preparations.append(Pokemon.self)
    }

in router
get("version"){
            request in
            let result = try Pokemon.database?.driver.raw("select sqlite_version();")
            return try JSON(node: result)
        }

MySql

start mysql server
docker run -p 3306:3306 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest

Tags: 

combine adding CGRects in array

Adding two CGRect:

let area0 = CGRectZero //{x 0 y 0 w 0 h 0}
let area1 = CGRect(x:0,y:0,width: 2.0, height: 2.0)//{x 0 y 0 w 2 h 2}
let area2 = CGRect(x:2.0,y:2.0,width: 2.0, height: 2.0)
let area3 = CGRect(x:4.0,y:4.0,width: 2.0, height: 2.0)
let union = CGRectUnion(area1, area2)//{x 0 y 0 w 4 h 4}

in an array
var areatotal:[CGRect] = []
areatotal.append(area1)
areatotal.append(area2)
areatotal.append(area3)
areatotal.append(area0)
areatotal.reduce(CGRectZero, combine: CGRectUnion)//{x 0 y 0 w 6 h 6}

Tags: 

Swift Perfect

mkdir hjh
cd hjh
swift package init --type executable
swift package generate-xcodeproj
open ./hjh.xcodeproj/

edit package.swift

import PackageDescription
let package = Package(
  name: "hjh",
  dependencies: [
    .Package(url: "https://github.com/PerfectlySoft/Perfect-
HTTPServer.git", majorVersion: 2),
    .Package(url: "https://github.com/SwiftORM/SQLite-StORM.git",
majorVersion: 1, minor: 0),
    .Package(url: "https://github.com/PerfectlySoft/Perfect-
Mustache.git", majorVersion: 2),
] )

terminal:

swift package update
swift package generate-xcodeproj

main.swift:

import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

terminal:

mkdir public
touch public/file.txt
swift package generate-xcodeproj

terminal:

mkdir public
touch public/file.txt
swift package generate-xcodeproj

let server = HTTPServer()
server.serverPort = 8080
server.documentRoot = "public"

do {
  try server.start()
} catch PerfectError.networkError(let err, let msg) {
  print("Network error thrown: \(err) \(msg)")
}

// func for fitst json response
func jsonresponsefunc(request: HTTPRequest, response: HTTPResponse) {
  do {
    try response.setBody(json: ["message": "JSON!"])
      .setHeader(.contentType, value: "application/json")
      .completed()
  } catch {
    response.setBody(string: "Error handling request: \(error)")
      .completed(status: .internalServerError)
  }
}
// routes
var routes = Routes()
routes.add(method: .get, uri: "/", handler: jsonresponsefunc)
server.addRoutes(routes)

Tags: 

Read file

file io swift 2.2

        let fileLocation = NSBundle.mainBundle().pathForResource("2311393", ofType: "xml")!
        let text : String
        do
        {
            text = try String(contentsOfFile: fileLocation)
        }
        catch
        {
            text = ""
        }

Tags: 

swift server Kitura

first

mkdir tuinhok
cd tuinhok
swift package init --type executable

adjust Package.swift
import PackageDescription


let package = Package(
  name: "proj1",
  dependencies: [
    .Package(url: "https://github.com/IBM-Swift/Kitura.git",
             majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1)
    ]
)

swift package generate-xcodeproj
mkdir public - for js css img etc
mkdir Views - for stencil files

in main swift
import Kitura
import LoggerAPI
import HeliumLogger
import KituraStencil

HeliumLogger.use(.info)
let router = Router()
router.setDefault(templateEngine: StencilTemplateEngine())
router.all("/static", middleware: StaticFileServer())

router.get("/") {
  request, response, next in
  defer { next() }
  try response.render("home", context: [:])
}

Kitura.addHTTPServer(onPort: 8090, with: router)

Kitura.run()

Tags: 

xcode 3.7.1 cocoapods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'testNetworkingOperation' do
    pod 'Alamofire', '~> 3.0'
     pod 'SwiftyJSON', '2.4.0'
end

Tags: 

Before After in collection

public extension Collection where Iterator.Element: Equatable {

public func after(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(after: idx) < endIndex else { return nil }
let nextIdx = index(after: idx)
return self[nextIdx]
}

public func before(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(before: idx) >= startIndex else { return nil }
let previousIdx = index(idx, offsetBy: -1)
return self[previousIdx]
}

public func index(before idx: Index) -> Index {
return index(idx, offsetBy: -1)
}
}

Tags: 

ZoomableGridVC

enum GridFillDirection
{
    case Horizontal, Vertical
}

class ZoomableGridViewController: UIViewController,UIScrollViewDelegate {
   
    //MARK: - Properties
   
    var scrollView: UIScrollView!
    var scrollIsZoomedIn = false
    var gridView: UIView!//Grid!//or image etc
   
    var puzzleDirection:GridFillDirection = .Horizontal
   
    var logText:UILabel!
   
    //MARK: - VC
    override func viewDidLoad() {
        super.viewDidLoad()
       
        gridView = UIImageView(image: UIImage(named: "nasa_big"))//UIView(frame: CGRectMake(0,0,view.bounds.width,view.bounds.width))//
       
        scrollView = UIScrollView(frame: CGRectMake(0,80,view.bounds.width,view.bounds.width))
        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.contentSize = gridView.bounds.size
        scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
        scrollView.delegate = self
        scrollView.maximumZoomScale = 4.0
        setZoomScale()
        scrollView.contentOffset = CGPoint(x: 0, y: 0)
        scrollView.addSubview(gridView)
        view.addSubview(scrollView)
       
        setupGestureRecognizer()
       
        setupLogText()
    }
   
    //MARK: - Setup Layout
    func setupLogText()
    {
        let logtextHeight:CGFloat = 40
        logText = UILabel(frame: CGRectMake(0,view.bounds.height-logtextHeight,view.bounds.width,logtextHeight))
        logText.textAlignment = .Center
        view.addSubview(logText)
        createLogText()
    }
   
    func createLogText()
    {
        let text = (puzzleDirection == .Horizontal) ? "Hori" :  "Verti"
        logText.text = "\(text) zoom : \(scrollView.zoomScale) "
    }
   
    func setZoomScale() {
       
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        let heightScale = scrollView.bounds.size.height / gridView.bounds.size.height
       
        scrollView.minimumZoomScale = min(widthScale, heightScale)
        scrollView.zoomScale = widthScale
    }
   
    //MARK: - ScrollView delegates
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return gridView
    }
   
    func scrollViewDidZoom(scrollView: UIScrollView) {
       
        let verticalPadding = gridView.bounds.size.height < scrollView.bounds.size.height ? (scrollView.bounds.size.height - gridView.bounds.size.height) / 2 : 0
        let horizontalPadding = gridView.bounds.size.width < scrollView.bounds.size.width ? (scrollView.bounds.size.width - gridView.bounds.size.width) / 2 : 0
       
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
       
    }
   
    //MARK: - Gestures
    func setupGestureRecognizer() {
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleDoubleTap(_:)))
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
       
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSingleTap(_:)))
        singleTap.numberOfTapsRequired = 1
        scrollView.addGestureRecognizer(singleTap)
       
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRight)
       
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeDown.direction = UISwipeGestureRecognizerDirection.Down
        self.view.addGestureRecognizer(swipeDown)
       
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        self.view.addGestureRecognizer(swipeLeft)
       
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeUp.direction = UISwipeGestureRecognizerDirection.Up
        self.view.addGestureRecognizer(swipeUp)
       
    }
   
    func handleSwipeGesture(gesture: UIGestureRecognizer) {
       
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
           
            createLogText()
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
               
                logText.text? += "Swiped right select next horizontal region"
                if swipeGesture.state == UIGestureRecognizerState.Began
                {
                   
                }
               
            case UISwipeGestureRecognizerDirection.Down:
               
                logText.text? += "Swiped down select next vertical region"
               
               
            case UISwipeGestureRecognizerDirection.Left:
               
                logText.text? += "Swiped left select previous horizontal region"
               
               
            case UISwipeGestureRecognizerDirection.Up:
               
               
                logText.text? += "Swiped up select previous vertical region"
               
               
            default:
                break
            }
        }
    }
   
    func checkZoomState()
    {
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        if widthScale == scrollView.zoomScale
        {
            //print("zoom scale full")
            scrollIsZoomedIn = false
        }
        else
        {
            //print("zoom scale zoomed")
            scrollIsZoomedIn = true
        }
    }
   
    func handleSingleTap(recognizer: UITapGestureRecognizer)
    {
        checkZoomState()
        createLogText()
        if scrollIsZoomedIn
        {
            logText.text? += "singleTap - selected cell if selected change direction"
        }
        else
        {
            logText.text? += "singleTap - selected cell "
        }
    }
   
    func handleDoubleTap(recognizer: UITapGestureRecognizer) {
        //print("double tap")
        checkZoomState()
        createLogText()
        if puzzleDirection == .Horizontal
        {
            puzzleDirection = .Vertical
        }
        else
        {
            puzzleDirection = .Horizontal
        }
    
    }
 
}

Tags: 

UIGesture Tap

let tap = UITapGestureRecognizer(target: self, action: #selector({class}.{func}))
addGestureRecognizer(tap)

Tags: 

Pool

class Pool<T> {
    private var objectPool = [T]()
   
    init(items:[T]) {
        objectPool.reserveCapacity(objectPool.count)
        for item in items {
            objectPool.append(item)
        }
    }
   
    func getFromPool() -> T? {
        var result:T?
        if objectPool.count > 0 {
            result = self.objectPool.removeAtIndex(0)
        }
        return result
    }
   
    func returnToPool(item:T) {
        self.objectPool.append(item)
    }
}

Tags: 

Touch Tap

func handleSingleTap(sender:UITapGestureRecognizer){
        print("tapped")
    }
   
    func addTapGesture()
    {
        let singleTap = UITapGestureRecognizer(target:self, action:#selector(handleSingleTap))
        singleTap.numberOfTouchesRequired = 1
        singleTap.addTarget(self, action:#selector(handleSingleTap))
        view.userInteractionEnabled = true
        view.addGestureRecognizer(singleTap)
    }

or a touch view

enum Tap {
    case Single
    case Draw
    case Long
   
}

protocol HJHTouchViewDelegate: class{
    func removeSelectedFields()
    func checkThisLoc(pnt:CGPoint)
    func checkThisLocForMove(pnt:CGPoint)
    func touchEnded()
    func longpressAt(pnt:CGPoint)
    func longPressEnd()
}

class TouchView: UIView {
   
    weak var delegate: HJHTouchViewDelegate?
    var tC = 0
    var touchCells = [UIButton]()
    var startTime = NSDate()
    var longPresseTime:Double = 0.5
    var longPressTimer = NSTimer()
    var isInLongPress = false
    var isMoving = false
   
   
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        let touch = touches.first!
        tC = 0
        longPressTimer = NSTimer()
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.removeSelectedFields()
        delegate?.checkThisLoc(pnt)
        isInLongPress = false
        isMoving = false
       
        startTime = NSDate()
        longPressTimer =
            NSTimer.scheduledTimerWithTimeInterval(longPresseTime, target: self, selector: #selector(TouchView.updateTime(_:)), userInfo: [pnt.x, pnt.y], repeats: false
        )
       
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        isMoving = true
        if isInLongPress
        {
            isInLongPress = false
            delegate?.longPressEnd()
        }
        let touch = touches.first! //as! UITouch
        tC += 1
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.checkThisLocForMove(pnt)
       
    }
   
   
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        longPressTimer.invalidate()
        isInLongPress = false
       
        delegate?.touchEnded()
    }
   
    func updateTime(timer:NSTimer)
    {
        if isInLongPress ==  true || isMoving == true
        {
            return
        }
       
        if timer.userInfo != nil
        {
            if let info: AnyObject = timer.userInfo
            {
                if isInLongPress == false
                {
                    isInLongPress = true
                    var arr:[CGFloat] = info as! [CGFloat]
                    delegate?.longpressAt( CGPoint(x: arr[0],y: arr[1]))
                }
            }
        }
    }
}

Tags: 

base64

var str = "Hello, playground"
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)//<48656c6c 6f2c2070 6c617967 726f756e 64>

if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
   
    "Encoded:  \(base64Encoded)"//"Encoded:  SGVsbG8sIHBsYXlncm91bmQ="
   
    if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
        .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
    {
        // Convert back to a string
        "Decoded:  \(base64Decoded)"//"Decoded:  Optional(Hello, playground)"
    }
}

Tags: 

Regex

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var string = "aarde"
matchesForRegexInText("aa..e", text: string)

Tags: 

Remove Duplicates Use a Set

// Initialize the Array
var a = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates:
// first by converting to a Set
// and then back to Array
a = Array(Set(a))

print(a)

Tags: 

Pages

Subscribe to RSS - swift