Creating NSData from NSString in Swift

前端 未结 9 2346
情深已故
情深已故 2020-11-27 11:11

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 UITextFie

相关标签:
9条回答
  • 2020-11-27 11:50

    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)
    
    0 讨论(0)
  • 2020-11-27 11:51

    Swift 4

    let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)
    
    0 讨论(0)
  • 2020-11-27 11:54

    In swift 5

    let data = Data(YourString.utf8)
    
    0 讨论(0)
  • 2020-11-27 12:01

    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)
    }
    
    0 讨论(0)
  • 2020-11-27 12:07
    // 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)!
    
    0 讨论(0)
  • 2020-11-27 12:07

    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)
          }
       }
    
    0 讨论(0)
提交回复
热议问题