[string] How to initialise a string from NSData in Swift

I have been trying to initialise a string from NSData in Swift.

In the NSString Cocoa Documentation Apple is saying you have to use this:

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

However Apple did not include any example for usage or where to put the init.

I am trying to convert the following code from Objective-C to Swift

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

I have been trying a lot of possible syntaxes such as the following (of course it did not work):

var string:NSString!
string = init(data: fooData,encoding: NSUTF8StringEncoding)

This question is related to string swift cocoa nsdata

The answer is


Swift 2.0

It seems that Swift 2.0 has actually introduced the String(data:encoding:) as an String extension when you import Foundation. I haven't found any place where this is documented, weirdly enough.

(pre Swift 2.0) Lightweight extension

Here's a copy-pasteable little extension without using NSString, let's cut the middle-man.

import Foundation

extension NSData
{
    var byteBuffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: UnsafeMutablePointer<UInt8>(self.bytes), count: self.length) }}
}

extension String
{
    init?(data : NSData, encoding : NSStringEncoding)
    {
        self.init(bytes: data.byteBuffer, encoding: encoding)
    }
}

// Playground test
let original = "Nymphs blitz quick vex dwarf jog"
let encoding = NSASCIIStringEncoding

if let data = original.dataUsingEncoding(encoding)
{
    String(data: data, encoding: encoding)
}

This also give you access to data.byteBuffer which is a sequence type, so all those cool operations you can do with sequences also work, like doing a reduce { $0 &+ $1 } for a checksum.

Notes

In my previous edit, I used this method:

var buffer = Array<UInt8>(count: data.length, repeatedValue: 0x00)
data.getBytes(&buffer, length: data.length)
self.init(bytes: buffer, encoding: encoding)

The problem with this approach, is that I'm creating a copy of the information into a new array, thus, I'm duplicating the amount of bytes (specifically: encoding size * data.length)


This is the implemented code needed:

in Swift 3.0:

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

or just

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

Older swift version:

in Swift 2.0:

import Foundation

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

in Swift 1.0:

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

Objective - C

NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);

Swift

//This your data containing the string
   let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)

   //Use this method to convert the data into String
   let myStringFromData =  String(data:myStringData!, encoding: NSUTF8StringEncoding)

   print("My string value:" + myStringFromData!)

http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html


Another answer based on extensions (boy do I miss this in Java):

extension NSData {
    func toUtf8() -> String? {
        return String(data: self, encoding: NSUTF8StringEncoding)
    }
}

Then you can use it:

let data : NSData = getDataFromEpicServer()
let string : String? = data.toUtf8() 

Note that the string is optional, the initial NSData may be unconvertible to Utf8.


Since the third version of Swift you can do the following:

let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)

simialr to what Sunkas advised.


import Foundation
var string = NSString(data: NSData?, encoding: UInt)

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to cocoa

How to update a single pod without touching other dependencies How to initialise a string from NSData in Swift Input from the keyboard in command line application Get current NSDate in timestamp format Xcode build failure "Undefined symbols for architecture x86_64" Cocoa Autolayout: content hugging vs content compression resistance priority setValue:forUndefinedKey: this class is not key value coding-compliant for the key iOS - Build fails with CocoaPods cannot find header files Get Current date & time with [NSDate date] Remove all whitespaces from NSString

Examples related to nsdata

Convert UIImage to NSData and convert back to UIImage in Swift? Creating NSData from NSString in Swift How to initialise a string from NSData in Swift Convert between UIImage and Base64 string convert UIImage to NSData Convert NSData to String? Convert UTF-8 encoded NSData to NSString How do I convert an NSString value to NSData?