0

i know how to replacing characters but when i try to replacing this characters \ and " gives me error is there any way to do. thanks

\ and " are from keyboard but i want replacing because i am using in URL and this URL don't read this.

when i click in character \ or " In keyboard xcode give me error

code:

// I want make some like termClean1

@IBOutlet weak var SearchBar: UISearchBar!

var term: String = "" {
    didSet {
    let termClean1 = term.replacingOccurrences(of: "\", with: "+")

    print(" \(term)")
    print("\(termClean1)")
    }

}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    self.term = searchBar.text!

}
Elsa Martins
  • 61
  • 1
  • 4
  • Maybe you can describe the broader problem you're trying to solve. If you're trying to let the user type in a URL and you want to make sure it's valid, perhaps you should do what all modern web browsers do, namely, let the user type whatever they want, but before using that URL, percent escape the invalid characters. But they don't generally show the user the percent-escaped version, because that's too confusing, but do it when they do the request. – Rob Sep 10 '17 at 19:19
  • But how i can replacing this invalid characters like (\ or " ) if xcode give me error ? – Elsa Martins Sep 10 '17 at 19:24
  • If a user types in a query like `"war & peace"` (with quotes), you often don't want to replace/remove anything as they're entering it, but when you initiate your request, the app would percent escape it behind the scenes, rendering something like `https://www.google.com/search?q=%22war+%26+peace%22`. But we don't want to subject/expose the user to that ugly percent-escaping process. See https://stackoverflow.com/a/39818985/1271826 for how to percent escape when preparing the URL (or body of `POST` request). – Rob Sep 10 '17 at 19:41
  • Elsa, Just to clarify, rmaddy is right that the backslash syntax is incorrect, if you were going to replace a backslash with a plus sign, it would be `string.replacingOccurrences(of: "\\", with: "+")` because the backslash has to be escaped in string literals with, confusingly, another backslash. That having been said, I still don't think that replacing characters is the right approach at all: If you're trying to construct a request to send to a server via `URLSession`, you should percent escape. Or use a library like Alamofire that does that for you. – Rob Sep 13 '17 at 06:10

0 Answers0