0

I am looking to do this in Swift 2.x: Say I enter text in a textfield. - 'Apple iPhone http://www.apple.com'

I am now updating a UIButton with label - Apple iPhone. And I want the IBAction when the button is clicked to launch 'http://www.apple.com.

I can set this up, but the part where I am having trouble is - How do I parse 'Apple iPhone' and 'http://www.apple.com' from the textfield and separate them so I can update the UIButton label with some text and use the URL for launching Safari ? More specifically, I want to be able to to detect any 'text' followed by 'http://', and always use the text to update a label and the http to launch a browser with the url. Thanks for answering.

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
NetCod
  • 191
  • 1
  • 2
  • 12

3 Answers3

6

there is a simple solution for this question as i mention below

var x = "Apple iPhone http://www.apple.com"

@IBAction func click(_ sender: UIButton) {
    let url = x.substring(from: x.range(of: "http")!.lowerBound)
    UIApplication.shared.openURL(NSURL(string: url)! as URL)
}

but there is a problem with this solution and all given solutions, if you have a string like this : var x = "Apple iPhone http://www.apple.com wwdc" you can't get the correct result. the generic solution can be like this:

@IBAction func click(_ sender: UIButton) {
    var text = "Apple iPhone http://www.apple.com wwwdc"

    let startIndex = text.range(of: "http")?.lowerBound
    var startString = text.substring(from: startIndex!)
    let endIndex = startString.range(of: " ")!.lowerBound
    var url = startString.substring(to: endIndex)

    UIApplication.shared.openURL(NSURL(string: url)! as URL)

}

it will extract the url correctly.

Mina
  • 2,167
  • 2
  • 25
  • 32
2

You can find url on string using datadetactor ,Try this

        let types: NSTextCheckingType = .Link
        let detector = try? NSDataDetector(types: types.rawValue)
        let matches = detector!.matchesInString("your_string", options: .ReportCompletion, range: NSMakeRange(0,ActivityText!.characters.count))
        if matches.count > 0 {
            let urlResult = matches.first
            let url = urlResult?.URL

            //now open this url
        }
  • Thanks. Will look into this solution and using NSDataDetector. Wasn't aware of this. How would I also keep track of the rest of the text before the url so I can save that separately ? – NetCod Dec 07 '16 at 08:33
2

You need to use the

componentsSeparatedByString method from foundation framework.

It returns an array of strings.

let array = inputField.text.componentsSeparatedByString("http://")

In your case, it will have 2 objects in an array. first will be the text for label and second the URL which you want to open in webView.

if array.count>=2 {
    let text = array[0]
    let url = array[1]
}