NSDictionary to NSData and NSData to NSDictionary in Swift
You can use NSKeyedArchiver
and NSKeyedUnarchiver
Example for swift 2.0+
var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0]
let dataExample : NSData = NSKeyedArchiver.archivedDataWithRootObject(dictionaryExample)
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample)! as? NSDictionary
Swift3.0
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]
Screenshot of playground
How can I convert NSDictionary to NSData and vice versa?
NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
Convert nsdictionary to nsdata
You can use an NSKeyedArchiver to serialize your NSDictionary to an NSData object. Note that all the objects in the dictionary will have to be serializable (implement NSCoding at some point in their inheritance tree) in order for this to work.
Too lazy to go through my projects to lift code, so here is some from the Internet:
Encode
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
/** data is ready now, and you can use it **/
[data release];
Decode:
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
Converting NSData to NSDictionary
You have to convert NSData
into UTF8 before parsing it using NSJSONSerialization
.
NSError* error = nil;
NSString *strISOLatin = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSData *dataUTF8 = [strISOLatin dataUsingEncoding:NSUTF8StringEncoding];
id dict = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:0 error:&error];
if (dict != nil) {
NSLog(@"Dict: %@", dict);
} else {
NSLog(@"Error: %@", error);
}
converting NSDictionary object to NSData object and vice-versa
use NSKeyedArchiver
To convert NSDictionary To NSData
NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];
[data writeToFile:YOURFILEPATH atomically:YES];
[data release];
[archiver release];
To get the NSDictionary back from the stored NSData
NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
Cannot convert Data to NSDictionary
[ ]
means array in JSON. { }
means dictionary. You have an array of dictionary. Note that when you print an array in Swift, you will see ( )
.
Don't use NSArray
or NSDictionary
in Swift without a very clearly understood and specific reason. Use a Swift array and dictionary of the proper types.
Your code should be:
do {
if let results = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
// results is now an array of dictionary, access what you need
} else {
print("JSON was not the expected array of dictonary")
}
} catch {
print("Can't process JSON: \(error)")
}
And really you shouldn't be using data!
either. Somewhere above this you should have a if let data = data {
How to change an NSData to an NSDictionary or JSON
A very standard way to convert to JSON from NSData, feel free to ask a question
self.get(url).responseJSON { (response) -> Void in
self.notify(FetchCompletion, response: response.response, result: response.result)
print("response: ")
print(response.response)
print("data: ")
let dataExample = response.data
print(dataExample)
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(dataExample!, options: NSJSONReadingOptions()) as! NSDictionary
}
catch {
// catch error.
}
}
convert JSONresponse to NSDATA or NSDICTIONARY in swift4
You are already using Alamofire as your network requester, So it is not necessary to convert the response object to JSON object or Data object. The library itself will provide to parsed JSON object. So check the below sample code to check the JSON object.
let urlString = "https://......"
let securityToken: String = "Basic YWFnZTQxNDAxMjgwODYyNDk3NWFiYWNhZjlhNjZjMDRlMWY6ODYyYTk0NTFhYjliNGY1M2EwZWJiOWI2ZWQ1ZjYwOGM="
var headers: HTTPHeaders = [:]
headers["Authorization"] = securityToken
let parameters: Parameters = ["city": 100, "minutesBehind" : 60, "miutesAhead" :0]
Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
if let jsonObject = response.result.value{
print("response.result.value \(String(describing: jsonObject))")
}
if let jsonObject = response.value{
print("response.value \(String(describing: jsonObject))")
}
}
Related Topics
Swift - Json Error: the Data Couldn'T Be Read Because It Isn'T in the Correct Format
Uistackview Hiding/Unhiding Arrangedsubview Issue
Determine Device (Iphone, Ipod Touch) With Ios
Adjust Uilabel Height Depending on the Text
Bold & Non-Bold Text in a Single Uilabel
Ios 8 Uitableview Separator Inset 0 Not Working
Starting Iphone App Development in Linux
Undefined Symbols For Architecture I386: _Objc_Class_$_Skpsmtpmessage", Referenced From: Error
Iphone Keyboard Covers Uitextfield
How to Change Uipickerview Height
Updating Configuration Profile Installed in iOS Device in Mdm
How to Determine the Current Iphone/Device Model
How to Apply a Perspective Transform to a Uiview
Figure Out Size of Uilabel Based on String in Swift
Uiscrollview Scrollable Content Size Ambiguity