Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 3.0 Data to String?

Tags:

string

swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {} 

I want deviceToken to string

but:

let str = String.init(data: deviceToken, encoding: .utf8) 

str is nil

swift 3.0

how can I let data to string ?

Registering for Push Notifications in Xcode 8/Swift 3.0? not working and the answer is a few months ago, I had tried it:

enter image description here

and print:

enter image description here

like image 535
weijia.wang Avatar asked Sep 21 '16 12:09

weijia.wang


People also ask

How do you convert something to a string in Swift?

To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.

What is NSData in IOS?

Overview. NSData and its mutable subclass NSMutableData provide data objects, or object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects.

What is utf8 in Swift?

UTF8View Elements Match Encoded C Strings When you call a C function using a String , Swift automatically creates a buffer of UTF-8 code units and passes a pointer to that buffer. The code units of that buffer match the code units in the string's utf8 view.

What is data in Swift?

Data in Swift 3 is a struct that conforms to collection protocol. It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255). – Leo Dabus.


Video Answer


2 Answers

I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:

var testString = "This is a test string" var somedata = testString.data(using: String.Encoding.utf8) var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String! 
like image 64
4redwings Avatar answered Oct 03 '22 23:10

4redwings


here is my data extension. add this and you can call data.ToString()

import Foundation  extension Data {     func toString() -> String?     {         return String(data: self, encoding: .utf8)     } } 
like image 29
luhuiya Avatar answered Oct 03 '22 23:10

luhuiya