2016-10-20 42 views
2

我正在尋找一種方法將PDF文件保存在我的項目目錄中,但我從Web服務中收到了一個基本的64位pdf字符串。我必須將其轉換爲NSData或類似的東西嗎?如何使用base64字符串製作PDF文件? Swift

我在編碼方面很新,但我可以按照你的指示。

我希望你能幫助我。由於

+1

將base 64字符串解碼爲Data,然後保存數據 – PeejWeej

+0

用一些相關代碼更新您的問題。顯示迄今爲止關於PDF數據的內容。同時解釋你的嘗試。 – rmaddy

回答

0

你想要的東西,如:

if let d = Data(base64Encoded: base64string) { 
    do { 
     try d.write(to: outputFile) 
    } catch { 
     // handle error 
    } 
} 

哪裏base64string是PDF格式的base64字符串,outputFile是PDF輸出文件的URL。

+1

不要使用'try!'。做實際的,適當的錯誤處理。 – rmaddy

+0

對不起,他們給了我這個項目在Swift 2.0,什麼是que相當於? –

6

是的,您必須將其轉換爲數據,然後將其保存到設備上的文檔目錄中。像這樣的功能將起作用:

func saveBase64StringToPDF(_ base64String: String) { 

    guard 
     var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last, 
     let convertedData = Data(base64Encoded: base64String) 
     else { 
     //handle error when getting documents URL 
     return 
    } 

    //name your file however you prefer 
    documentsURL.appendPathComponent("yourFileName.pdf") 

    do { 
     try convertedData.write(to: documentsURL) 
    } catch { 
     //handle write error here 
    } 

    //if you want to get a quick output of where your 
    //file was saved from the simulator on your machine 
    //just print the documentsURL and go there in Finder 
    print(documentsURL) 
} 
+0

這是工作。我以3.0的速度嘗試過 – Dalvik

相關問題