Rectangle 27 14

Here is code to convert between JSON and NSData in swift 2.0 (adapted from Shuo's answer)

// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

@SunilTarge Xcode does a fair job of converting it for you if you follow the warnings, that way you'll also quickly pick up the differences between Swift 2 and 3.

xcode - Converting JSON to NSData, and NSData to JSON in Swift - Stack...

json xcode swift nsdata
Rectangle 27 10

I have no idea on SwiftyJSON. I use following code snippet to convert between json and nsdata

// Convert from NSData to json object
public class func nsdataToJSON(data: NSData) -> AnyObject? {
    return NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil)
}

// Convert from JSON to nsdata
public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}

Thanks for your response Shuo, I'm not sure how to use your solution, ie how do I pass in the key 'encryptedData' to identify the data I want to get back? Thanks for your help!

xcode - Converting JSON to NSData, and NSData to JSON in Swift - Stack...

json xcode swift nsdata
Rectangle 27 14

In SwiftyJSON you can use rawData method to get NSData:

if let encryptedData:NSData = json["encryptedData"].rawData() {
    NSLog(NSString(data: encryptedData, encoding: NSUTF8StringEncoding)!)
}

To generate JSON as you want you should convert data to array object:

if let encryptedDataArray = JSON(data: encryptedData).arrayObject {
    let jsonObject:JSON = [
        "transactionID" : 12345,
        "encryptedData" : encryptedDataArray
    ]
    NSLog(NSString(data: jsonObject.rawData()!, encoding: NSUTF8StringEncoding)!)
}

Hi Tish, thank you very much for your response. Unfortunately SwiftyJSON does not support 'rawValue()'. I would had expected SwiftyJSON to support something like this.

It does according to documentation. But rawValue is not a method, it is a property. Unlike a rawData() method which you can see in my response. You can find examples at GitHub documentation: github.com/SwiftyJSON/SwiftyJSON#raw-object

xcode - Converting JSON to NSData, and NSData to JSON in Swift - Stack...

json xcode swift nsdata
Rectangle 27 3

@Sunil Targe here is the Swift3 version. Hope this helps. (Adapted from Ciprian Rarau's answer)

func dataToJSON(data: Data) -> Any? {
   do {
       return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
   } catch let myJSONError {
       print(myJSONError)
   }
   return nil
}
func jsonToData(json: Any) -> Data? {
    do {
        return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

Thanks you. Note, this can be done in one single line of code, by returning try? (for those who don't need to print myJSONError).

xcode - Converting JSON to NSData, and NSData to JSON in Swift - Stack...

json xcode swift nsdata
Rectangle 27 5

Instead of converting your NSData to String, you can use NSData as it is.

import Foundation

var error: NSError?
let jsonData: NSData = response.responseObject

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

good point! I did not think of that

No issues. Happy to be of help. :)

ios - Swift - Unable to create JSON object from NSData - Stack Overflo...

ios json swift nsdata
Rectangle 27 72

UIImage(data:imageData,scale:1.0)

Yea that does the job. Many thanks

ios - Convert UIImage to NSData and convert back to UIImage in Swift? ...

ios swift uiimage nsdata
Rectangle 27 4

Here is a code to make the conversions between JSON and NSData in Swift 2.0

// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

ios - How to parse a JSON file in swift? - Stack Overflow

ios swift
Rectangle 27 30

Thanks. Helped me a lot. Converted to Swift 3 and worked

let data = UIImagePNGRepresentation(image) as NSData?
let imagePt = UIImage(data: (caminhodaImagem as! NSData) as Data)
let imagePt = UIImage(data: caminhodaImagem)

ios - Convert UIImage to NSData and convert back to UIImage in Swift? ...

ios swift uiimage nsdata
Rectangle 27 22

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

ios - Convert UIImage to NSData and convert back to UIImage in Swift? ...

ios swift uiimage nsdata
Rectangle 27 2

You need to change a couple things. First, you are using NSData. You should be using the Swift type Data. To convert from NSData? to Data?, just add as Data? to the end of the variable declaration.

Also, Your type is optional, but you can't pass in an optional type, so you need to unwrap it (using, in this example, if let data = data { /* stuff here */}):

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL) as Data? // <==== Added 'as Data?'
    if let data = data { // <====== Added 'if let'
        let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
        if let result = json["results"] as? Dictionary {
            if let address = result[0]["address_components"] as? Array {
                let number = address[0]["short_name"] as! String
                let street = address[1]["short_name"] as! String
                let city = address[2]["short_name"] as! String
                let state = address[4]["short_name"] as! String
                let zip = address[6]["short_name"] as! String
                weatherDisplay.text = "\(city),\(state)"
            }
        }
    }
}
let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary

When you cast to the type Dictionary, the compiler does not know what you are talking about because Dictionary is a generic type. So you need to cast to Dictionary<String, AnyObject> or [String: AnyObject] (They are the same).

Thanks for the quick response! Now it's saying (on the let = json line) "Generic Parameter 'key' could not be inferred in cast to 'Dictionary<_,_>"

now, on the line if let address = result[0]["address_components"] as? Array {, it says "Ambiguous reference to member 'subscript'". Is there something else I should add/change?

@EricPhillips Not sure. I do know that the Array type is like the Dictionary type. You need to add what type the array is, i.e. Array<String>. If you have more questions, I would suggest Googling then asking a new question on SO (Stack Overflow).

ios - How to convert NSData to Data in Swift 3? - Stack Overflow

ios json swift xcode
Rectangle 27 2

You need to change a couple things. First, you are using NSData. You should be using the Swift type Data. To convert from NSData? to Data?, just add as Data? to the end of the variable declaration.

Also, Your type is optional, but you can't pass in an optional type, so you need to unwrap it (using, in this example, if let data = data { /* stuff here */}):

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL) as Data? // <==== Added 'as Data?'
    if let data = data { // <====== Added 'if let'
        let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
        if let result = json["results"] as? Dictionary {
            if let address = result[0]["address_components"] as? Array {
                let number = address[0]["short_name"] as! String
                let street = address[1]["short_name"] as! String
                let city = address[2]["short_name"] as! String
                let state = address[4]["short_name"] as! String
                let zip = address[6]["short_name"] as! String
                weatherDisplay.text = "\(city),\(state)"
            }
        }
    }
}
let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary

When you cast to the type Dictionary, the compiler does not know what you are talking about because Dictionary is a generic type. So you need to cast to Dictionary<String, AnyObject> or [String: AnyObject] (They are the same).

Thanks for the quick response! Now it's saying (on the let = json line) "Generic Parameter 'key' could not be inferred in cast to 'Dictionary<_,_>"

now, on the line if let address = result[0]["address_components"] as? Array {, it says "Ambiguous reference to member 'subscript'". Is there something else I should add/change?

@EricPhillips Not sure. I do know that the Array type is like the Dictionary type. You need to add what type the array is, i.e. Array<String>. If you have more questions, I would suggest Googling then asking a new question on SO (Stack Overflow).

ios - How to convert NSData to Data in Swift 3? - Stack Overflow

ios json swift xcode
Rectangle 27 8

import UIKit

func base64StringForImage(image: UIImage) -> String? {
    guard let data = UIImagePNGRepresentation(image) else { return nil }
    return data.base64EncodedStringWithOptions([])
}

func imageFromBase64String(string: String) -> UIImage? {
    guard let data = NSData(base64EncodedString: string, options: []) else { return nil }
    return UIImage(data: data)
}

here is the implementation in objc:

#import <UIKit/UIKit.h>

NS_INLINE NSString * base64StringForImage_objc(UIImage *image) {
    NSData *imageData = UIImagePNGRepresentation(image);
    return [imageData base64EncodedStringWithOptions:0];
}

NS_INLINE UIImage * imageFromBase64String_objc(NSString *string) {
    NSData *imageData = [[NSData alloc] initWithBase64EncodedString: string options: 0];
    return [[UIImage alloc] initWithData:imageData];
}

ios - UIImage encoded to NSData in ObjectiveC and then decoded in Swif...

ios objective-c swift uiimage nsdata
Rectangle 27 3

To save as data:

From StoryBoard, if you want to save "image" data on the imageView of MainStoryBoard, following codes will work.

let image = UIImagePNGRepresentation(imageView.image!) as NSData?

To load "image" to imageView: Look at exclamation point "!", "?" closely whether that is quite same as this one.

imageView.image = UIImage(data: image as! Data)

"NSData" type is converted into "Data" type automatically during this process.

ios - Convert UIImage to NSData and convert back to UIImage in Swift? ...

ios swift uiimage nsdata
Rectangle 27 6

// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
import Foundation
//: # NSData to String Conversion Playground
//: ### Step 1
//: The first step is to take an array of bytes and conver them into a NSData object.  The bytes are as follows:

// Hello World
var testBytes : [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]

//: ### Step 2
//: Convert the byte array into an **NSData** Object

var immutableData = NSData(bytes: testBytes, length: testBytes.count)

//: ### Step 3
//: Attempt to convert the **NSData** object into a string so it can be sent around as ascii.  This for some reason seems to be failing, however.

var convertedString = NSString(data: immutableData, encoding: NSUTF8StringEncoding)

println("String = \(convertedString)")
"String = Optional(Hello World)"
String(data: immutableData, encoding: NSUTF8StringEncoding)

ios - NSData to String in Swift Issues - Stack Overflow

ios xcode swift nsdata
Rectangle 27 1

I realise that the question is using Swift 2, but since there are no answers and everyone should be using Swift 3, here is the Swift 3 solution.

func preloadData(){

    func failed(msg: String){

        let alert = UIAlertController(title: "Error", message: msg, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

        self.addChildViewController(alert)
    }

    guard let navigationController = self.window!.rootViewController as? UINavigationController else { failed(msg: "The root view controller is not a UINavigationController"); return }

    guard let masterController = navigationController.childViewControllers[0] as? PlayerViewController else { failed(msg: "There is no PlayerViewController"); return }

    guard let url = URL(string: "Whatever your URL is") else { failed(msg: "This is an invalid URL"); return }

    guard let contents = try? Data(contentsOf: url) else { failed(msg: "Cannot retrieve data from this URL"); return }

    guard let json = try? JSONSerialization.jsonObject(with: contents, options: .mutableContainers) else { failed(msg: "Contents is not in JSON format."); return }

    guard let dict = json as? Dictionary<String,Any> else { failed(msg: "Cannot convert JSON to dictionary."); return }

    guard let players = dict["Players"] as? Array<Dictionary<String,String>> else { failed(msg: "There is no players."); return }

    for player in players {

        guard
            let firstName   = player["First Name"],
            let lastName    = player["Last Name"],
            let position    = player["Position"],
            let bats        = player["Bats"],
            let _throws     = player["Throws"],
            let height      = player["Height"],
            let weight      = player["Weight"],
            let dob         = player["DOB"],
            let number      = player["Number"] else { continue }

        masterController.objects.append(Player(firstName: firstName, lastName: lastName, position: position, bats: bats, throws: _throws, height: height, weight: weight, dob: dob, number: number))

    }
}

swift - Converting JSON NSData to a dictionary - Stack Overflow

json swift nsdata
Rectangle 27 2

kinda late but this happened to me today and I solved it like this, inside the completionHandler:

if let data = content {
        self.imageData = UIImage(data: NSData(contentsOfURL: data as! NSURL)!)                      
  }

ios - Converting NSSecureCoding to NSData - Xcode - Swift - Stack Over...

ios objective-c xcode swift nsdata
Rectangle 27 2

let responseString = String(data: data!, encoding: NSUTF8StringEncoding) does not apply any magic on the response, it just converts the bytes sent by the server to characters. If you don't see something you'd expect to see, that's because the server doesn't send it.

You are absolutely correct. I took a closer look at the JSON that is sent in the original request and it is missing 2 [ ] brackets. I have this:

ios - Converting NSData to readable JSON format Swift - Stack Overflow

ios json swift2 swift3 nsdata
Rectangle 27 268

var dataString = String(data: fooData, encoding: .utf8)

in Swift 2.0:

import Foundation

var dataString = String(data: fooData, encoding: NSUTF8StringEncoding)

in Swift 1.0:

var dataString = NSString(data: fooData, encoding:NSUTF8StringEncoding)

Swift 2 has a different way of doing this

Added a Swift 2.0 version as well now

error: use of unresolved identifier 'NSUTF8StringEncoding'

Added a Swift 3.0 version as well. Damn, Apple like changing stuff!

You have to compile against a specific version of Swift, so your code will all be written against either 2.x or 3.x. Also, note with the 3.0 version you can shorten it by using var dataString = String(data: fooData, encoding: .utf8).

How to initialise a string from NSData in Swift - Stack Overflow

string swift cocoa nsdata
Rectangle 27 2

var NsdataArray:[AnyObject] = [image1, image2, image3]
//convert everything to this array
var imageArray:[UIImage] = [UIImage]()

for aData in NsdataArray {
   var image = UIImage(data: aData as? NSData) 
   if let _image = image {
       imageArray.append(_image) 
   } else {
       //error when convert to UIImage
   }
}

ios - How to convert a NSData object to a UIImage? Using Swift - Stack...

ios arrays xcode swift nsdata
Rectangle 27 202

UInt
NSUTF8StringEncoding
let datastring = NSString(data: fooData, encoding:NSUTF8StringEncoding)

Is it possible to convert NSData directly into a Swift String (instead of an NSString)?

String
NSString
var datastring = String(data: someData, encoding: NSUTF8StringEncoding)

How to initialise a string from NSData in Swift - Stack Overflow

string swift cocoa nsdata