Error with encoding a base64 String - ios

I have the following code:
#IBAction func loadData(sender: AnyObject) {
let plainString = "foo"
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // Zm9v
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // foo
}
But i got the error: NSData? does not have a member named "base64EncodeString withOptions
what i have to change in the code?

Related

Issue in converting Base64string into string

I am trying to convert base64 string in to string format but I always get nil. My base64 string is "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
After decoding, Is suppose to look like this "5d0056f8bf4cbb63c1e2474360123130208|60123130208|5d0056f8bэ͌Ŕ٥ѥQشĂs3C�".
Here is my code event I tried to remove the "=\n" from string but not succeed.
func qrScanningSucceededWithCode(_ str: String?) {
scanTicketView.qrData = QRData(codeString: str)
let charsToRemove: Set<Character> = Set("=\n")
let newNumberCharacters = String(str!.filter { !charsToRemove.contains($0) })
let decodedString = String(data: Data(base64Encoded: newNumberCharacters)!, encoding: .utf8)!
print(decodedString)
}
This works:
let string = "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
let joined = string.replacingOccurrences(of: "\n", with: "")
if let data = Data(base64Encoded: joined) {
String(data: data, encoding: .utf8)
}

Swift 2.3 - Decode Emoji String [duplicate]

I'm trying to encode and decode Emojis to send them to my database.
I use this to encode:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}
And it works. But now I don't know how to decode the emoji.
This is the type of encode ---> \ud83d\ude1a
Your encoding code can be simplified to
func encode(_ s: String) -> String {
let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
Note that it encodes all non-ASCII characters as \uNNNN, not only
Emojis. Decoding is done by reversing the transformations:
func decode(_ s: String) -> String? {
let data = s.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
This returns an optional because it can fail for invalid input.
Example:
let s = "Hello 😃."
let e = encode(s)
print(e) // Hello \ud83d\ude03.
if let d = decode(e) {
print(d) // Hello 😃.
}
Of course you can also define the code as extension methods of the
String type, and you might want to choose better function names.
I fixed this. If you have a server with encode utf8mb4, then for encoding emojis use this code:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}// comentario contains the emoji encoded
DECODING:
let data = comentarios.data(using: String.Encoding.utf8, allowLossyConversion: false)
if data != nil{
let valueunicode = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String
if valueunicode != nil{
comentarios = valueunicode!
}
}//comentarios contantes the deecode string(emoji)

How to convert JSON response string to in JSON object using Swift 3.1?

I am struggling with Swift 3. I am getting (hexString) response from server in encrypted form and I am first converting it into Data.
Below is my method to converting hexString to in Data:
extension String {
func dataFromHexadecimalString() -> Data? {
var data = Data(capacity: characters.count / 2)
let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in
let byteString = (self as NSString).substring(with: match!.range)
var num = UInt8(byteString, radix: 16)!
data.append(&num, count: 1)
}
guard data.count > 0 else {
return nil
}
return data
}
}
After that I am Decrypting the data using CryptoSwift framework. Here below is my method to decrypt the data :-
func getAllShops(data : [String : AnyObject]) {
AFWrapper.sharedInstance.requestPOSTURL(My_URL, params: data, headers: nil, success: {(json) in
// Key for AES
let key = "My_Key"
// Iv for AES
let iv = "My_IV"
//Hex String from Server Response
let str = json["encrypted"].string!
do {
//Converting Hex String to Data
let dataStr = str.dataFromHexadecimalString()
//Decrypt the Data
let decryptedData = try AES(key: key, iv: iv, blockMode: .CBC, padding: NoPadding()).decrypt(dataStr!)
//Getting json string Response
var jsonResponse = String(bytes: decryptedData, encoding: .utf8)!
/*let response = JSON(jsonResponse)
print(response)
let validJson = JSONSerialization.isValidJSONObject(response)//(JSONSerialization.JSONObjectWithData(jsonData, options:nil, error: &error) != nil)
print("Valid JSON: \(validJson)")*/
/*let data = jsonResponse.data(using: String.Encoding.utf8)
let jsonsdd = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print(jsonsdd)*/
}
catch {
print(error)
}
}, failure: {(Error) in
print(Error.localizedDescription)
})
}.
I am trying to convert that json String to in JSON object so that I can parse the data.
I tried with swiftyJSON and JSONSerialization in my code that part is commented. but not able to convert it.
I guess I am missing small thing that I don't know.

Decode base64 + decrypt - Swift

let originalMsg:String = "THIS IS A TEST"
let sessionData = originalMsg.dataUsingEncoding(NSUTF8StringEncoding)
var encryptedPublic:NSData = RNCryptor.encryptData(sessionData!, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
var base64EncodedPublic:NSData = encryptedPublic.base64EncodedDataWithOptions([])
var encryptedPrivate = RNCryptor.encryptData(base64EncodedPublic, password: privateKey)
var base64EncodedString:String = encryptedPrivate.base64EncodedStringWithOptions([])
How would you decode + decrypt base64EncodedString to get the original input? I think I am struggling with the base64 decoding.
This is how you get a UTF-8 encoded NSString from a base64 string in Swift 2:
let decodedData = NSData(base64EncodedString: base64EncodedString,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
But if you want to decrypt, you'll just want the data:
do {
let decodedData = NSData(base64EncodedString: base64EncodedString,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decryptedPrivate = RNDecryptor.decryptData(decodedData, password: privateKey)
let decodedPrivate = NSData(base64EncodedData: decryptedPrivate,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decryptedPublic = RNDecryptor.decryptData(decodedPrivate, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
let decryptedMessage = NSString(data: decryptedPublic, encoding: NSUTF8StringEncoding) as String
} catch {
// handle decryption errors...
}

NSData base64Encode return nil swift

i tryed
let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents,
options:NSDataBase64DecodingOptions())
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions(rawValue: 0)!)
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
always EXC_BAC_INSTRUCTION from decodedString
maybe decodedData return nil
why NSData return nil
Use .Encoding64CharacterLineLength as option, and apply .base64EncodedStringWithOptions to the data:
if let contents = results["contents"] as? String,
decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions(rawValue: 0)) {
let decodedString = decodedData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
You're using so many force unwrap operators (!); don't do this!
What if results has no mapping for the "contents" key?
What if results has a mapping for the "contents" key but it isn't a String?
What if results has a mapping for the "contents" key, and it is a String, but it's not valid Base 64 encoded data? In this case, NSData's initialization will fail, and return nil.

Resources