-1

I am currently working on an app in which the user can save their favorite place to a table view and by selecting a row in that table view it opens a new view controller with a web view. In that web view, I want it to display a google search of the place that the user has added to the table.

I've tried using NSUserDefaults to try and save the URL of the google search but I was unable to access it from within a different view controller file.

I've researched on google but have still been unable to find exactly what I'm looking for.

I wanted to find out if anyone knows how to save a URL and access it from within a different file to be the URL that the web view displays.

Here's my code: SecondViewController(Has a table view with the names of the places that the user saves, selecting should open a view with a google search of the name of the place that the user saved)

import UIKit
var favoritePlaces = [String]()

class SecondViewController: UIViewController, UITableViewDelegate, UITextFieldDelegate, UITableViewDataSource {



    @IBAction func alertButtonPressed(sender: AnyObject) {


            let addNewPlaceAlert = UIAlertController(title: "Add A Favorite Place", message: "Enter the name of the place here", preferredStyle: .Alert)
        let saveAction = UIAlertAction(title: "Done", style: .Default) { (alert: UIAlertAction!) -> Void in
            NSLog("You pressed button OK")
            addNewPlaceAlert.dismissViewControllerAnimated(true, completion: nil)
            let textField = addNewPlaceAlert.textFields![0] as UITextField
            favoritePlaces.append(textField.text!)
            self.favoritePlacesTable.reloadData()
            NSUserDefaults.standardUserDefaults().setObject(favoritePlaces, forKey: "favoritePlaces")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (alert: UIAlertAction!) -> Void in
            NSLog("You pressed button OK")


        }

    addNewPlaceAlert.addAction(saveAction)
        addNewPlaceAlert.addAction(cancelAction)
        addNewPlaceAlert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in

                   }

        presentViewController(addNewPlaceAlert, animated: true, completion: nil)




    }
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            favoritePlaces.append(alertView.textFieldAtIndex(0)!.text!)
            favoritePlacesTable.reloadData()
        }
    }


    @IBOutlet var favoritePlacesTable: UITableView!

      override func viewDidLoad() {

        super.viewDidLoad()

        if NSUserDefaults.standardUserDefaults().objectForKey("favoritePlaces") != nil {

            favoritePlaces = NSUserDefaults.standardUserDefaults().objectForKey("favoritePlaces") as! [String]


        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        favoritePlacesTable.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        print("Row: \(row)")

        print(favoritePlaces[row] as String)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section:Int) -> Int {

        return favoritePlaces.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell? = favoritePlacesTable.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
        cell!.textLabel?.text = favoritePlaces[indexPath.row]

        if (cell != nil)
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
                                   reuseIdentifier: "Cell")
        }

        // At this point, we definitely have a cell -- either dequeued or newly created,
        // so let's force unwrap the optional into a UITableViewCell


        return cell!
    }
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let row = indexPath.row
        performSegueWithIdentifier("showContent", sender: row)
    }


    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {

            favoritePlaces.removeAtIndex(indexPath.row)

            NSUserDefaults.standardUserDefaults().setObject(favoritePlaces, forKey: "favoritePlaces")

            favoritePlacesTable.reloadData()
        }
    }







    override func viewDidAppear(animated: Bool) {

        favoritePlacesTable.reloadData()

            }



}

    Favorite Place View Controller(The view that opens once a user selects a row)
 import UIKit

class FavoritePlaceViewController: UIViewController {

    enter code here
    @IBOutlet var favoritePlaceWV: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

let url = NSURL(string: "https://www.google.com")!
        favoritePlaceWV.loadRequest(NSURLRequest(URL: url))
        // Do any additional setup after loading the view.

        NSUserDefaults.standardUserDefaults().objectForKey("secondUrl")
    }

    `enter code here`override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
kaptain ken
  • 57
  • 1
  • 7
  • please show us your code. – Christian Abella Aug 17 '16 at 03:36
  • 1
    No need to use `NSUserDefaults` nor a global variable – which is overkill – to pass data between view controllers. Just pass the data in `prepareForSegue` – vadian Aug 17 '16 at 16:04
  • @vadian could you explain this more please – kaptain ken Aug 23 '16 at 00:33
  • Here are many many suggestions how [passing data between controllers](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – vadian Aug 23 '16 at 04:43
  • @vadian Thank you for that page but it seems that the variable that I want to pass to a different controller is trapped inside an if let statement. Would I need a global variable for that? – kaptain ken Aug 23 '16 at 14:20

1 Answers1

0

I used a struct to define base urls for different end points as follows. This is accessible to all models and view controllers as well, according to my need. I guess this was your requirement.

struct URL {
private static let BaseURL = "https://yourdomain.com/urlendpoint/api/"
private static let CurrentVersion = "v202/json/en/"
private static let year15 = "2015/"
private static let currentYear = "2016/"

//MARK:- Update URl
static var UpdateURL: String {
    return BaseURL + CurrentVersion + currentYear + "update.json"
}

static var FirstURL: [String] {
    var urls: [String] = []
    for i in 0...11 {
        urls.append(BaseURL + CurrentVersion + currentYear + + FirstMonth + String(i) + ".json")
    }
    return urls
}


static var SecondURL: String {
    return BaseURL + CurrentVersion + "second.json"
}

//MARK:- Dream
static var ThirdURL: String {
    return BaseURL + CurrentVersion + "third_results.json"
}

static var FourthURL: String {
    return BaseURL + CurrentVersion + "fourth.json"
}

static var FifthURL: String {
    return BaseURL + CurrentVersion + currentYear + "fifth.json"
} 

}

amagain
  • 2,042
  • 2
  • 20
  • 36
  • You should not name your struct `URL`. This is a type defined in `Foundation` in Swift 3. https://developer.apple.com/reference/foundation/url – FelixSFD Aug 17 '16 at 15:24
  • I've updated my answer above with my code. I'm thinking that I could add a subtitle to the cell and change the subtitle's text to the URL of the google search. Then save that as a global variable so I can use it in the SecondViewController and the Favorite Places View Controller. – kaptain ken Aug 17 '16 at 15:25