SwiftでAFHTTPRequestOperationManagerを利用する

Swiftでファイルダウンロードの進捗を表示するために、 AFNetworkingのAFHTTPRequestOperationManagerを利用する方法です。


//ファイルの保存先をfilePathに指定 let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String let cacheKey = "/test1" let filePath = documentsPath+cacheKey+"/"+fileName //managerの宣言 let manager = AFHTTPRequestOperationManager() //レスポンスの形式を設定 manager.responseSerializer = AFHTTPResponseSerializer() //HTTPメソッド、接続先のURL、リクエストパラメータを設定 var request:NSMutableURLRequest = manager.requestSerializer.requestWithMethod("GET", URLString: path, parameters: parameters, error: nil) //Operationを宣言して、完了時と失敗時の動作を設定 var operation:AFHTTPRequestOperation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, responseObject) -> Void in println("完了") }, failure: { (operation, error) -> Void in println("失敗") //失敗したファイルが残ってしまっている場合には削除しておく let fileManager = NSFileManager.defaultManager() let isFile = fileManager.fileExistsAtPath(filepath, isDirectory: nil) if isFile { fileManager.removeItemAtPath(filepath,error:nil) } }) //ダウンロードの進捗を表示する処理を設定 operation.setDownloadProgressBlock({ (bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in //Progress println("進捗") let progress = (CGFloat(totalBytesRead) / CGFloat(totalBytesExpectedToRead) * 100) println(progress) }) //レスポンスの保存先をfilePathに設定 operation.outputStream = NSOutputStream(toFileAtPath: filepath, append: false) //ダウンロードを開始 manager.operationQueue.addOperation(operation)

参考にさせていただいたサイト:http://dev.classmethod.jp/smartphone/iphone/ios-afnetworking2/