7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで入力された文字をカタカナに変換して取得する

Last updated at Posted at 2017-03-11

これはなに?

String の Extension でやってみる

import Foundation

extension String {
    
    public func hiraganaToKatakana() -> String {
        
        if #available(iOS 9.0, *) {
            guard let prefLang = Locale.preferredLanguages.first else { return self }
            if prefLang.hasPrefix("ja") {
                // 言語設定が日本語の時のみ
                if let kana = self.applyingTransform(.hiraganaToKatakana, reverse: false) {
                    return kana
                } else {
                    return self
                }
            } else {
                return self
            }
        } else {
            return self
        }
    }
    
    public func katakanaFurigana() -> String {
        
        guard let prefLang = Locale.preferredLanguages.first else { return "" }
        if prefLang.hasPrefix("ja") {
            
            // 言語設定が日本語の時のみ
            let inputText: NSString = self as NSString
            let furigana = NSMutableString()
            
            let range: CFRange = CFRangeMake(0, inputText.length)
            let locale: CFLocale = CFLocaleCopyCurrent()
            let tokenizer: CFStringTokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, inputText as CFString, range, kCFStringTokenizerUnitWordBoundary, locale)
            
            var tokenType: CFStringTokenizerTokenType = CFStringTokenizerGoToTokenAtIndex(tokenizer, 0)
            
            while tokenType != CFStringTokenizerTokenType(rawValue: 0) {
                let latin: CFTypeRef = CFStringTokenizerCopyCurrentTokenAttribute(tokenizer, kCFStringTokenizerAttributeLatinTranscription)
                
                guard let romanAlphabet: NSMutableString = latin as? NSMutableString else { continue }
                CFStringTransform(romanAlphabet as CFMutableString, nil, kCFStringTransformLatinHiragana, false)
                
                furigana.append(romanAlphabet as String)
                tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
            }
            
            let outputText: String = furigana as String
            return outputText.hiraganaToKatakana()        

        } else {
            return ""
        }
    }
}

補足

  • 言語設定が日本語の時のみにしておかないと、英語などになるとクラッシュします
  • iOSの連絡帳も言語設定が英語になると、ふりがなは表示されませんでした

参考資料

7
9
0

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
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?