How to convert Base64 data and NSData into string - ios

i am new in IOS and i am making a project in which i receive Base64 data from web service. how to convert Base64 data into string and how to open a pdf view in swift and also check that is there any pdf owner application install or not in iPhone .and i want to know that how to convert NSDATA in string swift.Help me
example like this is Base64 data
JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s//vj
Like this is nsdata
<25504446 2d312e34 0a25c7ec 8fa20a35 2030206f 626a0a3c 3c2f4c65 6e677468 20362030 20522f46 696c7465 72202f46 6c617465 4465636f 64653e3e 0a737472 65616d0a 789cb55c cdaf1cb7 9187d6b2 bd7a3214 db89643b 91ad27cb d69b913c

There are two parts to this question. First, converting the base 64 string into a Data/NSData. But you've done that already, so you don't need help there.
Second, converting that Data/NSData into a string. But, if you look at that file carefully, you'll see that data is a PDF file, not a text string. For example, if I save that as a file and look at it in a hex editor, I can clearly see it's a PDF:
You can't just convert that PDF binary data to a string. (In fact, that's why it was base64-encoded in the first place, because it was complex binary data.)
But you can, for example, use UIDocumentInteractionController to preview the PDF file that you saved to a file.
For example:
// convert base 64 string to data
let base64 = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s/"
guard let data = Data(base64Encoded: base64) else {
print("unable to convert base 64 string to data")
return
}
// given the data was PDF, let's save it as such
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("test.pdf")
try! data.write(to: fileURL)
// if it was a string, you could convert the data to string, but this will fail
// because the data is a PDF, not a text string
//
// guard let string = String(data: data, encoding: .utf8) else {
// print("Unable to convert data into string")
// return
// }
// print(string)
// So, instead, let's use `UIDocumentInteractionController` to preview the PDF:
let controller = UIDocumentInteractionController(url: fileURL)
controller.delegate = self
controller.presentPreview(animated: true)
Where, the view controller conforms to UIDocumentInteractionControllerDelegate:
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
// or, if this view controller is already in navigation controller, don't
// return `self`, like above, but instead return the navigation controller itself
//
// return navigationController!
}
}

From Base64 to Data to String.
let base64String = "dGhpcyBpcyBmb3IgdGVzdGluZw=="
if let data = Data(base64Encoded: base64String) {
if let string = String(data: data, encoding: .utf8) {
print(string)
}
}
From Base64 to NSData to String.
let data = NSData(base64Encoded: base64String, options: .ignoreUnknownCharacters)
var string = String(data: data, encoding: .utf8)
}

Swift 3.0
A handy extension of string. Hope will help you.
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}

Related

Text with emoji is not decoding - iOS Swift

I have used the following code to encode/decode the string which has emojis.
extension String {
func encodeEmoji() -> String {
let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
func decodeEmoji() -> String? {
let data = self.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
}
I have called this function like this below. Converted the response in the 'User' model.
let user = User() // Loaded API's response in this model
let textWithEmoji = user.aboutMe.decodeEmoji() //Here, I am getting the string as the same as before decoding
lblAboutMe.text = textWithEmoji
Following is the encoded string which is not decoding:
"I love too...\n\u2705 Laugh \uD83D\uDE02\n\u2705 Read novels \uD83D\uDCDA\n\u2705 Watch movies \uD83C\uDFAC\n\u2705 Go for bike rides \uD83D\uDEB5\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Go for long walks \uD83D\uDEB6\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Cook \uD83D\uDC69\uD83C\uDFFD\u200D\uD83C\uDF73\n\u2705 Travel \uD83C\uDDEA\uD83C\uDDFA\uD83C\uDDEE\uD83C\uDDF3\uD83C\uDDEC\uD83C\uDDE7\n\u2705 Eat \uD83C\uDF2E\uD83C\uDF5F\uD83C\uDF73\n\u2705 Play board games \u265F\n\u2705 Go to the theatre \uD83C\uDFAD\nMy favourite season is autumn \uD83C\uDF42, i love superhero movies \uD83E\uDDB8\u200D\u2642\uFE0F and Christmas is the most wonderful time of the year! \uD83C\uDF84"
Here is the original text image:
The string you are using is invalid ("I love too...\n\u2705 Laugh \uD83D\uDE02\n\u2705 Read novels \uD83D\uDCDA\n\u2705 Watch movies \uD83C\uDFAC\n\u2705")
It should be in valid String literal
"\\uD83D\\uDCDA\\u2705"
You have a string non-BMP characters in form of JSON String. And your decodeEmoji cannot convert them into valid characters.
So we need to forcefully convert such strings.
extension String {
var jsonStringRedecoded: String? {
let data = ("\""+self+"\"").data(using: .utf8)!
let result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! String
return result
}
}
After that you need to decode emoji from above string using below function.
extension String {
var decodeEmoji: String? {
let data = self.data(using: String.Encoding.utf8,allowLossyConversion: false);
let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
if decodedStr != nil{
return decodedStr as String?
}
return self
}
}
Usually JSON decoder can decode these type of characters into emoji
May be there is chances of invalid JSON
First need to verify these things that json is valid or not before using.
USAGE:
let jsonDecodedString = "Your string".jsonStringRedecoded
let decodedEmojiText = jsonDecodedString?.decodeEmoji
debugPrint("\(decodedEmojiText)")

Cannot convert value of type 'NSData?' to type 'Data' in coercion

Im trying to convert a base64 string to an UIImage
First. I decode the String as shown below
let decodedData = NSData(base64Encoded: decodeIMG, options: NSData.Base64DecodingOptions(rawValue: 0))
Then I try to convert the decoded data to an UIImage like this:
let decodedIamge = UIImage(data: decodedData as Data)
But on that line I get the following error:
Cannot convert value of type 'NSData?' to type 'Data' in coercion
I already tried using another approach to convert it by using an extension that looks like this
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
And get this error
Incorrect argument label in call (have 'base64Encoded:', expected
'map:')

Swift convert NSMutableArray in string format to NSMutableArray

Hey guys so I create a NSMutableArray send it to my mysql server convert it to base64, then when the app reads the data, it decodes the base64 code into a string format. Now im trying to convert the string back into an NSMutableArray. I cant seem to get it work heres the code that converts it to a string.
let string = String(data: (Data(base64Encoded:((data?.value(forKey: "14112017") as! NSArray)[0] as! NSDictionary)["data"] as! String)!), encoding: .utf8)!
So the answer to my question ended up converting my array to a JSONstring first which I did by using:
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: UniversalArray)
let jsonString = String(data: jsonData!, encoding: .utf8)
then when retreiving it I get back my jsonString, however it has "\" which I replace using:
let cleanJsonString = myData.replacingOccurrences(of: "\\", with: "")
then to finally finish it off I just send this cleanJsonString to this function:
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: [])
} catch {
print(error.localizedDescription)
}
}
return nil
}
when calling this function I used this:
let array = convertToDictionary(text: myMutableArray) as? [AnyObject]
Thanks everyone for the amazing support, heres the answer to this bogus mess I created.
There are 2 parts to this: Serializing your array for transmission to your server, and then deserializing it from the server.
We need to see the code you use to serialize your array first. (The code that converts it to a string.) Based on what you post, it appears to be in JSON format. If so you may be able to skip the base64 encoding step, depending on what you're doing with the data. JSON is a good format for transmission to remote servers. You don't typically base64 encode JSON before transmission.
If you are receiving JSON that was then base64 encoded, you'll need to un-encode it back to data, and then use the JSONSerializer class to convert the JSON back to objects like arrays or dictionaries:
let data = Data(base64Encoded: base64DataFromServer)
guard let object = try? JSONSerialization.jsonObject(with: data) else {
return nil
}
(Note that the JSON you posted contains a dictionary as the top-level object, not an array.)

how to create GIF from base64 string in swift

I am getting base64 string with extension and I want to convert base64 string to GIF and display it in ImageView. I am using iOSDevCenters+GIF.swift file. I am getting NSData from string but when data converted in image, its giving nil.Below is my code:
let imageData = profileImageString.data(using: .utf8)
self.thumbnailMedia.image = UIImage.gifImageWithData(imageData!)
Does anybody have any ideas on how to do this?
If you are starting from a base64 string, you should decode it as a base64 string not UTF8.
if let data = Data(base64Encoded: imageDataString) {
let image = UIImage(data: data)
}
This snippet simply takes the encode image string, decode into a Data object and create an image from the data.
If you are working a lot using base64 string I strongly suggest you to extend the String structure functionalities.
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
This snippet was taken from Github, credits to Stringer.
Also another way is use the extension created by Leo Dabus that is compliant with Swift convention:
extension String {
var data: Data { return Data(utf8) }
var base64Encoded: Data { return data.base64EncodedData() }
var base64Decoded: Data? { return Data(base64Encoded: self) }
}
extension Data {
var string: String? { return String(data: self, encoding: .utf8) }
}

How to convert Data received from UIImagePNGRepresentation() to String and vice versa?

This is how I create Data from UIImage:
let data = UIImagePNGRepresentation(image)
And then I need to convert it to String;
if let data = data {
let stringFromData = String(data: data, encoding: .utf8)
}
but stringFromData is nil. Why?
You can get it using the Data method base64EncodedString()
if let data = data {
let stringFromData = data.base64EncodedString()
// to decode base 64 string you can use Data base64Encoded String initializer
if let dataFromBase64 = Data(base64Encoded: stringFromData) {
print(data)
}
}
Convert Your image data in Base64 string
For Encode
let stringFromData : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
And decode
let strBase64 = imageData.base64EncodedStringWithOptions(.allZeros)

Resources