applicationDidFinishLaunching未在Console App上调用

时间:2017-06-23 07:05:46

标签: macos swift3 nsnotificationcenter

我正在尝试编写一个简单的命令行应用程序,可以显示通知的一些信息。但是,代表没有被调用,通知也没有,我不确定这里缺少什么。

从我的输出来看,我认为整个问题源于AppDelegate未被实例化。但是我在显示调用showNotification之前创建了一个。

我在这里缺少什么?

的src / main.swift

import Foundation
import AppKit

var sema = DispatchSemaphore( value: 0 )

let server: String = "http://jsonip.com"
let port: String = "80"
let path: String = "/"
let todoEndpoint: String = server + ":" + port + path

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: todoEndpoint)!

let task = session.dataTask(with: url, completionHandler: {
    (data, response, error) in

    if error != nil {

        print(error!.localizedDescription)

    } else {

        do {

            if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
            {

                print(json)
                let ad = AppDelegate()
                ad.showNotification(title: "Title", subtitle: "SubTitle", informativeText: String(describing: json))
                sema.signal()

            }

        } catch {

            print("error in JSONSerialization")

        }

    }

})

print("Resume Task")
task.resume()

print("Wait for Semaphore")
sema.wait()

的src / AppDelegate.swift

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

    func applicationDidFinishLaunching(aNotification: Notification) {
        NSUserNotificationCenter.default.delegate = self
        print("Delegate Self")
    }

    // NSUserNotificationCenterDelegate implementation
    private func userNotificationCenter(center: NSUserNotificationCenter!, didDeliverNotification notification: NSUserNotification!) {
        //implementation
    }

    private func userNotificationCenter(center: NSUserNotificationCenter!, didActivateNotification notification: NSUserNotification!) {
        //implementation
    }

    private func userNotificationCenter(center: NSUserNotificationCenter!, shouldPresentNotification notification: NSUserNotification!) -> Bool {
        //implementation
        return true
    }

    func showNotification(title: String, subtitle: String, informativeText: String) -> Void {
        let notification: NSUserNotification = NSUserNotification()
        print("Show Notification")
        notification.title = title
        notification.subtitle = subtitle
        notification.informativeText = informativeText
        //notification.contentImage = contentImage
        notification.soundName = NSUserNotificationDefaultSoundName
        NSUserNotificationCenter.default.deliver(notification)
        print(notification.isPresented)

    }
}

输出

Resume Task
Wait for Semaphore
["about": /about, "reject-fascism":
Impeach Trump!, "ip": 110.50.73.141, "Pro!": http://getjsonip.com]
Show Notification
false
Program ended with exit code: 0

0 个答案:

没有答案
相关问题