LoginSignup
11
7

More than 5 years have passed since last update.

MacアプリでiOSアプリみたいにURL Scheme起動すんのってどうやんの?を調べてみた

Posted at

意外と説明している記事がなかったのであげてみる。
info.plistにURL Schemeを設定するのはiOSと全く一緒だった。

iOSだとAppDelegateにopenUrlみたいなハンドラがあるんだけど、Macの場合はAPIが違った。

AppDelegate.swift
  func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:replyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
    var appUrl = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent("", isDirectory: true)
    var a:Boolean = 0 // true
    var status = LSRegisterURL(appUrl as CFURL!, a)
  }

  func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    println("yay");
  }

これだけやれば、
ターミナルから
$ open [URLスキーマ]://
とか、
WEBページの
<a href="[URLスキーマ]://">Open your app</a>
とかで起動できた。
アプリが起動してなくても、インストール済みであればダイジョブだった。

サンプルを以下に置いてますのでご参考まで。
https://github.com/toshi0383/MacAppURLSchemeSample

11
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7