How can I encode a string to Base64 in Swift?
I don’t have 6.2 installed but I don’t think 6.3 is any different in this regard:
dataUsingEncoding
returns an optional, so you need to unwrap that.
NSDataBase64EncodingOptions.fromRaw
has been replaced with NSDataBase64EncodingOptions(rawValue:)
. Slightly surprisingly, this is not a failable initializer so you don’t need to unwrap it.
But since NSData(base64EncodedString:)
is a failable initializer, you need to unwrap that.
Btw, all these changes were suggested by Xcode migrator (click the error message in the gutter and it has a “fix-it” suggestion).
Final code, rewritten to avoid force-unwraps, looks like this:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
println("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
{
// Convert back to a string
println("Decoded: \(base64Decoded)")
}
}
(if using Swift 1.2 you could use multiple if-lets instead of the map)
Swift 5 Update:
import Foundation
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: .utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
print("Encoded: \(base64Encoded)")
if let base64Decoded = Data(base64Encoded: base64Encoded, options: Data.Base64DecodingOptions(rawValue: 0))
.map({ String(data: $0, encoding: .utf8) }) {
// Convert back to a string
print("Decoded: \(base64Decoded ?? "")")
}
}
Convert string to base64 in Swift 3
Use this instead:
let longstring = "test123"
if let data = (longstring).data(using: String.Encoding.utf8) {
let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
print(base64)// dGVzdDEyMw==\n
}
Swift Data to base64 String with data:content/type
Alobaili made a good point. In the end, I ended up implementing a Data extension like that rather than hard coding it has we support different formats.:
extension Data {
/// Returns the image format if known
var imageFormat: ImageFormat {
guard let header = map({ $0 as UInt8 })[safe: 0] else {
return .unknown
}
return ImageFormat(byte: header)
}
/// Returns the base64 String representation of an Image data:image/png;base64, **BASE64STRING**
var imageBase64URIOutputString: String? {
guard let mimeType = imageFormat.mimeType else {
return nil
}
return "data:\(mimeType);base64,\(base64EncodedString())"
}
}
Where:
enum ImageFormat: String, CaseIterable {
/// Is a PNG image
case png
/// Is a JPEG image
case jpeg
/// Is a GIF image
case gif
/// Unknown image format
case unknown
/// Initialises the image format
/// - Parameters:
/// - byte: The byte that identifies the format
init(byte: UInt8) {
switch byte {
case 0x89:
self = .png
case 0xFF:
self = .jpeg
case 0x47:
self = .gif
default:
self = .unknown
}
}
/// Returns the mimeType for the image. If image format is png, **image/png** will be returned. If image format is unknown, **nil** will be returned
var mimeType: String? {
switch self {
case .unknown:
return nil
default:
return "image/" + rawValue // Avoid using \()
}
}
}
And can be call like that:
print(myImageData.imageBase64URIOutput)
Decrypt from Base64 format (Swift)
- Base64 is not encryption, it is an encoding.
- The length is incorrect ignoring the enclosing parenthesis, Base64 encoding must be a multiple of 4 characters.
Example:
Deleting the last character to create a valid length.
First decode the Base64 string to Data, then encode to aUTF-8 string.
let base64 = "ew0KICAiTmV3c0dyYXBoIjogWw0KICAgIHsNCiAgICAgICJEYXRlIjogIjA0LUZlYiIsDQogICAgICAiTmV3c1Njb3JlIjogNTAuMCwNCiAgICAgICJUYWJsZU5hbWUiOiAiTmV3c0dyYXBoIg0KICAgIH0sDQogICAg"
let decodedData = Data(base64Encoded: base64)!
let decodedString = String(data: decodedData, encoding: .utf8)
print(decodedString!)
Result:
{
"NewsGraph": [
{
"Date": "04-Feb",
"NewsScore": 50.0,
"TableName": "NewsGraph"
},
It would seem that Base64 string in the question is incomplete and has been truncated.
Decode from Base64 format in swift
finally I found solution for my issue am getting exact out put.
extension Character {
var isAscii: Bool {
return unicodeScalars.allSatisfy { $0.isASCII }
}
}
extension RangeReplaceableCollection where Self: StringProtocol {
var asciiPrintable: Self {
return filter { $0.isAscii }
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let base64Encoded = "oPvvNMsiOd//bheeboamB65AXi8r+go9NLz2rTPEJRU="
let decodedData = Data(base64Encoded: base64Encoded, options: [])
var decodedString: String? = nil
if let decodedData = decodedData {
decodedString = String(data: decodedData, encoding: .ascii)
print(decodedString)
let ascivalue = decodedString!.asciiPrintable
print(ascivalue)
}
}
}
Output:
Optional(" ûï4Ë\"9ßÿn\u{17}n¦\u{07}®@^/+ú\n=4¼ö3Ä%\u{15}")
4"9nn@^/+
=43%
How to convert a base64String to String in Swift?
Try this:
let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="
var decodedString = ""
if let decodedData = Data(base64Encoded: base64Encoded) {
decodedString = String(data: decodedData, encoding: .utf8)!
}
if !decodedString.isEmpty {
print(decodedString)
} else {
print("Oops, invalid input format!")
}
Make sure your base 64 encoded string is valid.
WARNING (edit)
In most base64
decoding implementations like Java
, the padding-character is not needed, but Data(base64Encoded:)
returns nil
if it's missing.
Swift 5 solution; use String.fromBase64(_:)
instead, after implementing like:
extension Data {
/// Same as ``Data(base64Encoded:)``, but adds padding automatically
/// (if missing, instead of returning `nil`).
public static func fromBase64(_ encoded: String) -> Data? {
// Prefixes padding-character(s) (if needed).
var encoded = encoded;
let remainder = encoded.count % 4
if remainder > 0 {
encoded = encoded.padding(
toLength: encoded.count + 4 - remainder,
withPad: "=", startingAt: 0);
}
// Finally, decode.
return Data(base64Encoded: encoded);
}
}
extension String {
public static func fromBase64(_ encoded: String) -> String? {
if let data = Data.fromBase64(encoded) {
return String(data: data, encoding: .utf8)
}
return nil;
}
}
As mentioned on editor's profile,
above edit's code allows Apache 2.0 license as well,
without attribution need.
How to convert a local Video to base64 in swift?
- Get data from file url
- Get Base64 string from data
guard let url = info[.mediaURL] as? URL else { return }
let data = Data(contentsOf: url)
let base64String = data.base64EncodedString()
For upload file to server use Multipart/form-data
, because Base64 has 4/3 of original file size
Related Topics
Swift Uitableviewautomaticdimension Is Not Working
Value' Is Inaccessible Due to 'Internal' Protection Level
Swift Conforming Multiple Protocols Inherits from Same Protocol with Associated Type
How to Use Querystartingatvalue in My Searchcontroller to Search for Users
Convert from Utc to Local Timezone Give Wrong Result
What Does the Snapshot/Observer Code Do in Firebase
Why Does Xcode Line-Out Autocomplete Methods for Selector
How to Check for Value in Firebase That Is Held Under a Autoid Child
Loading Uiviewcontroller from Instantiateviewcontrollerwithidentifier - Nil Outlets
Alamofire 4 Error Request 'Extra Argument in Call'
Getting the Count of an Optional Array as a String, or Nil
Uibuttons Are Not Correctly Shaped on All Devices
Sending Variables with a Segue
What Is the Shortest Way to Run Same Code N Times in Swift
How to Find a Maximum Value in a Swift Dictionary
Bulk Fix Hundreds of "#Selector Not Exposed to Objective-C" Errors in Xcode 9 or 9.1