当有 space 时,文本字段 returns 为零
Text Field returns nil when there's a space
如果有人可以帮助我 understand/fix 为什么它会保留 crashing/saying 当有一个实际的字符串被发送时我的结果是零。
我知道问题与白色有关 space 但我做错了什么?
- 当我键入 "Hello" 时,它工作正常。
- 当我键入 "Hello Word" 时,出现错误并提示它为 nil。
fatal error: unexpectedly found nil while unwrapping an Optional value
import Alamofire
import SwiftyJSON
@IBAction func searchBtn(sender: UIButton) {
let searchTerm:String = self.searchTextField.text!
let apiUrl = "http://localhost/v1/define?term=\(searchTerm)"
Alamofire.request(.GET, apiUrl!).responseJSON { response in print(response)
let jsonData = JSON(response.result.value!)
if jsonData["result_type"] == "exact" {
let definitionText = jsonData["list"][0]["definition"].string
self.resultLabel.text = definitionText
} else {
self.resultLabel.text = "Sorry, your word does not have a definition."
}
}
}
我正在使用这个 URL 在 swift 2 中编码,希望它有用
let escapedSearchText = searchText.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.letterCharacterSet())!
你可以试试这个方法:stringByAddingPercentEncodingWithAllowedCharacters:
var searchTerm:String = self.searchTextField.text!
searchTerm = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let apiUrl = "http://localhost/v1/define?term=\(searchTerm)"
如果有人可以帮助我 understand/fix 为什么它会保留 crashing/saying 当有一个实际的字符串被发送时我的结果是零。
我知道问题与白色有关 space 但我做错了什么?
- 当我键入 "Hello" 时,它工作正常。
- 当我键入 "Hello Word" 时,出现错误并提示它为 nil。
fatal error: unexpectedly found nil while unwrapping an Optional value
import Alamofire
import SwiftyJSON
@IBAction func searchBtn(sender: UIButton) {
let searchTerm:String = self.searchTextField.text!
let apiUrl = "http://localhost/v1/define?term=\(searchTerm)"
Alamofire.request(.GET, apiUrl!).responseJSON { response in print(response)
let jsonData = JSON(response.result.value!)
if jsonData["result_type"] == "exact" {
let definitionText = jsonData["list"][0]["definition"].string
self.resultLabel.text = definitionText
} else {
self.resultLabel.text = "Sorry, your word does not have a definition."
}
}
}
我正在使用这个 URL 在 swift 2 中编码,希望它有用
let escapedSearchText = searchText.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.letterCharacterSet())!
你可以试试这个方法:stringByAddingPercentEncodingWithAllowedCharacters:
var searchTerm:String = self.searchTextField.text!
searchTerm = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let apiUrl = "http://localhost/v1/define?term=\(searchTerm)"