下記ページなどを参考にアプリとToday Extensionの間でRealmデータの共有をしたいのですが、
https://qiita.com/oidy/items/3bcb26d67a1c4c9d90c7

下記あたりのコードの書き方が分からなくて色々と試しているのですがアプリが落ちたりしています。

var config = Realm.Configuration()
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.example.MyApp")!
config.fileURL = url.appendingPathComponent("db.realm")

アプリ側のコードです。

// AppDelegate.swift
func setupRealm() {
    var fileNum = 0
    var config = Realm.Configuration.defaultConfiguration

    var realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u0.realm")

    let fileMng = FileManager.default

    if !fileMng.fileExists(atPath: realmFileURL.path) {
        realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u1.realm")
        fileNum = 1
    }

    config.fileURL = realmFileURL
    Realm.Configuration.defaultConfiguration = config

    compaction(fileNum: fileNum)
}

func compaction(fileNum: Int) {
    let config = Realm.Configuration.defaultConfiguration

    let realmFileURL = config.fileURL!

    var copyFileURL = realmFileURL.deletingLastPathComponent().appendingPathComponent("u1.realm")
    if fileNum == 1 {
        copyFileURL = realmFileURL.deletingLastPathComponent().appendingPathComponent("u0.realm")
    }

    let fileManager = FileManager()
    if fileManager.fileExists(atPath: realmFileURL.path) {
        autoreleasepool {
            do {
                let realm = try Realm(configuration: config)
                try realm.writeCopy(toFile: (copyFileURL as NSURL) as URL)
            } catch {
                let _ = try? fileManager.removeItem(at: realmFileURL)
            }
        }

        let _ = try? fileManager.removeItem(at: realmFileURL)
        let _ = try? fileManager.moveItem(at: copyFileURL, to: realmFileURL)
    }
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {        
    setupRealm()

    return true
}

Today Extension側のコードです。

// TodayViewController.swift
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {        
    var config = Realm.Configuration.defaultConfiguration

    var realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u0.realm")

    let fileMng = FileManager.default

    if !fileMng.fileExists(atPath: realmFileURL.path) {
        realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u1.realm")
    }

    config.fileURL = realmFileURL
    Realm.Configuration.defaultConfiguration = config

    completionHandler(NCUpdateResult.newData)
}

環境はXcode 9.1、Swift 4です。
どうぞ、よろしくお願いいたします。