This question already has an answer here:
Xcode 8.2.1 / Swift 3 - Load TableView from Plist Array of Dictionaries
(1 answer)
Closed 5 years ago.
early this month i started learning swift as i found it fun and easier than obj-c
i came up with an idea trying to show english words and meaning on my language,
for that case i have a plist ready on my hand and a UITableViewController
with 2 Labels
here is my plist
so on my UITableViewController, i tried to get hands on the plist file with this code
let path = NSBundle.mainBundle().pathForResource("TableData", ofType: "plist")
let array = Array(contentsOfFile: path!)
and i got stuck on the rest
thanks
If you are just staring to learn Swift please start with Swift 3. Your Swift 2 code is outdated.
The recommended way to load a property list file is PropertyListSerialization
let url = Bundle.main.url(forResource: "TableData", withExtension: "plist")!
do {
let data = try Data(contentsOf: url)
let dataArray = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:String]]
print(dataArray)
} catch {
print("This error must not happen", error)
}
Related
This question already has answers here:
Swift - encode URL
(19 answers)
Closed 5 years ago.
I tried to call a custom url using this code below:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl)
print(converted)
But what I'm getting as result in converted is just "nil".
I'm pretty sure this is because of the wrong characters set in relation to the URL() class.
After some research all I got so far is this outdated Swift code:
var myurl = "https://myserver.com/call?a|b|c"
var newurl = myurl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
print(newurl)
But it doesn't seems working this way.
How can I achieve to avoid the "nil" result using (in my case) Swift 4?
Found the solution on my own:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
print(converted!)
The new function is called addingPercentEncoding & I have to call it with the urlQueryAllowed property.
The urlQueryAllowed charset adds some characters like this to the url encoding: "!*'();:#&=+$,/?%#[]|"
VoliĆ !
This question already has answers here:
WKWebView does load resources from local document folder
(8 answers)
Closed 5 years ago.
While working on a web app for weeks, I used a external URL in my (WKWebView) web view. Now I'm moving towards production I want to embed the webapp and load a local webpage.
I simply moved from
let url = URL(string: "http://hidden-url.com/")
self.webView!.load(URLRequest(url: url!))
To
let url = URL(string: Bundle.main.path(forResource: "index_prod", ofType: "html")!)
self.webView!.load(URLRequest(url: url!))
But this causes my app to crash. I'm sure the file is loaded correctly and a print before, in-between and after the lines will appear in the console.
The error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
You need to load the string content from the file, use contentsOfFile method to get the string and use loadHTMLString method of webview, print the error or create some enum which shows the error
enum WebError: Swift.Error {
case fileNotFound(name: String)
case parsing(contentsOfFile: String)
}
guard let url = Bundle.main.path(forResource: "index_prod", ofType: "html") else {
throw WebError.fileNotFound(name: file) // throw file not found error
}
do {
let html = try String(contentsOfFile: url)
self.webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
} catch {
throw WebError.parsingError(contentsOfFile: file)
}
I'm working with AEXML to write and read xml documents in Swift. I have the writing working no problem. And I have everything setup for the reading, but I can't seem to turn the saved text xml into the document object. It only ever gets the first element and none of the children. I've tried removing all the lines and spaces but still nothing. The content is reading into the String just fine and I've tried converting the data back to a string and it isn't getting messed up in conversion. Is this even possible with AEXML or am I just doing it wrong?
let doc = AEXMLDocument()
let content = try String(contentsOf:NSURL(string:file) as! URL)
let data = content.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let xml = NSString(data:data, encoding:String.Encoding.utf8.rawValue)
try doc.loadXMLData(data)
So I figured out that I was actually using an outdated version of AEXML which clearly wasn't working anymore. The updated code looks like this.
let content = try String(contentsOf:NSURL(string:file) as! URL)
let data = content.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let options = AEXMLOptions()
let doc = try AEXMLDocument(xml:data,options:options)
This question already has answers here:
Swift2 retrieving images from Firebase
(2 answers)
Closed 7 years ago.
On the process of trying Firebase, as a possible replacement to Parse.com (unfortunately to disappear), I have saved a PNG image online using the code below, in Swift.
let fn = self.toolBox.getDocumentsDirectory().stringByAppendingPathComponent("M0-1.png")
let im = UIImage(contentsOfFile: fn),
dat = UIImagePNGRepresentation(im!),
b64 = dat?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
qs = ["string": b64!],
r = diltRootRef.childByAppendingPath("zs"),
us = ["img": qs]
r.setValue(us)
The saving part seems to work, but how am I suppose to get back the image I saved? All I have tried so far failed.
I would recommend retrieving images using observeSingleEventOfType(:_), because it's a one-time read.
Once you have the string value synchronized, you can use an NSData() initializer, and then create an UIImage.
imageRef.observeSingleEventOfType(.Value) { (imageSnap: FDataSnapshot!) in
let base64String = imageSnap.value as! String
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
let image = UIImage(data: decodedData!)
}
Check out this example repo on using base64 images in a UITableView.
I need to be able to reference a file which is stored in my Xcode project in the following way:
I want to be able to use files which I have stored inside of the "data" folder.
How do I reference it to be able to read its contents? What is it's directory path?
I just figured it out. The apple swift documentation and other developer references are really unclear about it.
The way you would reference the "data" folder so as to scan the entire contents is by writing the following:
let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("data")
var error: NSError?
let filesInDirectory: [String]! = fileManager.contentsOfDirectoryAtPath(path!, error: &error) as? [String]
This will return the contents of the files in the "data" folder as an array of filenames.
Hope this helps :)
Relative to swift 3
let bundleURL = Bundle.main.bundleURL
let dataFolderURL = bundleURL.appendingPathComponent("data")
let fileURL = dataFolderURL.appendingPathComponent("file.txt")
print(fileURL.path)
print(FileManager.default.fileExists(atPath: fileURL.path))
let bundleURL = NSBundle.mainBundle().bundleURL
let dataFolderURL = bundleURL.URLByAppendingPathComponent("data")
let fileURL = dataFolderURL.URLByAppendingPathComponent("fileName.txt")