我的代码******
let responseDownloaded = Alamofire.download(.GET, url, destination: { (url, response) -> NSURL in
let pathComponent = "recent.json"
let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileUrl = directoryURL.URLByAppendingPathComponent(pathComponent)
return fileUrl
})
responseDownloaded.responseArray(keyPath: "aTracks") {[unowned self] (response: Response< [DataMusic], NSError>) in
switch response.result {
case .Success(let music):
// some code
case .Failure(let error):
// some code
}
}
带有json的文件被下载到磁盘,但responseArray给我的响应为零。这有什么不对?
答案 0 :(得分:1)
Alamofire.download()没有返回任何值。
如果您需要访问响应数据:
Alamofire.download(
url,
method: .get,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil,
to: destination).downloadProgress(closure: { (progress) in
//progress closure
}).response(completionHandler: { (DefaultDownloadResponse) in
//here you able to access the DefaultDownloadResponse
//result closure
})
答案 1 :(得分:1)
我的解决方案(使用ObjectMapper和SwiftyJSON):
var fileName: String?
var finalPath: NSURL?
Alamofire.download(.GET, url, destination: { (temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
fileName = response.suggestedFilename!
finalPath = directoryURL.URLByAppendingPathComponent(fileName!)
return finalPath!
}
return temporaryURL
})
.response { (request, response, data, error) in
var fileExist: Bool!
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("recent.json").path!
let fileManager = NSFileManager.defaultManager()
fileExist = fileManager.fileExistsAtPath(filePath) ? true : false
if fileExist != nil {
let jsonData = JSON(data: NSData(contentsOfURL: NSURL(fileURLWithPath: filePath))!)
if let aTracks = jsonData.dictionary {
if let track = aTracks["aTracks"] {
if let arrTack = Mapper<DataMusic>().mapArray(track.rawString()) {
}
}
}
}
}