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条回答
你好瞎i
2楼-- · 2020-01-24 20:11

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)
查看更多
The star\"
3楼-- · 2020-01-24 20:12

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)
}
查看更多
登录 后发表回答