Skip to content

Commit

Permalink
Merge pull request #65 from swipe-org/use_system_lang_if_exists
Browse files Browse the repository at this point in the history
Open a swipe file in a preferred language specified by the system
  • Loading branch information
snakajima committed Dec 29, 2016
2 parents 6c6ea54 + f170ffe commit c6318a4
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions core/SwipeViewController.swift
Expand Up @@ -91,8 +91,7 @@ class SwipeViewController: UIViewController, UIScrollViewDelegate, SwipeDocument
self.book = SwipeBook(bookInfo: document, url: url, delegate: self)

if let languages = self.book.languages(),
let language = languages.first,
let langId = language["id"] as? String {
let langId = preferredLangId(in: languages) {
self.book.langId = langId
}

Expand All @@ -118,6 +117,29 @@ class SwipeViewController: UIViewController, UIScrollViewDelegate, SwipeDocument
callback(prefetcher.progress, nil)
}
}

private func preferredLangId(in languages: [[String : Any]]) -> String? {
// 1st, find a lang id matching system language.
// A lang id can be in "en-US", "en", "zh-Hans-CN" or "zh-Hans" formats (with/without a country code).
// "en-US" or "zh-Hans-CN" formats with a country code have higher priority to match than "en" or "zh-Hans" without a country code.
if let systemLanguage = NSLocale.preferredLanguages.first?.components(separatedBy: "-") {
for rangeEnd in systemLanguage.indices.reversed() {
let langId = systemLanguage[0...rangeEnd].joined(separator: "-")
if languages.contains(where: { $0["id"] as? String == langId }) {
return langId
}
}
}
// 2nd, use the default lang id ("*") if no lang id matches, and the default id exists.
if languages.contains(where: { $0["id"] as? String == "*" }) {
return "*"
}
// At last, use the first lang id in the language list if still no lang id is specified.
if let langId = languages.first?["id"] as? String {
return langId
}
return nil
}

// <SwipeDocumentViewer> method
func setDelegate(_ delegate:SwipeDocumentViewerDelegate) {
Expand Down

0 comments on commit c6318a4

Please sign in to comment.