我正在尝试从 Flickr 下载图像并将它们保存到文档目录。
获取结果成功返回,并且每个返回的图像 url,我都会发出另一个下载图像的请求。
从我的调试来看,我遇到的问题是这一行:
let savePath = documentsDirectory! + "/\(imageURL)"
每当我尝试将 imagePath/文件名保存为“imageURL”时,当我运行我的代码从文档目录中读取时它不会保存。
但是当我尝试类似的事情时:
let savePath = documentsDirectory! + "/someImage.jpg"
let savePath = documentsDirectory! + "/abc.jpg"
它可以正确保存,并且我读取文档目录的代码可以正确打印出来。
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()
从文档目录读取数据的代码:
// 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)
}