Home > database >  How to open user's URL-link (any link) from UITextField in SFSafariViewController with interval
How to open user's URL-link (any link) from UITextField in SFSafariViewController with interval

Time:09-13


Hello everyone!) Need some help!)

How can I open any URL-link from UITextField in SFSafariViewController with interval?


This is what I meant when I said "any link"…

First: I means that if we have full link with https://.., like: https://www.google.com/ In this case, the link should be opened automatically with interval like 3 seconds.

Second: If we have link with without https://.., like: www.google.com In this case - https:// must be added automatically, then the link should be opened automatically with interval like 3 seconds.

And the third: If we have only stackoverflow.com without https://www.., Then - https://www must be added automatically and then the link should be opened automatically with interval like 3 seconds.


Code:

import UIKit
import Foundation
import SafariServices

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    if let urlString = linkTextField.text {
        let url: URL?
        if urlString.hasPrefix("http://") {
            url = URL(string: urlString)
        } else {
            url = URL(string: "http://"   urlString)
        }
        if let url = url {
            let sfViewController = SFSafariViewController(url: url)
            self.present(sfViewController, animated: true, completion: nil)
            print ("Your link was opened in SFSafariViewController")
        }
    }
    return true
}

Do you have any ideas how to implement this?) Thanks for every answer!)


CodePudding user response:

Even though I don't think it'll be a good user interface(for instance the user is thinking while typing & takes too long), use DispatchQueue.main.asynAfter:

DispatchQueue.main.asynAfter(deadline: .now() numberOfSeconds) {
    let sfViewController = SFSafariViewController(url: url)
    self.present(sfViewController, animated: true, completion: nil)
}
  • Related