I have user localizable strings for the strings used in storyboard or source files which are fixed. These are defined in files like Localizable.string (Spanish), Localizable.string (German) etc. But I have a requirement where these strings can keep changing. These strings are received as a response to REST API call. My question is how can I use it.
Current code is let text = NSLocalizedString("Some string", comment: "")
Where NSLocalizedString looks for Localizable.string file. How can I make NSLocalizedString look for localized words from my custom dictionary/Json?
Try this
First you need to copy that files in document directory .
Get Localised Label
let localisedString = self.getLocalizatioString(key: "your key", stringFileName: "test.strings") //
Function
func getLocalizatioString(key : String?, stringFileName : String ) -> String {
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = doumentDirectoryPath.appendingPathComponent(stringFileName)
let dict = NSDictionary.init(contentsOfFile: destinationPath)
return (dict?.object(forKey: key!) as? String)!
}
Output
In String file
Related
I request you to give me a solution where the result of NSString and String both are same
downloadedFile = MOM'&^*%s-HC.pdf (In NSString)
let path = pathComponent.appendingPathComponent(downloadedFile as String)
print(path) //OutPut: ttt_gmail_com/MOM'&%5E*%25s-HC-2.pdf
If I test with regular expression result is OK.
let NSStringValue = "MOM'&^*%s-HC.pdf" as NSString
print(NSStringValue) // Output: MOM'&^*%s-HC.pdf
let StringValue = downloadedFile as String
print(StringValue) // Output: MOM'&^*%s-HC.pdf
but while I put that code in appendingPathComponent it changes my result.
You have a file name which has all the special characters here, I tried your case in a sample project trying to load such file in UIDocumentInteractionController and it seems when I have a file name with special character in my document directory and i try to retrieve it, few special characters are URL encoded.
Observe the file name I used here is "MOM'&^*%s-HC.pdf" and saved it in the doc directory but when I retrieve it from the document directory using the following code few characters are URL encoded as I am fetching the path as URL.
So this means that your original file name
MOM'&^*%s-HC.pdf
is now alterated and replaced by percentage escape sequence strings,
MOM'&%5E*%25s-HC.pdf
observe the below code which I used
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent(fileName)
To resolve this all i did was removed the percentage escape sequence when I am creating the URL and it worked I was able to view the PDF in the UIDocumentInteractionController
fileName.removingPercentEncoding!
Hope it helps.
I am new to swift/ios programming. I created a small app with settings but I can't seem to read value.
UserDefaults.standard.register(defaults: [String : Any]())
let settings = UserDefaults.standard;
let k = Bundle.main.infoDictionary!;
let b = settings.dictionaryRepresentation()
let val3 = Bundle.main.object(forInfoDictionaryKey: "digit_preference")
let value2 = settings.string(forKey: "digit_preference")
I can't find my settings "digit_preference" in Bundle.main.InfoDictionary or UserDefaults.standard.dictionaryRepresentation()
I can view my application settings properly in my phone. (Digits set to 2)
You need to cast the file data to a dictionary at first since the root structure is a Dictionary. This of course, if the file you're showing us is actually a .plist file; the following is how to access a .plist file, but the first step is also common for almost every other file type in your app bundle. What differs (say from .txt, .json, etc) is the second step depending on what you want to do..
Like so:
guard let idForResource = Bundle.main.path(forResource: "pListFilename", ofType: ".plist"),
let dict = NSDictionary(contentsOfFile: idForResource) as? [String: Any] else {
return }
Then you access the variable through dict like you would from any other dictionary.
I have a to compare a string with the string from the db.
var variableFromDB = "test"
if "test" == variableFromDB{
print("Success")
}
It works fine in the English Language. I don't know how to compare it in the arabic language. Is the need to check in arabic language also. Please tell me know to check it.
In general it's a bad idea for your code to make decisions based on display strings. That goes double for display strings.
If your primary audience is Arabic-speaking, you could make your development language Arabic and then localize for other languages as needed.
In any case, I would suggest using a set of fixed strings as keys, and then calling NSLocalizedString(_:tableName:bundle:value:comment:) or one of it's variants to fetch a display string. Example:
Put this code somewhere central so the keys can be shared:
let screen1Prompt = "screen1Prompt"
Then when you need a localized string for display:
let prompt = NSLocalizedString(screen1Prompt)
Where the actual prompt string might be "Please select the date for your payment." in English, Arabic, etc.
Then if you need to match something in your database, look it up using the unlocalized key, not the localized display string.
That way if you later change the display string, your code still works.
var language: String
UserDefaults.standard.set("AE", forKey: "Apple") // manually set language
UserDefaults.standard.synchronize()
self.language = UserDefaults.standard.object(forKey: "Apple")as! String
// self.language = Locale.current.languageCode // your device language
extension String {
func stringlocalized(lang:String) ->String {
let path = Bundle.main.path(forResource: lang, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}}
// Check You Localization string from your current language
let str = “ test”.localized(lang: self.language! )
if str ==variableFromDB
{ // Your logic here
}
I'm using the following code to save a 2D String array to a plist:
func saveFavourites(favouriteStops: [[String]]) {
let directories = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
if let library = directories.first {
if let libraryUrl = URL(string: library) {
let favouritesUrl = libraryUrl.appendingPathComponent("favourites.plist")
// Write favourites to disk
let favsArray = favouriteStops as NSArray
print(favsArray)
favsArray.write(toFile: favouritesUrl.path, atomically: true)
}
}
}
The above snippet properly creates the .plist file (confirmed by looking at the simulator's filesystem in ~/Library/Developer/CoreServices). However, when I try reading it back to a NSArray with the following snippet, it results in nil:
let directories = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
if let library = directories.first {
if let libraryUrl = URL(string: library) {
let favouritesUrl = libraryUrl.appendingPathComponent("favourites.plist")
// favsToLoad is nil
let favsToLoad = NSArray(contentsOf: favouritesUrl)
// Do stuff with favsToLoad, if it would load properly
}
}
You're doing two very basic things wrong.
First, never make a URL from a file path by saying URL(string); this is a file on disk, so you must use URL.fileURL.
Second, don't start with a file path at all! Obtain the directory as a URL right from the start.
(Also, though I do not know whether this is the source of the issue, do not read and write directly in the Library directory. Use the Documents directory, the Application Support directory, or similar.)
So, for example, I would write:
let fm = FileManager.default
let docsurl = try fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let favouritesurl = docsurl.appendingPathComponent("favourites.plist")
I see your problem. You misspelled "favorites". :)
But seriously...
Plists can only contain a very small set of "property list objects": (dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values).
If your array's "object graph" (the objects the array contains and any container objects inside the array recursively contain) contain anything other than the above types, the save will fail.
I don't honestly know what gets saved when it fails. Have you tried opening the plist file in a text editor and looking at it?
My guess is that something other than a string has snuck into your array, it's not one of the above types, and THAT'S why it's failing.
My question, after I open PDF file with my app('register the document types that your application can open with iOS') I getting the files as NSCFString format)
Example:
let filemgr: NSFileManager = NSFileManager.defaultManager();
var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true);
let documentsDirectory: String = paths[0] as! String
let inboxPath: String = documentsDirectory.stringByAppendingPathComponent("Inbox");
do
{
let dirFiles: [AnyObject] = try filemgr.contentsOfDirectoryAtPath(inboxPath);
}
catch{}
My question is from this step I want to gather all this documents to one document and also open it with UIWebView. from what i read i need to find a way to convert it to nsdata or even draw it as PDF, but i really dont know how to handle it.
Thank you for help