I want to array string to base64 and then back to the string
I try the following
let array = [[1,2,"preved"], [3,4,"hola"], [5,6,"poka"]]
let encodedData = NSKeyedArchiver.archivedData(withRootObject: array)
let base64String = encodedData.base64EncodedString()
let data = Data(base64Encoded: base64String)
let decodedData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(decodedData)
problem is that decoded data prints back nil
What am I doing wrong ?
When using NSKeyedArchivercoder , NSKeyedUnarchiver decoder should be also used:
NSKeyedArchiver, a concrete subclass of NSCoder, provides a way to
encode objects (and scalar values) into an architecture-independent
format that can be stored in a file. When you archive a set of
objects, the class information and instance variables for each object
are written to the archive. The companion class NSKeyedUnarchiver
decodes the data in an archive and creates a set of objects equivalent to the original set.
-In the simplest way- as follows:
let array = [[1,2,"preved"], [3,4,"hola"], [5,6,"poka"]]
let encodedData = NSKeyedArchiver.archivedData(withRootObject: array)
if let decodedArray = NSKeyedUnarchiver.unarchiveObject(with: encodedData) as? [Any] {
// ...
}
Note that since array data type is [Array<Any>], you should cast it as [Any]
Related
I am new to the swift language. I am trying to fetching some data from an API call and response to that API is "{"status":1,"msg":"Please enter Mobile number"}"
I have the above response in a string How can I convert this string to JSONObject and then parse it and get status value?
I am an android developer we have evaluate expression while debugging code is there some like in Xcode so I can execute some code run time
I suggest use SwiftyJson library .
first create a model from your json using http://jsoncafe.com
you can parse data and model it using the following code
let json = JSON(response)
let message = Message(fromJson: json )
then you have access to your variable => message.status
JSONSerialization is the tool you are looking for. It handles converting JSON into objects, and objects into JSON. If you receive a JSON string represented as Data, you can pass it into JSONSerialization.jsonObject(with:options:)
If you are wanting to convert Data into an object:
//Where 'data' is the data received from the API call
guard let jsonObject = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]) else {
return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String
If you are wanting to convert String into an object:
//Where 'string' is the JSON as a String
guard let jsonObject = try? (JSONSerialization.jsonObject(with: string.data(using: .utf8), options: []) as! [String:Any]) else {
return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String
Source: https://developer.apple.com/documentation/foundation/jsonserialization
As a Swift newcomer, I am very confused about how to parse some JSON data obtained from an API. I am able to get the JSON data from the api using an alamofire request. At this point, I think I have an NSDictionary object, JSON as print(JSON) logs to console a good deal of JSON.
if let result = response.result.value {
let JSON = result as! NSDictionary
print("this is what JSON is")
print(JSON)
My question is, first, is JSON in fact an NSDictionary. Second, how would I access a value in the JSON. Do I need to first convert this to a data object. Or how do I get at the nested data.
For example, let's say the JSON looks like this:
{
"contact": {
"first": "Bob",
"second":"Jones"
}
}
I came across this code on SO:
let data = JSON(data: JSON)
print("data\(data["contact"]["first"])")
But it throws an error. I have swiftyJSON installed but happy for solution with or without it.
Thanks in advance for any suggestions
Can you try
if let result = response.result.value as? [String:Any] {
if let contact = result["contact"] as? [String:Any] {
if let first = contact["first"] as? String {
print(first)
}
}
}
also this
let data = JSON(data: JSON)
gives error because parameter should be of type Data not Dictionary
I would prefer to return Data from Alamofire request and use Decodable to parse it and convert to required model
TRY THIS!
if let data = response.data {
let jsonData = JSON(data: data)
print("data : \(jsonData["contact"]["first"].string)")
}
Swift4 introduce amazing Codable protocol.
Using Codable, we can model JSONObject or PropertyList file into equivalent Struct or Classes by writing very few lines of code.
There are many online tool available which creates model class from you JSON
(http://www.json4swift.com/)
Example
let decoder = JSONDecoder()
let parsedObject = try decoder.decode(Class.self, from: data)
You can find detail at below link:
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
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.)
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()
}
}
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)