【问题标题】:Alamofire get pdf as NSDataAlamofire 获取 pdf 作为 NSData
【发布时间】:2015-10-09 10:12:38
【问题描述】:

我使用这个 alamofire 请求来获取一个 pdf 文件,我想将它保存为 NSData:

func makeDataCall(urlString: String, completionHandler: (responseObject: NSData?, error: NSError?) -> ()) {
    //Perform request
    Alamofire.request(.GET, urlString, headers: ["Authorization": auth])
        .responseData { request, response, responseData in
            print(request)
            print(response)
            print(responseData)
            completionHandler(responseObject: responseData.data, error: nil)
    }
}

在回复中我得到这个:

"Content-Length" = 592783;
"Content-Type" = "application/pdf";

但是responseData.data 为零。

我做错了什么?

【问题讨论】:

  • 您使用的是哪个版本的 Alamofire?
  • 最新的,适用于 swift 2.0
  • on their page 的语法与你的不同,所以我想你可能没有使用最新版本。

标签: ios swift nsdata alamofire


【解决方案1】:

编辑我之前的回复,我读你的问题太快了。

要下载像 pdf 这样的文件,您应该使用 Alamofire.download 而不是 request

文档中有一个部分: https://github.com/Alamofire/Alamofire#downloading-a-file

刚刚检查了一些来自互联网的随机 pdf,这对我来说很好:

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "http://box2d.org/manual.pdf", destination: destination)
  .response { _, _, _, error in
  if let error = error {
    print("Failed with error: \(error)")
  } else {
    print("Downloaded file successfully")
  }
}

【讨论】:

  • 在 Alamofire 4.4、Swift 3.1 中,现在是:let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory, in: .userDomainMask)Alamofire.download("http://box2d.org/manual.pdf", to: destination)。另外,如果我理解正确的话,看起来响应闭包现在只包含一个参数:response(其中有 response.error 作为字段)。
【解决方案2】:

在 Swift 4 中,如果您想下载 pdf,请使用此代码

    let h: HTTPHeaders = [
        "Accept": "application/pdf",
        "Content-Type": "application/pdf",
    ]
    //random document name
    let randomString = NSUUID().uuidString

    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent("\(randomString).pdf")
        return (documentsURL, [.removePreviousFile])
    }

    Alamofire.download("yourURL",method: .get,headers: h, to: destination).response { response in
        if let destinationUrl = response.destinationURL {
            print("destinationUrl \(destinationUrl.absoluteURL)")
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多