Creating NSData from NSString in Swift

2020-01-24 19:49发布

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.

8条回答
疯言疯语
2楼-- · 2020-01-24 19:56

Swift 4

let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-24 19:56

In swift 5

let data = Data(YourString.utf8)
查看更多
不美不萌又怎样
4楼-- · 2020-01-24 19:59

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)
查看更多
Bombasti
5楼-- · 2020-01-24 20:08

Here very simple method

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
查看更多
霸刀☆藐视天下
6楼-- · 2020-01-24 20:09

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)
查看更多
该账号已被封号
7楼-- · 2020-01-24 20:10
// 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)!
查看更多
登录 后发表回答