nullios11swift4nsurlcomponents

URLComponents finding nil


So my condition here is that if the URL is contained com://******/sendto/webview then it should open in a browser inside my app or else it will open in Safari. I can't figure out what am I doing wrong?

        if let url = homeObject["deeplink_url"] as? String, url != "" {

            if url.contains("com://******/sendto/webview") {

                if url.contains("?url") {

                    self.fixMalformedURL(url)

                } else {

                    if let urlComponents = URLComponents(url: URL(string: url)!, resolvingAgainstBaseURL: true) {
                        let webViewTitle = urlComponents.queryItems!.filter({ $0.name == "title" }).first
                        let webViewURL = urlComponents.queryItems!.filter({$0.name == "url"}).first

                        let storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let vc = storyboard.instantiateViewController(withIdentifier: "FeaturedWebViewController") as! FeaturedWebViewController
                        vc.webViewTitle = webViewTitle!.value
                        vc.dynamicURL = webViewURL!.value
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }

            } else {

                UIApplication.shared.openURL(URL(string: url)!)
            }

        }

Solution

  • Your app may be crash because you try to get filter of "title" field but it filed does not exist in url so here is working code if url has whitespace then remove it

    let homeObject = ["deeplink_url":"com://www.xxxyyy.com?title=topPersons&url=google.com"]
        if let url = homeObject["deeplink_url"], url != "" {
    
          if url.contains("www.xxxyyy.com") {
    
            if url.contains("?url") {
             //asdj asd asd asdasdfasdf asdfa sdf asdf asdf asdf asdf a sdf asd asdghgjkkjkjkljkljkjkl jkljkljkl jklj jl jljasd asd asdf asd asdf asdf asdf asd asdf asdf aasasaasdasdfasdf asdf asdasdfasdf hoasdasd
    
    
            } else {
    
    
    
    
              if let urlComponents = URLComponents(url:URL.init(string: url)!, resolvingAgainstBaseURL: false)
              {
    
    
                let webViewTitle = urlComponents.queryItems!.filter({ $0.name == "title" }).first
                let webViewURL = urlComponents.queryItems!.filter({$0.name == "url"}).first
    
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc = storyboard.instantiateViewController(withIdentifier: "FeaturedWebViewController") as! FeaturedWebViewController
                vc.webViewTitle = webViewTitle!.value
                vc.dynamicURL = webViewURL!.value
                self.navigationController?.pushViewController(vc, animated: true)
              }
            }
    
          } else {
    
            UIApplication.shared.openURL(URL(string: url)!)
          }