Convert UTF-8 encoded NSData to NSString

前端 未结 7 795
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 08:43

I have UTF-8 encoded NSData from windows server and I want to convert it to NSString for iPhone. Since data contains characters (like a degree symb

相关标签:
7条回答
  • 2020-11-22 09:06

    The Swift version from String to Data and back to String:

    Xcode 10.1 • Swift 4.2.1

    extension Data {
        var string: String? {
            return String(data: self, encoding: .utf8)
        }
    }
    

    extension StringProtocol {
        var data: Data {
            return Data(utf8)
        }
    }
    

    extension String {
        var base64Decoded: Data? {
            return Data(base64Encoded: self)
        }
    }
    

    Playground

    let string = "Hello World"                                  // "Hello World"
    let stringData = string.data                                // 11 bytes
    let base64EncodedString = stringData.base64EncodedString()  // "SGVsbG8gV29ybGQ="
    let stringFromData = stringData.string                      // "Hello World"
    

    let base64String = "SGVsbG8gV29ybGQ="
    if let data = base64String.base64Decoded {
        print(data)                                    //  11 bytes
        print(data.base64EncodedString())              // "SGVsbG8gV29ybGQ="
        print(data.string ?? "nil")                    // "Hello World"
    }
    

    let stringWithAccent = "Olá Mundo"                          // "Olá Mundo"
    print(stringWithAccent.count)                               // "9"
    let stringWithAccentData = stringWithAccent.data            // "10 bytes" note: an extra byte for the acute accent
    let stringWithAccentFromData = stringWithAccentData.string  // "Olá Mundo\n"
    
    0 讨论(0)
提交回复
热议问题