iOS swift NSMutableData has no member appendString

Rome Torres picture Rome Torres · Dec 16, 2016 · Viewed 7.3k times · Source

Hello I am new to swift and I am following a tutorial and creating the same code in order to Upload an image . I am now using swift 3 and it seems like NSMutableData() no longer has the appendString method available what can I do as a substitute ? The tutorial I am following is here http://swiftdeveloperblog.com/image-upload-example/ and my code is this

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
       let body = NSMutableData()

        if parameters != nil {
            for (key, value) in parameters! {
                body.("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString(options: <#T##NSData.Base64EncodingOptions#>)("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendString("\r\n")



        body.appendString("--\(boundary)--\r\n")

        return body
    }

Again the issue is with the appendString as I am getting the error:

value of type NSMutableData has no member appendString

I been searching for work arounds but have not found any and I have the append method available but it does not take a String.

Answer

Paul Cantrell picture Paul Cantrell · Dec 16, 2016

As @dan points out in the comments, that method is part of the tutorial you’re looking at. It’s easy enough in Swift without defining a custom method, though.

First, don’t use NSMutableData; instead, use the new Data struct, which will be either mutable or immutable depending on whether you use var or let:

var body = Data()

Then to append UTF-8 bytes:

body.append(Data("foo".utf8))

(There are other String methods for other encodings if you need something other than UTF-8.)

If you want the exact behavior of the tutorial, here’s how to translate its method to Swift 3:

extension Data {
  mutating func append(string: String) {
    let data = string.data(
        using: String.Encoding.utf8,
        allowLossyConversion: true)
    append(data!)
  }
}

…

body.append("foo")

I wouldn’t recommend this code, though, for two reasons. First, the lossy conversion means that your app may silently discard important data. Second, the force unwrap (data! instead of data) means that in case of encoding trouble, your app will crash instead of displaying a useful error.