How to delete an App from command line

1. List all simulators

Find out all simulators

xcrun simctl list

Find out active simulator

xcrun simctl list | grep Booted

You will get the result like:

$ xcrun simctl list |grep Booted
iPhone 11 (AE8852AB-378E-47FB-BD23-4CF77BFBC6DC) (Booted)

Now you can erase the simulator by

xcrun simctl erase AE8852AB-378E-47FB-BD23-4CF77BFBC6DC

2. Delete the app from active simulator

xcrun simctl uninstall booted your.bundle.id

Or

xcrun simctl uninstall AE8852AB-378E-47FB-BD23-4CF77BFBC6DC your.bundle.id

reference:

https://medium.com/xcblog/simctl-control-ios-simulators-from-command-line-78b9006a20dc

Posted in iOS | Tagged | Leave a comment

Combine Asynchronous Programming

1 Combine basics

  • Combine is a declarative, reactive framework for processing asynchronous events over time.
  • It aims to solve existing problems, like unifying tools for asynchronous programming, dealing with mutable state and making error handling a starting team player.
  • Combine revolves around three main types: publishers to emit events over time, operators to asynchronously process and manipulate upstream events and subscribers to consume the results and do something useful with them.

The three key moving pieces in Combine are publishers, operators and subscribers

1.1 Publishers

Publishers are types that can emit values over time to one or more interested parties, such as subscribers. Regardless of the internal logic of the publisher, which can be pretty much anything including math calculations, networking or handling user events, every publisher can emit multiple events of these three types:
1. An output value of the publisher's generic Output type.
2. A successful completion.
3. A completion with an error of the publisher's Failure type.

Take a look at the Publisher protocol and one of its most crucial extensions:

public protocol Publisher {
  associatedtype Output
  associatedtype Failure : Error
  func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}
extension Publisher {
    public func subscribe<S>(_ subscriber: S) where S : Subscriber,
    Self.Failure == S.Failure,
    Self.Output == S.Input
}

The associated types are the publisher’s interface that a subscriber must match in order to create a subscription.

1.1.1 Primitive value type Publisher

  • Just, it’s a publisher that emits its output to each subscriber once and then finishes.
let just = Just("Hello world!")
_ = just.sink(
    receiveCompletion: {
        print("Received completion", $0)
    },
    receiveValue: {
        print("Received value", $0)
    })

1.2. Operators

Operators are methods declared on the Publisher protocol that return either the same or a new publisher. That's very useful because you can call a bunch of operators one after the other, effectively chaining them together.

1.2.1 sink(_:_:)

The sink(_:_:) operator allows you to provide closures with your code that will receive output values and completions. From there, you can do anything your heart desires with the received events.
sink(_:_:), it simply provides an easy way to attach a subscriber with closures to handle output from a publisher.

let just = Just("Hello world!")
_ = just .sink(
      receiveCompletion: {
        print("Received completion", $0)
      },
      receiveValue: {
        print("Received value", $0)
    })

1.2.2 assign(to:on:)

The assign(to:on:) operator allows you to, without the need of custom code, bind the resulting output to some property on your data model or on a UI control to display the data directly on-screen via a key path. assign(to:on:), the built-in assign(to:on:) operator enables you to assign the received value to a KVO-compliant property of an object.

1.3. Subscribers

Every subscription ends with a subscriber. Subscribers generally do "something" with the emitted output or completion events.

Subscriber protocol:

public protocol Subscriber: CustomCombineIdentifierConvertible {
    associatedtype Input
    associatedtype Failure: Error
    func receive(subscription: Subscription)
    func receive(_ input: Self.Input) -> Subscribers.Demand
    func receive(completion: Subscribers.Completion<Self.Failure>) 
}

1.4. Subscription

The connection between the publisher and the subscriber is the subscription. Here’s the Subscription protocol:

public protocol Subscription: Cancellable, CustomCombineIdentifierConvertible {
    func request(_ demand: Subscribers.Demand) 
}

2. Custom subscriber

final class IntSubscriber: Subscriber {
    typealias Input = Int
    typealias Failure = Never
    func receive(subscription: Subscription) {
        subscription.request(.max(3)) 
    }
    func receive(_ input: Int) -> Subscribers.Demand { 
        print("Received value", input)
        return .none 
    }
    func receive(completion: Subscribers.Completion<Never>) {
        print("Received completion", completion)
    }
}
Posted in iOS, Mobile | Tagged | Leave a comment

Configure Visual Studio Code for Swift development

1. Build sourcekit-lsp

https://github.com/apple/sourcekit-lsp#building-sourcekit-lsp

$ git clone https://github.com/apple/sourcekit-lsp.git
$ swift package update
$ swift build

The sourcekit-lsp will be here:

/Users/zhihuitang/repo/common/sourcekit-lsp/.build/x86_64-apple-macosx/debug/sourcekit-lsp

2. Configure sourcekit-lsp

In the sourcekit-lsp settings, set the Language Server Mode to sourcekit-lsp

Set Server Path:

Posted in iOS | Tagged | Leave a comment

HOW TO RUN VISUAL STUDIO CODE FROM ZSH ON MAC OSX

Adding the codefunction to .zshrc file:

function code {
    if [[ $# = 0 ]]
    then
        open -a "Visual Studio Code"
    else
        local argPath="$1"
        [[ $1 = /* ]] && argPath="$1" || argPath="$PWD/${1#./}"
        open -a "Visual Studio Code" "$argPath"
    fi
}

hen from Terminal you can type:

code – opens Visual Studio Code
code . – opens current directory in Visual Studio Code
code somefile – opens somefile in Visual Studio Code

Posted in Mac | Tagged , | Leave a comment

MongoDB on Mac

1.What’s MongoDB?

MongoDB is a document database which belongs to a family of databases called NoSQL – not only SQL. In MongoDB, records are documents which behave a lot like JSON objects in JavaScript. Values in documents can be looked up by their field’s key. Documents can have some fields/keys and not others, which makes Mongo extremely flexible.

This is different than SQL databases like MySQL and PostgreSQL, where fields correspond to columns in a table and individual records correspond to rows.

2. Install and Run MongoDB with Homebrew

  • Open the Terminal app and type brew update.
  • After updating Homebrew brew install mongodb
  • The install creates:
    the configuration file (/usr/local/etc/mongod.conf)

    systemLog:
        destination: file
        path: /usr/local/var/log/mongodb/mongo.log
        logAppend: true
    storage:
        dbPath: /usr/local/var/mongodb
    net:
        bindIp: 127.0.0.1
    

    the log directory path (/usr/local/var/log/mongodb)
    the data directory path (/usr/local/var/mongodb)

3. Run the MongoDB daemon

In one of your terminal windows run mongod. This should start the Mongo server.
Oops, something is wrong:

[main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
[initandlisten] MongoDB starting : pid=13410 port=27017 dbpath=/data/db 64-bit host=Zhihuis-Mac-mini.local
[initandlisten] db version v4.0.3
[initandlisten] git version: 7ea530946fa7880364d88c8d8b6026bbc9ffa48c
[initandlisten] allocator: system
[initandlisten] modules: none
[initandlisten] build environment:
[initandlisten]     distarch: x86_64
[initandlisten]     target_arch: x86_64
[initandlisten] options: {}
[initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
[initandlisten] shutdown: going to close listening sockets...
[initandlisten] removing socket file: /tmp/mongodb-27017.sock
[initandlisten] now exiting
[initandlisten] shutting down with code:100

It complains that exception in initAndListen: NonExistentPath: Data directory /data/db not found.

You can either

  • create the db folder manually by mkdir -p /data/db, Make sure that the /data/db directory has the right permissions by running

    > sudo chown -R `id -un` /data/db
    > # Enter your password
    

    or

  • Specify the mongod.conf when Running the daemon mongod --config /usr/local/etc/mongod.conf. The db file locates in /usr/local/var/log/mongodb

Alternatively, to run MongoDB as a macOS service, issue the following (the process uses the /usr/local/etc/mongod.conf file, created during the install):
brew services start mongodb

4. Connect and Use MongoDB

mongo

5. Exit/Stop the Mongo

To exit the Mongo shell run quit()
To stop the Mongo daemon hit ctrl-c

Reference

Install MongoDB Community Edition on macOS

Posted in Mobile | Tagged | Leave a comment

Python3 Virtualenv Setup

Install python3

brew install python3

Pip3 is installed with Python3

Upgrade virtualenv

To install virtualenv via pip run:

pip install --upgrade virtualenv

Create virtualenv

virtualenv -p python3 python3-venv

Activate the virtualenv

source python3-venv/bin/activate

Deactivate the virtualenv

deactivate
Posted in Mobile | Tagged | Leave a comment

LLDB you should know

LLDB is a next generation, high-performance debugger. It is built as a set of reusable components which highly leverage existing libraries in the larger LLVM Project, such as the Clang expression parser and LLVM disassembler.
LLDB is the default debugger in Xcode on Mac OS X and supports debugging C, Objective-C and C++ on the desktop and iOS devices and simulator.

LLDB syntax:

<command> [<subcommand> [<subcommand>...]] <action> [-options [option-value]] [argument [argument...]]

1. breakpoint

set breakpoints for all some:

breakpoint set -r some

-r: All method names including some will be set breakpoint
-n: All method names with some will be set breakpoint

// set breakpoint for all methods which including `viewDidLo`:
breakpoint set -r viewDidLo

// set breakpoint for all methods `viewDidLoad`:
breakpoint set -n viewDidLoad

// list all breakpoints
breakpoint list

// disable/enable all breakpoints
breakpoint disable/enable

// delete all breakpoints
breakpoint delete

2. register

register read Show current thread General Purpose Register:

(lldb) register read
General Purpose Registers:
       rax = 0x0000000000000001
       rbx = 0x0000000110d16c05  "count"
       rcx = 0x00007ff78b873f28
       rdx = 0x0000000000000000
       rdi = 0x00007ff78a832400
       rsi = 0x0000000120e1cc47  "viewDidLoad"
       rbp = 0x00007ffee43f7150
       rsp = 0x00007ffee43f7150
        r8 = 0x00000000000001ff
        r9 = 0x00006000029266c0
       r10 = 0x0000000000000047
       r11 = 0x000000010b90ff90  Facebook`@objc Facebook.BrowseViewController.viewDidLoad() -> () at <compiler-generated>
       r12 = 0x0000000000000018
       r13 = 0x00007ff78a832400
       r14 = 0x000000012156b9e4  UIKitCore`_UIApplicationLinkedOnVersion
       r15 = 0x0000000110206d80  libobjc.A.dylib`objc_msgSend
       rip = 0x000000010b90ff94  Casino`@objc Facebook.BrowseViewController.viewDidLoad() -> () + 4 at <compiler-generated>
    rflags = 0x0000000000000246
        cs = 0x000000000000002b
        fs = 0x0000000000000000
        gs = 0x0000000000000000

Write a new decimal 124 to current thread rax

register write rax 123

Posted in iOS | Tagged , , | Leave a comment

Xcode instruments

The two columns worth noting in Instruments are # Persistent and # Transient. The Persistent column keeps a count of the number of objects of each type that currently exist in memory. The Transient column shows the number of objects that have existed but have since been deallocated. Persistent objects are using up memory, transient objects have had their memory released.

Posted in iOS, Mobile | Tagged | Leave a comment

Git tips

How do I discard changes in my working copy that are not in the index?

git stash save --keep-index --include-untracked

You don't need to include –include-untracked if you don't want to be thorough about it.

or drop the stash

git stash drop

or all unstaged files in current working directory use:

git checkout -- .

For a specific file use:

git checkout -- path/to/file/to/revert

Add alias:

Here is what alias I have:

# ~/.gitconfig
[alias]
    squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
    last = log -1 HEAD
    fb = "!f() { git branch -a | grep ${1} --color=auto; }; f"
    graph = "!f() { git log --graph --date=relative --pretty=tformat:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%an %ad)%Creset'; };f"
    cb = "!f() { git branch -a | grep -m1 -e ${1}.*${2} --color=auto | xargs git checkout; }; f"

git squash

You can add alias by:

$: git config --global alias.squash '!f(){ git reset --soft HEAD~${1} && git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"; };f'

You will the command you add in ~/.gitconfig

squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"

e.g: squash the last 5 commits to 1 commit:

git squash 5

Reference

git find branch

Find the branch whose name includes some keyword

fb = "!f() { git branch -a | grep ${1} --color=auto; }; f"

e.g: find a branch whose name includes certificate:

$: git fb certificate
remotes/origin/bugfix/PGIA-571-fix-certificates

git find branch and checkout

Find the branch name whose name includes some keword:

cb = "!f() { git branch -a | grep -m1 -e ${1}.*${2} --color=auto | xargs git checkout; }; f"

e.g: Find and checkout the branch whose name includes bugfix and 754

$: git cb bugfix 754
Switched to branch 'bugfix/PGIA-754-cannot-close-game'
Your branch is behind 'origin/bugfix/PGIA-754-cannot-close-game' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)
$:(bugfix/PGIA-754-cannot-close-game) ✗
Posted in git | Tagged | Leave a comment

Views vs. layers

A layer is a simple model class that exposes a number of properties to represents some image-based content. Every UIView is backed by a layer, so you can think of layers as the lower-level behind the scenes class behind your content.
A layer is different from a view (with respect to animations) for the following reasons:
A layer is a model object – it exposes data properties and implements no logic. It has no complex Auto Layout dependencies nor does it handle user interactions.
It has pre-defined visible traits – these traits are a number of data properties that affect how the contents is rendered on screen, such as border line, border color, position and shadow.
Finally, Core Animation optimizes the caching of layer contents and fast drawing directly on the GPU.
To compare views and layers side by side:

Views

  • Complex view hierarchy layouts, Auto Layout, etc.
  • User interactions.
  • Often have custom logic or custom drawing code that executes on the main thread on the CPU.
  • Very flexible, powerful, lots of classes to subclass.

Layers

  • Simpler hierarchy, faster to resolve layout, faster to draw.
  • No responder chain overhead.
  • No custom logic by default. and drawn directly on the GPU.
  • Not as flexible, fewer classes to subclass.

If you need to choose between views and layers here is tip: choose view animations any time you can to do the job; you will know when you need more performance or flexibility and have to switch to layer animations instead.

Posted in iOS, Mobile | Tagged | Leave a comment