iosswift2uitextfielduitextfielddelegate

How to store my first textfield to not ask for the second time in swift


I created a UITextField where, when the user writes a link and enters, my textfield disappears and my webView appears.

What I am trying to do is, when the user writes the first time their link, the textfield saves that link and when the user opens again the app, the web view opens directly from the last link that the user wrote in the textfield. Basically the stored link should run the second time.

Here is all my code:

import UIKit
import Foundation


let urlKey = "User URL"

class ViewController: UIViewController, UITextFieldDelegate {
  
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var webView: UIWebView!
  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.webView.hidden = true
            self.textField.addTarget(self, action: #selector(ViewController.textFieldDidUpdate(_:)), forControlEvents: UIControlEvents.EditingChanged)
      
      if doesURLExist() {
        self.textField.text = getURL()
  }
}
    // Text Field Delegate
    func textFieldDidUpdate(textField: UITextField)
    {
        // Remove Spaces
        textField.text = textField.text!.stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)
        
        // Validate URL
        NSURL.validateUrl(textField.text, completion: { (success, urlString, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                if (success)
                {
                  self.saveURL(urlString!)
                  self.webView.hidden = false
                  self.textField.hidden = true 
                  let request = NSURLRequest(URL: NSURL(string: urlString!)!)
                  self.webView.loadRequest(request)
                }
                else
                {
                    self.webView.stopLoading()
                    self.webView.hidden = true
                }
            })
        })
    
          }
    @IBAction func dismissKeyboard(sender: AnyObject) {
        self.resignFirstResponder()
        self.view.endEditing(true)
    }
  func saveURL(urlString: String)  {
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(urlString, forKey: urlKey)
  }
  
  func getURL() -> String {
    let defaults = NSUserDefaults.standardUserDefaults()
    let urlString = defaults.objectForKey(urlKey) as! String
    return urlString
  }
  
  func doesURLExist() -> Bool {
    let defaults = NSUserDefaults.standardUserDefaults()
    guard let _ = defaults.objectForKey(urlKey) where defaults.objectForKey(urlKey) is String else {
      return false
    }
    return true
  }
}

Here is my project in GitHub: https://github.com/anappleapp/NSURLvalidation


Solution

  • You'll want to check if the url exists first by calling doesURLExist, if it does, you opt out of presenting that textfield. If it does not exist, call saveURL. NSUserDefaults provides a simple means to store lightweight data.

    let urlKey = "User URL"     
    
    func saveURL(urlString: String)  {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(urlString, forKey: urlKey)
    }
    
    func getURL() -> String {
        let defaults = NSUserDefaults.standardUserDefaults()
        let urlString = defaults.objectForKey(urlKey) as! String
        return urlString
    }
    
    func doesURLExist() -> Bool {
        let defaults = NSUserDefaults.standardUserDefaults()
        guard let _ = defaults.objectForKey(urlKey) where defaults.objectForKey(urlKey) is String else {
            return false
        }
        return true
    }
    

    So your class should look something like:

    import UIKit
    import Foundation
    
    let urlKey = "User URL"     
    
    class ViewController: UIViewController, UITextFieldDelegate {
    
        @IBOutlet weak var textField: UITextField!
        @IBOutlet weak var webView: UIWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.webView.hidden = true
    
            self.textField.addTarget(self, action: #selector(ViewController.textFieldDidUpdate(_:)), forControlEvents: UIControlEvents.EditingChanged)
    
            if(doesURLExist) {
                self.textField.text = getURL()
            }
            // Demo UI Settings
        }
    }
    
      // Text Field Delegate
    func textFieldDidUpdate(textField: UITextField)
    {
        // Remove Spaces
        textField.text = textField.text!.stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)
    
        // Validate URL
        NSURL.validateUrl(textField.text, completion: { (success, urlString, error) -> Void in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                if (success) {
                  self.saveURL(urlString)
                  self.webView.hidden = false
                  self.textField.hidden = true 
                  let request = NSURLRequest(URL: NSURL(string: urlString!)!)
                  self.webView.loadRequest(request)
                } else {
                    self.webView.stopLoading()
                    self.webView.hidden = true
                }
            })
        })
    }
    

    Don't forget to add the original functions to your class.