我使用textview做了搜索功能并有一些要求:
1)当用户输入文本
时,在最后添加问号(?)2)插入符号应位于问号(?)
之前所以我使用了textView的委托。代码是:
func textViewDidChange(_ textView: UITextView) {
if textView.text.count == 0 {
added = false
}
if !added {
if textView.text.count > 0 && !textView.text.contains("?") {
textView.text = textView.text + "?"
textView.selectedRange = NSRange(location: textView.text.count - 1, length: 0)
added = true
}
}
}
但是当我输入一些表情符号时,项目崩溃了。错误:
'NSInvalidArgumentException', reason: '*** +[NSURLComponents setPercentEncodedQuery:]:
invalid characters in percentEncodedQuery'
它看起来像包含一些无效字符的参数。所以我打印了textView的文本。当我输入表情符号时,文字就像这样:
为什么会这样?我用moya提出请求:
func searchQuestion(_ text: String) {
provider.rx.request(MultiTarget(QuestionAPI.searchQuestion(text: text))).asObservable()
.subscribe(onNext: { [weak self] response in
do {
let result = try response.filterSuccessfulStatusCodes()
let json = try result.mapJSON() as! JsonObject
if let model = SearchQuestionModel(JSON: json), let data = model.data {
self?.searchResult.onNext(data)
}
} catch { }
}).disposed(by: rx.disposeBag)
}
请求API是:
enum QuestionAPI {
case searchQuestion(text: String)
}
extension QuestionAPI: TargetType {
var baseURL: URL {
return URL(string: AppConfig.release)!
}
var path: String {
switch self {
case .searchQuestion:
return "/api/client/questions/search"
}
}
var method: Moya.Method {
switch self {
case .searchQuestion:
return .get
}
}
var sampleData: Data {
switch self {
case .searchQuestion,
return "QuestionAPI".utf8Encoded
}
}
var task: Task {
switch self {
case .searchQuestion(let text):
return .requestParameters(parameters: ["title": text], encoding: URLEncoding.default)
}
}
var headers: [String: String]? {
return nil
}
}