2

I'm trying to fetch image from its default class to store in my own class model. Image seems to loads okay but it didn't store to my class. here's my code

dataImage model

 class dataImage {
    var userId: String
    var value: Double

    var photo: UIImage?

    init(userId:String, value: Double, photo: UIImage?){
        self.userId = userId
        self.value = value
        self.photo = photo
}

}

view controller

    for asset in photos{
        asset.fetchFullScreenImageWithCompleteBlock({ image, info in
            let images = image
            let data1 = dataImage(userId: "1", value: 1.0, photo: images)
            self.datas += [data1]
            print("*")
        })
    }
    print("datas: \(datas.count)")

so i have 6 'image' in photos and '*' print 6 times, but datas.count is 0, how to fix this?

1 Answer 1

1

The asset.fetchFullScreenImageWithCompleteBlock call is asynchronous and returns immediately. Therefore your for loop finishes very quickly, while all 6 asset fetches occur in the background. By the time the print executes, the fetches have not yet finished, so the completion block has not yet run for each.

One simple method to overcome this would be to put the print inside the completion block, surrounded by an if that counts up to the number of photos. Something along the lines of:

let completed = 0
for asset in photos{
    asset.fetchFullScreenImageWithCompleteBlock({ image, info in
        let images = image
        let data1 = dataImage(userId: "1", value: 1.0, photo: images)
        self.datas += [data1]
        print("*")
        tableView.reloadData()
        completed++
        if completed == photos.count {
          print("datas: \(datas.count)")
        }
    })
}

Since you want to ultimately show this in a tableView, I have included the reloadData at the appropriate point.

Then

func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return datas.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var data = datas[indexPath.row]
    var cell = tableView.dequeueReusableCellWithIdentifier... etc
}
Sign up to request clarification or add additional context in comments.

3 Comments

but dataImage still not transferred into datas, i need it to be included in datas so i could show it in table view @Michael
If you're trying to show this in a table view, you would do it slightly differently so it updates with each image coming in, rather than printing a message when all are loaded. I will update the answer.
it works!!! I keep forgetting that "tableview.reloadData" line. thanks a lot!! @Michael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.