Alamofire.download() method: Where is the file and did it save successfully?

后端 未结 5 724
无人及你
无人及你 2021-02-02 11:16

The example for using Alamofire.download() works just fine, but there isn\'t any detail in how to access the resulting downloaded file. I can figure out where the file is and wh

5条回答
  •  深忆病人
    2021-02-02 11:34

    I spent about 8 hours looking for an answer to this one. The solution below works for me, and basically I chain to the download method to display the image. In the example below, I'm downloading the profile image of a user knowing his Facebook ID:

        let imageURL = "http://graph.facebook.com/\(FBId!)/picture?type=large"
    
        let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
            (temporaryURL, response) in
    
            if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
                var localImageURL = directoryURL.URLByAppendingPathComponent("\(self.FBId!).\(response.suggestedFilename!)")
                return localImageURL
            }
            return temporaryURL
        }
    
        Alamofire.download(.GET, imageURL, destination).response(){
            (_, _, data, _) in
                if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
                    var error: NSError?
                    let urls = NSFileManager.defaultManager().contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: nil, options: nil, error: &error)
    
                    if error == nil {
                        let downloadedPhotoURLs = urls as! [NSURL]
                        let imagePath = downloadedPhotoURLs[0] // assuming it's the first file
                        let data = NSData(contentsOfURL: imagePath)
                        self.viewProfileImage?.image = UIImage(data: data!)
                    }
                }
        }
    

提交回复
热议问题