Lawrence  Lesch

Lawrence Lesch

1675454160

Shortcuts-js: A JavaScript IOS 12 Shortcuts Creator

Shortcuts-js

A Node.js iOS 12 Shortcuts creator.

Minimal Example

npm install @joshfarrant/shortcuts-js
// Only used to create the .shortcut file
const fs = require('fs');

const {
  actionOutput,
  buildShortcut,
  withVariables,
} = require('@joshfarrant/shortcuts-js');
const {
  calculate,
  comment,
  number,
  showResult
} = require('@joshfarrant/shortcuts-js/actions');

// We'll use this later to reference the output of a calculation
const calcVar = actionOutput();

// Define our list of actions
const actions = [
  comment({
    text: 'Hello, world!',
  }),
  number({
    number: 42,
  }),
  calculate({
    operand: 3,
    operation: '/',
  }, calcVar),
  showResult({
    /**
     * We can use the result of the calculation in this Shortcuts's input
     * by passing the string to the 'withVariables' tag function
     */
    text: withVariables`Total is ${calcVar}!`,
  }),
];

// Generate the Shortcut data
const shortcut = buildShortcut(actions);

// Write the Shortcut to a file in the current directory
fs.writeFile('My Fancy Shortcut.shortcut', shortcut, (err) => {
  if (err) {
    console.error('Something went wrong :(', err);
    return;
  }
  console.log('Shortcut created!');
});

Running this code will build a Shortcut named 'My Fancy Shortcut.shortcut' in the current directory.

This can be AirDropped to an iPhone or iPad running iOS 12, at which point it will be automatically opened and imported into Shortcuts.

Shortcut Image

Further Examples

For brevity, these examples omit the code for writing the file to disk and just focus on building the Shortcut. See the Minimal Example above for an example of how to create the .shortcut file.

Battery level checker, with conditional action

const {
  actionOutput,
  buildShortcut,
  withVariables,
} = require('@joshfarrant/shortcuts-js');
const {
  conditional,
  getBatteryLevel,
  setLowPowerMode,
  showResult,
} = require('@joshfarrant/shortcuts-js/actions');

const batteryLevel = actionOutput();

const actions = [
  getBatteryLevel({}, batteryLevel),
  conditional({
    input: '<',
    value: 20,
    ifTrue: [
      setLowPowerMode({
        value: true,
      }),
      showResult({
        text: withVariables`Your battery is at ${batteryLevel}%, you might want to charge it.`,
      }),
    ],
    ifFalse: [
      showResult({
        text: withVariables`Your battery is at ${batteryLevel}%, you're probably fine for now.`,
      }),
    ],
  })
];

const shortcut = buildShortcut(actions);

Battery Checker Shortcut Image

Shortcut folder creator

This example creates folders and subfolders of Shortcuts so they can be easily run from one 'Folder' Shortcut.

This Shortcut could be tedious to set up using the drag-and-drop interface of the Shortcuts app, however we can simplify the generation of this Shortcut by using a function to build our actions from a predefined array of strings.

const {
  buildShortcut,
  withVariables,
} = require('@joshfarrant/shortcuts-js');
const {
  conditional,
  getBatteryLevel,
  setLowPowerMode,
  showResult,
} = require('@joshfarrant/shortcuts-js/actions');

const foldersArr = [
  ['Health', [ // The name of the folder
    'Log Sleep', // The names of Shortcuts to contain in that folder
    'Log Run',
    'Log Cycle',
  ]],
  ['Home', [
    ['Lights', [
      'Lights On', // We can go as many levels deep as we like
      'Lights Off',
    ]],
    ['Heating', [
      'Heating On',
      'Heating Off',
    ]],
    ['Cameras', [
      'Cameras On',
      'Cameras Off',
    ]],
    ['Door', [
      'Lock Door',
      'Unlock Door',
    ]],
  ]],
  ['Audio', [
    'Play Playlist',
    'Resume Podcast'
  ]],
];

const buildFolders = (arr) => (
  arr.map(shortcut => (
    Array.isArray(shortcut) ? ({
      label: shortcut[0],
      actions: [
        chooseFromMenu({
          prompt: shortcut[0],
          items: buildFolders(shortcut[1]),
        }),
      ],
    }
    ) : ({
      label: shortcut,
      actions: [
        runShortcut({
          name: shortcut,
        }),
      ],
    })
  ))
);

const actions = [
  chooseFromMenu({
    prompt: 'Open',
    items: buildFolders(foldersArr),
  }),
];

const shortcut = buildShortcut(actions);

Folder Shortcut Gif

Anything Else

If you're having any issues getting started, or you'd just like some advice, then please don't be afraid to Open an Issue, we're here to help!


Find out more at Shortcuts.fun.

@joshfarrant/shortcuts-js on npm.

NPM | Documentation | Contributing | Medium | Discord

See this issue for a complete list of all Actions implemented so far.

We have a Discord! If you need any help or have any questions, come and say hi! Join the Discord

Is the Action you want not available?

We're still working our way through the long list of built-in Shortcut Actions, if there's one you need sooner rather than later then Open an Issue and let us know; we might be able to prioritise it.

Alternatively, it's super easy to add an Action yourself! A simple Action should only take about 15 minutes to implement. Check out the Contributing Guide for more info on where to start. If for any reason you get stuck just Open an Issue. We're happy to help!


Download Details:

Author: joshfarrant
Source Code: https://github.com/joshfarrant/shortcuts-js 
License: GPL-3.0 license

#typescript #javascript #ios #apple #nodejs 

Shortcuts-js: A JavaScript IOS 12 Shortcuts Creator
Rupert  Beatty

Rupert Beatty

1675088100

iOS: Most Usable tools for iOS Penetration Testing

iOS/macOS penetration testing cheatsheet

ActionmacOSLinuxWiniOS w/JB
MobSFMobSFMobSFMobSF---
Plist viewplutil or Xcodeapt-get install libplist-utilsPlist Viewerplutil
GhidraGhidraGhidraGhidra---
FridaFridaFridaFrida---
Awesome FridaAwesome Frida------Awesome Frida
ObjectionObjectionObjectionObjectionObjection
NeedleNeedleNeedle------
Keychain dumperKeychain dumper------Keychain dumper
iOS URL SchemesiOS URL Schemes------iOS URL Schemes
Debug HacksDebug Hacks---------
SandBox DumperSandBox Dumper---------
PassionFruitPassionFruitPassionFruit------
iPhoneTunneliPhoneTunnel---iPhoneTunnel---
iRETiRET---------
idbidbidb------
XSecurityXSecurity---------

macOS Quick Look plugin for iOS & OSX developers

https://github.com/ealeksandrov/ProvisionQL – Generate amazing preview for .ipa .app .appex .mobileprovision .provisionprofile

iOS / macOS obfuscation

https://github.com/obfuscator-llvm/obfuscator/wiki – ollvm

Static analyze

Project/AppSwiftObjective-c
Swift Lint+-

Jailbreak

Jailbreak check
Jailbreak Chart
Can I Jailbreak?
Jailbreak list
Repos
http://cydia.iphonecake.com
http://apt.saurik.com/
http://repo.nesolabs.de/
https://build.frida.re/
http://appsec-labs.com/cydia/
http://cydia.zodttd.com/repo/cydia/
http://mobiletools.mwrinfosecurity.com/cydia/
http://repo666.ultrasn0w.com/
http://apt.thebigboss.org/repofiles/cydia/
http://cydia.radare.org/
http://apt.modmyi.com/
http://coolstar.org/publicrepo/
http://getdelta.co/ < Flex3 working
http://julioverne.github.io/
http://brunonfl.github.io/
http://apt.bingner.com/
http://repo.dynastic.co/
http://mcapollo.github.io/Public/
http://apt.hackcn.net/
http://repo.chariz.io/
http://cydia.ichitaso.com/
https://level3tjg.github.io < bfdecrypt (ios11/ios12)
http://ryleyangus.com/repo < Liberty Lite (beta) for JB bypas

Little h4ck for sslpinning bypass (help in some cases when sslkillswitch useless)

  • Configure burp proxy on iOS device – Visit [your_proxy_adress]:[proxy_port]/mobileassistant.deb – Download file and install
    • Via iFile
    • Via ssh like `dpkg -i path/to/mobileassistant.deb
  • Respring
  • Launch Mobile Assistant
  • Add app in bottom panel
  • Turn-on switcher next to app
  • Launch your app
  • Congrats

More info here NB! in some cases you may face with lack of libraries, do not replace anything manually in iOS, it may lead to infinity loop)

AppSign / Rebuild / Resign / Inject / Useful tools

Schema

Download and decrypt

ToolDescriptionLink
iFunBoxAppiFunBox
AppdbDownload&resign .ipaAppdb
iphonecakeDownload&resign .ipaiphonecake
4pdaDownload&resign .ipa4pda
iTunes w/app tabiTunes 12.6.3.6Apple Support
Download old version .ipaManual how-toLifehacker

Extract data

ToolDescriptionLink
RasticracJailbreak(+)Rasticrac
ClutchJailbreak(+)Clutch
bfinjectJailbreak(+), iOS 11-12bfinject

All in one (Inject > Repack > Resign > Upload)

ToolDescriptionLink
IPA PatchXcode ProjectIPA Patch
ResignXcode ProjectRegisn

Inject framework

ToolDescriptionLink
CydiaSubstrateFrameworkSite & .deb file
Reveal appProjectReveal app
JSPatchFrameworkJSPatch
FRAPLFrameworkFRAPL
Frida GadgetFrameworkFrida Gadget
CycriptFrameworkFrida+Cycript & Site

Repack and resign binary

ToolDescriptionLink
Node ResignXcode ProjectNode Resign
iOS App SignerXcode ProjectiOS App Signer
AppAddictAppAppAddict

Upload and run on device

ToolDescriptionLink
iFunBoxAppiFunBox
ImpactorAppCydia Impactor
IPA installerXcode ProjectIPA installer

Useful tools

ToolDescriptionLink
Runtime HeadersXcode ProjectRuntime Headers
SSL Killswitch 2Jailbreak(+)SSL Killswitch 2
TheosProjectTheos
DumpdecryptedProjectDumpdecrypted
BundleIDJailbreak(+)BundleID
IPSWDownload FirmwareIPSW

Slides and articles and links

NameLink
Malware wellbeing on iOS devicesSlides
DVIAHomepage
Dynamic analysis of iOS apps w/o JailbreakArticle En Article RU & Slides
Ro(o)tten Apples Vulnerability Heaven in the iOS SandboxSlides
Light and Dark side of Code InstrumentationSlides
Комбайны безопасности для iOS и AndroidSlides

Download Details:

Author: ansjdnakjdnajkd
Source Code: https://github.com/ansjdnakjdnajkd/iOS 
License: Apache-2.0 license

#macos #swift #security #ios #apple 

iOS: Most Usable tools for iOS Penetration Testing
Rupert  Beatty

Rupert Beatty

1673943903

ARShooter: A Demo Augmented Reality Shooter Made with ARKit in Swift

ARShooter

ARShooter is an open source Augmented Reality shooter made with ARKit and written in Swift. Hence, it is only useable with iOS 11.

For more details on how to get started with ARKit and make your own AR Shooter, take a look at the complementary (and complimentary) tutorial.

status

Requirements

  • Xcode 9
  • iOS 11
  • A9 or better chip for ARWorldTrackingConfiguration

Note: The app automatically detects if your device supports the ARWorldTrackingConfiguration. If not, it will use the less immersive AROrientationTrackingConfiguration, which is supported by all devices.

Communication

  • If you found a bug, open an issue after checking the FAQ.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Download

Simply navigate to your directory of interest, then clone.

$ git clone https://github.com/farice/ARShooter.git

If you'd like bullets to disappear rather than collect in the space around you, then switch to the bullets-disappear branch

 $ git checkout bullets-disappear

Finally, open the *.xcodeproj file and build to your supported device

FAQ

I am getting the SCNMatrix error:

Cannot invoke initializer for type 'SCNMatrix4' with an argument list of type '(matrix_float4x4)'

Please update to the latest Xcode version (this error is a result of a syntactical change made in Beta 2). If you insist on using Xcode Beta 1, then simply replace SCNMatrix4 with SCNMatrix4FromMat4.


Thanks

ARShooter has been featured by

Download Details:

Author: farice
Source Code: https://github.com/farice/ARShooter 
License: Apache-2.0 license

#swift #ios #demo #apple 

ARShooter: A Demo Augmented Reality Shooter Made with ARKit in Swift
Rupert  Beatty

Rupert Beatty

1673653500

StatusAlert: Display Apple System-like Self-hiding Status Alerts

StatusAlert is being sponsored by the following tool; please help to support us by takin a look and signing up to a free trial.

GitAds

StatusAlert is an iOS framework that displays status alerts similar to Apple's system self-hiding alerts. It is well suited for notifying user without interrupting user flow in iOS-like way.

It looks very similar to the alerts displayed in Podcasts, Apple Music and News apps. System StatusAlert

Features

  • System-like look and feel
  • Reduce transparency mode support
  • VoiceOver support
  • Safe Areas support
  • Universal (iPhone & iPad)
  • Objective-C support

Requirements

  • Xcode 9.0 or later
  • iOS 9.0 or later
  • Swift 3.2 or later

Installation

CocoaPods

To install StatusAlert using CocoaPods, add the following line to your Podfile:

pod 'StatusAlert', '~> 1.1.1'

Carthage

To install StatusAlert using Carthage, add the following line to your Cartfile:

github "LowKostKustomz/StatusAlert" ~> 1.1.1

Swift Package Manager

To install StatusAlert using Swift Package Manager add this to your dependencies in a Package.swift file:

dependencies: [
    .package(url: "https://github.com/LowKostKustomz/StatusAlert.git", .exact("1.1.1"))
]

Manual installation

You can also add this project:

  • as git submodule
  • simply download and copy source files to your project

Objective-C integration

StatusAlert is fully compatible with Objective-C. To import it to your project just add the following line:

@import StatusAlert;

Demo

Demo application is included in the StatusAlert workspace. To run it clone the repo.

Demo StatusAlert

Usage

// Importing framework
import StatusAlert

// Creating StatusAlert instance
let statusAlert = StatusAlert()
statusAlert.image = UIImage(named: "Some image name")
statusAlert.title = "StatusAlert title"
statusAlert.message = "Message to show beyond title"
statusAlert.canBePickedOrDismissed = isUserInteractionAllowed

// Presenting created instance
statusAlert.showInKeyWindow()

All the alert components (image, title, message) are optional, but at least one should be present. Otherwise show() method will be ignored.

IMPORTANT

The alert must be presented only from the main thread, otherwise application will crash with an appropriate error.

Customization

Wiki with more content and examples available

Different configurations

Present alert with any set of image, title and message

Vertical position

Display alert anywhere you want, either on the top, in the center or at the bottom of the view, and with any offset.

Appearance

You can customize a single alert's appearance via the StatusAlert's appearance property or for all alerts at once with StatusAlert.Appearance's common property

var titleFont: UIFont
var messageFont: UIFont
var tintColor: UIColor
var backgroundColor: UIColor
var blurStyle: UIBlurEffect.Style

Dismissal

Alert will hide itself after 2 seconds timeout.

You can change alert showing duration by setting alertShowingDuration property. You also can set canBePickedOrDismissed property to true. After that you will be able to dismiss the alert manually by tapping it and delay dismissal by long tapping the alert.

Apps Using StatusAlert

 
Bitxfy 

BitxfyScreenShot


NotifyMe

NotifyMeScreenShot

Feel free to submit pull request if you are using this framework in your apps.

Download Details:

Author: LowKostKustomz
Source Code: https://github.com/LowKostKustomz/StatusAlert 
License: MIT license

#swift #ios #apple #alert #ui #system 

StatusAlert: Display Apple System-like Self-hiding Status Alerts
Rupert  Beatty

Rupert Beatty

1673142360

VisualEffectView: Dynamic Blur Background View with Tint Color

VisualEffectView

VisualEffectView is a blur effect library with tint color support. This library uses the UIVisualEffectView to generate the blur.

Demo GIF

Demo Video

$ pod try VisualEffectView

Requirements

  • iOS 9.0+
  • Xcode 9.0+
  • Swift 5 (VisualEffectView 4.x), Swift 4 (VisualEffectView 3.x), Swift 3 (VisualEffectView 2.x), Swift 2 (VisualEffectView 1.x)

Usage

Add an instance of VisualEffectView to your view.

import VisualEffectView

let visualEffectView = VisualEffectView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))

// Configure the view with tint color, blur radius, etc
visualEffectView.colorTint = .redColor()
visualEffectView.colorTintAlpha = 0.2
visualEffectView.blurRadius = 10
visualEffectView.scale = 1

addSubview(visualEffectView)

Depending on the desired effect, the effect may affect content layered behind the view or content added to the visual effect view’s contentView. After you add the visual effect view to the view hierarchy, add any subviews to the contentView property of the visual effect view. Do not add subviews directly to the visual effect view itself. Refer to the UIVisualEffectView for more info.

For more examples, take a look at the example project.

Customization

var colorTint: UIColor // tint color. default is nil
var colorTintAlpha: CGFloat // tint color alpha. default is 0
var blurRadius: CGFloat // blur radius. default is 0
var scale: CGFloat // scale factor. default is 1

If you want colorTintAlpha to be different from 0, make sure you always set it right after setting the colorTint or it may not be applied as expected. You also have to make sure you don't set colorTintAlpha if colorTint is nil.

Storyboard Support

Works great with storyboards and xibs.

Installation

CocoaPods

To install with CocoaPods, simply add this in your Podfile:

use_frameworks!
pod "VisualEffectView"

Carthage

To install with Carthage, simply add this in your Cartfile:

github "efremidze/VisualEffectView"

Manually

  1. Download and drop VisualEffectView.swift in your project.
  2. Congratulations!

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Disclaimer

VisualEffectView utilizes a private UIKit API to do its magic. Use caution, submitting this code to the App Store adds the risk of being rejected!

Credits

https://github.com/collinhundley/APCustomBlurView

Download Details:

Author: Efremidze
Source Code: https://github.com/efremidze/VisualEffectView 
License: MIT license

#swift #ios #apple 

VisualEffectView: Dynamic Blur Background View with Tint Color
Kevon  Krajcik

Kevon Krajcik

1672836736

How to Create A To-do List App for Apple Watch

In this post, you will build a realtime iOS application involving a watch and an iPhone. We will be creating a realtime todo watch app with an accompanying iPhone app.

Here is how your application will look afterward:

watchOS-todo-demo-1

Prerequisites

To follow along in this article, you need the following:

  • A Pusher Channel app. You can create one here (take note of your app keys as you’ll need them later).
  • Xcode installed on your machine. You can download here.
  • Node JS and NPM (Node Package Manager) installed on your machine. Check here for the latest releases.

Let’s get started.

Building the backend

Our app will be powered by a local Node.js server. Create a folder on your machine, say todo-backend. Create a package.json file inside it and set it up like so:

    // File: ./package.json
    {
      "name": "todo",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "body-parser": "^1.18.3",
        "express": "^4.16.4",
        "pusher": "^2.2.0"
      }
    }

This file contains a description to our app and the dependencies we will make use of. Next, create an index.js file and paste this:

    // File: ./index.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const Pusher = require('pusher');
    const app = express();
    
    app.use(bodyParser.json());
    
    var pusher = new Pusher({
      appId: 'PUSHER_APP_ID',
      key: 'PUSHER_APP_KEY',
      secret: 'PUSHER_APP_SECRET',
      cluster: 'PUSHER_APP_CLUSTER'
    });
    
    app.post('/addItem', function (req, res) {
      pusher.trigger('todo', 'addItem', { text: req.body.value});
      res.send(200);
    })
    
    app.listen(process.env.PORT || 5000);

Here, we added a single endpoint that will add todo items. Our watch app will make use of this API and send a todo trigger to Pusher.

Replace PUSHER_APP_* placeholders with the credentials from your dashboard

Run the npm install command in the directory to install the Node modules after which you run your server using:

    $ node index.js

The localhost runs on port 5000.

Building the iOS app

Creating a project

Open your Xcode and create a new project. You will be presented with a template wizard. Choose watchOS and select iOS App with WatchKit App.

watchOS-todo-demo-2

Next, you enter a product name - say TodoWatchApp, team, and organization details. Choose Swift as the default language and choose Next. You will then be asked to choose the directory where you want the project to be created. After this, you’re good to go!

Here is how the directory of your project should look.

watchOS-todo-demo-3

This is quite different from when you are developing just the main app. We have three folders, one for the phone app and two for the watch.

The TodoWatchApp WatchKit App folder is where we design the interface for the watch while the TodoWatchApp WatchKit Extension is where we will write the logic and view controllers.

Building our iOS phone app

So, we will start with the phone app. The phone app will listen to triggers from Pusher. These triggers will be sent by the app. First, we will need to add the Pusher dependency. Follow these steps to set it up.

Run this command on your main app directory:

    $ pod init

This will create a Podfile where you can insert your dependencies. Paste this into the file:

    # File: ./Podfile
    target 'TodoWatchApp' do
      use_frameworks!
      pod 'PusherSwift'
    end
    
    target 'TodoWatchApp WatchKit App' do
      use_frameworks!
    end
    
    target 'TodoWatchApp WatchKit Extension' do
      use_frameworks!
    end

We only added the dependency for the main app as the library does not support watchOS yet. You can follow this GitHub issue to learn the latest on that.

Next, run this command still in the main app directory:

    $ pod install

After the installation is complete, close your project -TodoWatchApp.xcodeproj. Still in Xcode, open TodoWatchApp.xcworkspace located in the folder of your project. This was generated after you installed your dependencies.

For now, we will work with the TodoWatchApp folder. Now, let us design the interface for the app. All the app needs is a table view to display the todo items. Open the Main.storyboard file, delete the default ViewController scene. Now, drag the TableViewController element and drop on the empty light grey area. You should now have something like this:

watchOS-todo-demo-4

Set the controller to be the initial controller. You can do that in the identity inspector pane.

Go to your ViewController.swift class and change the class it is extending from UIViewController to UITableViewController.

The UITableViewController still extends the UIViewController class but it is specially configured to table views. Go back to your storyboard, select the Table View Controller element, in the identity inspector (third icon at the top right as seen in the image ), change the class to your ViewController class like so:

watchOS-todo-demo-5

Next, select the Table Cell which is a grandchild of the Table View Controller element, in the attributes inspector, enter an identifier of your choice or better still, use cell. This is the unique name used to identify the row name in the Swift file, later on.

Next, let us design how each row of the table view will look like. We will just want a label displaying the todo item. Simply drag a label to the Content View of the Table Cell. Your design should now look like this:

watchOS-todo-demo-6

The additions we just made are reflected in the screenshot above.
Next, create a TableCell.swift file and paste this:

    // File: ./TableCell.swift
    import Foundation
    import UIKit
    
    class TableCell: UITableViewCell {
    
        @IBOutlet weak var textView: UILabel!
    
        func setLabel(labelValue:String) {
            textView.text = labelValue
        }
    }

This class mimics how each row in the table view will look. It has just one UILabel as we earlier specified on our storyboard. Now that we have created this file, go back to the Main.storyboard , select the cell, in the attributes inspector, replace the default class there with TableCell like so:

watchOS-todo-demo-7

Be sure to link the @IBOutlet variable from your storyboard to the file.

Now, let us hook things up in our ViewController swift file. Paste this in the file:

    // File: ./ViewController.swift
    import UIKit
    import PusherSwift
    
    class ViewController: UITableViewController {
        var pusher: Pusher!
    
        var itemList = [String]() {
            didSet {
                self.tableView.reloadData()
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            setupPusher()
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return itemList.count
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            // inflate each row
            let currentItem = itemList[indexPath.row]
            let todoCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableCell
            todoCell.setLabel(labelValue: currentItem)
            return todoCell
        }
    }

Let us go through what we have here: first, we declared a Pusher variable and our list. In the viewDidLoad method, we call the setupPusher method which we will look at shortly.

The other two methods are for the table view, to get the size of the table and to get data for each row. Next, paste the setupPusher function inside the class like so:

    func setupPusher() {
        let options = PusherClientOptions(
            host: .cluster("PUSHER_APP_CLUSTER")
        )
    
        pusher = Pusher(
            key: "PUSHER_APP_KEY",
            options: options
        )
    
        // subscribe to channel and bind to event
        let channel = pusher.subscribe("todo")
    
        let _ = channel.bind(eventName: "addItem", callback: { (data: Any?) -> Void in
            if let data = data as? [String : AnyObject] {
                let value = data["text"] as! String
                self.itemList.append(value)
            }
        })
    
        pusher.connect()
    }

This method initializes Pusher and listens to the todo channel for updates.

Replace the Pusher holder with keys found on your dashboard

With this, we are done with our phone app. We will now build the watch app.

Building our watchOS app

Go to the TodoWatchApp WatchKit App folder, open the Interface.storyboard. Delete the controller scenes except for the Interface Controller Scene. Now drag a group element library to the watch screen. Set the orientation of the group to horizontal. Next, add a label and a button as children to the group.

We will use a custom icon for the button. You can download the icon here. Open the Assets.xcassets in the TodoWatchApp WatchKit App folder and import the new image asset. Make sure it is named add_item. After importing, go back to the Interface.storyboard , select the button, and select the icon as the background in the identity inspector. Clear the title on the button, then set the width and height to fixed using 20 as the value.

Next, we will hookup an action from the add button in the storyboard to our InterfaceController file. We use the assistant editor(icon with rings at top right) to split the two files like so:

watchOS-todo-demo-8

After that, open the InterfaceController.swift file in the TodoWatchApp WatchKit Extension folder and make sure your file looks like this:

    // File: ./InterfaceController.swift
    import WatchKit
    import Foundation
    
    class InterfaceController: WKInterfaceController {
        @IBAction func addNewItem() {
            let suggestionsArray = ["Visit Neo", "Write Pusher article"]
    
            presentTextInputController(withSuggestions: suggestionsArray,allowedInputMode: WKTextInputMode.allowEmoji, completion: { (result) -> Void in
    
                guard let choice = result else { return }
                
                let newItem = choice[0] as! String
                self.postValue(value: newItem)
            })
        }
    
        func postValue(value:String){
            let parameters = ["value": value] as [String : Any]
            let url = URL(string: "http://127.0.0.1:5000/addItem")!
            let session = URLSession.shared
    
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
    
            do {
                request.httpBody = try JSONSerialization.data(
                  withJSONObject: parameters, 
                  options: .prettyPrinted
                )
            } catch let error {
                print(error.localizedDescription)
            }
    
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
    
            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                guard error == nil else {
                    return
                }
    
                guard let data = data else {
                    return
                }
    
                do {
                    //create json object from data
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)
                    }
                } catch let error {
                    print(error.localizedDescription)
                }
            })
            
            task.resume()
        }
    }

Here, when the add button is clicked, the watch opens the input controller where you can either handwrite your todo, or choose from the suggestions, or dictate it. When you confirm your text, the watch sends the item to the server.

You can now run both applications on the simulator. You can select the WatchApp build so it runs both simulators at once.

When you run the app, it should look like this:

watchOS-todo-demo-1

Original article sourced at: https://pusher.com

#watch #apple 

How to Create A To-do List App for Apple Watch
Royce  Reinger

Royce Reinger

1672168740

Awesome-CoreML-Models: Largest list of models for Core ML for iOS 11+

Since iOS 11, Apple released Core ML framework to help developers integrate machine learning models into applications. The official documentation

We've put up the largest collection of machine learning models in Core ML format, to help iOS, macOS, tvOS, and watchOS developers experiment with machine learning techniques.

If you've converted a Core ML model, feel free to submit a pull request.

Recently, we've included visualization tools. And here's one Netron

Models

Image - Metadata/Text

Models that take image data as input and output useful information about the image.

Image - Image

Models that transform images.

Text - Metadata/Text

Models that process text data

Miscellaneous

Visualization Tools

Tools that help visualize CoreML Models

Supported formats

List of model formats that could be converted to Core ML with examples

The Gold

Collections of machine learning models that could be converted to Core ML

Individual machine learning models that could be converted to Core ML. We'll keep adjusting the list as they become converted.

  • LaMem Score the memorability of pictures.
  • ILGnet The aesthetic evaluation of images.
  • Colorization Automatic colorization using deep neural networks.
  • Illustration2Vec Estimating a set of tags and extracting semantic feature vectors from given illustrations.
  • CTPN Detecting text in natural image.
  • Image Analogy Find semantically-meaningful dense correspondences between two input images.
  • iLID Automatic spoken language identification.
  • Fashion Detection Cloth detection from images.
  • Saliency The prediction of salient areas in images has been traditionally addressed with hand-crafted features.
  • Face Detection Detect face from image.
  • mtcnn Joint Face Detection and Alignment.
  • deephorizon Single image horizon line estimation.

Contributing and License

  • See the guide
  • Distributed under the MIT license. See LICENSE for more information.

Download Details:

Author: likedan
Source Code: https://github.com/likedan/Awesome-CoreML-Models 
License: MIT license

#machinelearning #python #ios #apple 

Awesome-CoreML-Models: Largest list of models for Core ML for iOS 11+

Learn Apple M1 Processor Overview and Compatibility

The Apple M1 processor represents a significant step forward for Apple, but what does it mean for developers, designers, and other professionals using Apple hardware? In this article, Toptal Engineering Blog Editor Nermin Hajdarbegovic outlines what makes the M1 different and what professionals need to keep in mind should they choose to upgrade their hardware.

Every Apple event attracts a lot of attention, but the launch of the 2020 MacBook Air, MacBook Pro, and Mac Mini was about more than new features and sleek industrial design. This year, the big news is hidden deep inside the anodized aluminum chassis of new MacBooks, in the form of the Apple M1 System on a Chip (SoC), which is replacing Intel processors in 13-inch MacBooks and the Mac Mini.

Why is the transition to Apple processors so important? After all, Apple has been designing its smartphone processors since 2010, and this is not the first time it has embraced a new CPU architecture. Apple has gone through a number of different architectures, from Motorola CPUs in its Wozniak days, through PowerPC chips in the ‘90s, to Intel x86 processors in 2005. Now the company is moving to an ARM-based processor of its own design. In contrast, the Windows PC platform has stuck to x86 processors since the first IBM PC launched in 1981.

Today we will be taking a closer look at Apple’s new M1 chip, its implications for software engineers, designers, consumers, and the industry as a whole. We will not provide you with detailed performance reviews or test the compatibility of individual software suites and tools, legacy software, SDKs, and so on for brevity. Since you can easily find benchmarks and reviews on reputable hardware sites, we will focus on the big picture and address some concerns voiced by designers and developers interested in buying Apple’s new M1 MacBooks.

What Makes the Apple M1 Processor Different?

What makes the Apple M1 processor different? The Apple M1 differs from Intel processors used in previous MacBooks in many respects:

  • The M1 is an ARM processor, not an x86 processor.
  • It integrates more components than an Intel CPU.
  • The Apple M1 also integrates RAM in the same package.
  • It features Rosetta 2 dynamic binary translation that allows it to run x86 software.
  • The chip boasts eight CPU cores, in addition to the integrated GPU.
  • It is manufactured using the 5-nanometer process and has 16 billion transistors.

For the average user, most of these specifications won’t mean much, but power users should take note: The ARM-based Apple M1 is supposed to run legacy x86 software using Rosetta, which could cause adverse effects on performance when running x86 applications. Fortunately, due to its speed, the M1 will still outperform older Intel chips in most scenarios, even with legacy x86 apps. Also, some teething problems are to be expected, as exotic tools and applications might not run out of the box, or they may incur a performance penalty. Still, these problems will be ironed out, and most users needn’t worry about them.

For example, Docker users were unsure whether or not their x86-64 images would work properly. For the time being, they are facing serious issues, and Docker is not working properly. Although Adobe is working to optimize its products for the M1, designers relying on third-party plug-ins for Adobe products are experiencing compatibility issues.

This is to be expected on new hardware, as developers need time to catch up to ensure compatibility and port their software for the new hardware. It may take a while.

Designed by Apple, Marketed by Apple

Apple used the event to claim the M1 is the fastest CPU core on the market, but hardware enthusiasts were quick to point out that some of its performance claims were vague and difficult to confirm. We are not going to put every Apple marketing claim to the test as independent reviewers have already done that and the reviews are overwhelmingly positive. The M1 is not the fastest CPU on the planet, but it seems to be the fastest CPU for ultraportable notebooks.

Let’s take a closer look at the design of the Apple M1 and explain what makes it ingenious and how it could profoundly impact the industry.

Apple M1 Design and Features

The Apple M1 chip features four big Firestorm CPU cores for high-load scenarios, backed by four smaller Icestorm CPU cores designed for efficiency. If this sounds familiar, you’ve probably encountered Android phones with a similar ARM CPU layout. ARM calls this layout ARM big.LITTLE and it’s been around since 2014. The CPU uses the AArch64 or ARM64 extension set of the ARM architecture.

Likewise, you are probably used to integrated GPUs as well, as they’ve been used in Intel and AMD chips for years. The GPU used in the Apple M1 has eight cores and takes up just a bit more space on the chip than the eight CPU cores. Apple claims the GPU can deliver 2.6 TFLOPS. To put this in perspective, Nvidia’s GeForce GTX 1050Ti from 2016 manages 2.1 TFLOPS. That’s a desktop graphics card with 3.3 billion transistors that draws up to 75W of power, beaten by integrated graphics on a passively cooled MacBook Air.

The only downside is that there’s no eGPU support and you can’t get discrete graphics. Apple didn’t offer optional discrete GPUs on 13-inch MacBooks powered by Intel processors, either. In case you need a Radeon Pro on your new MacBook, you will still need to get a 16-inch MacBook Pro.

 

Apple M1 Processor

 

The M1 also integrates RAM in the SoC package, just like the company’s latest A-series processors used in iPhones and iPads. This is a first for processors that aren’t designed for content consumption devices like phones.

Previously, MacBooks featured DDR4 memory soldered on the motherboard. This new approach allows Apple to use a new unified memory architecture. The Apple M1 uses LP-DDR4X memory running at 3733MHz. This allows both the CPU and GPU to access it at high speeds, but this high degree of integration comes at a price.

The downside is that the M1 chip will be available with only 8GB and 16GB of RAM, at least for the time being. Sticking to 8GB or 16GB of RAM on the MacBook Air or Mac Mini shouldn’t be a problem for most users, but many MacBook Pro enthusiasts won’t be thrilled by the prospect of buying a 16GB machine that cannot be upgraded.

Granted, we are used to laptops with soldered RAM, but this is different. With soldered RAM, manufacturers can refresh their product lineup by swapping out the RAM chips with higher capacity ones, e.g. using two 16GB RAM chips instead of two 8GB units. This approach should not require any changes to the motherboard or other components. However, with RAM integrated into the SoC, this would require doubling the memory capacity in the chip package, i.e. a revised M1 chip. Therefore, Apple is unlikely to add a 32GB RAM option in its mid-2021 update, as it will most likely have to wait for a new M-series processor, which could take 12 to 18 months.

In addition to the CPU, GPU, and RAM, the Apple M1 also features a 16-core Neural Engine, a new image signal processor (ISP), Secure Enclave, Rosetta hardware optimization, support for AES encryption hardware, as well as dedicated encode and decode engines for audio and video content. According to early reviews, the latter allows it to outpace x86-based Macs by a significant margin.

The M1 has a standard range of I/O options with a Thunderbolt controller capable of supporting USB 4. However, there’s no support for 10Gbit networking out of the box (if you need it), and the new MacBooks have only two USB Type-C/Thunderbolt ports. Of course, the desktop Mac Mini has a few additional ports compared to MacBooks.

Apple M1 Compatibility and Virtualization Concerns

Since we are discussing new hardware, we cannot make definitive judgments at this early stage, although things are looking quite good. Some applications will need to be optimized for the new processor to ensure support for M1 processors and enable them to utilize its full performance potential. Luckily, the Apple M1 is so fast that some x86 applications running on Rosetta 2 will still run faster than on older x86 chips. Thanks to Rosetta-optimized hardware, the new Macs have enough performance to take the x86-to-ARM performance penalty and come out on top.

It is essential to distinguish between software that is not optimized for the Apple M1 and software that currently cannot run on Rosetta 2. Lack of optimization will result in degraded performance, while lack of compatibility will result in unworkable projects and a lot of frustration.

Virtualization is another source of trouble. We already mentioned issues brought up by the Docker community, and it’s easy to see why x86 images might prove problematic at this early stage. Unfortunately, a lot of information on virtualization support on the M1 processor is still not available. Although Apple isn’t saying much, VMware and Parallels have already announced they are working on M1-optimized updates, though it should be noted that VMware stopped short of revealing a timeline for its rollout.

How serious are these problems? For the time being, some crucial tools either won’t run on new Macs or won’t run properly. These include Docker, Android Studio, and Haskell. The list of tools that will run on Rosetta 2 but aren’t optimized for the M1 is much more extensive and includes Atom, RStudio, PHPStorm, R, Flutter, VSCode, Golang, .NET, and even PHP. They are expected to be optimized for Apple silicon in the coming weeks and months.

You can consult IsAppleSiliconReady.com for additional information and updates. Of course, you can also check the status of each component of your stack on your own.

Designers have less to worry about, as most software suites will work fine, although some still aren’t optimized for the M1. There was a lot of talk about Adobe products and whether or not they will be fully compatible at launch. It seems this won’t be a big problem, as Adobe is expected to roll out updates in early 2021 and make sure everything is working properly. Due to the popularity of Apple hardware among designers, rest assured that Adobe and other software vendors will do their best to optimize software for the new architecture.

Third-party plug-ins for Adobe products are a more significant concern, as it could take a while before they are all updated.

Lest we forget, most servers still use x86 chips, although ARM processors made inroads in certain niches of the server market. For years, Macs were the go-to platform for software developers because they allowed them to work on a UNIX-based operating system running on x86 hardware. They would produce code designed to run on servers using the same instruction set and another UNIX-based operating system. With the M1, this will change as Apple developers will be developing software on ARM hardware and then rolling it out on x86 servers.

On the other hand, new MacBooks can run iOS apps natively, as Macs and iPhones now share the same CPU architecture. Users can download and install iOS apps through the App Store, though the UI might not offer a polished user experience we’ve come to expect from Apple.

Implications for Real-world Users

Apple has managed to design a potent mobile processor that will breathe new life into MacBooks and Mac Mini. Although some of the company’s performance figures were vague, reviewers confirm the new processor easily beats previous generation products based on Intel processors. It even outpaces more powerful desktop CPUs from Intel and AMD in some scenarios, such as video, thanks to dedicated hardware encoders.

So, all is well in the MacBook universe? It’s looking good so far, but it ultimately depends on your priorities and your stack.

Improved Battery Life and Efficiency

The M1 excels at many things. Performance in most scenarios is second to none, and due to improved efficiency, your next MacBook could run a few hours longer with no changes to battery capacity. Efficiency doesn’t only improve battery life. It also means the MacBook Air can deliver a lot of performance with passive cooling. The MacBook Pro has a fan, though it probably won’t spin until you put it under a lot of load. Everyone loves silent computers, and the M1 promises a lot of performance without much fan noise or heat.

There is a caveat worth mentioning. ARM processors tend to be more efficient than their x86 counterparts in low-power scenarios, but due to higher leakage and loss of efficiency at high core clocks, this advantage is likely to decrease under heavy load. Battery life improvements will be higher if you spend most of your time browsing, editing documents, or writing code. They probably won’t be as impressive if you compile a lot of code or do 3D rendering daily.

The MacBook Air, typically used for content consumption and web applications, is likely to benefit more than the MacBook Pro, which is mostly used for productivity and high-load applications. In both cases, though, users can expect a lot more battery life.

But will MacBook Pro users gain a lot of performance thanks to superior cooling, which will enable the processor to run at high clock speeds without thermal throttling? It’s not as straightforward as with Intel chips, which greatly benefit from higher clocks. As we noted earlier, ARM chips are different and they lose efficiency and deliver a smaller performance boost at higher clocks.

Connectivity and Expansion

This has been a source of controversy following every MacBook Pro launch in recent years, as Apple tends to remove physical ports with each new generation. With the new MacBooks, users will have even fewer options, and they may require more dongles and USB Type-C hubs than ever before.

Limited connectivity will not be much of an issue for the average MacBook Air user, but MacBook Pro lovers will have something to complain about, again. Let’s not forget the lack of on-board 10Gbit networking, either. This won’t affect most users, but some professionals still rely on fast, wired networks to quickly copy large video files and databases over their local network. Also, some video professionals are reporting compatibility issues with specialized hardware and peripherals.

Once again, the MacBook Air seems to come out on top, as most of its user base won’t miss things like 10Gbit networking. If you’re starting to see a pattern here, you’re not alone.

Upgradeability and Customization

Finally, here is something the Apple M1 does not excel at. We already outlined the problem with integrated RAM as opposed to soldered RAM modules. Integrating RAM on the processor has its advantages as it simplifies power delivery, reduces the footprint of the motherboard, and unlocks more performance. Still, there’s a high price to pay for this approach. It is hard to see how Apple could offer 32GB or 64GB options anytime soon. If you need a lot of RAM, your only option at this time is to choose a MacBook Pro with an Intel processor.

Is this a deal-breaker for many users? Probably not, as we are talking about 13-inch laptops. If you’re in the market for a powerful mobile workstation, you would probably go for the 16-inch version anyway. So what’s the problem? Well, judging by the performance figures, Intel-based Macs may end up slower in many scenarios, so some users may have to sacrifice CPU performance to get a system with more RAM.

However, if you’re looking to replace your 5-year-old MacBook Air, you should be fine with 16GB or maybe even 8GB of memory. Again, the Air customer doesn’t have to compromise like their Pro counterpart.

Long-term Implications for Linux and Windows Users

For the first time in almost two decades, Mac users will be using processors superior to x86 chips powering Windows PCs. Since 2006, Mac and Windows machines used the same processors, but now Apple has its own silicon to back its operating system. This isn’t just a matter of prestige or fodder for online flame wars – this is vertical integration at a level previously unseen in the industry. Apple now controls its OS as well as its CPU design. It relies on third parties only for manufacturing and commoditized components such as storage, displays, touchpads, and so on.

The ARM architecture offers more efficiency and scales better than x86. Intel’s x86 chips no longer provide substantial performance improvements with each new generation, though it should be noted that AMD is doing better with its Ryzen processors. ARM chips are evolving faster and delivering far greater performance boosts from generation to generation. In under ten years, Apple’s A-series smartphone chips have managed to catch up with Intel’s x86 notebook chips, and the M-series has overtaken them. If we continue to see similar performance improvements with future M-series processors, Apple will be in a very strong position for years to come.

Windows remains stuck on x86, not just because Microsoft hasn’t made much progress with Windows on ARM, but because there aren’t that many ARM processors and hardware platforms suitable for Windows desktop applications. In fact, Apple recently stated that it’s “up to Microsoft” to make Windows run on the M1. However, some intrepid developers already managed to run Windows for ARM on Apple silicon, and the results are good, as it outperformed Microsoft’s own Surface Pro X.

Of course, Apple isn’t going to sell its chips to the higher bidder, but let’s not forget other ARM chipmakers such as Qualcomm and Samsung. It is also worth noting that Nvidia is in the process of acquiring ARM and this could shake up the market as well.

The Hackintosh community might end up being the biggest loser of this transition. In the long run, as Apple starts to tie its OS to its silicon, the Hackintosh may become a footnote in computing history. For the time being, you can forget about running Windows via Bootcamp as well, and Linus Torvalds recently expressed doubts that Linux will get ported to the Apple M1. UNIX-based operating systems can run on ARM and x86, so in theory, it shouldn’t be too hard, but there could be problems with drivers, bootloaders, and so on.

Should I Buy an Apple M1 Mac?

Yes, provided you do your homework first, as early adopters could experience some compatibility issues. As companies update and optimize their products for the M1 processor, most of these concerns will fade away.

If you can live with 16GB of RAM and make sure the tools you use will work from day one, there’s no reason to have misgivings about switching to a new architecture. After all, we are talking about an industry heavyweight with a significant market share. Every software vendor will make sure their products work on Apple hardware, although this may take a few weeks or months. No, you won’t feel like a beta tester, and no, Apple will not treat new Macs like the first-generation iPad or the zero-gen Apple Watch.

While Apple’s marketing may have been vague and overly optimistic in some respects, it is obvious that the M1 is a very capable processor. While it might not outpace some Intel and AMD chips in the high-end segment, the fact that Mac users can get this level of performance in a passively cooled MacBook Air or a compact desktop like the Mac Mini is a testament to Apple’s engineering prowess.

Eagle-eyed readers may have noticed I omitted the MacBook Pro, and hardware enthusiasts probably know why. The difference between M1-based MacBook Pros and MacBook Airs simply isn’t that big anymore. The Pro has a Touch Bar, a marginally bigger battery, and better cooling. Unfortunately, we already mentioned that ARM chips don’t excel at high clocks as much as their x86 counterparts, so this advantage is blunted by virtue of the architecture. In other words, the Pro won’t be noticeably faster than the Air in most scenarios. In burst loads, they should be on a par.

Apple has been removing physical ports from the MacBook Pro for years, causing a lot of frustration in professional circles. With this generation, they went a step further, maybe even a step too far. Like the Air, the MacBook Pro lacks connectivity, expansion, and RAM options desired by enthusiasts and professionals, yet it only delivers marginally better performance compared to the Air. This makes it a much harder sell than the MacBook Air.

Bottom line: the Apple M1 is an impressive feat of engineering that will shake up the industry. No, it won’t kill off cheaper Windows laptops or x86 chips. However, at this point, it looks like it could very well end up hurting the 13-inch MacBook Pro unless Apple can surprise us with a more enticing version soon. A 32GB variant could do the trick, but given the integrated RAM, it’s unlikely we will see one until Apple unveils the M2 processor.

Original article source at: https://www.toptal.com/

#apple #compatibility 

Learn Apple M1 Processor Overview and Compatibility

Guide for App Owners: Sign in With Apple

Apple has announced a new sign-in feature called “Sign In with Apple.” This new feature will allow users to sign in to apps and websites using their Apple ID rather than creating a separate username and password. 

Here’s what you need to know about how Sign In with Apple will work for app owners.

What is Sign in with Apple

Sign In with Apple works similarly to how current users set up two-factor authentication sign-in. When users select Sign In with Apple, they will be prompted for their password and a six-digit verification code. Unlike other sign-in methods, this code is either sent to a device associated with the account or sent as a push notification. 

The first time a user signs into your app using Sign In with Apple, you’ll have an opportunity to prompt them to save their credentials, so future logins become easier - without requiring security codes or generating new tokens. If preferred, you can also choose not to generate those alerts at all. 

Don’t worry about any of that, though: iOS will handle most of the heavy lifting on your app’s behalf by default.

What does Sign In with Apple mean for users?

Apple made it clear that they approach sign-in and user security with a holistic approach: your Apple ID’s security is their priority. They want to increase convenience without sacrificing security, or vice versa. 

For this reason, some users may consider Sign In with Apple as an alternative login method for their apps - not as a replacement to existing methods. These users will appreciate how easy it is to use their already-existing credentials, especially those who have already set up two-factor authentication. 

Many users will likely be thrilled by the idea of never having to type out long usernames and passwords again – but keep in mind that having two different forms of login may be preferable for power users. 

What does Sign In with Apple mean for app owners?

According to our initial estimates, the launch of Sign In with Apple has a relatively small impact on the overall number of logged-in sessions within your app. Many users are already using their Apple IDs to authenticate into apps via Facebook or Google - so the benefits are limited. 

For this reason, it doesn’t make sense to leave out 2-factor authentication if you’re concerned about security breaches to your login store. Having at least one additional verification method (e.g., text message) can help protect against hijackings and credential stuffing, which we’ve written about in-depth in our past blog posts. 

Last but not least, Apple is positioning Sign In with Apple as an alternative login method for existing apps - not a replacement to other existing methods like Facebook or Google login. It’s also worth noting that they’re encouraging developers to keep the latest version of iOS on all devices running your app up-to-date to ensure compatibility with new sign-in integrations that will be introduced over time. This may help reduce support requests for login issues down the road.

Is Sign in with Apple mandatory for App Owners

No, Apple does not require developers to use Sign In with Apple (when we do not use social login). It’s worth reiterating that this feature should be considered an alternative login method rather than a replacement for existing methods. If you’d like, you can choose to disable it completely or show a reminder message instead of automatically signing in users - but don’t assume that your users will mind having their data auto-populated without their permission. 

When you need to implement Sign-in with Apple

Sign In with Apple is mandatory for app owners if they use another social login like Google or Facebook. In this scenario, the user needs to have iOS 11 on their devices to sign in.

Will there be any impact on my current integration?

It shouldn’t have any effect if other supported authentication providers are used in the app, but keep in mind there may be some potential impact if your app can already auto-fill user credentials using watchOS or macOS. 

This is because Sign In with Apple works similarly to how those AutoFill methods do. So you will need to unify those login flows if AutoFill is enabled. 

The good news: Apple has provided a few different workflows that developers can choose from in the App Store Connect documentation.

Will I be able to provide custom branding?

Yes, but only for certain prompting and alert styles. While we’re still investigating other options, at least one way of providing custom branding for Sign In with Apple is by using Accessibility Customization (e.g., Guided Access or VoiceOver). 

This may seem like it would prevent users from adding additional authentication factors without removing the customization. However, it’s important to note that this workaround should not prevent users from requiring 2-factor authentication via SMS

How to implement Sign-in with Apple in your app

To implement Sign In with Apple, you’ll need to add the following entitlement to your project:  

  • com.apple.developer.associated-domains 

This entitlement will be used to verify that a user’s email is associated with an Apple ID and needs access to use this App Store feature. 

It can be added by going into “Capabilities” within Xcode and searching for it under Associated Domains. This entitlement is required from version 11.0 of the iOS SDK through 12.0 (inclusive).

If you need help adding Sign In with Apple to your app, please contact us for assistance.

Conclusion

Sign In with Apple is available now on iOS 12 and can be enabled through iTunes Connect.

New users who set up two-factor authentication using their Apple ID will be prompted to use Sign In with Apple. 

If you’re concerned with security breaches, we suggest adding at least one additional verification method (e.g., text message), which can help protect against hijackings and credential stuffing.

Sign In with Apple is positioned as an alternative login method for existing apps and not a replacement to other existing methods like Facebook or Google login.

For more information about Sign In with Apple, please visit: https://developer.apple.com/sign-in-with-apple/

If you need help adding Sign In with Apple to your app, please contact us for assistance. Our experts will be happy to help you!

Original article source at: https://www.blog.duomly.com/

#apple #sign #app 

 Guide for App Owners: Sign in With Apple

How to Creating Apple's Website with Bootstrap 4

Apple's home page is an example for a lightweight and modern design that looks good on any screen size. In this lesson we will recreate it using our powerful web design tool - Bootstrap Studio.

Some of the highlights of the video are the way we customize the navbar to make it fixed to the top and all links evenly spaced out. Also, you can watch us use Bootstrap's rows and columns to construct a responsive product grid.

products-grid-preview.png

You can watch the video on YouTube, where we've linked to the images we used and the final bsdesign file. For more videos like this, visit and subscribe to our channel. Happy learning!

Watch the step-by-step video below, and learn how to use the Bootstrap framework and write mobile-first CSS to make your website responsive.

Original article source at: https://tutorialzine.com/

#bootstrap #apple #website 

How to Creating Apple's Website with Bootstrap 4
Rupert  Beatty

Rupert Beatty

1668134460

Alerttoast: Create Apple-like Alerts & Toasts using SwiftUI

AlertToast-SwiftUI

Present Apple-like alert & toast in SwiftUI

🌄 Example

ToastExample.gif

🔭 Overview

Currently in SwiftUI, the only way to inform the user about some process that finished for example, is by using Alert. Sometimes, you just want to pop a message that tells the user that something completed, or his message was sent. Apple doesn't provide any other method rather than using Alert even though Apple using all kinds of different pop-ups. The results are poor UX where the user would need to tap "OK/Dismiss" for every little information that he should be notified about.

Alert Toast is an open-source library in Github to use with SwiftUI. It allows you to present popups that don't need any user action to dismiss or to validate. Some great usage examples: Message Sent, Poor Network Connection, Profile Updated, Logged In/Out, Favorited, Loading and so on…

  • Built with pure SwiftUI.
  • 3 Display modes: Alert (pop at the center), HUD (drop from the top) and Banner (pop/slide from the bottom).
  • Complete, Error SystemImage, Image, Loading, and Regular (Only Text).
  • Supports Light & Dark Mode.
  • Works with any kind of view builder.
  • Localization support.
  • Font & Background customization.

If you like the project, don't forget to put star 🌟.

💻 Installation

Cocoapods

AlertToast Cocapods Website

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate AlertToast into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'AlertToast'

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

To integrate AlertToast into your Xcode project using Xcode 12, specify it in File > Swift Packages > Add Package Dependency...:

https://github.com/elai950/AlertToast.git, :branch="master"

For Xcode 13, please refer this article to install AlertToast


Manually

If you prefer not to use any of dependency managers, you can integrate AlertToast into your project manually. Put Sources/AlertToast folder in your Xcode project. Make sure to enable Copy items if needed and Create groups.

🧳 Requirements

  • iOS 13.0+ | macOS 11+
  • Xcode 12.0+ | Swift 5+

🛠 Usage

First, add import AlertToast on every swift file you would like to use AlertToast.

Then, use the .toast view modifier:

Parameters:

  • isPresenting: (MUST) assign a Binding<Bool> to show or dismiss alert.
  • duration: default is 2, set 0 to disable auto dismiss.
  • tapToDismiss: default is true, set false to disable.
  • alert: (MUST) expects AlertToast.

Usage example with regular alert

import AlertToast
import SwiftUI

struct ContentView: View{

    @State private var showToast = false

    var body: some View{
        VStack{

            Button("Show Toast"){
                 showToast.toggle()
            }
        }
        .toast(isPresenting: $showToast){

            // `.alert` is the default displayMode
            AlertToast(type: .regular, title: "Message Sent!")
            
            //Choose .hud to toast alert from the top of the screen
            //AlertToast(displayMode: .hud, type: .regular, title: "Message Sent!")
            
            //Choose .banner to slide/pop alert from the bottom of the screen
            //AlertToast(displayMode: .banner(.slide), type: .regular, title: "Message Sent!")
        }
    }
}

Complete Modifier Example

.toast(isPresenting: $showAlert, duration: 2, tapToDismiss: true, alert: {
   //AlertToast goes here
}, onTap: {
   //onTap would call either if `tapToDismis` is true/false
   //If tapToDismiss is true, onTap would call and then dismis the alert
}, completion: {
   //Completion block after dismiss
})

Alert Toast Parameters

AlertToast(displayMode: DisplayMode,
           type: AlertType,
           title: Optional(String),
           subTitle: Optional(String),
           style: Optional(AlertStyle))
           
//This is the available customizations parameters:
AlertStyle(backgroundColor: Color?,
            titleColor: Color?,
            subTitleColor: Color?,
            titleFont: Font?,
            subTitleFont: Font?)

Available Alert Types:

  • Regular: text only (Title and Subtitle).
  • Complete: animated checkmark.
  • Error: animated xmark.
  • System Image: name image from SFSymbols.
  • Image: name image from Assets.
  • Loading: Activity Indicator (Spinner).

Alert dialog view modifier (with default settings):

.toast(isPresenting: Binding<Bool>, duration: Double = 2, tapToDismiss: true, alert: () -> AlertToast , onTap: () -> (), completion: () -> () )

Simple Text Alert:

AlertToast(type: .regular, title: Optional(String), subTitle: Optional(String))

Complete/Error Alert:

AlertToast(type: .complete(Color)/.error(Color), title: Optional(String), subTitle: Optional(String))

System Image Alert:

AlertToast(type: .systemImage(String, Color), title: Optional(String), subTitle: Optional(String))

Image Alert:

AlertToast(type: .image(String), title: Optional(String), subTitle: Optional(String))

Loading Alert:

//When using loading, duration won't auto dismiss and tapToDismiss is set to false
AlertToast(type: .loading, title: Optional(String), subTitle: Optional(String))

You can add many .toast on a single view.

📖 Article

I wrote an article that contains more usage examples.

Medium - How to toast an alert in SwiftUI

👨‍💻 Contributors

All issue reports, feature requests, pull requests and GitHub stars are welcomed and much appreciated.



Download Details:

Author: elai950
Source Code: https://github.com/elai950/AlertToast 
License: MIT license

#swift #apple #alert #xcode #dialog #popup 

Alerttoast: Create Apple-like Alerts & Toasts using SwiftUI
Rupert  Beatty

Rupert Beatty

1667874180

Cluster: Easy Map annotation Clustering

Cluster

Cluster is an easy map annotation clustering library. This repository uses an efficient method (QuadTree) to aggregate pins into a cluster.

Demo Screenshots

Features

  •  Adding/Removing Annotations
  •  Clustering Annotations
  •  Multiple Managers
  •  Dynamic Cluster Disabling
  •  Custom Cell Size
  •  Custom Annotation Views
  •  Animation Support
  •  Documentation

Requirements

  • iOS 8.0+
  • Xcode 9.0+
  • Swift 5 (Cluster 3.x), Swift 4 (Cluster 2.x), Swift 3 (Cluster 1.x)

Demo

The Example is a great place to get started. It demonstrates how to:

  • integrate the library
  • add/remove annotations
  • reload annotations
  • configure the annotation view
  • configure the manager

Demo GIF

Demo Video

$ pod try Cluster

Installation

Cluster is available via CocoaPods and Carthage.

CocoaPods

To install Cluster with CocoaPods, add this to your Podfile:

pod "Cluster"

Carthage

To install Cluster with Carthage, add this to your Cartfile:

github "efremidze/Cluster"

Usage

The Basics

The ClusterManager class generates, manages and displays annotation clusters.

let clusterManager = ClusterManager()

Adding an Annotation

Create an object that conforms to the MKAnnotation protocol, or extend an existing one. Next, add the annotation object to an instance of ClusterManager with add(annotation:).

let annotation = Annotation(coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))
manager.add(annotation)

Configuring the Annotation View

Implement the map view’s mapView(_:viewFor:) delegate method to configure the annotation view. Return an instance of MKAnnotationView to display as a visual representation of the annotations.

To display clusters, return an instance of ClusterAnnotationView.

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? ClusterAnnotation {
            return CountClusterAnnotationView(annotation: annotation, reuseIdentifier: "cluster")
        } else {
            return MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
        }
    }
}

For performance reasons, you should generally reuse MKAnnotationView objects in your map views. See the Example to learn more.

Customizing the Appearance

The ClusterAnnotationView class exposes a countLabel property. You can subclass ClusterAnnotationView to provide custom behavior as needed. Here's an example of subclassing the ClusterAnnotationView and customizing the layer borderColor.

class CountClusterAnnotationView: ClusterAnnotationView {
    override func configure() {
        super.configure()

        self.layer.cornerRadius = self.frame.width / 2
        self.layer.masksToBounds = true
        self.layer.borderColor = UIColor.white.cgColor
        self.layer.borderWidth = 1.5
    }
}

See the AnnotationView to learn more.

Annotation Styling

You can customize the appearance of the StyledClusterAnnotationView by setting the style property of the annotation.

let annotation = Annotation(coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))
annotation.style = .color(color, radius: 25)
manager.add(annotation)

Several styles are available in the ClusterAnnotationStyle enum:

  • color(UIColor, radius: CGFloat) - Displays the annotations as a circle.
  • image(UIImage?) - Displays the annotation as an image.

Once you have added the annotation, you need to return an instance of the StyledClusterAnnotationView to display the styled annotation.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? ClusterAnnotation {
        return StyledClusterAnnotationView(annotation: annotation, reuseIdentifier: identifier, style: style)
    }
}

Removing Annotations

To remove annotations, you can call remove(annotation:). However the annotations will still display until you call reload().

manager.remove(annotation)

In the case that shouldRemoveInvisibleAnnotations is set to false, annotations that have been removed may still appear on map until calling reload() on visible region.

Reloading Annotations

Implement the map view’s mapView(_:regionDidChangeAnimated:) delegate method to reload the ClusterManager when the region changes.

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    clusterManager.reload(mapView: mapView) { finished in
        // handle completion
    }
}

You should call reload() anytime you add or remove annotations.

Configuring the Manager

The ClusterManager class exposes several properties to configure clustering:

var zoomLevel: Double // The current zoom level of the visible map region.
var maxZoomLevel: Double // The maximum zoom level before disabling clustering.
var minCountForClustering: Int // The minimum number of annotations for a cluster. The default is `2`.
var shouldRemoveInvisibleAnnotations: Bool // Whether to remove invisible annotations. The default is `true`.
var shouldDistributeAnnotationsOnSameCoordinate: Bool // Whether to arrange annotations in a circle if they have the same coordinate. The default is `true`.
var distanceFromContestedLocation: Double // The distance in meters from contested location when the annotations have the same coordinate. The default is `3`.
var clusterPosition: ClusterPosition // The position of the cluster annotation. The default is `.nearCenter`.

ClusterManagerDelegate

The ClusterManagerDelegate protocol provides a number of functions to manage clustering and configure cells.

// The size of each cell on the grid at a given zoom level.
func cellSize(for zoomLevel: Double) -> Double? { ... }

// Whether to cluster the given annotation.
func shouldClusterAnnotation(_ annotation: MKAnnotation) -> Bool { ... }

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Mentions

Credits

Download Details:

Author: Efremidze
Source Code: https://github.com/efremidze/Cluster 
License: MIT license

#swift #ios #apple #clustering #map 

Cluster: Easy Map annotation Clustering
Hermann  Frami

Hermann Frami

1667645117

Appwrite: Secure Backend Server for Web, Mobile & Flutter Developers

Appwrite

A complete backend solution for your [Flutter / Vue / Angular / React / iOS / Android / *ANY OTHER*] app

Appwrite 1.0 has been released! Learn what's new!

Appwrite is an end-to-end backend server for Web, Mobile, Native, or Backend apps packaged as a set of Docker microservices. Appwrite abstracts the complexity and repetitiveness required to build a modern backend API from scratch and allows you to build secure apps faster.

Using Appwrite, you can easily integrate your app with user authentication & multiple sign-in methods, a database for storing and querying users and team data, storage and file management, image manipulation, Cloud Functions, and more services.


Appwrite - 100% open source alternative for Firebase | Product Hunt 

 

Appwrite

Find out more at: https://appwrite.io

Installation

Appwrite backend server is designed to run in a container environment. Running your server is as easy as running one command from your terminal. You can either run Appwrite on your localhost using docker-compose or on any other container orchestration tool like Kubernetes, Docker Swarm, or Rancher.

The easiest way to start running your Appwrite server is by running our docker-compose file. Before running the installation command, make sure you have Docker installed on your machine:

Unix

docker run -it --rm \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
    --entrypoint="install" \
    appwrite/appwrite:1.0.3

Windows

CMD

docker run -it --rm ^
    --volume //var/run/docker.sock:/var/run/docker.sock ^
    --volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
    --entrypoint="install" ^
    appwrite/appwrite:1.0.3

PowerShell

docker run -it --rm `
    --volume /var/run/docker.sock:/var/run/docker.sock `
    --volume ${pwd}/appwrite:/usr/src/code/appwrite:rw `
    --entrypoint="install" `
    appwrite/appwrite:1.0.3

Once the Docker installation completes, go to http://localhost to access the Appwrite console from your browser. Please note that on non-Linux native hosts, the server might take a few minutes to start after installation completes.

For advanced production and custom installation, check out our Docker environment variables docs. You can also use our public docker-compose.yml and .env files to manually set up an environment.

Upgrade from an Older Version

If you are upgrading your Appwrite server from an older version, you should use the Appwrite migration tool once your setup is completed. For more information regarding this, check out the Installation Docs.

One-Click Setups

In addition to running Appwrite locally, you can also launch Appwrite using a pre-configured setup. This allows you to get up and running with Appwrite quickly without installing Docker on your local machine.

Choose from one of the providers below:

DigitalOcean Logo
DigitalOcean
Gitpod Logo
Gitpod

Getting Started

Getting started with Appwrite is as easy as creating a new project, choosing your platform, and integrating its SDK into your code. You can easily get started with your platform of choice by reading one of our Getting Started tutorials.

Services

  • Account - Manage current user authentication and account. Track and manage the user sessions, devices, sign-in methods, and security logs.
  • Users - Manage and list all project users when building backend integrations with Server SDKs.
  • Teams - Manage and group users in teams. Manage memberships, invites, and user roles within a team.
  • Databases - Manage databases, collections and documents. Read, create, update, and delete documents and filter lists of document collections using advanced filters.
  • Storage - Manage storage files. Read, create, delete, and preview files. Manipulate the preview of your files to fit your app perfectly. All files are scanned by ClamAV and stored in a secure and encrypted way.
  • Functions - Customize your Appwrite server by executing your custom code in a secure, isolated environment. You can trigger your code on any Appwrite system event, manually or using a CRON schedule.
  • Realtime - Listen to real-time events for any of your Appwrite services including users, storage, functions, databases and more.
  • Locale - Track your user's location, and manage your app locale-based data.
  • Avatars - Manage your users' avatars, countries' flags, browser icons, credit card symbols, and generate QR codes.

For the complete API documentation, visit https://appwrite.io/docs. For more tutorials, news and announcements check out our blog and Discord Server.

SDKs

Below is a list of currently supported platforms and languages. If you wish to help us add support to your platform of choice, you can go over to our SDK Generator project and view our contribution guide.

Client

  • ✅   Web (Maintained by the Appwrite Team)
  • ✅   Flutter (Maintained by the Appwrite Team)
  • ✅   Apple - Beta (Maintained by the Appwrite Team)
  • ✅   Android (Maintained by the Appwrite Team)

Server

  • ✅   NodeJS (Maintained by the Appwrite Team)
  • ✅   PHP (Maintained by the Appwrite Team)
  • ✅   Dart - (Maintained by the Appwrite Team)
  • ✅   Deno - Beta (Maintained by the Appwrite Team)
  • ✅   Ruby (Maintained by the Appwrite Team)
  • ✅   Python (Maintained by the Appwrite Team)
  • ✅   Kotlin - Beta (Maintained by the Appwrite Team)
  • ✅   Apple - Beta (Maintained by the Appwrite Team)
  • ✅   .NET - Experimental (Maintained by the Appwrite Team)

Community

Looking for more SDKs? - Help us by contributing a pull request to our SDK Generator!

Architecture

Appwrite Architecture

Appwrite uses a microservices architecture that was designed for easy scaling and delegation of responsibilities. In addition, Appwrite supports multiple APIs (REST, WebSocket, and GraphQL-soon) to allow you to interact with your resources by leveraging your existing knowledge and protocols of choice.

The Appwrite API layer was designed to be extremely fast by leveraging in-memory caching and delegating any heavy-lifting tasks to the Appwrite background workers. The background workers also allow you to precisely control your compute capacity and costs using a message queue to handle the load. You can learn more about our architecture in the contribution guide.

Contributing

All code contributions - including those of people having commit access - must go through a pull request and be approved by a core developer before being merged. This is to ensure a proper review of all the code.

We truly ❤️ pull requests! If you wish to help, you can learn more about how you can contribute to this project in the contribution guide.

Security

For security issues, kindly email us at security@appwrite.io instead of posting a public issue on GitHub.

Follow Us

Join our growing community around the world! See our official Blog. Follow us on Twitter, Facebook Page, Facebook Group, Dev Community or join our live Discord server for more help, ideas, and discussions.


It's going to get cloudy! 🌩 ☂️ The Appwrite Cloud is coming soon! You can learn more about our upcoming hosted solution and signup for free credits at: https://appwrite.io/cloud 


English | 简体中文

Download Details:

Author: Appwrite
Source Code: https://github.com/appwrite/appwrite 
License: BSD-3-Clause license

#serverless #javascript #android #swift #docker #ios #apple 

Appwrite: Secure Backend Server for Web, Mobile & Flutter Developers
Rupert  Beatty

Rupert Beatty

1667602200

Ring Progress View Similar to Activity App on Apple Watch

MKRingProgressView

Ring progress view similar to Activity app on Apple Watch

MKRingProgressView

Features

  • Progress animation
  • Customizable start/end and backdrop ring colors
  • Customizable ring width
  • Customizable progress line end style
  • Customizable shadow under progress line end
  • Progress values above 100% (or 360°) can also be displayed

Installation

CocoaPods

To install MKRingProgressView via CocoaPods, add the following line to your Podfile:

pod 'MKRingProgressView'

Carthage

To install MKRingProgressView via Carthage, add the following line to your Cartfile:

github "maxkonovalov/MKRingProgressView"

Swift Package Manager

Note: Instructions below are for using SwiftPM without the Xcode UI. It's the easiest to go to your Project Settings -> Swift Packages and add MKRingProgressView from there.

To integrate using Apple's Swift package manager, without Xcode integration, add the following as a dependency to your Package.swift:

.package(url: "https://github.com/maxkonovalov/MKRingProgressView.git", .upToNextMajor(from: "2.3.0"))

Usage

See the example Xcode project. It contains 2 targets:

  • ProgressRingExample - a simple example containing a single progress ring with adjustable parameters.
  • ActivityRingsExample - an advanced usage example replicating Activity app by Apple. It also contains additional classes for convenient grouping of 3 ring progress views together.

Interface Builder

MKRingProgressView can be set up in Interface Builder. To use it, set the custom view class to MKRingProgressView. Most of the control's parameters can be customized in Interface Builder.

Code

let ringProgressView = RingProgressView(frame: CGRect(x: 0, y: 100, width: 100, height: 100))
ringProgressView.startColor = .red
ringProgressView.endColor = .magenta
ringProgressView.ringWidth = 25
ringProgressView.progress = 0.0
view.addSubview(ringProgressView)

The progress value can be animated the same way you would normally animate any property using UIView's block-based animations:

UIView.animate(withDuration: 0.5) {
    ringProgressView.progress = 1.0
}

Performance

To achieve better performance the following options are possible:

  • Set gradientImageScale to lower values like 0.5 (defaults to 1.0)
  • Set startColor and endColor to the same value
  • Set shadowOpacity to 0.0
  • Set allowsAntialiasing to false

Requirements

  • iOS 9.0
  • tvOS 9.0

Download Details:

Author: Maxkonovalov
Source Code: https://github.com/maxkonovalov/MKRingProgressView 
License: MIT license

#swift #ios #apple #progress 

Ring Progress View Similar to Activity App on Apple Watch
Rupert  Beatty

Rupert Beatty

1667598300

Tailor: Cross-platform Static analyzer and Linter for Swift

Tailor

Tailor is a cross-platform static analysis and lint tool for source code written in Apple's Swift programming language. It analyzes your code to ensure consistent styling and help avoid bugs.

Tailor. Cross-platform static analyzer and linter for Swift.

Tailor supports Swift 3.0.1 out of the box and helps enforce style guidelines outlined in the The Swift Programming Language, GitHub, Ray Wenderlich, and Coursera style guides. It supports cross-platform usage and can be run on Mac OS X via your shell or integrated with Xcode, as well as on Linux and Windows.

Tailor parses Swift source code using the primary Java target of ANTLR:

ANTLR is a powerful parser generator [ . . . ] widely used in academia and industry to build all sorts of languages, tools, and frameworks.

About the ANTLR Parser Generator

Getting Started

Installation

Requires Java (JRE or JDK) Version 8 or above: Java SE Downloads

Homebrew, Linuxbrew

brew install tailor

Mac OS X (10.10+), Linux

curl -fsSL https://tailor.sh/install.sh | sh

Windows (10+)

iex (new-object net.webclient).downloadstring('https://tailor.sh/install.ps1')

Manually

You may also download Tailor via GitHub Releases, extract the archive, and symlink the tailor/bin/tailor shell script to a location in your $PATH.

Continuous Integration

If your continuous integration server supports Homebrew installation, you may use the following snippet:

before_install:
  - brew update
  - brew install tailor

In other cases, use this snippet:

Replace ${TAILOR_RELEASE_ARCHIVE} with the URL of the release you would like to install, e.g. https://github.com/sleekbyte/tailor/releases/download/v0.1.0/tailor.tar.

before_script:
  - wget ${TAILOR_RELEASE_ARCHIVE} -O /tmp/tailor.tar
  - tar -xvf /tmp/tailor.tar
  - export PATH=$PATH:$PWD/tailor/bin/

Usage

Run Tailor with a list of files and directories to analyze, or via Xcode.

$ tailor [options] [--] [[file|directory] ...]

Help for Tailor is accessible via the [-h|--help] option.

$ tailor -h
Usage: tailor [options] [--] [[file|directory] ...]

Perform static analysis on Swift source files.

Invoking Tailor with at least one file or directory will analyze all Swift files at those paths. If
no paths are provided, Tailor will analyze all Swift files found in '$SRCROOT' (if defined), which
is set by Xcode when run in a Build Phase. Tailor may be set up as an Xcode Build Phase
automatically with the --xcode option.

Options:
 -c,--config=<path/to/.tailor.yml>             specify configuration file
    --debug                                    print ANTLR error messages when parsing error occurs
    --except=<rule1,rule2,...>                 run all rules except the specified ones
 -f,--format=<xcode|json|cc|html>              select an output format
 -h,--help                                     display help
    --invert-color                             invert colorized console output
 -l,--max-line-length=<0-999>                  maximum Line length (in characters)
    --list-files                               display Swift source files to be analyzed
    --max-class-length=<0-999>                 maximum Class length (in lines)
    --max-closure-length=<0-999>               maximum Closure length (in lines)
    --max-file-length=<0-999>                  maximum File length (in lines)
    --max-function-length=<0-999>              maximum Function length (in lines)
    --max-name-length=<0-999>                  maximum Identifier name length (in characters)
    --max-severity=<error|warning (default)>   maximum severity
    --max-struct-length=<0-999>                maximum Struct length (in lines)
    --min-name-length=<1-999>                  minimum Identifier name length (in characters)
    --no-color                                 disable colorized console output
    --only=<rule1,rule2,...>                   run only the specified rules
    --purge=<1-999>                            reduce memory usage by clearing DFA cache after
                                               specified number of files are parsed
    --show-rules                               show description for each rule
 -v,--version                                  display version
    --xcode=<path/to/project.xcodeproj>        add Tailor Build Phase Run Script to Xcode Project

Features

Enabling and Disabling Rules

Rule identifiers and "preferred/not preferred" code samples may be found on the Rules page.

Rules may be individually disabled (blacklist) or enabled (whitelist) via the --except and --only command-line flags.

Except

tailor --except=brace-style,trailing-whitespace main.swift

Only

tailor --only=redundant-parentheses,terminating-semicolon main.swift

Cross-Platform

Tailor may be used on Mac OS X via your shell or integrated with Xcode, as well as on Linux and Windows.

Linux

Tailor on Ubuntu

Windows

Tailor on Windows

Automatic Xcode Integration

Tailor can be integrated with Xcode projects using the --xcode option.

tailor --xcode /path/to/demo.xcodeproj/

This adds the following Build Phase Run Script to your project's default target. Run Script

Tailor's output will be displayed inline within the Xcode Editor Area and as a list in the Log Navigator. Xcode messages

Configure Xcode to Analyze Code Natively (⇧⌘B)

Add a new configuration, say Analyze, to the project

screen shot 2016-11-30 at 12 29 34 am

Modify the active scheme's Analyze phase to use the new build configuration created above

screen shot 2016-11-30 at 12 37 08 am

Tweak the build phase run script to run Tailor only when analyzing the project (⇧⌘B)

if [ "${CONFIGURATION}" = "Analyze" ]; then
    if hash tailor 2>/dev/null; then
        tailor
    else
        echo "warning: Please install Tailor from https://tailor.sh"
    fi
fi

Colorized Output

Tailor uses the following color schemes to format CLI output:

Dark theme (enabled by default) Dark theme

Light theme (enabled via --invert-color option) Light theme

No color theme (enabled via --no-color option) No color

Warnings, Errors, and Failing the Build

--max-severity can be used to control the maximum severity of violation messages. It can be set to error or warning (by default, it is set to warning). Setting it to error allows you to distinguish between lower and higher priority messages. It also fails the build in Xcode, if any errors are reported (similar to how a compiler error fails the build in Xcode). With max-severity set to warning, all violation messages are warnings and the Xcode build will never fail.

This setting also affects Tailor's exit code on the command-line, a failing build will exit 1 whereas having warnings only will exit 0, allowing Tailor to be easily integrated into pre-commit hooks.

Disable Violations within Source Code

Violations on a specific line may be disabled with a trailing single-line comment.

import Foundation; // tailor:disable

Additionally, violations in a given block of code can be disabled by enclosing the block within tailor:off and tailor:on comments.

// tailor:off
import Foundation;
import UIKit;
import CoreData;
// tailor:on

class Demo() {
  // Define public members here
}

Note

  • // tailor:off and // tailor:on comments must be paired

Configuration

The behavior of Tailor can be customized via the .tailor.yml configuration file. It enables you to

  • include/exclude certain files and directories from analysis
  • enable and disable specific analysis rules
  • specify output format
  • specify CLI output color scheme

You can tell Tailor which configuration file to use by specifying its file path via the --config CLI option. By default, Tailor will look for the configuration file in the directory where you will run Tailor from.

The file follows the YAML 1.1 format.

Including/Excluding files

Tailor checks all files found by a recursive search starting from the directories given as command line arguments. However, it only analyzes Swift files that end in .swift. If you would like Tailor to analyze specific files and directories, you will have to add entries for them under include. Files and directories can also be ignored through exclude.

Here is an example that might be used for an iOS project:

include:
    - Source            # Inspect all Swift files under "Source/"
exclude:
    - '**Tests.swift'   # Ignore Swift files that end in "Tests"
    - Source/Carthage   # Ignore Swift files under "Source/Carthage/"
    - Source/Pods       # Ignore Swift files under "Source/Pods/"

Notes

  • Files and directories are specified relative to where tailor is run from
  • Paths to directories or Swift files provided explicitly via CLI will cause the include/exclude rules specified in .tailor.yml to be ignored
  • Exclude is given higher precedence than Include
  • Tailor recognizes the Java Glob syntax

Enabling/Disabling rules

Tailor allows you to individually disable (blacklist) or enable (whitelist) rules via the except and only labels.

Here is an example showcasing how to enable certain rules:

# Tailor will solely check for violations to the following rules
only:
    - upper-camel-case
    - trailing-closure
    - forced-type-cast
    - redundant-parentheses

Here is an example showcasing how to disable certain rules:

# Tailor will check for violations to all rules except for the following ones
except:
    - parenthesis-whitespace
    - lower-camel-case

Notes

  • only is given precedence over except
  • Rules that are explicitly included/excluded via CLI will cause the only/except rules specified in .tailor.yml to be ignored

Specifying output format

Tailor allows you to specify the output format (xcode/json) via the format label.

Here is an example showcasing how to specify the output format:

# The output format will now be in JSON
format: json

Note

  • The output format explicitly specified via CLI will cause the output format defined in .tailor.yml to be ignored

Specifying CLI output color scheme

Tailor allows you to specify the CLI output color schemes via the color label. To disable colored output, set color to disable. To invert the color scheme, set color to invert.

Here is an example showcasing how to specify the CLI output color scheme:

# The CLI output will not be colored
color: disable

Note

  • The CLI output color scheme explicitly specified via CLI will cause the output color scheme defined in .tailor.yml to be ignored

Formatters

Tailor's output format may be customized via the -f/--format option. The Xcode formatter is selected by default.

Xcode Formatter (default)

The default xcode formatter outputs violation messages according to the format expected by Xcode to be displayed inline within the Xcode Editor Area and as a list in the Log Navigator. This format is also as human-friendly as possible on the console.

$ tailor main.swift

********** /main.swift **********
/main.swift:1:    warning: [multiple-imports] Imports should be on separate lines
/main.swift:1:18: warning: [terminating-semicolon] Statements should not terminate with a semicolon
/main.swift:3:05: warning: [constant-naming] Global Constant should be either lowerCamelCase or UpperCamelCase
/main.swift:5:07: warning: [redundant-parentheses] Conditional clause should not be enclosed within parentheses
/main.swift:7:    warning: [terminating-newline] File should terminate with exactly one newline character ('\n')

Analyzed 1 file, skipped 0 files, and detected 5 violations (0 errors, 5 warnings).

JSON Formatter

The json formatter outputs an array of violation messages for each file, and a summary object indicating the parsing results and the violation counts.

$ tailor -f json main.swift
{
  "files": [
    {
      "path": "/main.swift",
      "violations": [
        {
          "severity": "warning",
          "rule": "constant-naming",
          "location": {
            "line": 1,
            "column": 5
          },
          "message": "Global Constant should be either lowerCamelCase or UpperCamelCase"
        }
      ],
      "parsed": true
    }
  ],
  "summary": {
    "violations": 1,
    "warnings": 1,
    "analyzed": 1,
    "errors": 0,
    "skipped": 0
  }
}

HTML Formatter

The html formatter outputs a complete HTML document that should be written to a file.

tailor -f html main.swift > tailor.html

HTML format

Developers

Please review the guidelines for contributing to this repository.

Development Environment

External Tools and Libraries

Development & Runtime

ToolLicense
ANTLR 4.5The BSD License
Apache Commons CLIApache License, Version 2.0
JansiApache License, Version 2.0
XcodeprojMIT
SnakeYAMLApache License, Version 2.0
GsonApache License, Version 2.0
Mustache.javaApache License, Version 2.0

Development Only

ToolLicense
GradleApache License, Version 2.0
Travis CIFree for Open Source Projects
MockitoMIT
JUnitEclipse Public License 1.0
Java HamcrestThe BSD 3-Clause License
FindBugsGNU Lesser General Public License
CheckstyleGNU Lesser General Public License
PMDBSD-style
JaCoCoEclipse Public License v1.0
CoverallsFree for Open Source
BundlerMIT
CodacyFree for Open Source
System RulesCommon Public License 1.0
RonnMIT

Download Details:

Author: Sleekbyte
Source Code: https://github.com/sleekbyte/tailor 
License: MIT license

#swift #apple #linter #static #analyzer 

Tailor: Cross-platform Static analyzer and Linter for Swift