简体   繁体   中英

Swift: Why it's a nil NSData when the image file exists in Assets?

I use Gifu to display animated Gif. But there's no image showing on my simulator. I inspect that its source code let imagePath = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent("loading.gif") returns file:///Users/Aario/Library/Developer/CoreSimulator/Devices/25C4D6CF-2482-40GA-4A6E-9493A918DDBC/data/Containers/Bundle/Application/D1F6DE41-0EB8-43A6-B4DC-70AA524E9620/test.app/default.jpeg and let imageData = NSData(contentsOfURL: imagePath) returns nil

So I try to get the NSData from some other images. The default.jpeg exits in Assets directory. It works well with named:

let imgView = UIImageView(UIImage(named: "default"))
view.addSubview(imgView)

But why I can't convert it into its proper NSData by follow code?

let imgPath = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent("default.jpeg")
let imgData = NSData(contentsOfURL: imgPath)
print(imgPath)  // print  file:///Users/Aario/Library/Developer/CoreSimulator/Devices/25C4D6CF-2482-40GA-4A6E-9493A918DDBC/data/Containers/Bundle/Application/D1F6DE41-0EB8-43A6-B4DC-70AA524E9620/test.app/default.jpeg
print(imgData)  // print nil
let imgView = UIImageView(UIImage(data: imgData))
view.addSubview(imgView)

Error Message: fatal error: unexpectedly found nil while unwrapping an Optional value

Use this PPSwiftGifs library for Swift:

  • Add PPSwiftGifs.swift & ImageIO.framework to your project.

And assign like this:

@IBOutlet weak var ImageVw: UIImageView!
ImageVw.image = PPSwiftGifs.animatedImageWithGIFNamed("imageName")

If you don't want to use any third party libraries then export all the images from your GIF image and give them a name from 1 to its screen count and add all images into your project then you can show that images into imageView this way:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loadingImage: UIImageView!

    var imageArray = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

        for var i = 1; i < 16; i++ {

            imageArray.append(UIImage(named: "\(i)")!)
        }

        loadingImage.animationImages = imageArray
        loadingImage.animationDuration = 1
        loadingImage.animationRepeatCount = 0
        loadingImage.startAnimating()
    }
}

Project sample for more Info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM