Kunal
Kunal

Reputation: 119

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

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

Upvotes: 1

Views: 11438

Answers (4)

Hemang
Hemang

Reputation: 27072

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))

Upvotes: 8

Raj
Raj

Reputation: 11

Where would you pick the file, That file path has to be given:

  1. First generate the base64 string you can use it

  2. 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 { }

Upvotes: -1

TonyDev
TonyDev

Reputation: 11

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

Upvotes: 1

Ullas Pujary
Ullas Pujary

Reputation: 359

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)

Upvotes: 2

Related Questions