-1

My code is to display image.jpg in a window. That was written in Swift 3. Recently, I updated to Swift 4 with Xcode 10.2 . It doesn't work at all. I also rewrote it in Swift 5. It still doesn't work. I had to download the old Xcode 10 in order to run my code in Swift 3 to work again. I wonder what happened to the code.

Here is my main code to display the picture.

override func viewDidAppear() {
    super.viewDidAppear()

    imageView.image = NSImage(byReferencingFile: "\(ViewController.GlobaVariable.selecFile)" )

    print("\(ViewController.GlobaVariable.selecFile)")
    /// The print statement work  but not the image.
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
N4A
  • 1
  • 5
  • Did you check that the `NSImage(byReferencingFile: "\(ViewController.GlobaVariable.selecFile)" )` is not nil? – Bjarke H. Søndergaard Apr 24 '19 at 01:28
  • I checked the output was nil. How can I fix it? I wonder why it worked in swift 3 but not in swift 4 and 5? – N4A Apr 24 '19 at 01:40
  • where is your file located? Don't save the whole file path. You should save only the file name and its location/directory – Leo Dabus Apr 24 '19 at 01:41
  • file is located in document directory. I just use GlobaVaraible to transfer the path. It worked well in swift 3. – N4A Apr 24 '19 at 01:44
  • you just need to recreate your file url appending its filename to the document directory url and use the resulting url path property – Leo Dabus Apr 24 '19 at 01:48
  • Ok, let me try. Thanks. – N4A Apr 24 '19 at 03:31
  • 1
    Let us see the code that declares `selecFile`. You shouldn’t be turning it into a string using string interpolation. Different versions of Swift might do slightly different interpolations, depending on the property’s type. – Rudedog Apr 24 '19 at 05:09
  • Thanks for helped. I got it work. I will post the code later when complete program. Thank YOU. – N4A Apr 24 '19 at 20:37
  • After updated swift 3 to 4 and 5, The code had been changed. Therefore, the path could not be completely selected correctly. – N4A Apr 24 '19 at 21:22

1 Answers1

-1
    let openPanel = NSOpenPanel()
    openPanel.beginSheetModal(for:self.view.window!) { (response) in
        if response.rawValue == NSFileHandlingPanelOKButton
        {
            let fileURL = openPanel.url!

            //////////////////
            let ph = fileURL.absoluteString
            let path = (ph as NSString).substring(from: 7)
            //print(path)

            //////////////////////

            GlobaVariable.selecFile = path

        }
    }
N4A
  • 1
  • 5