2016-09-21 54 views
0

我的代碼******Alamofire3 - Alamofire.download:responseArray返回響應零

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給我回應爲零。什麼是錯的?

回答

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 
    }) 
+0

這是Alamofire 4或3 –

+1

這是Alamofire 4.0使用斯威夫特3。如果您尋找Alamofire 3.x解決方案,請更新您的問題。 – pedrouan

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()) { 

          } 

         } 
        } 
      } 


    }