swift 网络工具类

//
//  NetworkUtils.swift
//  ArtCircle
//
//  Created by wupeng on 15/12/2.
//
//

import Alamofire
typealias uploadProgress = ((bytesW:Int64, totalBytesW:Int64, totalBytesExpectedToW:Int64) -> Void)
class NetworkUtils: NSObject {
    static func getDomain() -> String {
        return "jianbao.artxun.com"
    }
    static func getRequest(URLString: URLStringConvertible,parameters: [String: AnyObject]? = nil,successHandler:Response<AnyObject, NSError> -> Void,failHandler:Response<AnyObject, NSError> -> Void) -> Request
    {
        AccountSessionUtils.setCookie()
        return Alamofire.request(.GET,URLString, parameters: parameters).responseJSON(completionHandler: { response -> Void in
            if response.result.isSuccess {
                successHandler(response)
            } else {
                //                    网络问题
                failHandler(response)
                AlertShowUtils.showTopTipsAlert("网络不可达")
            }
        })
    }
    static func wp_getRequest(URLString: URLStringConvertible,parameters: [String: AnyObject]? = nil,successHandler:( (value:AnyObject) -> Void ),withFailHandler fail:((error:NSError) -> Void )? = nil) -> Request
    {
        AccountSessionUtils.setCookie()
        AlertShowUtils.showLoading()
        return Alamofire.request(.GET,URLString, parameters: parameters).responseJSON(completionHandler: { response -> Void in
            AlertShowUtils.hiddenLoading()
            if response.result.isSuccess {
                successHandler(value: response.result.value!)
            } else {
                //                    网络问题
                if fail != nil {
                    fail!(error: response.result.error!)
                }
                AlertShowUtils.showTopTipsAlert("网络不可达")
            }
        })
    }
    static func wp_postRequest(URLString: URLStringConvertible,parameters: [String: AnyObject]? = nil,successHandler: ( (value:AnyObject) -> Void ),withFailHandler fail:((error:NSError) -> Void )) -> Request
    {
        AccountSessionUtils.setCookie()
        return Alamofire.request(.POST,URLString, parameters: parameters).responseJSON(completionHandler: { response -> Void in
            if response.result.isSuccess {
                successHandler(value: response.result.value!)
            } else {
                //                    网络问题
                fail(error: response.result.error!)
                AlertShowUtils.showTopTipsAlert("网络不可达")
            }
        })
    }
    static func postRequest(URLString: URLStringConvertible,parameters: [String: AnyObject]? = nil,successHandler: Response<AnyObject, NSError> -> Void,failHandler:Response<AnyObject, NSError> -> Void) -> Request
    {
        AccountSessionUtils.setCookie()
        return Alamofire.request(.POST,URLString, parameters: parameters).responseJSON(completionHandler: { response -> Void in
                if response.result.isSuccess {
                    successHandler(response)
                } else {
                    //                    网络问题
                    failHandler(response)
                    AlertShowUtils.showTopTipsAlert("网络不可达")
                }
            })
    }
    static func wp_Upload(URLString: String,parameters: Dictionary<String,String>,imageData:NSData,successHandler: ( (value:AnyObject) -> Void ),withFailHandler fail:((error:NSError) -> Void ),byProgress progress:uploadProgress) -> Request {
        let urlRequest = NetworkUtils.urlRequestWithComponents(URLString, parameters: parameters, imageData: imageData)
        return Alamofire.upload(urlRequest.0, data: urlRequest.1)
            .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
                print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    progress(bytesW: bytesWritten, totalBytesW: totalBytesWritten, totalBytesExpectedToW: totalBytesExpectedToWrite)
                })
            }
            .responseJSON { response  in
                if response.result.isSuccess {
                    successHandler(value: response.result.value!)
                } else {
                    fail(error: response.result.error!)
                    AlertShowUtils.showTopTipsAlert("网络不可达")
                }
        }
    }
    static func Upload(URLString: String,parameters: Dictionary<String,String>,imageData:NSData,successHandler: Response<AnyObject, NSError> -> Void,failHandler:Response<AnyObject, NSError> -> Void) -> Request {
        let urlRequest = NetworkUtils.urlRequestWithComponents(URLString, parameters: parameters, imageData: imageData)
        return Alamofire.upload(urlRequest.0, data: urlRequest.1)
            .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
                print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
            }
            .responseJSON { response  in
                if response.result.isSuccess {
                    successHandler(response)
                } else {
                    failHandler(response)
                    AlertShowUtils.showTopTipsAlert("网络不可达")
                }
        }
    }
    /**
     多文件上传
     
     - parameter URLString:                 服务器地址
     - parameter parameters:                POST参数
     - parameter mutilFilePartFormData:     多文件字典格式为Dictionary<String,NSURL>
     - parameter progress:                  闭包返回当前上传进度
     - parameter totalBytesWritten:         一共写了多少字节
     - parameter totalBytesExpectedToWrite: 要写多少字节
     - parameter success:                   成功回调
     - parameter fail:                      失败回调
     
     - returns: 返回一个request可以继续用Alamofire进行闭包衔接
     */
    static func uploadMultiPartFile(URLString: String,
        parameters: Dictionary<String,String>,
        mutilFilePartFormData:Dictionary<String,UIImage>,
        oneProgress progress:(((bytesWritten:Int64, totalBytesWritten:Int64, totalBytesExpectedToWrite:Int64) -> Void)),
        successHandler success: Response<AnyObject, NSError> -> Void,
        failHandler fail:Response<AnyObject, NSError> -> Void)
        -> Request {
        
            AccountSessionUtils.setCookie()
        let fileUploader = FileUploader()
        for (name,image)  in mutilFilePartFormData {
            let imageData = UIImageJPEGRepresentation(image, 0.6)
//            fileUploader.addFileURL(fileURL, withName: name)
            fileUploader.addFileData( imageData!, withName: name, withMimeType: "image/jpeg" )
        }
        for (key, value) in parameters {
            fileUploader.setValue( value, forParameter: key)
        }
        let request = NSMutableURLRequest( URL: NSURL(string: URLString )!)
        request.HTTPMethod = "POST"
        return fileUploader.uploadFile(request: request)!.responseJSON { response in
            if response.result.isSuccess {
                success(response)
            } else {
                fail(response)
                AlertShowUtils.showTopTipsAlert("网络不可达")
            }
            } .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                print(totalBytesWritten)
                progress(bytesWritten: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
        }
    }
    static func wp_uploadMultiPartFile(URLString: String,
        parameters: Dictionary<String,String>,
        mutilFilePartFormData:Dictionary<String,UIImage>,
        oneProgress progress:(((bytesWritten:Int64, totalBytesWritten:Int64, totalBytesExpectedToWrite:Int64) -> Void)),
        successHandler: ( (value:AnyObject) -> Void ),withFailHandler fail:((error:NSError) -> Void ))
        -> Request {
            AccountSessionUtils.setCookie()
            let fileUploader = FileUploader()
            for (name,image)  in mutilFilePartFormData {
                let imageData = UIImageJPEGRepresentation(image, 0.6)
                //            fileUploader.addFileURL(fileURL, withName: name)
                if imageData != nil {
                    fileUploader.addFileData( imageData!, withName: name, withMimeType: "image/jpeg" )
                }
            }
            for (key, value) in parameters {
                fileUploader.setValue( value, forParameter: key)
            }
            let request = NSMutableURLRequest( URL: NSURL(string: URLString )!)
            request.HTTPMethod = "POST"
            return fileUploader.uploadFile(request: request)!.responseJSON { response in
                if response.result.isSuccess {
                    successHandler(value: response.result.value!)
                } else {
                    fail(error: response.result.error!)
                    AlertShowUtils.showTopTipsAlert("网络不可达")
                }
                } .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                    print(totalBytesWritten)
                    progress(bytesWritten: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
            }
    }
    
    // this function creates the required URLRequestConvertible and NSData we need to use Alamofire.upload
    static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {
        
        // create url request to send
        let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
        let boundaryConstant = "myRandomBoundary12345";
        let contentType = "multipart/form-data;boundary="+boundaryConstant
        mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
        
        
        
        // create upload data to send
        let uploadData = NSMutableData()
        
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData)
        
        // add parameters
        for (key, value) in parameters {
            uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
            uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
        }
        uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        
        
        
        // return URLRequestConvertible and NSData
        return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
    }

}


你可能感兴趣的:(swift 网络工具类)