how to convert .pdf file to base64 string in swift 2.0? - swift

I have to upload document in swift , I have to do this using the iCloud , so that I can upload file to my server using icloud

Swift 3.x
let filePath = ... //URL of the PDF
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))

Drag the pdf file to the project or five the path before to hold
let url1 = Bundle.main.url(forResource: "pdffilename without extension", withExtension: "pdf")
let one1 = NSData(contentsOf: url1!)
let pdfstring:String = one1!.base64EncodedString(options: .endLineWithLineFeed)
print(pdfstring)

let filePath = "" // real path of the pdf file
let fileData = NSData(contentsOfFile: path)
let fileStream = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) // base64 string

Where would you pick the file, That file path has to be given:
First generate the base64 string you can use it
Then generate the bytes
Which one comfortable could use it.
do {
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let decodeData = Data(base64Encoded: fileStream, options: .ignoreUnknownCharacters)
body.append(decodeData!)
}
catch { }

Related

How to generate a PDF with SimplePDF in Swift

I've got a problem regarding how to use SimplePDF.
I would like to export a PDF file from my application when I press a simple UIButton.
Now I try to use the standard code give by SimplePDF but I still have a problem :
The code :
let a4PaperSize = CGSize(width: 210, height: 297)
let pdf = SimplePDF(pageSize: a4PaperSize)
pdf.setContentAlignment(.center)
// add logo image
let logoImage = UIImage(named:"train-icon180.png")!
pdf.addImage(logoImage)
// [...]
// Generate PDF data and save to a local file.
// Here is where I've got a problem
if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let fileName = "\(ReceptionOuvertureLigne).pdf"
let documentsFileName = documentDirectories + "/" + fileName
let pdfData = pdf.generatePDFdata()
do{
try pdfData.writeToFile(documentsFileName, options: .DataWritingAtomic)
print("\nThe generated pdf can be found at:")
print("\n\t\(documentsFileName)\n")
}catch{
print(error)
}
In fact the line : try pdfData.writeToFile(documentsFileName, options: .DataWritingAtomic) in the PDF generating part result by an error :
Value of type 'Data' has no member 'writeToFile'
I don't know how to solve it ...

How to use vapor for uploading/downloading image?

Now: i am uploading data and saving it to my public folder:
let info = req.data
guard let fileBytes = info["photo"]?.bytes
else {
var answerJson = JSON();
try answerJson.set("success", "false");
return answerJson
}
let dir = URL(fileURLWithPath: self.config.workDir).appendingPathComponent("Public/FleaMarketProductImages")
let dirWithImage = dir.appendingPathComponent("test3.jpg")
let fileManager = FileManager()
let data = Data(bytes: fileBytes)
fileManager.createFile(atPath: dirWithImage.path, contents: data, attributes: nil)
Then on device for downloaing this file i am doing next:
Alamofire.download(url).responseData { response in
if let data = response.result.value {
completionHandler(data)
}
}
I am getting some data, but when i do UIImage(data: data), i dont see my image. Where i did something wrong? Maybe there is another way to do it. And files in my public directory dont looks like image. They just files. Maybe do you know how to save it like an image????
The uploaded image will be one part of a multi-part request, so you need to use just the part that contains the image. .bytes will give you the whole request. I use:
guard let fileBytes = info.formData?["photo"]?.part.body
Or
guard let fileBytes = info?["photo"]?.part.body
if you aren't using a form.

Swift3 : How to load html file to WKWebview from document directory

Can anyone explain how to load local html file to WKWebView?
I tried with the below code works well in simulator but not on device
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath: String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath + "/" + "\(NameF.fileName)/\(NameF.Languages)/page_\(i + 1 ).html")
print("D2\(destinationURLForFile)")
let request = NSURLRequest(url: destinationURLForFile)
webView!.load(request as URLRequest)
Any suggestions would be helpful!
Thank you for your response guys and for who tried my question.Finally found the answer by opening the local file and read its content and then send that string into a WKWebview
And the piece of code is
do{
let fileName = try String(contentsOf: destinationURLForFile)
print("fileName is equal to\(fileName)")
webView.loadHTMLString(fileName, baseURL: destinationURLForFile)
}catch{
}

Load Url image from Plist in Swift

I have a plist running in my project which contains number of image urls.I am trying to pass the url image to my imageView which is in the same viewController.I found similar questions from github like Loading/Downloading image from URL on Swift , Swift - Read plist , Can't get plist URL in Swift I went through all those answers but no luck so far rather than fatal crash. My partial codes as follows....
Method 1:
override func viewDidLoad() {
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "apps", ofType: "plist"),
let root = (NSArray(contentsOfFile: path))
{
let url = NSURL(string: path)
let data = NSData(contentsOf: url! as URL)
if let imageData = data {
imageView.image = UIImage(data: imageData as Data)
}
**// Swift Console Printinging as Follows**
print(root)
// printing all my plist url links like {icon = "https://xxxxxxxxxxx.com/image/girl_face_freckles_eyes_92358_1920x1080.jpg";}
print(url)
// (/Users/xxxxxx/Library/Developer/CoreSimulator/Devices/52DA3F73-83E0-4C29-9DE1-D8D5F0731C13/data/Containers/Bundle/Applica ... ps.plist)
print(data)
// nil
print(imageView.image)
//nil
} else {
print("Either the file does not exist or the root object is an array")
}
Method 2:
let path = Bundle.main.path(forResource: "apps", ofType: "plist")
let url = NSURL(string: path!)
let imgData = try? Data(contentsOf: url as! URL)
let img = UIImage(data: imgData!)!
print(img) // fatal crash
}
path is the path to your plist, not to your image URL.
The image URL is in the key "icon" in the "root" array.
Get the first item of the array and subscript with the key, you should get your image URL:
if let item = root[0] as? [String:Any] {
if let result = item["icon"] as? String {
print(result)
}
}
The path in (NS)Bundle is a file system path and these paths must be created with URL(fileURLWithPath:)
let path = Bundle.main.path(forResource: "apps", ofType: "plist")
let url = URL(fileURLWithPath: path!)
But why does nobody use the URL related API which is much more convenient
let url = Bundle.main.url(forResource: "apps", withExtension: "plist")

Search for all txt files in directory - Swift

a. How should I get all the txt files in directory?
i got a path of directory and now i should find all the txt files and change every one a little.
i try to run over all the files:
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String {
}
}
but I stuck there. How can I check if the filetype is text?
b. When i get to a directory (in the directory I run), I want get in and search there too, and in the end get out to the place I was and continue.
a is much more important to me but if I get an answer to b too it will be nice.
a. Easy and simple solution for Swift 3:
let enumerator = FileManager.default.enumerator(atPath: folderPath)
let filePaths = enumerator?.allObjects as! [String]
let txtFilePaths = filePaths.filter{$0.contains(".txt")}
for txtFilePath in txtFilePaths{
//Here you get each text file path present in folder
//Perform any operation you want by using its path
}
Your task a is completed by above code.
When talking about b, well you don't have to code for it because we are here using a enumerator which gives you the files which are inside of any directory from your given root directory.
So the enumerator does the work for you of getting inside a directory and getting you their paths.
You can use for .. in syntax of swift to enumerate through NSEnumerator.
Here is a simple function I wrote to extract all file of some extension inside a folder.
func extractAllFile(atPath path: String, withExtension fileExtension:String) -> [String] {
let pathURL = NSURL(fileURLWithPath: path, isDirectory: true)
var allFiles: [String] = []
let fileManager = NSFileManager.defaultManager()
if let enumerator = fileManager.enumeratorAtPath(path) {
for file in enumerator {
if let path = NSURL(fileURLWithPath: file as! String, relativeToURL: pathURL).path
where path.hasSuffix(".\(fileExtension)"){
allFiles.append(path)
}
}
}
return allFiles
}
let folderPath = NSBundle.mainBundle().pathForResource("Files", ofType: nil)
let allTextFiles = extractAllFile(atPath: folder!, withExtension: "txt") // returns file path of all the text files inside the folder
I needed to combine multiple answers in order to fetch the images from a directory and I'm posting my solution in Swift 3
func searchImages(pathURL: URL) -> [String] {
var imageURLs = [String]()
let fileManager = FileManager.default
let keys = [URLResourceKey.isDirectoryKey, URLResourceKey.localizedNameKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsPackageDescendants, .skipsSubdirectoryDescendants, .skipsHiddenFiles]
let enumerator = fileManager.enumerator(
at: pathURL,
includingPropertiesForKeys: keys,
options: options,
errorHandler: {(url, error) -> Bool in
return true
})
if enumerator != nil {
while let file = enumerator!.nextObject() {
let path = URL(fileURLWithPath: (file as! URL).absoluteString, relativeTo: pathURL).path
if path.hasSuffix(".png"){
imageURLs.append(path)
}
}
}
return imageURLs
}
and here is a sample call
let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
let destinationPath = documentsDirectory.appendingPathComponent("\(filename)/")
searchImages(pathURL: projectPath)
Swift 4
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = URL(fileURLWithPath: documentsPath)
let fileManager = FileManager.default
let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: url.path)!
while let element = enumerator.nextObject() as? String, element.hasSuffix(".txt") {
// do something
}
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String where element.pathExtension == "txt" {
// element is txt file
}
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath!)!
while let element = enumerator.nextObject() as? String {
if (element.hasSuffix(".txt")) { // element is a txt file }
}