【问题标题】:Swift. URL returning nil迅速。网址返回零
【发布时间】:2017-03-15 01:59:52
【问题描述】:

我正在尝试在我的应用中打开一个网站,但由于某种原因,一行代码一直返回 nil,这是我的代码:

let url = URL(string: "http://en.wikipedia.org/wiki/\(element.Name)")!
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

第一行 (let url = URL...) 不断返回此错误:

致命错误:在展开 Optional 值时意外发现 nil。

我应该怎么做才能解决这个问题?

【问题讨论】:

  • 检查element.Name。如果它是一个可选的字符串插值可能会导致意外的行为。

标签: swift url fatal-error uiapplication


【解决方案1】:

我认为这会有所帮助。 您的 element.name 可能在单词之间包含空格,因此添加 PercentEncoding 会生成 PercentEncoding 字符串。

let txtAppend = (element.Name).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = "http://en.wikipedia.org/wiki/\(txtAppend!)"
let openUrl = NSURL(string: url)
if #available(iOS 10.0, *) {
    UIApplication.shared.open(openUrl as! URL, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(openUrl as! URL)
}

【讨论】:

    【解决方案2】:

    用于此修复的 Swift 4 版本:

    str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    

    【讨论】:

      【解决方案3】:

      不要用 (!) 强行打开它。当您使用 (!) 并且变量的值为 nil 时,您的程序会崩溃并且您会收到该错误。相反,您希望使用“guard let”或“if let”语句安全地打开可选项。

      guard let name = element.Name as? String else {
          print("something went wrong, element.Name can not be cast to String")
          return
      }
      
      if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
          UIApplication.shared.openURL(url)
      } else {
          print("could not open url, it was nil")
      }
      

      如果这不起作用,则可能是 element.Name 有问题。因此,如果您仍然遇到问题,我会检查一下这是否是可选的。

      更新

      我添加了一种可能的方法来检查 element.Name 属性,看看您是否可以将其转换为字符串并创建您想要创建的所需 url。可以在我之前贴的代码上面看到代码。

      【讨论】:

      • 这只是解决错误,而不是错误的原因。我确定目标是最终得到一个有效的 URL。
      • 您能进一步解释一下吗?如果他/她没有从中获得有效的 url,那么我接下来会查看 element.Name 属性。
      • OP 想要使用element.Name 创建一个 URL。照原样,这导致 URL 为 nil 导致崩溃。您的回答只是防止了崩溃,但并没有解决根据需要创建 URL 的问题。
      • 它解决了问题中给出的错误。我同意你的观点,它没有提供从 element.Name 创建 url 的完整解决方案,但如果不了解有关 element.Name 的更多信息,我不知道还能做什么。
      • @rmaddy 我在 element.Name 上添加了额外的检查以提供完整的解决方案。希望这将是令人满意的。如果没有,我希望您能就如何改进它提供指导。
      【解决方案4】:

      这绝对适合你。由于您的字符串 URL 之间存在空格,因此出现问题。解决这个问题

      let imagePath = "https://homepages.cae.wisc.edu/~ece533/images/arcti cha re.png"
      
      let urlString = imagePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) //This will fill the spaces with the %20
      
      let url = URL(string: urlString) //This will never return nil
      

      【讨论】:

        【解决方案5】:

        它可能包含零宽度空间,顾名思义,它是一个Unicode字符,肉眼看不见

        extension String {
            func replacePattern(pattern: String, replaceWith: String = "") -> String {
                do {
                    let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
                    let range = NSMakeRange(0, self.count)
                    return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
                } catch {
                    return self
                }
            }
            
            var fixZeroWidthSpace: String {
                addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacePattern(pattern: "%E2%80%8B", replaceWith: "") ?? ""
            }
        }
        
        let url = urlString.fixZeroWidthSpace 
        

        【讨论】:

          【解决方案6】:

          我猜你的 URL 在添加 element.Name 后格式不正确。 所以只需使用该功能

          addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
          

          令人惊讶的是,URL 构造函数没有考虑 URL 格式

          【讨论】:

            【解决方案7】:

            可能是编码问题。 你试过了吗

            let str = "http://en.wikipedia.org/wiki/\(element.Name)"
            let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCha‌​racterSet.URLQueryAl‌​lowedCharacterSet()
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-03-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-11-07
              • 2021-10-21
              • 2016-12-27
              • 1970-01-01
              相关资源
              最近更新 更多