diff --git a/core/SwipeViewController.swift b/core/SwipeViewController.swift index d509c31..399b326 100755 --- a/core/SwipeViewController.swift +++ b/core/SwipeViewController.swift @@ -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 } @@ -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 + } // method func setDelegate(_ delegate:SwipeDocumentViewerDelegate) {