reading localizable strings giving output as chinese characters - swift

I am trying to read content of Localizable.strings file in my project as I want to create enum of strings file.
if let filepath = Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: "en.lproj") {
do {
let contents = try String(contentsOfFile: filepath, encoding: .utf16)
print("foundd")
print(contents)
} catch {
print("error==\(error)")
}
}
I get response as
foundd
扰汩獴〰툁ȃђ敮卥渲坅湧汩獨塅湧汩獨㈈ഐᐜā%
If I change encoding to .utf8, I get error as beloow.
error==Error Domain=NSCocoaErrorDomain Code=261 "The file “Localizable.strings” couldn’t be opened using text encoding Unicode (UTF-8)." UserInfo={NSFilePath=/Users/mac/Library/Developer/CoreSimulator/Devices/383D23B1-F6F7-4961-B94B-040F357139D2/data/Containers/Bundle/Application/683BB485-5851-4A12-B391-901B021B9BDA/Excel.app/en.lproj/Localizable.strings, NSStringEncoding=4}
In localization file, I have below
/*
File.strings
Excel
Created by mac on 16/02/2023.
*/
"en"="English";
"en2"="English2";
Any idea why I am getting like this?

Your file is a binary Property List file because there is recognizable bplist file signature:
('扰汩獴〰툁ȃђ敮卥渲坅湧汩獨塅湧汩獨㈈ഐᐜā%'
.encode('utf-16-be')
.decode('latin1'))
'bplist00Ò\x01\x02\x03\x04RenSen2WEnglishXEnglish2\x08\r\x10\x14\x1c\x01\x01\x00%'
You face a mojibake case (above example given in Python for its universal intelligibility).
In any case, converting a binary content to string does not give any sense. You need to know and follow its structure…

Related

How can I read text from a file inside the bundle in Swift?

I downloaded this code from hackingwithswift.com, but it always fails at loading the file where it says "contents could not be loaded". Does anyone have an idea what might cause this problem? Here's my code:
if let filepath = Bundle.main.path(forResource: "german", ofType: "dic") {
do {
contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
print("contents could not be loaded \(error)")
}
} else {
print("file not found")
}
text = contents.components(separatedBy: "\n")
It then outputs the error:
domain=NSCocoaErrorDomain Code=264 "The file “german.dic” couldn’t be opened because the text encoding of its contents can’t be determined." UserInfo={NSFilePath=/private/var/containers/Bundle/Application/0F0F9BBA-3964-41FA-B5EE-114C64F44189/SchoolAid Pro.app/german.dic}
Problem solved: It seems like Swift just doesn't like the .dic format. After copying the contents of the .dic file and pasting them into a .txt file, everything worked out just fine.

How do I read a file from the filesystem in a Swift command line app?

I'm just starting learning Swift and to teach myself I'm making a simple command line app. It will eventually connect to an online data source but initially I want to load data from a file. I've seen various guides on reading the contents of a file in Swift but none of them seem to work for me. Here is my app so far:
import Foundation
// Set the file path
let path = "/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩"
do {
// Get the contents
let contents = try String(contentsOfFile: path, encoding: .utf8)
print(contents)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
Running it outputs:
Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=260 "The file “data.json⁩” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩, NSUnderlyingError=0x100e19a50 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
However on the terminal:
$ ls -l /Users/username/workspace/Swift/sis/sis/data.json
-rwxrwxrwx# 1 username staff 165563 16 Jan 17:14 /Users/username/workspace/Swift/sis/sis/data.json
(yeah I relaxed the permissions somewhat just in case that was the problem)
The only slightly anomalous thing I noticed (aside from the inaccurate assertion that the file doesn't exist) was that when I copy and past the path from the XCode output into iTerm2 it puts spaces between each path component:
(pasted as an image as copying it and pasting it back into this form seems to hide the spaces - this is probably irrelevant anyway)
Any help figuring this out would be really appreciated!
I copied your code, downloaded a sample json file to my desktop, and renamed it to example_ 1.json (I included a space inside the file name).
import Foundation
// Set the file path
let path = "/Users⁩/username/Desktop/example_ 1.json⁩"
do {
// Get the contents
let contents = try String(contentsOfFile: path, encoding: .utf8)
print(contents)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
It successfully printed the file. It also worked when I defined contents as a NSString.
let contents = try NSString(contentsOfFile: path,
encoding: String.Encoding.ascii.rawValue)
I am using Swift 4.2.1
you can not read if your command line app is sandboxed. what you can do is to add this file in your project and set path of file by looking the full path of file in identity inspector.
let path = "/Users/snx/EmailReplacer/EmailReplacer/shared_domains_staging.json"
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject> {
print(jsonResult)
}
} catch {
print(error)
}

I am saving a text file from swift playground. But not able to locate the file in my Mac

I followed the code exactly in the link:
Read and write data from text file
(Swift 2.2 solution)
I am writing the same code in playground file I created.
let file = "file.txt"
let text = "some text"
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}
There are no error messages. The code runs fine.
But I am not able to find the file - file.txt using my Mac finder.
How do I locate the file in the system?
In the Playground editor, on the right side it should give you a text representation of the URL. You can right click and choose "Open URL". This will open the text file and you can examine the title bar of TextEdit (right-click title) to find the exact path and move to point therein.

Converting Docx Files To Text In Swift

I have a .docx file in my temporary storage:
let location: NSURL = NSURL.fileURLWithPath(NSTemporaryDirectory())
let file_Name = location.URLByAppendingPathComponent("5 November 2016.docx")
What I now want to do is extract the text inside this document. But I cannot seem to find any converters or methods of doing this.
I have tried this:
let file_Content = try? NSString(contentsOfFile: String(file_Name), encoding: NSUTF8StringEncoding)
print(file_Content)
However it prints nil.
So how do I read the text in a docx file?
Swift 4, Xcode 9.1, OSX targets from 10.10 to 10.13
I have found that the following code extracts text handily from a Word .doc file, which then easily goes into a string. (The attributed string contains formatting information that might be parsed to good effect.) The main info that I wanted to convey was the bit about using .docFormat to specify the document type.
let openPanel = NSOpenPanel()
var fileString = String("")
var fileData = NSData()
let fileURL = openPanel.url
do {
fileData = try NSData(contentsOf: fileURL!)
if let tryForString = try? NSAttributedString(data: fileData as Data, options: [
.documentType: NSAttributedString.DocumentType.docFormat,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil) {
fileString = tryForString.string
} else {
fileString = "Data conversion error."
}
fileString = fileString.trimmingCharacters(in: .whitespacesAndNewlines)
} catch {
print("Word Document File Not Found")
}
Your initial issue is with how you get the string from the URL. String(File_Name) is not the correct way to convert a file URL into a file path. The proper way is to use the path function.
let location = NSURL.fileURLWithPath(NSTemporaryDirectory())
let fileURL = location.URLByAppendingPathComponent("My File.docx")
let fileContent = try? NSString(contentsOfFile: fileURL.path, encoding: NSUTF8StringEncoding)
Note the many changes. Use proper naming conventions. Name variables more clearly.
Now here's the thing. This still won't work because a docx file is a zipped up collection of XML and other files. You can't load a docx file into an NSString. You would need to use NSData to load the zip contents. Then you would need to unzip it. Then you would need to go through all of the files and find the desired text. It's far from trivial and it is far beyond the scope of a single stack overflow post.

SWIFT: Reading file: NSData successful, String fails. Why?

I'm trying to read large data from file. It is a text file. The following line is successful, data is read into memory:
if let data = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error)
This line return an error:
if let data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: &error)
But why? File is there, only Function is different. And I like to use second one, because I want to split all rows into separate strings in an array:
var array = data.componentsSeparatedByString("\n")
Any hint what to do?
Additional information: There are german umlauts, so code is larger than 127. But the file was saved as UTF-8. How could I load/use non ascii text?
I tried out every option and found the solution I didn't expect:
NSMacOSRomanStringEncoding
This setting accepts also german umlauts!