Swift網(wǎng)絡(luò)編程(二)文件上傳/下載

Swift網(wǎng)絡(luò)編程-文件下載上傳.png

一.前言

iOS開發(fā)中和服務(wù)器打交道除了數(shù)據(jù)請求外,還有文件的上傳及下載,OC中文件上傳及下載,筆者就不多說了,今天來看下Swift中該如何進(jìn)行文件的下載及上傳,同樣筆者做下簡單封裝,方便在其他地方調(diào)用.

二.實現(xiàn)

-1.首先導(dǎo)入Alamofire這個庫,并創(chuàng)建數(shù)據(jù)請求類(繼成NSObject)筆者命名為XHNetwork
-2.1.在XHNetwork.swift中import Alamofire這個庫,并創(chuàng)建下列屬性:
import UIKit
import Alamofire

class XHNetwork: NSObject {
    
    /**
     *  網(wǎng)絡(luò)請求成功閉包:
     */
    typealias XHNetworkSuccess = (response:AnyObject) -> ()
    
    /**
     *  網(wǎng)絡(luò)請求失敗閉包:
     */
    typealias XHNetworkFailure = (error:NSError) -> ()
    
    /**
     *  上傳進(jìn)度閉包:(回調(diào):1.單次上傳大小 2.已經(jīng)上傳大小,3.文件總大小)
     */
    typealias UploadProgress = (bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> ()
    
    /**
     *  下載進(jìn)度閉包:(回調(diào):1.單次寫入大小 2.已經(jīng)寫入大小,3.文件總大小)
     */
    typealias DownloadProgress = (bytesRead:Int64, totalBytesRead:Int64, totalBytesExpectedToRead:Int64) -> ()
    
    /**
     *  網(wǎng)絡(luò)請求單例
     */
    static let shareNetwork = XHNetwork()
    
}
-2.2.文件上傳
      /**
     文件上傳
     
     - parameter urlString:      URL
     - parameter fileURL:        要上傳文件路徑URL(包含文件名)
     - parameter uploadProgress: 上傳進(jìn)度回調(diào)(子線程)
     - parameter success:        成功回調(diào)
     - parameter failure:        失敗回調(diào)
     */
    func upload(urlString: String ,fileURL:NSURL,uploadProgress:UploadProgress, success: XHNetworkSuccess, failure: XHNetworkFailure){
        
        Alamofire.upload(.POST,urlString, file: fileURL)
            .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                
                /*
                 bytesWritten 單次上傳大小
                 totalBytesWritten  已經(jīng)上傳了大小
                 totalBytesExpectedToWrite 文件總大小
                 */
                
                /**
                 *  子線程回調(diào)上傳進(jìn)度
                 */
              uploadProgress(bytesWritten:bytesWritten,totalBytesWritten:totalBytesWritten,totalBytesExpectedToWrite:totalBytesExpectedToWrite)

            }
            .validate()
            .responseJSON { response in
                
                switch response.result {
                    
                case .Success(let value):
                    
                    /**
                     *  成功
                     */
                    success(response: value)
                    
                case .Failure(let error):
                    
                    /**
                     *  失敗
                     */
                    failure(error: error)
                    debugPrint(error)
                    
                }
        }
        
    }

-2.3.文件下載
    /**
     文件下載
     
     - parameter urlString: 下載URL
     - parameter downloadProgress: 下載進(jìn)度回調(diào)(子線程)
     - parameter fileSavePathURL: 文件存儲路徑URL(不含文件名)
     - parameter success:   成功回調(diào)
     - parameter failure:   失敗回調(diào)
     */
    func download(urlString: String ,savePathURL:NSURL ,downloadProgress: DownloadProgress, success: XHNetworkSuccess, failure: XHNetworkFailure){
        
        Alamofire.download(.GET, urlString) { temporaryURL, response in
            
            let pathComponent = response.suggestedFilename//建議文件名
            return  savePathURL.URLByAppendingPathComponent(pathComponent!)
            
            }.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead  in
                print(totalBytesRead)
                
                /*
                 bytesRead 單次下載大小
                 totalBytesRead  已經(jīng)下載大小
                 totalBytesExpectedToRead 文件總大小
                 */
                
                /**
                 *  子線程回調(diào)下載進(jìn)度
                 */
                downloadProgress(bytesRead:bytesRead,totalBytesRead:totalBytesRead,totalBytesExpectedToRead:totalBytesExpectedToRead)

            }
            .response { _, _, _, error in
                if let error = error {
                    
                    /**
                     *  失敗
                     */
                    failure(error:error)
                    debugPrint("Failed with error: \(error)")
                    
                } else {
                    
                    /**
                     *  成功
                     */
                    success(response: savePathURL.absoluteString)
                    
                }
        }
    }

三.調(diào)用

-1.1.文件上傳-調(diào)用
        
        //MARK : - 文件上傳
        XHNetwork.shareNetwork.upload(上傳URLString , fileURL: 文件完整路徑URL, uploadProgress: { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)  in
            
            /**
             *  子線程回調(diào)上傳進(jìn)度
             */
            debugPrint("單次上傳大小:\(bytesWritten)___一共上傳大小:\(totalBytesWritten)___總大小:\(totalBytesExpectedToWrite)")
            
            /**
             *  如需進(jìn)行UI處理,請到主線程操作
             */
             dispatch_async(dispatch_get_main_queue()) {
             
                 //處理UI
             }

            }, success: { (response) in
                
                /*
                成功
                */
                 debugPrint(response)
                
            }) { (error) in
                
                /*
                失敗
                */
                
                 debugPrint(error)
        }
-1.2.文件下載-調(diào)用
       //MARK: - 下載
       //文件保存路徑
       let savePathURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
       XHNetwork.shareNetwork.download("下載URLString", savePathURL: savePathURL
            , downloadProgress: { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
                
                /**
                 *  子線程回調(diào)下載進(jìn)度
                 */
                debugPrint("單次下載大小:\(bytesRead)___一共下載大小:\(totalBytesRead)___總大小:\(totalBytesExpectedToRead)")
                
                /**
                 *  如需進(jìn)行UI處理,請到主線程操作
                 */
                dispatch_async(dispatch_get_main_queue()) {
                
                     //處理UI
                }

            }, success: { (response) in
                
                /*
                成功(回調(diào)文件存儲路勁)
                */

                 debugPrint(response)
                
            }) { (error) in
                
                 /*
                 失敗
                 */

                 debugPrint(error)
        }
        

四.小節(jié)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 寫在時值1.27林心如生日 好像時間總是在不經(jīng)意間給你一個驚喜,告訴你,曾經(jīng)滄海難為...
    吹透的人閱讀 453評論 0 0
  • 是的,我是一名程序員。很多人說好炫酷,女程序員,聽起來好厲害。實不相瞞,入行的時候,我也是這么覺得的。 我畢業(yè)于一...
    皮卡球ca閱讀 4,202評論 153 92
  • 今冬去買件紅色的毛衣 其實與溫度沒絲毫關(guān)系 在那雨夾雪的夜晚 會給路燈驅(qū)散孤寂 最是留戀冰封的小溪 雪漫天飛舞卻無...
    唐泉閱讀 243評論 0 2

友情鏈接更多精彩內(nèi)容