Reputation: 177
I am trying to download images from a url and then save them in an array of NSData.
I have a Class called Data Manager in which all my data is stored as well as functions for downloading images and getting data from URL.
In the same class I declare a variable called imageData of type [NSData] and let it equal an empty array as follows:
var imageData: [NSData] = []
here is what my other 2 functions look like:
func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
func downloadImage(url: NSURL){
print("Download Started")
print("lastPathComponent: " + (url.lastPathComponent ?? ""))
getDataFromUrl(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
print(response?.suggestedFilename ?? "")
print("Download Finished")
self.imageData.append(data)
print("you have \(self.imageData.count)")
}
print("you still do have \(self.imageData.count)")
}
}
I call these functions in my app Delegate class under the function didFinishLaunchingWithOptions as so
let dataManager = DataManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
dataManager.URLStringArray.removeAll()
for url in dataManager.objects.imageURLS {
dataManager.URLStringArray.append(url)
}
for url in dataManager.URLStringArray {
dataManager.downloadImage(NSURL(string: url)!)
print(url)
}
return true
}
In my view controller I go to get the data in the image array via following function:
func returnImageData() -> [NSData] {
print("your image count is \(imageData.count))")
return imageData
}
but the array is empty! Even though through the whole process I noticed that the array was becoming larger and larger because the print to the logs were showing the array increasing!
Thanks!
Upvotes: 0
Views: 783
Reputation: 3661
Since you are using async call to download the image data, at the the time you are printing the count of the imageData the image is not yet downloaded and so the array is not yet populated. Of course this is assuming that you are using the right property names as Eric.D has pointed out.
Upvotes: 1