Friday, 22 July 2016

To covert all english numerics to arabic numerics inside a text , iOS Swift 2.2

// To covert all English numerics to arabic numerics iOS Swift 2.2

public extension String
{

 private static let numberFormatter: NSNumberFormatter = {
        let numberFormatter = NSNumberFormatter()
        return numberFormatter
    }()


public var localizedTextForNumber: String {
        var text = self ?? ""
        var numArray: [String] = []
        var locArray: [NSNumber] = []
        let scanner: NSScanner = NSScanner(string:text)
        let numbers: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
        while scanner.atEnd == false {
            var buffer: NSString?
            if scanner.scanCharactersFromSet(numbers, intoString: &buffer) {
                numArray.append((buffer as? String) ?? "")
                locArray.append(scanner.scanLocation)
            }
            else {
                scanner.scanLocation = (scanner.scanLocation + 1)
            }
        }
        for (index, element) in numArray.enumerate() {
            let len = String(numArray[index]).characters.count
            let loc : Int = Int(locArray[index] ) - len
            if( (loc + len) <= text.length) {
            text.replaceRange(text.startIndex.advancedBy(loc)..<text.startIndex.advancedBy(loc + len), with: element.localizedString)
            }
        }
        if(text.length != 0){
            return text
        }
        return self

    }

public var localizedString: String {
        
        // return arabic zero if string's each element is zero
        let numberStr = self
        let language = Preferences.sharedInstance.appLanguage()
        if(language == "ar") {
            let arrayfirst = numberStr.characters.filter{$0 == "0"}
            if numberStr.characters.count ==  arrayfirst.count {
                let array = numberStr.characters.map { (value) -> String in
                    if value == "0" {
                        return "٠" // Symbol for arabic zero
                    }
                    return ""
                }
                return array.joinWithSeparator("")
            }
        }
        
        let country = Preferences.sharedInstance.appCountry()
        var locale = Preferences.sharedInstance.appLocale()
        if country == "ae" && language == "ar" {
            locale = NSLocale(localeIdentifier: "ar_SA") ?? NSLocale.currentLocale()
        }
        
        String.numberFormatter.locale = locale
        if let str = String.numberFormatter.stringFromNumber(NSNumber(double: self.doubleValue)) 
        {
            return str
        }
        return self
    }

 }

//input - "Hi I have 99 balls".localizedTextForNumber

//outPut - Hi I have ٩٩ balls

// For only numbers to convert
// input - "99".localizedString
// output - ٩٩