Last active
August 31, 2018 06:08
-
-
Save doraTeX/990a0be19db0b6c8171f to your computer and use it in GitHub Desktop.
Swiftでシステム内蔵辞書を検索する方法 ref: http://qiita.com/doraTeX/items/9b290f4e39f1e100558b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let wisdomPath: String | |
if #available(OSX 10.13, *) { | |
wisdomPath = "/System/Library/Assets/com_apple_MobileAsset_DictionaryServices_dictionaryOSX/65c5f4f22827dba6b0a6bc85755863317890953b.asset/AssetData/Sanseido The WISDOM English-Japanese Japanese-English Dictionary.dictionary" | |
} else { | |
wisdomPath = "/Library/Dictionaries/Sanseido The WISDOM English-Japanese Japanese-English Dictionary.dictionary" | |
} | |
// "swift" の意味を取得 | |
let word = "swift" | |
if let content = DictionaryServiceManager().lookUp(word, inDictionary: wisdomPath) { | |
print(content) | |
} else { | |
print("NOT FOUND") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class DictionaryServiceManager { | |
private let AppleGlobalDomainName = "Apple Global Domain" | |
private let DictionaryServicesKey = "com.apple.DictionaryServices" | |
private let ActiveDictionariesKey = "DCSActiveDictionaries" | |
private var globalDomain: [String : Any]? { | |
return UserDefaults.standard.persistentDomain(forName: AppleGlobalDomainName) | |
} | |
private var dictionaryPreferences: [String : AnyObject]? { | |
return self.globalDomain?[DictionaryServicesKey] as! [String : AnyObject]? | |
} | |
private var currentDictionaryList: [String]? { | |
return self.dictionaryPreferences?[ActiveDictionariesKey] as! [String]? | |
} | |
private func setUserDictPreferences(_ activeDictionaries: [String]) { | |
if var currentPref = self.dictionaryPreferences { | |
currentPref[ActiveDictionariesKey] = activeDictionaries as AnyObject | |
if var gDomain = self.globalDomain { | |
gDomain[DictionaryServicesKey] = currentPref | |
UserDefaults.standard.setPersistentDomain(gDomain, forName: AppleGlobalDomainName) | |
} | |
} | |
} | |
func lookUp(_ word : String, inDictionary dictionaryPath : String) -> String? { | |
let currentPrefs = self.currentDictionaryList | |
self.setUserDictPreferences([dictionaryPath]) | |
let range = CFRangeMake(0, word.utf16.count) | |
let result = DCSCopyTextDefinition(nil, word as CFString, range)?.takeRetainedValue() as String? | |
if let currentPrefs = currentPrefs { | |
self.setUserDictPreferences(currentPrefs) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment