Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating NSData from NSString in Swift

In Swift 3

let data = string.data(using: .utf8)

In Swift 2 (or if you already have a NSString instance)

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

In Swift 1 (or if you have a swift String):

let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)

Also note that data is an Optional<NSData> (since the conversion might fail), so you'll need to unwrap it before using it, for instance:

if let d = data {
    println(d)
}

Swift 4 & 3

Creating Data object from String object has been changed in Swift 3. Correct version now is:

let data = "any string".data(using: .utf8)

Here very simple method

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

Swift 4

let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)

In swift 5

let data = Data(YourString.utf8)

// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)

// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")

var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)