I am trying to download images from Flickr and saving them to the Documents Directory.
The fetch results come back successfully and with each image url that comes back, I make another request to download the image.
From my debugging, the problem I have is this line:
let savePath = documentsDirectory! + "/\(imageURL)"
Whenever I try to save the imagePath/file name to be the "imageURL", it doesn't save when I run my codes to read from the Documents Directory.
But when I try something like:
let savePath = documentsDirectory! + "/someImage.jpg"
let savePath = documentsDirectory! + "/abc.jpg"
It saves properly and my codes that read the Documents Directory print them out properly.
let url = NSURL(string: "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=SOMEAPIKEY&lat=51.03&lon=-114.14&extras=url_s&per_page=20&format=json&nojsoncallback=1")! ;
let task = NSURLSession.sharedSession().dataTaskWithURL(url){(data, response, error) -> Void in
if let data = data {
// print(urlContent)
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jsonResult.count > 0 {
if let items = jsonResult["photos"] as? NSDictionary {
if let photoItems = items["photo"] as? NSArray {
for item in photoItems {
if let imageURL = item["url_s"] as? String {
dispatch_async(dispatch_get_main_queue(), {
print(imageURL)
self.items.append(imageURL)
self.collectionView.reloadData()
//take each imageURL and download them
let url = NSURL(string: imageURL)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (imageData, response, error) -> Void in
if error != nil {
print(error)
} else {
var documentsDirectory: String?
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if paths.count > 0 {
documentsDirectory = paths[0] as? String
let savePath = documentsDirectory! + "/\(imageURL)"
print(imageData)
print(savePath)
NSFileManager.defaultManager().createFileAtPath(savePath, contents: imageData, attributes: nil)
}
}
}
task.resume()
})
}
}
}
}
}
//
// print(jsonResult)
//
} catch {
print("JSON Serialization failed")
}
}
}
task.resume()
Codes to read data from the Documents Directory:
// We need just to get the documents folder url
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
// now lets get the directory contents (including folders)
do {
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
print(directoryContents)
} catch let error as NSError {
print(error.localizedDescription)
}