【问题标题】:Text Field returns nil when there's a space有空格时,文本字段返回 nil
【发布时间】:2015-12-21 03:55:29
【问题描述】:

如果有人可以帮助我理解/修复为什么在发送实际字符串时它一直崩溃/说我的结果为零。

我知道问题与空白有关,但我做错了什么?

  • 当我输入“Hello”时,它工作正常。
  • 当我键入“Hello Word”时,出现错误并显示它为 nil。

致命错误:在展开可选值时意外发现 nil

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不能直接用普通文本,要先根据你的服务器编码,大部分是stringByAddingPercentEscapesUsingEncoding
  • 我认为 API 不会为“Hello World”文本返回任何内容。

标签: ios swift swift2 alamofire swifty-json


【解决方案1】:

我在 swift 2 中使用它进行 URL 编码,希望它能工作

let escapedSearchText = searchText.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.letterCharacterSet())!

【讨论】:

  • 非常感谢!它就像一个魅力!为什么 NSCharacterSet.URLQueryAllowedCharacterSet() 不能像广告一样工作?
  • 我尝试使用NSCharacterSet.URLQueryAllowedCharacterSet() ,它也适用于我:O 我只使用letterCharacterSet 来编码搜索文本,但两者都产生相同的字符串
【解决方案2】:

你可以试试这个方法:stringByAddingPercentEncodingWithAllowedCharacters:

var searchTerm:String = self.searchTextField.text!
searchTerm = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let apiUrl = "http://localhost/v1/define?term=\(searchTerm)"

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多