How can I encode a string to Base64 in Swift?

前端 未结 15 688
情歌与酒
情歌与酒 2020-11-28 02:30

I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in p

相关标签:
15条回答
  • 2020-11-28 03:02

    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 ?? "")")
        }
    }
    
    0 讨论(0)
  • 2020-11-28 03:04

    Swift 3 / 4 / 5.1

    Here is a simple String extension, allowing for preserving optionals in the event of an error when decoding.

    extension String {
        /// Encode a String to Base64
        func toBase64() -> String {
            return Data(self.utf8).base64EncodedString()
        }
    
        /// Decode a String from Base64. Returns nil if unsuccessful.
        func fromBase64() -> String? {
            guard let data = Data(base64Encoded: self) else { return nil }
            return String(data: data, encoding: .utf8)
        }
    }
    

    Example:

    let testString = "A test string."
    
    let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="
    
    guard let decoded = encoded.fromBase64() // "A test string."
        else { return } 
    
    0 讨论(0)
  • 2020-11-28 03:05

    After all struggle I did like this.

    func conversion(str:NSString)
    {
    
        if let decodedData = NSData(base64EncodedString: str as String, options:NSDataBase64DecodingOptions(rawValue: 0)),
            let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
    
            print(decodedString)//Here we are getting decoded string
    

    After I am calling another function for converting decoded string to dictionary

            self .convertStringToDictionary(decodedString as String)
        }
    
    
    }//function close
    

    //for string to dictionary

    func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
    
                print(json)
                if let stack = json!["cid"]  //getting key value here
                {
                    customerID = stack as! String
                    print(customerID)
                }
    
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
    
    0 讨论(0)
提交回复
热议问题