Sending files via AirDrop through CLI

I use Airdrop a lot, given how unreliable iCloud Sync is. A classical use case is sending PDF plane tickets that don't offer Apple Wallet integration to my iPhone.

It's fairly cumbersome to quickly send files, so I've both a CLI and an Alfred workflow using Hammerspoon, my Mac Automation framework of choice. I've added this to my alfred-kitty tools, a collection of scripts to make Alfred and Kitty work well together, which is likely the most easy way for you to use this

For using this as a CLI

Put this into your  ~/.hammerspoon/init.lua


local hex_to_char = function(x)
  return string.char(tonumber(x, 16))
end

local unescape = function(url)
  return url:gsub("%%(%x%x)", hex_to_char)
end


hs.urlevent.bind("airdrop", function(eventName, params)
    local file = unescape(params["f"])
    print(file)
    local url = hs.sharing.fileURL(file)
    local ad = hs.sharing.builtinSharingServices.sendViaAirDrop
    local s = hs.sharing.newShare(ad)
    s:shareItems({url})
end)



The first two functions are for URL Encoding

Create a script, and make it executable:

touch ./airdrop && chmod +x ./airdrop && mv ./airdrop /usr/bin/local/
#! /usr/bin/bash

rawurlencode() {
  local string="${1}"
  local strlen=${#string}
  local encoded=""
  local pos c o

  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  REPLY="${encoded}" 
}

rawurlencode "$@"

/usr/bin/open -g "hammerspoon://airdrop?f=${REPLY}"

If these are new commands for you: touch creates a file, chmod makes it executable, we then add a command that will forward the script's arguments ( $@ ) to hammerspoon via Custom URLs , and then move it to a location that is likely accessible through your $PATH variable. The rawurlencode just URL encodes the passed command line args so you can pass filenames with non-ascii characters.

You need to reload your Hammerspoon config, and from now on you can do

airdrop ./myfile.txt

For using this as an Alfred file action

Allows you to do this (note: the other file actions, like opening in vim or visidata are all part of my alfred-kitty: workflow)

Most easily, just install my kitty extension. If you want to do it yourself:

Create a new workflow using

create new file action by right clicking on the canvas

create a new computation note (actions -> external scripts) and add the path to your airdrop script

That's it, now you should see it as a file action in Alfred.

Show Comments