I am doing this to get the content of a file using NSOpenPanel, but I am getting a lot of weird stuff returned from the .rtf file I select.
My panel code:
var panel: NSOpenPanel = NSOpenPanel()
var fileTypesArray: NSArray = ["txt", "rtf", "nil"]
panel.canChooseFiles = true
panel.allowedFileTypes = fileTypesArray as [AnyObject]
panel.allowsMultipleSelection = false
if panel.runModal() == NSModalResponseOK {
var url = panel.URL!.path
println(url)
let path = url
let expandedPath = path!.stringByExpandingTildeInPath
let data: NSData? = NSData(contentsOfFile: expandedPath)
if let fileData = data {
let content = NSString(data: fileData, encoding:NSUTF8StringEncoding) as! String
println(content)
}
}
The contents of my .rtf document is "Testing 123"
This is what is being printed to the console:
{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 Testing 123\
}
Is there any way I can get just the text from the file, and what is all the other stuff that is being printed?
That "other stuff" is the actual RTF data.
I would recommend using the NSAttributedString initializer NSAttributedString(path:documentAttributes:), which will read in and process the RTF data. Then you can access the plain text by using attributedString.string.
In your case, it would be
if let content = NSAttributedString(path: expandedPath, documentAttributes: nil) {
// do something with content or content.string
}
Related
I have a string file that contains base64string of image. I'm sure that base64String is correct, because i used the website for checking:
https://codebeautify.org/base64-to-image-converter
with file data:
https://www.dropbox.com/s/10zjyzgcyv7s08m/data_base.txt?dl=1
(download and copy the content to the above website to generate the image )
But, On IOS Device , i can't convert it to image . This is my code (Swift3) :
if let filepath = Bundle.main.path(forResource: "data_base", ofType: "txt") {
do {
let text3 = try String(contentsOfFile: filepath, encoding: String.Encoding.utf8)
let dataDecoded : Data = Data(base64Encoded: text3, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
self.imageView.image = decodedimage
} catch {
}
}else {
print("file is not exist")
}
Please help me to find out the solution.
I have an NSAttributedString which has an NSAttachment and some text. I have copied it to the pasteboard. I have also made sure that the string has no font attributes. When I paste it, it always changes the font to Helvetica. Is there any way to prevent this behavior?
let wrapper = NSFileWrapper()
wrapper.preferredFilename = "image"
let attachment = NSTextAttachment(fileWrapper: wrapper)
if let im = NSImage(data: data) { attachment.image = im }
let image = NSAttributedString(attachment: attachment)
let str = NSMutableAttributedString(attributedString: image)
str.appendAttributedString(NSAttributedString(string: "hello world"))
let range = NSMakeRange(0, str.length)
//remove font attributes
str.removeAttribute(NSFontAttributeName, range: range)
str.removeAttribute(NSFontSizeAttribute, range: range)
Swift.print(str.attributes) //prints an empty array
At this point I copy the data to the clipboard
if let d = str.RTFDFromRange(range, documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType]) {
let pboard = NSPasteboard.generalPasteboard()
pboard.clearContents()
pboard.declareTypes([NSPasteboardTypeRTFD], owner: self)
pboard.setData(d, forType: NSPasteboardTypeRTFD)
}
Here`s my code:
let fileName = "someFileName"
func saveDataToFile(urlStr:String){
let url = NSURL(string: urlStr)
var data:NSData!
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName
let fileManager = NSFileManager.defaultManager()
data = NSData(contentsOfURL: url!)
print(data) // prints a lot of data
if data != nil{
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
}
}
Now I want to read this data:
func readDataFromFile(){
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath) // prints the same path
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath){
data = fileManager.contentsAtPath(filePath)
}else{
print("*****BAD*****") // always prints this which means that file wasn`t created
}
}
What`s wrong with the first func? What is the right way to save file to DocumentDirectory?
OK, in this case the answer was following:
First need to create directory (aka folder) and only after that create file inside that directory.
Added to code this:
let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)
do{
try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
print(error.localizedDescription)
}
And as I said after this you create your file:
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
Thanks to Eric.D
Hope someone will find this useful.
var TestYou = "www,aa.com"
if let url = TestYou as? String {img.hidden = true}else{img.hidden = false}
I want to hide an image if an url is found. If it is not I want to show the image.
What do I have to do to fix it?
If I got that right from your "question" you are searching for something like this (do this in your AppDelegate):
if let url = NSURL(string: ("www.aa.com")) {
// check if your application can open the NSURL
if UIApplication.sharedApplication().canOpenURL(url){
img.hidden = true //hide image
} else {
img.hidden = false //show image
}
}
I would like to list all files in my iTunes shared folder in a 'Table View' using Swift.
I check on Google and nobody talk about it, it look like it's a uncommon need, so if anyone can help it would be really helpful.
EDIT: I found three links talking about it but in Objective-C, I have no experience in this language. If someone understand this, here are the links.
http://www.exampledb.com/objective-c-get-itunes-file-sharing-folder-files-with-full-path.htm
http://www.infragistics.com/community/blogs/stevez/archive/2013/10/14/ios-objective-c-working-with-files.aspx
http://www.raywenderlich.com/1948/itunes-tutorial-for-ios-how-to-integrate-itunes-file-sharing-with-your-ios-app
Based on this objective-C tutorial http://mobiforge.com/design-development/importing-exporting-documents-ios, I created three methods: listFilesFromDocumentsFolder which returns a list of the names of all documents I have in the apps iTunes shared folder and loadFileFromDocumentsFolder which loads the url for a given filename and passes the url to handleDocumentOpenUrl to load the file on a UIWebView. Find below the three methods.
You can also download the project from github: https://github.com/Euniceadu/Load-Shared-Documents
listFilesFromDocumentsFolder
func listFilesFromDocumentsFolder() {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var fileManager: NSFileManager = NSFileManager()
var fileList: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)!
var filesStr: NSMutableString = NSMutableString(string: "Files in Documents folder \n")
for s in fileList {
filesStr.appendFormat("%#", s as String)
}
self.displayAlert(filesStr)
}
loadFileFromDocumentsFolder
func loadFileFromDocumentsFolder(fileName: String) {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var filePath: String = documentsDirectory.stringByAppendingPathComponent(fileName);
var fileUrl: NSURL = NSURL(fileURLWithPath: filePath);
self.handleDocumentOpenURL(fileUrl)
}
handleDocumentOpenUrl
func handleDocumentOpenURL(url: NSURL) {
var requestObj = NSURLRequest(URL: url)
webView.userInteractionEnabled = true
webView.loadRequest(requestObj)
}
Hope this helps.