[xcode] Creating NSData from NSString in Swift

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.

This question is related to xcode nsstring nsdata swift nsmutableurlrequest

The answer is


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)

Swift 4

let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)

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)
      }
   }

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

// 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)!

In swift 5

let data = Data(YourString.utf8)

Here very simple method

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to nsstring

NSRange to Range<String.Index> Creating NSData from NSString in Swift How do I check if a string contains another string in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How do I URL encode a string Objective-C and Swift URL encoding Convert an NSURL to an NSString 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?

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 nsmutableurlrequest

Creating NSData from NSString in Swift