Read Local Text File in Swift IOS - ios

I have a data in text format and that text format is located in my app local file. I did my research but i couldn't find anything about it. How to read that text file in swift. Should i use Sqlite or normal text file format with NSBundle. I hope someone help me to start something with. Thank you.

The following will place the contents of the file into a string:
let filePath = NSBundle.mainBundle().pathForResource("file", ofType: "txt");
let fileData = String(filePath!, encoding:NSUTF8StringEncoding, error:nil)!

var filePath = NSBundle.mainBundle().pathForResource("world_country_state", ofType:"json")
var nsMutData = NSData(contentsOfFile:filePath!)
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData!, options: .MutableContainers, error: nil) as! NSMutableDictionary
let arraycOuntry: NSArray = sJson.valueForKey("world")?.allKeys as! NSArray
let states: NSArray = sJson.valueForKey("world")?.valueForKey("USA") as! NSArray
pickerDataSoruce = states.mutableCopy() as! NSMutableArray
In this Code world_country_state.json is My File just You replace your file name.
i think this Code is very helpful for you.

Related

Swift 4 How do I write/read dictionaries to/from the document directory?

I have encryptions in the form of dictionaries that I want to save to the document directory. I also want to be able to retrieve these dictionaries from the document directory to decrypt within the app. How can I write/read dictionaries to/from the document directory?
Dictionary has its own write method which writes a property list representation of the contents of the dictionary to a given URL. You can do it using below code:
Write
// Get application document directory path array
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
let fileName = "users"
if let documentPath = paths.first {
let filePath = NSMutableString(string: documentPath).appendingPathComponent(fileName)
let URL = NSURL.fileURL(withPath: filePath)
let dictionary = NSMutableDictionary(capacity: 0)
dictionary.setValue("valu1", forKey: "key1")
dictionary.setValue("valu2", forKey: "key2")
let success = dictionary.write(to: URL, atomically: true)
print("write: ", success)
}
Read
if let dictionary = NSMutableDictionary(contentsOf: URL){
print(dictionary)
}
Hope, it will work.
Steps include
Get Document URL
Write Date to File
Saving to Disk
Make use of syntax from here:
https://stackoverflow.com/a/26557965/6342609

strange error, returned value type different from the one in function body

I have XlsxReaderWritter Framework added to my app. I am having trouble with the first steps of using this framework, which is getting a worksheet in an excel file
Here is my code:
let file = BRAOfficeDocumentPackage.open(syllabusFileURL.relativePath)!
inputFile = file.workbook.worksheets[0] //this line does not compile and gives me this "Type [Any]! has no subscript members"
Alright so I cast it as the following:
inputFile = file.workbook.worksheets[0] as! BRAWorksheet
Now it compiles but I get a runtime error saying:
Could not cast value of type 'BRAWorksheet' (0x10df5fdc0) to 'BRAWorksheet' (0x10ce8e430).
So it seems the value is already BRAWorksheet and does not need casting, but as I said it wont compile saying its of type [Any]!
In the official documentation, here is how they get a worksheet;
#####Swift
//First worksheet in the workbook
var firstWorksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0]
//Worksheet named "Foo"
var fooWorksheet: BRAWorksheet = spreadsheet.workbook.createWorksheetNamed("Foo")
Since it is an imported framework, I checked the original Objective-C file for the function. It does not seem to return [Any]!. Here is the body:
- (NSArray *)worksheets {
NSMutableArray *worksheets = #[].mutableCopy;
for (BRASheet *sheet in _sheets) {
BRAWorksheet *worksheet = [self.relationships relationshipWithId:sheet.identifier];
worksheet.styles = _styles;
worksheet.sharedStrings = _sharedStrings;
worksheet.calcChain = _calcChain;
[worksheets addObject:worksheet];
}
return worksheets.count ? worksheets : nil;
}
So can Anyone tell me what the duck is going on??!
If You are using swift 3
let path: String = Bundle.main.path(forResource: "demo", ofType: "xlsx")!
let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(path)
let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet
let sheet: BRASheet = spreadsheet.workbook.sheets[0] as! BRASheet
print(sheet.name) // print "Sheet1"
You should take care of the optional result:
var firstWorksheet: BRAWorksheet? = spreadsheet.workbook.worksheets?[0]

read file content and get the values back

I have an function to write some numbers to a file
fun writeNumToFile -> Void {
//get Documents’ path
let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as? String
let filePath = docPath.stringByAppendingPathComponent(“myFlie.txt”)
//the count is NOT the count of elements in the array below.
//think it as an independent constant.
let count = 10
//Write count to file
String(count).writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//Write an array of numbers to file
for idx in [1,2,3] {
String(idx as! String).writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}
}
Now I want to read the numbers back from file, I know I can read the content of file by:
let fileContent = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
but how can I get count & [1,2,3] array back once I get the content?
You are writing code as if you are using low-level file i/o. You're not. The writeToFile:atomically: methods that you are using overwrite a file with new contents, not append data to an existing file. your second write deletes the contents of your first write.
NSArray supports the writeToFile:atomically: method, and a [String] array should be inter-operable with NSArray.
You should be able to simply say:
let array = [1, 2, 3]
let ok = array .writeToFile(filePath, atomically: false)
Then later,
let array = NSArray.contentsOfFile(filePath)
I say "should be able to" because I am still learning the subtleties of interaction between Swift and the Foundation classes.
EDIT:
If you need to save multiple discrete things into a file, create a dictionary:
let someValue = 42
let anArray = [1, 2, 3]
let aDictionary = [
"someValue": someValue,
"array": anArray]
let ok = aDictionary.writeToFile(filePath, atomically: false)
and to read it:
let aDictionary = NSDictionary(contentsOfFile: filePath)
let someValue = aDictionary["someValue"] as! Int
let anArray = aDictionary["array"] as! [Int]
There is no need to save the number of items in the array separately. The array is able to reconstitute itself from the file contents, including the correct count of elements.
EDIT #2:
Note that iOS includes the C file i/o library, which should be callable from Swift. If you are glutton for punishment you could do what you are trying to do using fopen(), fseek(), fwrite(), etc. (But don't. It's much more work, much more error-prone, and a non-standard way of doing it in iOS or Mac OS.)

Getting a number of a text(?) document downloaded from server

I need help understanding how to convert NSData into a Int. I first downloaded the textFile from a server by doing this:
let url = NSURL(string: "path to server")!
let data = NSData(contentsOfURL: url)!
print(data) //confirmed there is data
//output in console is <31343231 340a>
When I downloaded the file on my computer, the file looks like this:
I looked around for ways to convert NSData to Int, and came across a technique like this:
var src: Int = 0
data.getBytes(&src, length: sizeof(Int))
print("price: \(src)") //output was 11219279950897
Unfortunately 2929 != 11219279950897. I presume it's something to do with possible white space in the document. Would be grateful if I can get some advice on this!
What about this? (Swift 1.2)
let data = ...
if let
datastring = NSString(data: data, encoding: NSUTF8StringEncoding),
num = (datastring as String).toInt() {
print(num)
}
Hope this helps.

Print all filenames in a folder in iOS application

I have a folder with 4 subfolders in my iOS application with each of these containing about 20 files each. I would like to be able to iterate through each folder and print out the filenames. I am not sure how to go about doing this.
Here is what I have tried:
let docsPath = NSBundle.mainBundle().resourcePath! + "/Samples";
let fileManager = NSFileManager.defaultManager()
var error: NSError?
let docsArray = fileManager.contentsOfDirectoryAtPath(docsPath, error:&error)
println(docsArray)
This prints out nil. I expect it to print out each of the filenames. How do I make this happen?
You have two problems here:
1)
Check your built app to see if "Samples" is really ending up in the built binary. From the error of "The operation couldn’t be completed", I'm thinking you aren't copying "Samples" into the compiled app bundle or at least into the place you're expecting it to be.
2)
The call you're doing will give you the contents of the folder, but not the contents of the subfolders which is what you really want to list.
Use NSDirectoryEnumerator instead to get the contents of that folder and subfolders. Here is a related question that might give you one direction to go.
You can use the NSFileManager's enumerator if you want to get all the files including inside subdirectories.
Simple example:
if let enumerator = fileManager.enumeratorAtURL(docsPath, includingPropertiesForKeys: nil, options: nil, errorHandler: nil) {
while let url = enumerator.nextObject() as? NSURL {
println(url)
}
}
Nevermind, I figured it out:
var docsPath = NSBundle.mainBundle().resourcePath! + "/Snare";
let fileManager = NSFileManager.defaultManager()
var error: NSError?
let docsArray = fileManager.contentsOfDirectoryAtPath(docsPath, error:&error)
//println(error!.localizedDescription)
println(docsArray)
for filename in docsArray!
{
let subfolderPath = docsPath + "/"+(filename as! String)
println(docsPath)
let subarray = fileManager.contentsOfDirectoryAtPath(subfolderPath, error: &error)
println(subarray)
}

Resources