Search code examples
iosswiftmapkitassets

Importing text and images swift Map Kit


I am trying to get specific images and text files to imbed into my second view controller based on which pin is selected in my Map View. Currently I have my title being transferred through a segue. my thought was to name the text files and images the same as the title so they would be correctly selected when the title was found.

EG: Title = big ben : title = "big ben" hence select image title.png and title.txt However I am having trouble implementing this as I am unsure how to tell swift to select an image and text file from the assets folder.

I currently have the segue and prepare for segue implemented as:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.rightCalloutAccessoryView {
        if let artworkPin = view.annotation as? Artwork {
            performSegue(withIdentifier: "no", sender: artworkPin)
        }
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == "no" {
            if let artworkPin = sender as? Artwork {
                let ViewTwo = segue.destination as! ViewTwo
                ViewTwo.artworkPin = artworkPin
            }
        }
    }
}

}

and my second view class as:

@IBOutlet weak var art_image: UIImageView!

@IBOutlet weak var art_desc: UITextView!

@IBOutlet weak var art_title: UILabel!
var artworkPin: Artwork!



override func viewDidLoad() {
    super.viewDidLoad()
    art_title.text = artworkPin.title




}

how can I get swift to pull from the assets folder? I have attached my full code below: ViewControllerOne

ViewTwo


Solution

  • when storing non image files in XCAssets, you should use NSDataAsset to acccess their content

    Reference : https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSDataAsset_Class/

     func readBundle(file:String) -> String
    {
        var res = ""
        if let asset = NSDataAsset(name: file) , let string = String(data:asset.data, encoding: String.Encoding.utf8){
            res = string
        }
        return res
    }
    

    To load the image in second view controller

    @IBOutlet weak var art_image: UIImageView!
    
    @IBOutlet weak var art_desc: UITextView!
    
    @IBOutlet weak var art_title: UILabel!
    var artworkPin: Artwork!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        art_title.text = readBundle(artworkPin.title)
    art_image.image = UIImage(named:"PinSample")
    
    }
    

    Note : Asset image name and name in the code should be same