alamofire Swift:无法将图像下载到用户指定的位置

时间:2016-07-07 08:57:17

标签: swift macos cocoa alamofire

我正在努力使用Alamofire库

将url下载到用户指定的路径
let savePanel = NSSavePanel()
        savePanel.allowedFileTypes = ["jpg","gif","png","webp"]
        let result = savePanel.runModal()
        if ( result == NSFileHandlingPanelCancelButton) {
            print("cancelled")
            return
        }

        if let fileUrl:NSURL = savePanel.URL {

            Alamofire.download(.GET, imageUrl, destination: fileUrl)

        }

上面的代码似乎给了我一个错误: enter image description here

有没有人知道如何解决此问题以帮助用户将图像下载到文件位置?

2 个答案:

答案 0 :(得分:1)

试试这个为我工作: -

let manager = Alamofire.Manager.sharedInstance              
manager.session.configuration.timeoutIntervalForRequest = 600

var localPath: NSURL?
manager.download(.GET, savePanel.URL,destination: { (temporaryURL, response) in
             //Create directory
             let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
             let myDirectory = documentsPath.URLByAppendingPathComponent("MyDirectory")
             do {
                  try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.path!, withIntermediateDirectories: true, attributes: nil)
                } catch let error as NSError {
                     NSLog("Unable to create directory \(error.debugDescription)")
               }
                let directoryURL = myDirectory
                let pathComponent = response.suggestedFilename

                localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
                return localPath!
            })
                .response { (request, response, _, error) in
                    print(response)
                    if error != nil {
                        print("REQUEST: \(request)")
                        print("RESPONSE: \(response)")
                    }
                    if localPath != nil {
                         print("from url Downloaded file to \(localPath!)")
                    }

            }

答案 1 :(得分:0)

您应该使用::

的内容
Alamofire.request(.GET, "https://httpbin.org/image/png")
     .responseImage { response in
         debugPrint(response)

         print(response.request)
         print(response.response)
         debugPrint(response.result)

         if let image = response.result.value {
             print("image downloaded: \(image)")
         }
     }

This is on reference page here.

并且只使用导入AlamofireImage

并将其添加到您的podFile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'AlamofireImage', '~> 2.0'

我强烈推荐使用Alamofire Image,因为它是一个特定用途的库,是Alamofire用于下载图像的组件。