【问题标题】:Storing an NSURL in a global variable将 NSURL 存储在全局变量中
【发布时间】:2016-08-17 03:35:53
【问题描述】:

我目前正在开发一个应用程序,在该应用程序中,用户可以将他们最喜欢的位置保存到表格视图中,并通过在该表格视图中选择一行来打开一个带有 Web 视图的新视图控制器。在该网络视图中,我希望它显示用户添加到表格中的位置的谷歌搜索。

我尝试使用 NSUserDefaults 来尝试保存 google 搜索的 URL,但我无法从不同的视图控制器文件中访问它。

我在 google 上进行了研究,但仍然无法找到我正在寻找的确切内容。

我想知道是否有人知道如何保存 URL 并从另一个文件中访问它以作为 Web 视图显示的 URL。

这是我的代码: SecondViewController(有一个表格视图,其中包含用户保存的地点的名称,选择应该打开一个用谷歌搜索用户保存的地点名称的视图)

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.
    }

}

【问题讨论】:

  • 请向我们展示您的代码。
  • 不需要使用NSUserDefaults 也不需要使用全局变量——这太过分了——在视图控制器之间传递数据。只需将prepareForSegue中的数据传递给
  • @vadian 你能解释一下吗
  • 这里有很多建议passing data between controllers
  • @vadian 谢谢你的页面,但似乎我想传递给不同控制器的变量被困在 if let 语句中。我需要一个全局变量吗?

标签: swift nsurl


【解决方案1】:

我使用了一个结构来定义不同端点的基本 url,如下所示。根据我的需要,所有模型和视图控制器也可以访问它。我想这是你的要求。

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"
} 

}

【讨论】:

  • 你不应该将你的结构命名为URL。这是在 Swift 3 中的 Foundation 中定义的类型。developer.apple.com/reference/foundation/url
  • 我已经用我的代码更新了上面的答案。我在想我可以在单元格中添加一个副标题,并将副标题的文本更改为谷歌搜索的 URL。然后将其保存为全局变量,以便我可以在 SecondViewController 和 Favorite Places View Controller 中使用它。
猜你喜欢
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2021-02-18
  • 1970-01-01
相关资源
最近更新 更多