将图像保存到文档目录

时间:2016-04-12 21:29:44

标签: ios swift nsdocumentdirectory data-persistence

我正在尝试从Flickr下载图像并将其保存到文档目录。

获取结果成功返回,并且每个图像网址都会返回,我再次请求下载图像。

从我的调试中,我遇到的问题是这一行:

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)
        }

0 个答案:

没有答案