image is complaining fatal error: unexpectedly found nil while unwrapping an Optional value - swift

I have a master/detail app, where I need to get the image from the master and put it in the detail
It's complaining on the imageView line although I have a file called Gerbera.png image but it won't show. Also how do I call the image from the master to the detail page?
class DetailViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var btnCall: UIButton!
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = detailItem {
if let myWebview = webView {
let stringRepresentation = MasterViewController.MyVariables.urlString?.joined(separator:"")
print ("urlString", MasterViewController.MyVariables.urlString)
print ("sR",stringRepresentation)
let url = NSURL(string: stringRepresentation as! String)
let request = URLRequest(url: url! as URL)
myWebview.scalesPageToFit = true
myWebview.loadRequest(request)
}
imageView.image = UIImage(named:"Gerbera.png")!
}
}

Please try this line
imageView.image = UIImage(named:"Gerbera")!

I found the answer for this. My Detail View shows image on the top then web view on the bottom. I realized that the detail view should show code for the image first before code for the web view. So I put it under viewDidLoad() and it worked!
override func viewDidLoad() {
super.viewDidLoad()
imageView1.image = MasterViewController.MyVariables.flowerImage!.first

Related

Swift menu not showing on right navigation button click

New to Swift. I have a simple UI: put a UINavigationBar on top of a UIWebView, and a the right bar button item to have an action that shows a menu, to allow the use choose different pages to show in the web view.
Show the view controller looks like:
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var menu: UIBarMenuItem!
#IBOutlet weak var viewnav: UIView!
override func viewDidLoad() {
super.viewDidLoad();
let url = URL(string:"about:blank")
let req = URLRequest(url:url!)
webView.loadRequest(req)
}
#obj func dummy(){
}
#IBAction func MenuShow(sender: UIBarButtonItem){
let menu = UIMenuController.shared
viewnav.becomeFirstResponder()
menu.setTargetRect(viewnav.frame, in:viewnav)
let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))
menu.menuItems = [dummy]
menu.setMenuVisible(true, animated: true)
//for test only; should move to menu item actions
let url = URL(string:"https://www.apple.com")
let req = URLRequest(url:url!)
webView.loadRequest(req)
}
}
(I have connected the web view, the bar button to the UI object; for viewnav I tried adding a new dummy view in Main.storyboard or using the existing navigation bar, both have the same result)
The resulting app shows the empty page and when I hit the menu button, jumps into Apple's home page, so the above code runs as expected. But the menu didn't show up, so what is wrong for the code above?
(there are a few other simular questions like this, but they didn't seem to solving the problem)
This answer gives the solution:
override var canBecomeFirstResponder: Bool {
return true
}
And add this line to the viewDidLoad method
view.becomeFirstResponder()
Full version:
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var menuButton: UIBarMenuItem!
override func viewDidLoad() {
super.viewDidLoad();
let url = URL(string:"about:blank")
let req = URLRequest(url:url!)
webView.loadRequest(req)
view.becomeFirstResponder()
let menu = UIMenuController.shared
let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))
menu.menuItems = [dummy]
}
override var canBecomeFirstResponder: Bool {
return true
}
#obj func dummy(){
let url = URL(string:"https://www.apple.com")
let req = URLRequest(url:url!)
webView.loadRequest(req)
menu.setMenuVisible(true, animated: false)
}
#IBAction func MenuShow(sender: UIBarButtonItem){
let menu = UIMenuController.shared
let bv = menuButton.value(forKey: "view") as? UIView
menu.setTargetRect(bv!.frame, in:view)
menu.setMenuVisible(true, animated: true)
}
}

How to grab the value of a WebView in Swift

Suppose I have a label that is a NSTextField. I know I can access the value of that label by:
#IBOutlet weak var label: NSTextField!
let labelValue = label.stringValue
And then I can use that variable accordingly.
The same is easily said for an NSImage:
#IBOutlet weak var productImageView: NSImageView!
let img = productImageView.image
My question is how do I grab the value of a WebView. I am unsure which property allows me to use a WebView.
#IBOutlet weak var videoTemp: WebView!
let videoPassed = videoTemp //how do I access this videoTemp's value much like .stringValue and .image
I am trying to load dynamic video URL's to Youtube videos when I click on a collection view item. The line that I have commented in my setupAppVideo method is where my fatal error occurs:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
but when I print out the url and request variables their are no nil values and all of them are the correct links in the console.
import Cocoa
import WebKit
class test1: NSCollectionViewItem {
#IBOutlet weak var label: NSTextField!
#IBOutlet weak var label2: NSTextField!
#IBOutlet weak var productImageView: NSImageView!
#IBOutlet weak var videoTemp: WKWebView!
var buildProduct: ProductModel? {
didSet{
label.stringValue = (buildProduct?.product_name)!
label2.stringValue = (buildProduct?.product_price)!
setupAppIconImage()
setupAppVideo()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func setupAppIconImage() {
if let appIconImageURL = buildProduct?.product_image {
let url = NSURL(string: appIconImageURL)
URLSession.shared.dataTask(with: url! as URL,completionHandler:{(data, response, error) in
if error != nil {
print(error)
return
}
DispatchQueue.main.async(){
self.productImageView.image = NSImage(data: data!)
}
}).resume()
}
}
func setupAppVideo(){
if let appVideoURL = buildProduct?.product_video{
let url = NSURL(string: appVideoURL)
print(url)
let request = NSURLRequest(url: url as! URL)
print(request)
//self.videoTemp.load(request as URLRequest)
}
}
}

swift save multiple manage objects

Having issues saving my manage objects within my code. For some reason when i place data in the first view controller everything works well. For instance
I place new categories such as "Fruits", "Dairy", "Meats". The first view controller takes the data. When I click on the specific item such as "Dairy", and put in "Milk" for items within that section. If I go back to the previous view controller and click on "Meats", I see the same data i put in under "Dairy". How do i properly manage my NSManage objects.
Here is my code below.
import UIKit
import CoreData
class HomeSpecificItemViewController: UIViewController {
var selectedItem : [Items] = []
#IBOutlet weak var itemNameTextField: UITextField!
#IBOutlet weak var brandNameTextField: UITextField!
#IBOutlet weak var caloriesTextField: UILabel!
#IBOutlet weak var priceTextField: UILabel!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var threshHoldNumberField: UITextField!
#IBOutlet weak var stepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10
// Do any additional setup after loading the view.
}
#IBAction func saveButton(sender: AnyObject) {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let itemDescription = NSEntityDescription.insertNewObjectForEntityForName("Items", inManagedObjectContext: context) as! Items
itemDescription.setValue(itemNameTextField.text, forKey: "Items")
itemDescription.setValue(brandNameTextField.text, forKey: "Items")
do {
try context.save()
}catch _ {
}
/*
let request = NSFetchRequest(entityName: "Items")
let results : [AnyObject]?
do {
results = try context.executeFetchRequest(request)
}catch _ {
results = nil
}
if results != nil {
self.itemDescription = results as! [Items]
}
*/
}
#IBAction func cancelPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func increaseNumberStepper(sender: UIStepper) {
threshHoldNumberField.text = Int(sender.value).description
}
}
Do you have a specific view controller for each category? If so, what you have to do is add predicates to your more specific view controllers.
Something like:
var request = NSFetchRequest(entityName: "Food")
request.predicate = NSPredicate(format: "category == %#", "Meat")
meats = try! context.executeFetchRequest(request)
This would return an array of all Food objects whose category atribute holds the string "Meat".
I was saving my data to core data without properly declaring the manage context and without assigning the text labels to the core data object.
issue resolved!

Save and Load PDF in my App

I am downloading a .PDF file from a URL into a webview. It works fine , but because the pdf get updated mid month. I would like to download that file on the first of every month into my app, then the rest of the month load that saved file from the app rather than the web. Thank you for any help. I am using Swift.
following is my code so far :
import UIKit
import Social
// var justOnceThree:Bool = true
class KeyPagesViewController: UIViewController {
#IBOutlet weak var photoButton: UIButton!
#IBOutlet weak var baseKeypagesLabel: UILabel!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var keyPages: UIWebView!
var urlFra = "http://someURL.pdf"
var urlLhr = "http://someURL.pdf"
let requestURL = NSURL()
override func viewDidAppear(animated: Bool) {
PhotoButton()
}
override func viewDidLoad() {
super.viewDidLoad()
animationtitle()
let sharedDefaults = NSUserDefaults(suiteName: "group.birkyboy.TodayExtensionSharingDefaults")
var based = sharedDefaults!.objectForKey("base") as? String
if based == "HNL" {
let requestURL = NSURL(string:self.urlHnl)
let request = NSURLRequest(URL: requestURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.keyPages.hidden = false
self.keyPages.loadRequest(request)
self.baseKeypagesLabel.text = "HONOLULU"
}
if based == "IAH" {
let requestURL = NSURL(string:self.urlIah)
let request = NSURLRequest(URL: requestURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.keyPages.hidden = false
self.keyPages.loadRequest(request)
self.baseKeypagesLabel.text = "HOUSTON"
}
}
You can save the PDF in the users Documents folder. See "iOS Standard Directories: Where Files Reside" in the Apple documentation. There are various ways to get the PDF from a URL. See NSInputStream for one way to do it. Once you have it (as an NSData object, for example), you can save it as a file.

Working with NSTableView in Swift

I'm a newcomer to xcode and Swift and I was wondering if there was any simple way to add cells to a Table View similar to the method of adding selections to a Combo Box. Here's my code so far.
#IBOutlet weak var labelout: NSTextField!
#IBOutlet weak var partitionbox: NSComboBox!
#IBOutlet weak var comboboxtext: NSComboBoxCell!
#IBOutlet weak var launchtable: NSTableView!
#IBOutlet weak var tabletext: NSTextFieldCell!
#IBOutlet weak var pathlist: NSCell!
override func viewDidLoad() {
super.viewDidLoad()
partitionbox.removeAllItems()
let fileManager = NSFileManager.defaultManager()
var error: NSError? = nil
let contents = fileManager.contentsOfDirectoryAtPath("/Volumes", error: &error)
partitionbox.addItemsWithObjectValues(contents!)
// Do any additional setup after loading the
}
#IBAction func refreshbuttonpress(sender: AnyObject) {
partitionbox.removeAllItems()
let fileManager = NSFileManager.defaultManager()
var error: NSError? = nil
let contents = fileManager.contentsOfDirectoryAtPath("/Volumes", error: &error)
partitionbox.addItemsWithObjectValues(contents!)
}
#IBAction func inspectbuttonpress(sender: AnyObject) {
let fileManager = NSFileManager.defaultManager()
var error: NSError? = nil
let part = comboboxtext.stringValue
let directory = part + "/Library/LaunchAgents"
let cellcontent = fileManager.contentsOfDirectoryAtPath("/Library/LaunchAgents", error: &error)
// Anything similar to addItemsWithObjectValues for TableView?
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
My application aim is to have a list of all LaunchAgents, LaunchDaemons and Frameworks installed to an OS.
Thanks.