Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

skobuv

macrumors newbie
Original poster
Dec 10, 2016
10
0
I have 3 GIFs outside the Assets folder and I'm trying to pass the data from a table view to next view controller. I have two tables, created outlet to UIImageView. ThirdView.swift contains struct:
Code:
struct ThirdView {
    var ThirdViewArray = [String]()
    var Pic = [String]()
}
FirstTableViewController.swift contains arrays of gifs, which I would like to pass to imageViews (I tried to pass imageLiteral and also UIImage.gif(name: "nameOfGif")!):
Code:
class FirstTableViewController: UITableViewController {

var BodyPartsArray = [String]()
var SecondArray = [SecondTable]()
var ThirdArray = [ThirdView]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    BodyPartsArray = ["Neck", "Shoulders", "Upper Arms", "Forearms", "Back", "Chest", "Waist", "Hips", "Thighs", "Calves"]

    SecondArray = [
    SecondTable(SecondTitle: ["Neck1","Neck2","Neck3"]),
    SecondTable(SecondTitle: ["Shoulders1","Shoulders2","Shoulders3"]),
    SecondTable(SecondTitle: ["Upper Arms1","Upper Arms2","Upper Arms3"]),
    SecondTable(SecondTitle: ["Forearms1","Forearms2","Forearms3"]),
    SecondTable(SecondTitle: ["Back1","Back2","Back3"]),
    SecondTable(SecondTitle: ["Chest1","Chest2","Chest3"]),
    SecondTable(SecondTitle: ["Waist1","Waist2","Waist3"]),
    SecondTable(SecondTitle: ["Hips1","Hips2","Hips3"]),
    SecondTable(SecondTitle: ["Thighs1","Thighs2","Thighs3"]),
    SecondTable(SecondTitle: ["Calves1","Calves2","Calves3"])]

    ThirdArray = [
        ThirdView(ThirdViewArray: ["NeckText1","NeckText2","NeckText3"], Pic: [#imageLiteral(resourceName: "giphy.gif"),#imageLiteral(resourceName: "giphy2.gif"),#imageLiteral(resourceName: "giphy3.gif")]),
        ThirdView(ThirdViewArray: ["ShouldersText1","ShouldersText2","ShouldersText3"], Pic: [#imageLiteral(resourceName: "giphy3.gif"),#imageLiteral(resourceName: "giphy2.gif"),#imageLiteral(resourceName: "giphy.gif")]),
        ThirdView(ThirdViewArray: ["Upper ArmsText1","Upper ArmsText2","Upper ArmsText3"], Pic: []),
        ThirdView(ThirdViewArray: ["ForearmsText1","ForearmsText2","ForearmsText3"], Pic: []),
        ThirdView(ThirdViewArray: ["BackText1","BackText2","BackText3"], Pic: []),
        ThirdView(ThirdViewArray: ["ChestText1","ChestText2","ChestText3"], Pic: []),
        ThirdView(ThirdViewArray: ["WaistText1","WaistText2","WaistText3"], Pic: []),
        ThirdView(ThirdViewArray: ["HipsText1","HipsText2","HipsText3"], Pic: []),
        ThirdView(ThirdViewArray: ["ThighsText1","ThighsText2","ThighsText3"], Pic: []),
        ThirdView(ThirdViewArray: ["CalvesText1","CalvesText2","CalvesText3"], Pic: [])]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return BodyPartsArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let Cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
    Cell.textLabel?.text = BodyPartsArray[indexPath.row]

    return Cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow! as NSIndexPath
    let DestViewController = segue.destination as! SecondTableViewController
    var SecondTableArrayTwo: SecondTable
    SecondTableArrayTwo = SecondArray[indexPath.row]
    DestViewController.ExerciseListArray = SecondTableArrayTwo.SecondTitle


    var ThirdAnswerArray: ThirdView
    ThirdAnswerArray = ThirdArray[indexPath.row]
    DestViewController.SecondAnswerArray = ThirdAnswerArray.ThirdViewArray
    DestViewController.SecondAnswerArrayPic = ThirdAnswerArray.Pic
}

ExercisesViewController contains:

Code:
var FirstString = String()
var ExerciseImage = UIImage()

override func viewDidLoad() {
    TextView.text = FirstString
    self.ImageView.image = UIImage.gif(name: "")

}

I used this script to load Gifs:

Code:
import Foundation
import UIKit
import ImageIO

extension UIImageView {

public func loadGif(name: String) {
    DispatchQueue.global().async {
        let image = UIImage.gif(name: name)
        DispatchQueue.main.async {
            self.image = image
        }
    }
}

}

extension UIImage {

public class func gif(data: Data) -> UIImage? {
    // Create source from data
    guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
        print("SwiftGif: Source for the image does not exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source)
}

public class func gif(url: String) -> UIImage? {
    // Validate URL
    guard let bundleURL = URL(string: url) else {
        print("SwiftGif: This image named \"\(url)\" does not exist")
        return nil
    }

    // Validate data
    guard let imageData = try? Data(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(url)\" into NSData")
        return nil
    }

    return gif(data: imageData)
}

public class func gif(name: String) -> UIImage? {
    // Check for existance of gif
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    // Validate data
    guard let imageData = try? Data(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gif(data: imageData)
}

internal class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    // Get dictionaries
    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
    if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
        return delay
    }

    let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)

    // Get delay time
    var delayObject: AnyObject = unsafeBitCast(
        CFDictionaryGetValue(gifProperties,
                             Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
        to: AnyObject.self)
    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
                                                         Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as? Double ?? 0

    if delay < 0.1 {
        delay = 0.1 // Make sure they're not too fast
    }

    return delay
}

internal class func gcdForPair(_ a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    // Check if one of them is nil
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    // Swap for modulo
    if a! < b! {
        let c = a
        a = b
        b = c
    }

    // Get greatest common divisor
    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b! // Found it
        } else {
            a = b
            b = rest
        }
    }
}

internal class func gcdForArray(_ array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(val, gcd)
    }

    return gcd
}

internal class func animatedImageWithSource(_ source: CGImageSource) ->    UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    // Fill arrays
    for i in 0..<count {
        // Add image
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        // At it's delay in cs
        let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
                                                        source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    // Calculate full duration
    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    // Get frames
    let gcd = gcdForArray(delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    // Heyhey
    let animation = UIImage.animatedImage(with: frames,
                                          duration: Double(duration) / 1000.0)

    return animation
}

And the problem is, although it loads working gif, it shows the same gif, even though I am entering different imageLiterals or different name of the images.

What am I missing?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.