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.
Related
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)
}
I have a NSData object which needs to be converted to [String:Any] and here is the code I tried:
let multiOrder = _fields["multiOrder"] as? GPBValue
if let _ = multiOrder {
let data = NSKeyedArchiver.archivedData(withRootObject: multiOrder!)
if let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
}
GPBValue object looks like NSObject<NSSecureCoding, NSCopying>
But the above code is returning nil
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...
}
I want to parse a CSV file to create a String.
I fetch the data with the Dropbox API. Let's say my CSV file contains a simple word: "école". When I try to create a String I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.
My code:
client.files.download(path: "/\(selectedFile)", destination: destination).response { response, error in
if let (_, url) = response {
let data = NSData(contentsOfURL: url)
print("data: \(data!)")
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
let csv = CSwiftV(String: myString)
} else {
print(error!)
}
}
The print("data: \(data!)") works well, it prints a bunch of hexadecimal. So I understand my data are not nil (right?).
If my CSV file contains the word "ecole" instead of "école" it works perfectly. But as far as I know, UTF-8 encoding should support special character no?
It means that your data is encoded in other code rather NSUTF8StringEncoding decode it with the same encoding
For Example
let string = "école"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String //This is OK
let string = "école"
let data = string.dataUsingEncoding(NSUnicodeStringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String // This will not work and myString will be nil
And please try to avoid force Unwrap (!) even if you are sure that you have data there, because you can have a crash next time you use !
I would do it like this instead:
guard let data = NSData(contentsOfURL: url),
let myString = NSString(data: data, encoding: NSUTF8StringEncoding) else {
print("something terrible happened treat error")
}
let csv = CSwiftV(String: String(myString))
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?