swift基於Alamofire的簡易封裝整理 頂 原

//
//  BLHttpSessionsRequest.swift
//  ALSFinancial-Swift
//
//  Created by 冰淚 on 16/8/23.
//  Copyright © 2016年 冰淚. All rights reserved.
//網絡請求類封裝

import UIKit
import Alamofire

 

//創建請求類枚舉
enum RequestType: Int {
    case requestTypeGet
    case requestTypePost
}

//創建一個閉包(注:oc中block)
typealias sendVlesClosure = (AnyObject?, NSError?)->Void
typealias uploadClosure = (AnyObject?, NSError?,Int64?,Int64?,Int64?)->Void

class BLHttpSessionsRequest: NSObject {
    
    // --GET請求獲取JSON數據
    func BLGetJSONDataWithUrl(url: String, parameters: AnyObject, successed:(responseObject: AnyObject?) -> (), failed: (error: NSError?) -> ()) {
        
        Alamofire.request(.GET, url, parameters: parameters as? [String : AnyObject]).responseJSON { (data: Response<AnyObject, NSError>) in
            if data.result.isSuccess {
                successed(responseObject: data.data)
            }else {
                failed(error: data.result.error)
            }
        }
    }
    
    // --POST請求獲取JSON數據
    func BLPostJSONDataWithUrl(url: String, parameters: AnyObject, successed:(responseObject: AnyObject?) -> (), failed: (error: NSError?) -> ()) {
        //print(parameters)
        Alamofire.request(.POST, url, parameters: parameters as? [String : AnyObject]).responseJSON { (data: Response<AnyObject, NSError>) in
            if data.result.isSuccess {
                successed(responseObject: data.data)
            }else {
                failed(error: data.result.error)
            }
        }
        
    }
    
    // --文件上傳
    //fileURL實例:let fileURL = NSBundle.mainBundle().URLForResource("Default",withExtension: "png")
    func BLUpload(URLString:String,fileURL:NSURL,progress:(bytesWritten: Int64?,totalBytesWritten: Int64?,totalBytesExpectedToWrite: Int64?) -> Void, responseResult:(responseValue: AnyObject?,error: NSError?) -> Void) {
        
        Alamofire.upload(.POST, URLString, file: fileURL).progress {(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) -> Void in
            progress(bytesWritten:bytesWritten,totalBytesWritten:totalBytesWritten,totalBytesExpectedToWrite:totalBytesExpectedToWrite)
            }.responseJSON { response in
                responseResult(responseValue:response.result.value,error:response.result.error)
        }
    }
    /*
     ** 寫法二  block定義成宏的寫法
     //fileURL實例:let fileURL = NSBundle.mainBundle().URLForResource("Default",withExtension: "png")
     func BLUpload(URLString:String,fileURL:NSURL,block:uploadClosure) {
     
     Alamofire.upload(.POST, URLString, file: fileURL).progress {(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) -> Void in
     block(nil,nil,bytesWritten ,totalBytesWritten,totalBytesExpectedToWrite)
     }.responseJSON { response in
     block(response.result.value,response.result.error,nil,nil,nil)
     }
     }
     
     
     */
    
    // --文件下載
    //下載到默認路徑let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
    let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
    //默認路徑可以設置爲空,因爲有默認路徑
    func BLDownload(type:RequestType,URLString:String,progress:(bytesRead: Int64?,totalBytesRead: Int64?,totalBytesExpectedToRead: Int64?) -> Void, responseResult:(responseValue: AnyObject?,error: NSError?) -> Void) {
        switch type {
        case .requestTypeGet:
            Alamofire.download(.GET, URLString, destination: destination)
                .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
                    progress(bytesRead:bytesRead,totalBytesRead:totalBytesRead,totalBytesExpectedToRead:totalBytesExpectedToRead)
                }
                .response { (request, response, _, error) in
                    responseResult(responseValue:response,error:error)
            }
            break
        case .requestTypePost:
            Alamofire.download(.POST, URLString, destination: destination)
                .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
                    progress(bytesRead:bytesRead,totalBytesRead:totalBytesRead,totalBytesExpectedToRead:totalBytesExpectedToRead)
                }
                .response { (request, response, _, error) in
                    responseResult(responseValue:response,error:error)
            }
        }
    }
    
    /* block定義成宏的寫法
     
     let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
     //默認路徑可以設置爲空,因爲有默認路徑
     func BLDownload(type:RequestType,URLString:String,block:uploadClosure) {
     switch type {
     case .requestTypeGet:
     Alamofire.download(.GET, URLString, destination: destination)
     .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
     
     block(nil,nil,bytesRead, totalBytesRead, totalBytesExpectedToRead)
     }
     .response { (request, response, _, error) in
     block(response,error,nil,nil,nil)
     }
     break
     case .requestTypePost:
     Alamofire.download(.POST, URLString, destination: destination)
     .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
     block(nil,nil,bytesRead, totalBytesRead, totalBytesExpectedToRead)
     }
     .response { (request, response, _, error) in
     block(response,error,nil,nil,nil)
     }
     }
     }
     
     */
    
    // --上傳多張圖片
    func BLPostUploadMultiPicture(url: String, parameters: AnyObject, imgParameters: [UIImage]?, successed:(responseObject: AnyObject?) -> (), failed: (error: NSError?) -> ()) {
        Alamofire.upload(.POST, url, headers: parameters as? [String : String], multipartFormData: { (formData) in
            for index in 0..<imgParameters!.count {
                
                let imageData = UIImagePNGRepresentation(imgParameters![index] )
                formData.appendBodyPart(data: imageData!, name: "img\(index)", fileName: "\(index).jpg", mimeType: "image/png")
            }
        }, encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold){ (result) in
            switch result {
            case .Success(let upload, _, _):
                upload.responseJSON{ respone in
                    print(respone.data)
                    successed(responseObject: respone.data)
                    
                }
            case .Failure(let error):
                
                print(error)
                
                break
            }
        }
    }
    
    
}

轉載請註明出處謝謝 http://my.oschina.net/iceTear/blog/743007

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章