My question, after I open PDF file with my app('register the document types that your application can open with iOS') I getting the files as NSCFString format)
Example:
let filemgr: NSFileManager = NSFileManager.defaultManager();
var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true);
let documentsDirectory: String = paths[0] as! String
let inboxPath: String = documentsDirectory.stringByAppendingPathComponent("Inbox");
do
{
let dirFiles: [AnyObject] = try filemgr.contentsOfDirectoryAtPath(inboxPath);
}
catch{}
My question is from this step I want to gather all this documents to one document and also open it with UIWebView. from what i read i need to find a way to convert it to nsdata or even draw it as PDF, but i really dont know how to handle it.
Thank you for help
Related
I request you to give me a solution where the result of NSString and String both are same
downloadedFile = MOM'&^*%s-HC.pdf (In NSString)
let path = pathComponent.appendingPathComponent(downloadedFile as String)
print(path) //OutPut: ttt_gmail_com/MOM'&%5E*%25s-HC-2.pdf
If I test with regular expression result is OK.
let NSStringValue = "MOM'&^*%s-HC.pdf" as NSString
print(NSStringValue) // Output: MOM'&^*%s-HC.pdf
let StringValue = downloadedFile as String
print(StringValue) // Output: MOM'&^*%s-HC.pdf
but while I put that code in appendingPathComponent it changes my result.
You have a file name which has all the special characters here, I tried your case in a sample project trying to load such file in UIDocumentInteractionController and it seems when I have a file name with special character in my document directory and i try to retrieve it, few special characters are URL encoded.
Observe the file name I used here is "MOM'&^*%s-HC.pdf" and saved it in the doc directory but when I retrieve it from the document directory using the following code few characters are URL encoded as I am fetching the path as URL.
So this means that your original file name
MOM'&^*%s-HC.pdf
is now alterated and replaced by percentage escape sequence strings,
MOM'&%5E*%25s-HC.pdf
observe the below code which I used
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent(fileName)
To resolve this all i did was removed the percentage escape sequence when I am creating the URL and it worked I was able to view the PDF in the UIDocumentInteractionController
fileName.removingPercentEncoding!
Hope it helps.
I have user localizable strings for the strings used in storyboard or source files which are fixed. These are defined in files like Localizable.string (Spanish), Localizable.string (German) etc. But I have a requirement where these strings can keep changing. These strings are received as a response to REST API call. My question is how can I use it.
Current code is let text = NSLocalizedString("Some string", comment: "")
Where NSLocalizedString looks for Localizable.string file. How can I make NSLocalizedString look for localized words from my custom dictionary/Json?
Try this
First you need to copy that files in document directory .
Get Localised Label
let localisedString = self.getLocalizatioString(key: "your key", stringFileName: "test.strings") //
Function
func getLocalizatioString(key : String?, stringFileName : String ) -> String {
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = doumentDirectoryPath.appendingPathComponent(stringFileName)
let dict = NSDictionary.init(contentsOfFile: destinationPath)
return (dict?.object(forKey: key!) as? String)!
}
Output
In String file
I'm using the following code to save a 2D String array to a plist:
func saveFavourites(favouriteStops: [[String]]) {
let directories = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
if let library = directories.first {
if let libraryUrl = URL(string: library) {
let favouritesUrl = libraryUrl.appendingPathComponent("favourites.plist")
// Write favourites to disk
let favsArray = favouriteStops as NSArray
print(favsArray)
favsArray.write(toFile: favouritesUrl.path, atomically: true)
}
}
}
The above snippet properly creates the .plist file (confirmed by looking at the simulator's filesystem in ~/Library/Developer/CoreServices). However, when I try reading it back to a NSArray with the following snippet, it results in nil:
let directories = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
if let library = directories.first {
if let libraryUrl = URL(string: library) {
let favouritesUrl = libraryUrl.appendingPathComponent("favourites.plist")
// favsToLoad is nil
let favsToLoad = NSArray(contentsOf: favouritesUrl)
// Do stuff with favsToLoad, if it would load properly
}
}
You're doing two very basic things wrong.
First, never make a URL from a file path by saying URL(string); this is a file on disk, so you must use URL.fileURL.
Second, don't start with a file path at all! Obtain the directory as a URL right from the start.
(Also, though I do not know whether this is the source of the issue, do not read and write directly in the Library directory. Use the Documents directory, the Application Support directory, or similar.)
So, for example, I would write:
let fm = FileManager.default
let docsurl = try fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let favouritesurl = docsurl.appendingPathComponent("favourites.plist")
I see your problem. You misspelled "favorites". :)
But seriously...
Plists can only contain a very small set of "property list objects": (dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values).
If your array's "object graph" (the objects the array contains and any container objects inside the array recursively contain) contain anything other than the above types, the save will fail.
I don't honestly know what gets saved when it fails. Have you tried opening the plist file in a text editor and looking at it?
My guess is that something other than a string has snuck into your array, it's not one of the above types, and THAT'S why it's failing.
I need to unzip a .epub file in swift to read the data myself entirely. I know how to parse the output of an ePub if I can get it (I've written a working example in python), but SSZipArchive apparently will not unzip .epubs. It does, however, works fine on a dummy .zip file; only .epub is a problem. So far as I can tell, there has been no question asking how to actually do this by hand on S.O. beyond simply pointing people to projects that do it for you in objective-c with lots of overhead (which I don't understand or need) that defeats the purpose of what I need to do. Below is my current attempt. Note that the epub in question can be found at the following link (project gutenberg) http://www.gutenberg.org/ebooks/158.epub.noimages and that when I run this the print statement emits: "true, true, true, false" (that is, the files and paths all exist, but won't unzip):
import Foundation
class EpubExtractor: NSObject, SSZipArchiveDelegate {
init(fileName: String) {
fName = fileName
}
func getEpubInfo() {
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDir = paths[0]
let zipPath = documentsDir.stringByAppendingString("/MyZipFiles") // My folder name in document directory
let fileManager = NSFileManager.defaultManager()
let success1 = fileManager.fileExistsAtPath(zipPath) as Bool
if success1 == false {
print("no directory")
do {
try! fileManager.createDirectoryAtPath(zipPath, withIntermediateDirectories: true, attributes: nil)
}
}
let archivePath = zipPath.stringByAppendingString("/emma.epub") // Sample folder is going to zip with name Demo.zip
let success2 = fileManager.fileExistsAtPath(archivePath) as Bool
let destPath = zipPath.stringByAppendingString("/Hello")
let success3 = fileManager.fileExistsAtPath(destPath) as Bool
let worked = SSZipArchive.unzipFileAtPath(archivePath, toDestination: destPath, delegate:self)
print(success1, success2, success3, worked)
}
}
EDIT
Below is proof of concept code written in python in which I CAN get the very same epub to be recognized as a zip file and read its container content:
import zipfile
dir = "sampleData/epubs/"
fileName = "emma.epub"
print zipfile.is_zipfile(dir+fileName) # Check whether file is zip (this returns true, though in swift it fails)
zip = zipfile.ZipFile(dir+fileName)
txt = zip.read('META-INF/container.xml') # Print contents of container (this is what I need swift to be able to do)
print txt # This successfully prints the container content text
I figured it out after many many hours of reading. Turns out the solution is extremely simple if non-obvious.
The "fileName.epub" file needs to be renamed to "fileName.zip". That's it!
After that either SSZipArchive or Zip will unzip the file into its META-Inf, mimetype, and OEBPS files in a folder called "fileName" (at least as the default name).
Hope this helps anyone struggling with this. Of course if there is another way to do this please let me know in comments.
I am new to Swift and am using Xcode 6.
I am attempting to read data from the app's plist file, but it is not working.
The data.plist file is included in Xcode's Supporting Files group.
I am using the code below:
var dataList = NSDictionary(contentsOfURL:NSBundle.mainBundle().URLForResource("data", withExtension:"plist"))
however the NSURL:
NSBundle.mainBundle().URLForResource("data", withExtension:"plist")
always returns nil.
I don't know what is wrong.
Generally you would want to use this code to create your plist. This finds the the path to your plist and then moves it into the documents directory if it isn't already there. If you don't move it, you are not allowed to write to it, hence this chunk of code is vital. To fetch the information from the plist, use the second bit of code. Obviously if you have an array rather than a dictionary, you would have to alter it to deal with that.
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
path = path.stringByAppendingPathComponent("data.plist")
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(path) {
let sourcePath = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
fileManager.copyItemAtPath(sourcePath, toPath: path, error: nil)
}
.
let dict = NSMutableDictionary(contentsOfFile: path) as NSMutableDictionary