Creating NSData from NSString in Swift

XcodeNsstringNsdataSwiftNsmutableurlrequest

Xcode Problem Overview


I'm trying to ultimately have an NSMutableURLRequest with a valid HTTPBody, but I can't seem to get my string data (coming from a UITextField) into a usable NSData object.

I've seen this method for going the other way:

NSString(data data: NSData!, encoding encoding: UInt)

But I can't seem to find any documentation for my use case. I'm open to putting the string into some other type if necessary, but none of the initialization options for NSData using Swift seem to be what I'm looking for.

Xcode Solutions


Solution 1 - Xcode

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)
}

Solution 2 - Xcode

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)

Solution 3 - Xcode

In swift 5

let data = Data(YourString.utf8)

Solution 4 - Xcode

Here very simple method

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

Solution 5 - Xcode

Swift 4

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

Solution 6 - Xcode

// 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)!

Solution 7 - Xcode

To create not optional data I recommend using it:

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

Solution 8 - Xcode

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

Solution 9 - Xcode

Convert String to Data

extension String {
    func toData() -> Data {
        return Data(self.utf8)
    }
}

Convert Data to String

extension Data {
      func toString() -> String {
          return String(decoding: self, as: UTF8.self)
      }
   }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackson EganView Question on Stackoverflow
Solution 1 - XcodeGabriele PetronellaView Answer on Stackoverflow
Solution 2 - XcodeSaid SikiraView Answer on Stackoverflow
Solution 3 - XcodeSanjay MishraView Answer on Stackoverflow
Solution 4 - XcodeShafraz BuharyView Answer on Stackoverflow
Solution 5 - XcodejatinView Answer on Stackoverflow
Solution 6 - XcodeVinod JoshiView Answer on Stackoverflow
Solution 7 - XcodeRamisView Answer on Stackoverflow
Solution 8 - XcodemeMadhavView Answer on Stackoverflow
Solution 9 - XcodeSumitView Answer on Stackoverflow