How do I find out the exact error in catch block - swift

I have this swift beauty:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch {
print("shit happens")
}
Of course I am getting the error message because there's an error. How can I find out what the error is? (yes, the file exists)
Thanks

Make catch create an "error" constant for you, compatible with NSError:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch let error as NSError {
print(error.localizedDescription)
}
You can also just use catch which automatically creates an "error" constant:
do {
let path = "/Users/ADMIN/Desktop/hello.txt"
let str = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(str)
} catch {
print(error)
}

Related

Saving text input to device

I am trying to make a view where I can input text in a UITextField and save it to the device. I have searched different places and so far I got this below but I cannot get past this error. Can someone please help?
Use of unresolved identifier 'yyyytoss'
import UIKit
class WritestoryVC: UIViewController, UITextViewDelegate {
#IBOutlet weak var myStory : UITextView!
#IBAction func saveImageToDocumentDirectory(_ chosenImage: UITextField) -> Void {
let directoryPath = NSHomeDirectory().appending("/Documents/")
if !FileManager.default.fileExists(atPath: directoryPath) {
do {
try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath), withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
let filename = NSDate().string(withDateFormatter: yyyytoss).appending(".rtf")
let filepath = directoryPath.appending(filename)
let url = NSURL.fileURL(withPath: filepath)
do {
try UITextField(chosenImage, 1.0)?.write(to: url, options: .atomic)
return String.init("/Documents/\(filename)")
} catch {
print(error)
print("file cant not be save at path \(filepath), with error : \(error)");
return filepath
}
}
}
See if it helps:-
Also where you define yyyytoss constant, it should be like "yyyy-MM-dd"
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}

Persist simple textfile across app restarts

I am trying to persist a simple file with:
if let documents = directories.first {
if let urlDocuments = URL(string: documents) {
let urlText = urlDocuments.appendingPathComponent("file.txt")
print(urlText)
do {
try text.write(to: urlText, atomically: false, encoding: .utf8)
print(text)
}
catch {}
true)
}
}
but no matter what directory I choose, it saves it in something like
/Users/jaredearl/Library/Developer/CoreSimulator/Devices/6D477D99-7741-472D-8D16-4AE6771AF92E/data/Containers/Data/Appli ... file.txt
That tag there changes across restarts and when I use something like:
let documents = "/Users/jaredearl/Desktop/"
if let urlDocuments = URL(string: documents) {
let urlText = urlDocuments.appendingPathComponent("file.txt")
print(urlText)
do {
try text.write(to: urlText, atomically: false, encoding: .utf8)
print(text)
}
catch {/* error handling here */}
}
Then when I try to read the file I get: NSURLConnection finished with error - code -1002
How can I get it to persist across restarts?
In swift 3.0
You can use same function to read/write in file
func storeSyncLog(txtStor:String) {
let fileName = "a.txt"
let dir = try? FileManager.default.url(for: .documentDirectory,in: .userDomainMask, appropriateFor: nil, create: true)
//If the directory was found, we write a file to it and read it back
if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
var inString = ""
do {
inString = try String(contentsOf: fileURL)
} catch {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
//Write something in file
let outString = inString + "Date:\(Date()) yd : \(txtStor)\n\n"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
}
Hope its help

Writing Log Text File-Should I create an Array to store Filenames or Keep the File Open [duplicate]

I am trying to append a string into text file. I am using the following code.
let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if (dirs) != nil {
let dir = dirs![0] //documents directory
let path = dir.stringByAppendingPathComponent("votes")
let text = "some text"
//writing
text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
println(text2) //prints some text
}
this does not append the string to file. Even if I call this function repeatedly.
If you want to be able to control whether to append or not, consider using OutputStream. For example:
do {
let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("votes.txt")
guard let outputStream = OutputStream(url: fileURL, append: true) else {
print("Unable to open file")
return
}
outputStream.open()
let text = "some text\n"
try outputStream.write(text)
outputStream.close()
} catch {
print(error)
}
By the way, this is an extension that lets you easily write a String (or Data) to an OutputStream:
extension OutputStream {
enum OutputStreamError: Error {
case stringConversionFailure
case bufferFailure
case writeFailure
}
/// Write `String` to `OutputStream`
///
/// - parameter string: The `String` to write.
/// - parameter encoding: The `String.Encoding` to use when writing the string. This will default to `.utf8`.
/// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string. Defaults to `false`.
func write(_ string: String, encoding: String.Encoding = .utf8, allowLossyConversion: Bool = false) throws {
guard let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) else {
throw OutputStreamError.stringConversionFailure
}
try write(data)
}
/// Write `Data` to `OutputStream`
///
/// - parameter data: The `Data` to write.
func write(_ data: Data) throws {
try data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) throws in
guard var pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
throw OutputStreamError.bufferFailure
}
var bytesRemaining = buffer.count
while bytesRemaining > 0 {
let bytesWritten = write(pointer, maxLength: bytesRemaining)
if bytesWritten < 0 {
throw OutputStreamError.writeFailure
}
bytesRemaining -= bytesWritten
pointer += bytesWritten
}
}
}
}
For Swift 2 rendition, see previous revision of this answer.
You can also use FileHandle to append String to your text file. If you just want to append your string the end of your text file just call seekToEndOfFile method, write your string data and just close it when you are done:
FileHandle usage Swift 3 or Later
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// create a new text file at your documents directory or use an existing text file resource url
let fileURL = documentsDirectory.appendingPathComponent("simpleText.txt")
do {
try Data("Hello World\n".utf8).write(to: fileURL)
} catch {
print(error)
}
// open your text file and set the file pointer at the end of it
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()
// convert your string to data or load it from another resource
let str = "Line 1\nLine 2\n"
let textData = Data(str.utf8)
// append your text to your text file
fileHandle.write(textData)
// close it when done
fileHandle.closeFile()
// testing/reading the file edited
if let text = try? String(contentsOf: fileURL, encoding: .utf8) {
print(text) // "Hello World\nLine 1\nLine 2\n\n"
}
} catch {
print(error)
}
Please check the below code as its working for me. Just Add the code as it is:
let theDocumetFolderSavingFiles = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePath = "/theUserData.txt"
let thePathToFile = theDocumetFolderSavingFiles.stringByAppendingString(filePath)
let theFileManager = NSFileManager.defaultManager()
if(theFileManager.fileExistsAtPath(thePathToFile)){
do {
let stringToStore = "Hello working fine"
try stringToStore.writeToFile(thePathToFile, atomically: true, encoding: NSUTF8StringEncoding)
}catch let error as NSError {
print("we are geting exception\(error.domain)")
}
do{
let fetchResult = try NSString(contentsOfFile: thePathToFile, encoding: NSUTF8StringEncoding)
print("The Result is:-- \(fetchResult)")
}catch let errorFound as NSError{
print("\(errorFound)")
}
}else
{
// Code to Delete file if existing
do{
try theFileManager.removeItemAtPath(thePathToFile)
}catch let erorFound as NSError{
print(erorFound)
}
}
A simple solution that works for me. UPDATE, it looks like I must have gotten this from here, so credit where credit is due:
Append text or data to text file in Swift
Usage:
"Hello, world".appendToURL(fileURL: url)
Code:
extension String {
func appendToURL(fileURL: URL) throws {
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
extension Data {
func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else {
try write(to: fileURL, options: .atomic)
}
}
}
Check the reading part.
The method cotentsOfFile: is a method of NSString class. And you have use it wrong way.
So replace this line
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
Here you have to use NSString instead of String class.
let text2 = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)

Expression implicity coerced from "error?" to Any

I have this error:
Expression implicity coerced from "Error?" to Any
and I am not sure what it means, hoping to find help.
let task = URLSession.shared.dataTask(with: url) { (data,response, error) in
if error != nil {
print(error)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
print(jsonResult)
} catch {
print("JSON Processing Failed")
}
}
}
}
task.resume()
Check this line:
print(error)
You are printing an optional value. You should unwrap it with if let.
if let error = error {
print(error)
}

try-catch placement in converting Swift dictionary to JSON string

Here's what I've got:
do {
try let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
print("CAUGHT SOMETHING session token")
}
I'm getting an error try must be placed on the initial value expression. I tried 'rephrasing' like so:
do {
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted)
try jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
print("CAUGHT SOMETHING session token")
}
but this leads to an error Call can throw but is not marked with 'try'. How should I be structuring this try-catch and what do these error codes mean?
You have to change the location of where you are putting your try.
do {
if let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted) {
//is jsonString a variable you have previously declared?
//if not, put "if let" before it, because you are creating it IF:
//your "try" - attempt to get data from json succeeds
jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
}
} catch {
print("CAUGHT SOMETHING session token")
}