我知道如何向alamofire请求添加自定义标头,但是是否可以向alamofire下载添加自定义标头?另外,如何更改文件路径中保存的文件扩展名?
Alamofire.download(.GET, myURL, { (temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager()
.URLsForDirectory(.DocumentDirectory,
inDomains: .UserDomainMask)[0]
as? NSURL {
let pathComponent = response.suggestedFilename
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
return temporaryURL
}).response{ (_,_, data, err) -> Void in
println(data)
}
答案 0 :(得分:5)
Here's a code sample that matches yours using @mattt's suggestion of using an NSURLRequest
with the header already attached.
let URLString = "whatever/floats/your/boat"
let URLRequest = NSMutableURLRequest(URL: NSURL(string: URLString)!)
URLRequest.setValue("Header Value", forHTTPHeaderField: "Header Name")
let request = Alamofire.download(URLRequest) { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
if let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
let pathComponent = response.suggestedFilename
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
return temporaryURL
}
request.response { _, response, data, error in
if let data = data as? NSData {
println(NSString(data: data, encoding: NSUTF8StringEncoding))
} else {
println(response)
println(error)
}
}
答案 1 :(得分:-1)
我找到了解决方法。
var headers = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
headers = [ "X-ApiKey" : "someValue",
"Content-Type" : "application/json; charset=utf-8"]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = headers
let manager = Alamofire.Manager(configuration: configuration)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
manager.download(.GET, "place your URL here", destination: destination)
.progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
println(totalBytesRead)
}
.response { (request, response, data, error) in
fileName = response?.suggestedFilename
completionHandler(fileName: fileName as String?, error: error)
println(data)
}
希望这有助于某人。谢谢