2

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 ?

3
  • 1
    You are missing the reverse of NSKeyedArchiver => NSKeyedUnarchiverArchiver. Commented Jul 24, 2017 at 12:21
  • 2
    It is returning nil because you are base64 encoding the data from NSString but trying to construct it back using normal NSString initialiser. To get back the string use data!.base64EncodedString() Commented Jul 24, 2017 at 12:30
  • Replace create decodedData from NSString to if let data = Data(base64Encoded: base64String) { let decodedData = NSKeyedUnarchiver.unarchiveObject(with: data) print(decodedData) } Commented Jul 24, 2017 at 12:58

1 Answer 1

5

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.