В настоящее время я работаю над приложением, в котором пользователь может сохранить свое любимое место в виде таблицы, и выбрав строку в этом представлении таблицы, он открывает новый контроллер представления с веб-представлением. В этом веб-представлении я хочу, чтобы он отображал поиск в Google места, которое пользователь добавил в таблицу.Хранение NSURL в глобальной переменной
Я попытался использовать NSUserDefaults, чтобы попытаться сохранить URL-адрес google-поиска, но мне не удалось получить доступ к нему из другого файла контроллера.
Я исследовал Google, но до сих пор не смог найти то, что я ищу.
Я хотел узнать, знает ли кто-нибудь, как сохранить URL-адрес и получить доступ к нему из другого файла, чтобы быть URL-адресом, отображаемым веб-представлением.
Вот мой код: SecondViewController (имеет вид таблицы с названиями мест, которые позволяют пользователю сэкономить, выбрав должен открыть вид с поиском Google по названию места, которое спасло пользователь)
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
@vadian, можете ли вы объяснить это больше, пожалуйста, –