apps at startup

search for folders

Hard Drive/Library/LaunchAgents

Hard Drive/Library/LaunchDaemons

Tags: 

Crashreports turn on off

turn off crash reports

launchctl unload -w /System/Library/LaunchAgents/com.apple.ReportCrash.plist
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist

turn on

launchctl load -w /System/Library/LaunchAgents/com.apple.ReportCrash.plist
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist
Tags: 

Json serialize

using System;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;

public class Program
{
public class MyModel
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public bool MyBoolean { get; set; }
    public decimal MyDecimal { get; set; }
    public DateTime MyDateTime1 { get; set; }
    public DateTime MyDateTime2 { get; set; }
    public List<string> MyStringList { get; set; }
    public Dictionary<string, Person> MyDictionary { get; set; }
    public MyModel MyAnotherModel { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public static void Main()
{
var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true
};
Person p = new Person();
p.Id = 1;
p.Name = "HJH";
MyModel mm = new MyModel();
mm.MyInt = 1;
mm.MyBoolean = false;
mm.MyString = "string";

string s = JsonSerializer.Serialize(p, options);
Console.WriteLine(s);
string s2 = JsonSerializer.Serialize(mm, options);
Console.WriteLine(s2);
}
}

RxJs

useful site to exercise: Stephen Grider RxJs playground

const { fromEvent } = Rx;
const { map, pluck } = RxOperators;

const input = document.createElement('input');
const container = document.querySelector('.container');
container.appendChild(input);

const observable = fromEvent(input, 'input')
.pipe(
    pluck('target','value'),
  map(value=>parseInt(value)),
  map(value => {
    if(isNaN(value)){
        throw Error('The input must be a number.')
    }
    return value;
  })
);

observable.subscribe({
    next(value){
    console.log('You inserted '+value);
  },
  error(err){
    console.error('error : '+err.message);
  },
  complete(){},
});

observable;

result:

[Log] You inserted 1
[Log] You inserted 12
[Log] You inserted 123
Tags: 

Count characters

Operationqueue urlsession

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

Custom order in sorting, dutch alphabet 'ij' problem

const compareIJ =  (x, y) => {
  var a = x.toLowerCase()
  var b = y.toLowerCase()
  // combined char i+j
  if (a.startsWith('ij') && b.startsWith('i') ) {
    return -1
  } else if (a.startsWith('ij') && b.startsWith('j')){
    return 1
  }
  if (a.startsWith('i') && b.startsWith('ij')) {
    return -1
  } else if (a.startsWith('j') && b.startsWith('ij')){
    return 1
  }


  return 0;
}

const customSort = ({data, sortBy}) => {
  const sortByObject = sortBy.reduce(
    (arr, item) => {
      arr.push(item)
      return arr
    }, [])

  return data.sort((a, b) => {
    return sortByObject.indexOf(a[0]) - sortByObject.indexOf(b[0])
  }).sort(compareIJ)
}

var items = ['wer', 'qwe','ijsdf','lkj','fgh','asdf','bsdfs','csdf','ijsaasdf','isdf','ijsdf', 'jsdf', 'ksdf', 'wer', 'qwe']
const dutchAlphabet = ['a','b','c','d','e','f','g','h','i','ij','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

var a = customSort({data: items, sortBy: dutchAlphabet})

console.log(a)

Tags: 

GCloud

Dotnet core 2.2 project

In Program.cs

public static void Main(string[] args)
{
    CreateWebHostBuilder(args).UseUrls("http://:8080/").Build().Run();
}
Dockerfile
FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2
ENV ASPNETCORE_URLS=http://
:${PORT}
WORKDIR /app
COPY --from=build-env /app/out .

ENTRYPOINT ["dotnet", "tuinhok.dll"]

.dockerignore

bin\
obj\

docker build and push

docker build -t gcr.io/<gcp-project>/<appName>:latest .
docker push gcr.io/<gcp-project>/<appName>:latest

Node express server

const express = require('express')
const app = express()
const port = process.env.PORT || 8080

app.get('/', (req, res) => {
  res.json({
    message: 'Hello World'
  })
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

dockerfile for a node project:

FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

COPY . .
CMD ["node", "server-app.js"]

Angular

install angular cli

nom i angular-cli

create new project

ng new <project-name>

start proj

ng serve
ng s

generate component

ng g c <optional-folder/component-name>

component field - html prop

two way binding

<my-cmp [(title)]="name">

in component.ts

selector decorator:

@Component({
  selector: '.app-servers',
...
})

in html:

<!--selector "app-servers"-->
<app-servers></app-servers>

<!--selector "[app-server]" as attribute-->
<div app-servers></div>

<!--selector ".app-server" as className-->
<div class="app-servers"></div>

varname: type, ex: name: string;
or object (define class in folder models, like ObjectClass class { var a: number; }):
objectclass: ObjectClass

in .html

{{varname}} , ex: {{name}}
{{objectclass.a}}

component input @input()

<input [value]="my_name">

in parent-component .html

<component-name [name]="my_name" ....  

in component-name .ts

export component-name class {

@Input()
name: string;
...
}

events

in component .html

<button (click)="functionname($event)">button title</button>

in .ts
create function functionname($event)

export class ComponentClass {  
  ...  
  constructor(){}  
  ...  
 functionname(event: any) {  
  //do something  
  }  
  ...  
}  

Attribute Directives

<p appHighlight>Highlight me!</p>

ng g directive

to use it like [appClass] style of writing:

<li class="page-item"
        [appClass]="{'disabled':currentPage===images.length-1}">
</li>
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appClass]'
})
export class ClassDirective {

  constructor(private element: ElementRef) { }

  @Input('appClass') set classNames(classObj: any) {
    for (const key in classObj) {
      if (classObj[key]) {
        this.element.nativeElement.classList.add(key);
      } else {
        this.element.nativeElement.classList.remove(key);

      }
    }
  }
}

Structural Directives

What are structural directives?

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.
Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.

<div *ngIf="hero" class="name">{{hero.name}}</div>

The three common structural directives are ngIf ngFor ngSwitch

struct directive creation

ng g directive <directive-name>

to use like *appTimes

<ul *appTimes="5">
  <li>hi there!</li>
</ul>
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
// structural directive
@Directive({
  selector: '[appTimes]'
})
export class TimesDirective {

  constructor(
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>
  ) { }

  @Input('appTimes') set render(times: number) {
    this.viewContainer.clear();

    for (let i = 0 ; i < times; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef, {
        index: i
      });
    }
  }
}

ngFor

<ul>  
  <li *ngFor="let item of items; index as i">  
    {{i+1}} {{item}}  
  </li>  
</ul>  

The following exported values can be aliased to local variables:
- $implicit: T: The value of the individual items in the iterable (ngForOf).
- ngForOf: NgIterable: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).
- index: number: The index of the current item in the iterable.
- first: boolean: True when the item is the first item in the iterable.
- last: boolean: True when the item is the last item in the iterable.
- even: boolean: True when the item has an even index in the iterable.
- odd: boolean: True when the item has an odd index in the iterable.

ngIf

shorthand

<div *ngIf="condition">Content to render when condition is true.</div>

extended

<ng-template [ngIf]="condition"><div>Content to render when condition is true.</div></ng-template>  

with else block

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>  
<ng-template #elseBlock>Content to render when condition is false.</ng-template>  

if then else

<div *ngIf="condition; then thenBlock else elseBlock"></div>  
<ng-template #thenBlock>Content to render when condition is true.</ng-template>  
<ng-template #elseBlock>Content to render when condition is false.</ng-template>  

with value locally

<div *ngIf="condition as value; else elseBlock">{{value}}</div>  
<ng-template #elseBlock>Content to render when value is null.</ng-template>  

else in template, use #

<div class="hero-list" *ngIf="heroes else loading">  
 ...   
</div>  

<ng-template #loading>  
 <div>Loading...</div>  
</ng-template>

ngClass

Adds and removes CSS classes on an HTML element.

The CSS classes are updated as follows, depending on the type of the expression evaluation:
string - the CSS classes listed in the string (space delimited) are added,
Array - the CSS classes declared as Array elements are added,
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

<some-element [ngClass]="'first second'">...</some-element>  

<some-element [ngClass]="['first', 'second']">...</some-element>  

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>  

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>  

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>  

ngSwitch

A structural directive that adds or removes templates (displaying or hiding views) when the next match expression matches the switch expression.

<container-element [ngSwitch]="switch_expression">
  <!-- the same view can be shown in more than one case -->
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  <!--default case when there are no matches -->
  <some-element *ngSwitchDefault>...</some-element>
</container-element>
<container-element [ngSwitch]="switch_expression">
      <some-element *ngSwitchCase="match_expression_1">...</some-element>
      <some-element *ngSwitchCase="match_expression_2">...</some-element>
      <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
      <ng-container *ngSwitchCase="match_expression_3">
        <!-- use a ng-container to group multiple root nodes -->
        <inner-element></inner-element>
        <inner-other-element></inner-other-element>
      </ng-container>
      <some-element *ngSwitchDefault>...</some-element>
    </container-element>

ng-container

The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

ng-tempplate

renders only the hero-detail.

<template [ngIf]="currentHero">  
  <hero-detail [hero]="currentHero"></hero-detail>  
</template>  

pipes for extending func

formatting strings, dates, numbers, upper, lower, etc

date

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

Examples are given in en-US locale.
'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output is '43:11'

LowerCasePipe

{{ value_expression | lowercase }}

simular as UpperCasePipe, TitleCasePipe

PercentPipe

{{ value_expression | percent [ : digitsInfo [ : locale ] ] }}

<!--output '26%'-->  
    <p>A: {{a | percent}}</p>  

    <!--output '0,134.950%'-->  
    <p>B: {{b | percent:'4.3-5'}}</p>  

    <!--output '0 134,950 %'-->  
    <p>B: {{b | percent:'4.3-5':'fr'}}</p>  

SlicePipe

<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
...
    <p>{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'</p>  
    <p>{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''</p>  
    <p>{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'</p>  
    <p>{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'</p>  
    <p>{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'</p>  
    <p>{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''</p>  

AsyncPipe

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

@Component({
  selector: 'async-promise-pipe',
  template: `<div>
    promise|async: 
    <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
    <span>Wait for it... {{ greeting | async }}</span>
  </div>`
})
export class AsyncPromisePipeComponent {
  greeting: Promise<string>|null = null;
  arrived: boolean = false;

  private resolve: Function|null = null;

  constructor() { this.reset(); }

  reset() {
    this.arrived = false;
    this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });
  }

  clicked() {
    if (this.arrived) {
      this.reset();
    } else {
      this.resolve !('hi there!');
      this.arrived = true;
    }
  }
}

ViewChild, ViewChildren

A template reference variable as a string (e.g. query with @ViewChild('cmp'))
Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)
A TemplateRef (e.g. query with @ViewChild(TemplateRef) template;)

Directive, decorator

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.
like 'placeholder' in

<input value="abc" **placeholder**="firstname">  

reusable in whole project

creation

ng g directive directives/HighlightedDirective

@HostBinding @HostListener

or emit directive to other components:

@Input('highlighted')
  isHighlighted = false;

  @Output()
  toggleHighlight = new EventEmitter();

  constructor() {
    //console.log('highlighted created...');
  }

  @HostBinding('class.highlighted')
  get cssClasses() {
    return this.isHighlighted;
  }

  @HostBinding('attr.disabled')
  get disabled() {
    return "true";
  }

  @HostListener('mouseover', ['$event'])
  mouseover($event) {
    console.log($event);
    this.isHighlighted = true;
    this.toggleHighlight.emit(this.isHighlighted);
  }

toggle() {
    this.isHighlighted = !this.isHighlighted;
    this.toggleHighlight.emit(this.isHighlighted);
  }

Structural Directives

ng g directive directive/ngx-name

nix-name

ngxNameDirective
results to template

import { Directive,  TamplateRef } from '@angular/core';

@Directive({
  selector: {'[ngxngxName]'}
})
export class NgxNameDirective {

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {

  }

  @Input()
  set ngxName(condition:booleam);
}

Angular Injectable Services

Modules

ng g m MODULE_NAME (--routing)

heic convert

# convert any HEIC image in a directory to jpg format
magick mogrify -monitor -format jpg *.HEIC

# convert an HEIC image to a jpg image
magick convert example_image.HEIC example_image.jpg

swagger

add package:
NSwag.AspNetCore

startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddOpenApiDocument();
}

Configure(IApplicationBuilder app, IWebHostEnvironment env)
...(after endpoints)...
app.UseOpenApi();
app.UseSwaggerUi3();

goto url localhost:5000/swagger

Login ssh automation

import sys
import pyperclip
import subprocess

if len(sys.argv) == 1:
    print('login func needs client to login...')
elif sys.argv[1] == 'do':
    print('login at do, use paste')
    cb = pyperclip.copy('Password')
    bashCommand = "echo apt update"
    subprocess.call(["ssh", "user@ip.address.0.0"])
else:
    print('No login available for '+ sys.argv[1])

sys.exit(1)

adjust zshrc in

~/.zshrc add location python3 and filelocation

alias li="/Users/hjhubeek/Documents/development/python/li/bin/python /Users/hjhubeek/Documents/development/python/li/li.py"

Navigation link button makes master detail setup on iPad

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

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

Duplicate Symbols for Architecture arm64

Duplicate Symbols for Architecture arm64

remedy in build settings

set to ON
No Common Blocks
.. and then OFF

Tags: 

dotnet core notes

localize date time
CultureInfo ci = new CultureInfo("nl-NL");Console.WriteLine(DateTime.Now.ToString("D", ci));

scaffold mysql db
dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=root;database=opit" MySql.Data.EntityFrameworkCore -o Models -f

scan local network

sudo nmap -sn 192.168.1.0/24 > ~/Desktop/nmaplog.txt

git remove sensitive data from history in files

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch path_to_file" HEAD
It’s a time intensive task might takes good amount of time to complete. As it has to check each commit and remove.
If you want to push it to remote repo just do git push
git push -all

Tags: 

Git foreach use cases

What did I do before the holidays?

git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'

sort by date

git for-each-ref --sort=-committerdate refs/heads/

manual remove uninstall visual studio 2015

#!/bin/sh

# Uninstall Visual Studio for Mac
echo "Uninstalling Visual Studio for Mac..."

sudo rm -rf "/Applications/Visual Studio.app"
rm -rf ~/Library/Caches/VisualStudio
rm -rf ~/Library/Preferences/VisualStudio
rm -rf "~/Library/Preferences/Visual Studio"
rm -rf ~/Library/Logs/VisualStudio
rm -rf ~/Library/VisualStudio
rm -rf ~/Library/Preferences/Xamarin/
rm -rf ~/Library/Developer/Xamarin

# Uninstall Xamarin.Android
echo "Uninstalling Xamarin.Android..."

sudo rm -rf /Developer/MonoDroid
rm -rf ~/Library/MonoAndroid
sudo pkgutil --forget com.xamarin.android.pkg
sudo rm -rf /Library/Frameworks/Xamarin.Android.framework


# Uninstall Xamarin.iOS
echo "Uninstalling Xamarin.iOS..."

rm -rf ~/Library/MonoTouch
sudo rm -rf /Library/Frameworks/Xamarin.iOS.framework
sudo rm -rf /Developer/MonoTouch
sudo pkgutil --forget com.xamarin.monotouch.pkg
sudo pkgutil --forget com.xamarin.xamarin-ios-build-host.pkg


# Uninstall Xamarin.Mac
echo "Uninstalling Xamarin.Mac..."

sudo rm -rf /Library/Frameworks/Xamarin.Mac.framework
rm -rf ~/Library/Xamarin.Mac


# Uninstall Workbooks and Inspector
echo "Uninstalling Workbooks and Inspector..."

sudo /Library/Frameworks/Xamarin.Interactive.framework/Versions/Current/uninstall


# Uninstall the Visual Studio for Mac Installer
echo "Uninstalling the Visual Studio for Mac Installer..."

rm -rf ~/Library/Caches/XamarinInstaller/
rm -rf ~/Library/Caches/VisualStudioInstaller/
rm -rf ~/Library/Logs/XamarinInstaller/
rm -rf ~/Library/Logs/VisualStudioInstaller/

# Uninstall the Xamarin Profiler
echo "Uninstalling the Xamarin Profiler..."

sudo rm -rf "/Applications/Xamarin Profiler.app"

echo "Finished Uninstallation process."

Tags: 

double template code vs2015

change in solution file (.csproj)

    <ItemGroup>
        <None Remove="$(SpaRoot)**" />
        <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
    </ItemGroup>

Tags: 

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()

list finale files in dir to txt file

ls -1 | sed -e 's/ C.musx$//' > songs.txt

Tags: 

List example

From RW: Ray Wenderlich Video Tut

import PlaygroundSupport
import SwiftUI
struct Employee: Identifiable {
    var id = UUID()
    var name: String
    var title: String
}

let testData: [Employee] = [Employee(name: "Ray Wenderlich", title: "Owner"),
                            Employee(name: "Victoria Wenderlich", title: "Digital Artist"),
                            Employee(name: "Andrea Lepley", title: "Video Team Lead"),
                            Employee(name: "Sam Davies", title: "CTO"),
                            Employee(name: "Katie Collins", title: "Customer Support Lead"),
                            Employee(name: "Tiffani Randolph", title: "Marketing Associate")]

struct ContentView: View {
    var employees:[Employee] = []
   
    var body: some View {
       
            List(employees) { employee in
                NavigationButton(destination: Text(employee.name)) {
                    VStack(alignment: .leading) {
                        Text(employee.name)
                        Text(employee.title).font(.footnote)
                    }
                }
            }.navigationBarTitle(Text("Ray's Employees"))
       
    }
}
let vc = UIHostingController(rootView: NavigationView() { ContentView(employees: testData)})

PlaygroundPage.current.liveView = vc

Tags: 

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())
  }
}

SwiftUI

Playground

import PlaygroundSupport
import SwiftUI


struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}
let vc = UIHostingController(rootView: ContentView())

PlaygroundPage.current.liveView = vc

Shapes

Rectangle()
    .fill(Color.red)
    .frame(width: 200, height: 200)
Circle()
    .fill(Color.blue)
    .frame(width: 50, height: 50)

Try HStack en ZStach(!)

Triangles Shapes

struct ASymbol : View {
    let symbolColor: Color

    var body: some View {
        GeometryReader { geometry in
            Path { path in
                let side = min(geometry.size.width, geometry.size.height)
                path.move(to: CGPoint(x: side * 0.5, y: 0))
                path.addLine(to: CGPoint(x: side, y: side))
                path.addLine(to: CGPoint(x: 0, y: side))
                path.closeSubpath()

                }
                .fill(self.symbolColor)
        }
    }
}
struct ContentView : View {
    var body: some View {
        VStack{
        ASymbol(symbolColor: .green)
        ASymbol(symbolColor: .green).rotationEffect(Angle(degrees: 180))
        }
    }
}

Conditional:

struct ContentView: View {
    var body: AnyView {
        if Int.random(in: .min ... .max).isMultiple(of: 2) {
            return AnyView(Text("Even"))
        } else {
            return AnyView(Image(systemName: "star"))
        }
    }
}

Value with expiration

@propertyWrapper
struct Expirable<Value> {
    let duration: TimeInterval
    var expirationDate: Date = Date()
    private var innerValue: Value?
   
    var value: Value? {
        get{ return hasExpired() ? nil: innerValue }
        set{
            self.expirationDate = Date().addingTimeInterval(duration)
            self.innerValue = newValue
        }
    }
    init(duration: TimeInterval) {
        self.duration = duration
    }
    private func hasExpired() -> Bool {
        return expirationDate < Date()
    }
}

struct Tokens {
    @Expirable(duration: 3) static var authent: String
}

Tokens.authent = NSUUID().uuidString

sleep(2)
Tokens.authent ?? "token has expired"
sleep(2)
Tokens.authent ?? "token has expired"

Tags: 

Data Compression

let compressed = try data.compressed(using: .zlib)
public enum CompressionAlgorithm: Int {
  case lzfse
  case lz4
  case lama
  case zlib
}

Tags: 

Sequential Operations

class DownloadOperation : Operation {
   
    private var task : URLSessionDownloadTask!
   
    enum OperationState : Int {
        case ready
        case executing
        case finished
    }
   
    // default state is ready (when the operation is created)
    private var state : OperationState = .ready {
        willSet {
            self.willChangeValue(forKey: "isExecuting")
            self.willChangeValue(forKey: "isFinished")
        }
       
        didSet {
            self.didChangeValue(forKey: "isExecuting")
            self.didChangeValue(forKey: "isFinished")
        }
    }
   
    override var isReady: Bool { return state == .ready }
    override var isExecuting: Bool { return state == .executing }
    override var isFinished: Bool { return state == .finished }
   
    init(session: URLSession, downloadTaskURL: URL, completionHandler: ((URL?, URLResponse?, Error?) -> Void)?) {
        super.init()
       
        task = session.downloadTask(with: downloadTaskURL, completionHandler: { [weak self] (localURL, response, error) in
           
            /*
             if there is a custom completionHandler defined,
             pass the result gotten in downloadTask's completionHandler to the
             custom completionHandler
             */
            if let completionHandler = completionHandler {
                // localURL is the temporary URL the downloaded file is located
                completionHandler(localURL, response, error)
            }
           
            /*
             set the operation state to finished once
             the download task is completed or have error
             */
            self?.state = .finished
        })
    }
   
    override func start() {
        /*
         if the operation or queue got cancelled even
         before the operation has started, set the
         operation state to finished and return
         */
        if(self.isCancelled) {
            state = .finished
            return
        }
       
        // set the state to executing
        state = .executing
       
        print("downloading \(self.task.originalRequest?.url?.absoluteString ?? "")")
           
            // start the downloading
            self.task.resume()
    }
   
    override func cancel() {
        super.cancel()
       
        // cancel the downloading
        self.task.cancel()
    }
}

use it in vc:
class ViewController: UIViewController {

    @IBOutlet weak var downloadButton: UIButton!
   
    @IBOutlet weak var progressLabel: UILabel!
   
    @IBOutlet weak var cancelButton: UIButton!
   
    var session : URLSession!
    var queue : OperationQueue!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
       
        session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
       
        self.cancelButton.isEnabled = false
    }

    @IBAction func downloadTapped(_ sender: UIButton) {
        let completionOperation = BlockOperation {
            print("finished download all")
            DispatchQueue.main.async {
                self.cancelButton.isEnabled = false
            }
        }
       
        let urls = [
            URL(string: "https:/...zip")!,
            URL(string: "https:/...zip")!,
            URL(string: "https:/...zip")!,
            URL(string: "https:/...zip")!,
            URL(string: "https:/...zip")!,
        ]
       
        for (index, url) in urls.enumerated() {
            let operation = DownloadOperation(session: self.session, downloadTaskURL: url, completionHandler: { (localURL, urlResponse, error) in
               
                if error == nil {
                    DispatchQueue.main.async {
                        self.progressLabel.text = "\(index + 1) / \(urls.count) files downloaded"
                    }
                }
            })
           
            completionOperation.addDependency(operation)
            self.queue.addOperation(operation)
        }
       
        self.queue.addOperation(completionOperation)
        self.cancelButton.isEnabled = true
    }
   
    @IBAction func cancelTapped(_ sender: UIButton) {
        queue.cancelAllOperations()
       
        self.progressLabel.text = "Download cancelled"
       
        self.cancelButton.isEnabled = false
    }
   
}

Tags: 

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.
    }
}

Xcode multiselect

ALT + ⌘ + E to select next occurence of currently selected

ALT + SHIFT + ⌘ + E to select previous occurence of currently selected

ALT + ⌘ + G to find and select next

ALT + SHIFT + ⌘ + G to find and select previous

Pages

Subscribe to hjsnips RSS