1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
| import UIKit import Alamofire
public typealias Success = (_ response : [String : Any])->() public typealias Failure = (_ error : Error)->()
class NIRequest: NSObject {
static let shared = NIRequest() private override init() {
}
}
extension NIRequest {
class func getRequest( _ urlString: String, params: Parameters? = nil, success: @escaping Success, failure: @escaping Failure) { request(urlString, params: params, method: .get, success, failure) }
class func postRequest( _ urlString: String, params: Parameters? = nil, success: @escaping Success, failure: @escaping Failure) {
request(urlString, params: params, method: .post, success, failure) }
private class func request( _ urlString: String, params: Parameters? = nil, method: HTTPMethod, _ success: @escaping Success, _ failure: @escaping Failure) {
Alamofire.request(urlString, method: method, parameters: params) .validate(statusCode: 200..<300) .responseJSON { response in
switch response.result { case .success: if let value = response.result.value as? [String: AnyObject] { success(value) } case .failure(let error): failure(error) } }
}
}
extension NIRequest {
class func upLoadImage( _ urlString: String, data: Data, name: String = "image", fileName: String = "image.png", params: Parameters? = nil, success: @escaping Success, failure: @escaping Failure) { upLoadFiles(urlString, data: [data], names: [name], fileNames: [fileName], params: params, success: success, failure: failure) }
class func upLoadFiles( _ urlString: String, data: [Data], names: [String]? = nil, fileNames: [String]? = nil, params: Parameters? = nil, success: @escaping Success, failure: @escaping Failure) { Alamofire.upload( multipartFormData: { multipartFormData in
assert(names?.count == fileNames?.count, "names.count != fileNames.count There may be problems")
for i in 0..<data.count { let data_name = names?[i] ?? "image\(i)" let file_name = fileNames?[i] ?? "image\(i).png"
multipartFormData.append(data[i], withName: data_name ,fileName: file_name, mimeType: "multipart/form-data") }
if let params = params { for (key, value) in params { multipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!), withName: key)
} }
}, to: urlString, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in if let value = response.result.value as? [String: Any]{ success(value) } } case .failure(let encodingError): failure(encodingError) } } )
}
}
|