Creating NSData from NSString in Swift
Asked Answered
R

9

182

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.

Ruscio answered 4/6, 2014 at 14:14 Comment(0)
W
372

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)
}
Wireman answered 4/6, 2014 at 14:16 Comment(8)
Swift can infer NSData type?Variegation
@NicolasManzini sure it can, as with any other type.Wireman
Value of optional type 'NSData?' not unwrapped; did you mean to use '!' or '?'?Deenadeenya
@macdonjo yep, that API changed over time and now it returns an Optional<NSData>, which you need to unwrap before usingWireman
@GabrielePetronella In which case its probably cleaner to just use if let data = (swiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding){} to handle the conversation and optional all at once.Deuced
In Swift2, there's no need to use "as" cast since it's automatically bridgedHyacinthus
A conversion to UTF-8 cannot fail, therefore an optional binding it not really needed, you can force-unwrap here.Feverous
In Swift 3+ there is a better way: Data(string.utf8). The benefit is that the result is non-optional.Individualize
V
34

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)
Vandiver answered 19/8, 2016 at 13:12 Comment(2)
Thanks. This worked for me in swift 3 perfectly. let input = "test string" let xdata = input.data(using: String.Encoding.utf8)Stricture
Any idea why String(data: data!, encoding: .nonLossyASCII) will be nil?Couple
I
6

In swift 5

let data = Data(YourString.utf8)
Idalia answered 1/5, 2019 at 18:43 Comment(0)
S
4

Here very simple method

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Sepaloid answered 30/10, 2014 at 8:42 Comment(0)
C
4

Swift 4

let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)
Chesterfield answered 6/3, 2018 at 4:41 Comment(1)
Don't use NSString in Swift.Individualize
Z
4

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)
      }
   }
Zigrang answered 1/4, 2020 at 14:32 Comment(0)
T
3
// 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)!
Thoughtless answered 5/11, 2014 at 6:42 Comment(0)
C
3

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)
Charlton answered 21/11, 2018 at 7:24 Comment(1)
In Swift 3+ this is the most efficient way.Individualize
A
3

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)
Ardehs answered 9/1, 2019 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.