简体   繁体   中英

swift how to convert special unicode

let result = ["response": response,
              "callbackId": callbackId]

do {
    let data = try NSJSONSerialization.dataWithJSONObject(result, options: .PrettyPrinted)
    var str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String

    str = str?.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
    str = str?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
    str = str?.stringByReplacingOccurrencesOfString("\'", withString: "\\\'")
    str = str?.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
    str = str?.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
    //                            str = str?.stringByReplacingOccurrencesOfString("\f", withString: "\\f")
    //                            str = str?.stringByReplacingOccurrencesOfString("\u2028", withString: "\\u2028")
    //            str = str?.stringByReplacingOccurrencesOfString("\u2029", withString: "\\u2029")

    return "bridge.invokeJs('{\"response\" : {\"username\" : \"zhongan\"},\"callbackId\" : \(callbackId)}')"
} catch {
    return nil
}

I want to convert the json string to js script, and then call evaluateJavaScript , but can not convert the special character, like \\f \
 , this will give a compiler error and I don't know why.

Have a look at Strings and Characters Section Special Characters in String Literals .

According to this page \\f is not defined.

  • The escaped special characters \\0 (null character), \\ (backslash), \\t (horizontal tab), \\n (line feed), \\r (carriage return), \\" (double quote) and \\' (single quote)

  • An arbitrary Unicode scalar, written as \\u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point

So

  • \\f Form Feed you may be written in escaped form as \\u{000C}
  • \
 Page Feed has to be escaped as \\u{2029}
  • \
 Line Separator has to be escaped as \\u{2028}

See also " Unicode Control Characters "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM