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

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.

Related

reading localizable strings giving output as chinese characters

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…

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)
}

Xcode Swift 3.0 macOS (Sierra) app unable to create file, no permission

I'm fairly new to Xcode and Swift. I'm trying to create a file called "file.txt" in my Documents directory and getting the error "You don’t have permission to save the file."
Ultimately, I DO NOT want to use the default Documents directory as I'm using FIFinderSyncController to watch everything ("/").
let targetFile = (FIFinderSyncController.default().targetedURL()?.path)! + "/file.txt"
NSLog("%#", targetFile as NSString)
let fileManager = FileManager.default
if fileManager.fileExists( atPath: (targetFile) ) == false {
do {
let targetString = (FIFinderSyncController.default().targetedURL()?.path)! + "/Untitled.txt"
NSLog("%#", targetString as NSString)
let fileManager = FileManager.default
if fileManager.fileExists( atPath: targetString ) == false {
let content = "" // Just creating empty file.
//writing
try content.write(toFile: targetString, atomically: false, encoding: String.Encoding.utf8)
//reading
let readingText = try NSString(contentsOfFile: targetString, encoding: String.Encoding.utf8.rawValue)
NSLog("%#", readingText as NSString)
}
}
catch {
print(error.localizedDescription)
}
}
Log shows:
2017-04-06 13:35:46.450077-0700 Open New Text File[5177:1035580] /Users/david/Documents/file.txt
2017-04-06 13:35:46.450257-0700 Open New Text File[5177:1035580] /Users/david/Documents/file.txt
You don’t have permission to save the file “file.txt” in the folder “Documents”.
I found the answer here so I thought I would help out. The issue is the limitations of sandbox. If you add
com.apple.security.temporary-exception.files.home-relative-path.read-write
To the entitlements file for the target as an Array with strings for the parent folders you want to watch. In my case I just added "/" to watch everything. Here's mine:
<key>com.apple.security.temporary-exception.files.home-relative-path.read-write</key>
<array>
<string>/</string>
</array>
This will allow you to access everything relative to the folder mentioned.
One warning: it seems (not thoroughly tested) that if there are other FIFinderSyncController's set up (in other apps), they can effect each other.
What worked for me in a similar case was to select Read/Write in "User Selected Files" in the Capabilities of the Sandbox.
I had the same issue. I solved it by setting the "App Sandbox" key to "No" in the "Entitlements File".
Hope this will help.

Copy TPK file from AppGroup Container to Documents

I have a file that exists within the AppGroup Shared Container and I was wondering if it was possible to copy the file from the Shared Container into the application bundle.
I am getting the file path as follows :
let filePath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.sharedBasemap")!.URLByAppendingPathComponent("localLayer.tpk")!.path
The reason I am trying to do this is it seems that the ArcGIS SDK will not recognize the TPK file from within the App Group so I am wondering if it will recognize it if I copy it into the app bundle.
EDIT: Based on Leo's comment it appears that you can not copy to the bundle, so I am trying to copy to the App Support folder.Here is my code now, I see the "file exists" message but then it is displaying the Oops message indicating it can not move the file :
let filePath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.sharedBasemap")!.URLByAppendingPathComponent("localLayer.tpk")!.path!
let appSupportFolder = String(NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0]) + "localLayer.tpk"
let fileManager = NSFileManager.defaultManager()
if NSFileManager.defaultManager().fileExistsAtPath(filePath){
print("File exists at \(filePath)")
do {
try fileManager.copyItemAtPath(filePath, toPath: appSupportFolder)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
} else {
print("File does not exist")
}
EDIT 2: I have modified the code again to just move the TPK file into the documents directory.I believe that piece is working but I receive an error message when trying to load the TPK file into ArcGIS.At this point in time, I am thinking that the issue is related to the ArcGIS SDK and that it does not support loading a TPK file from anywhere except the application bundle.
let destPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let fullDestPath = NSURL(fileURLWithPath: destPath).URLByAppendingPathComponent("localLayer.tpk")
let fullDestPathString = fullDestPath!.path!
im pretty sure the appSupportFolder doesn't exist by default -- nobody creates it unless needed -- try to verify that first and create it if needed
pseudocode if(!fileExists(supportFolder)) { createDirectory(supportFolder) }