From e9564956654bc965ae62cc7cd02fdcedad2439d9 Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Thu, 20 Aug 2015 17:44:11 +0200 Subject: [PATCH] [Swift] Update to new Swift 2.0 syntax and Xcode 7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Note: configs with responseAs: “PromiseKit” won’t work yet --- .../src/main/resources/swift/APIs.mustache | 4 +- .../swift/AlamofireImplementations.mustache | 58 +++++++++++++++---- .../src/main/resources/swift/Models.mustache | 20 +++---- .../src/main/resources/swift/Podspec.mustache | 2 +- .../src/main/resources/swift/api.mustache | 8 +-- 5 files changed, 63 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index aa39ccfcbdd..de14b2afa90 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -19,7 +19,7 @@ class APIBase { if encoded! is [AnyObject] { var dictionary = [String:AnyObject]() - for (index, item) in enumerate(encoded as! [AnyObject]) { + for (index, item) in (encoded as! [AnyObject]).enumerate() { dictionary["\(index)"] = item } return dictionary @@ -46,7 +46,7 @@ class RequestBuilder { func execute() -> Promise> { fatalError("Not implemented") } - func addHeader(#name: String, value: String) -> Self { + public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 244d816332c..320cb463331 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -30,23 +30,57 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } - let defer = Promise>.defer() - request.responseJSON(options: .AllowFragments) { (req, res, json, error) in + request.responseJSON(options: .AllowFragments) { (req, res, result) in managerStore.removeValueForKey(managerId) - if let error = error { - defer.reject(error) - return - } - if res!.statusCode >= 400 { - //TODO: Add error entity - let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: [:]) - defer.reject(error) + if result.isFailure { + completion(response: nil, erorr: result.error) return } @@ -55,7 +89,7 @@ class AlamofireRequestBuilder: RequestBuilder { defer.fulfill(response) return } - if let json: AnyObject = json { + if let json: AnyObject = result.value { let body = Decoders.decode(clazz: T.self, source: json) let response = Response(response: res!, body: body) defer.fulfill(response) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 37c497ddcb9..4eed292f1d1 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -35,17 +35,17 @@ private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - static func addDecoder(#clazz: T.Type, decoder: ((AnyObject) -> T)) { + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - static func decode(#clazz: [T].Type, source: AnyObject) -> [T] { + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - static func decode(#clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictinoary = source as! [Key: AnyObject] var dictionary = [Key:T]() for (key, value) in sourceDictinoary { @@ -54,7 +54,7 @@ class Decoders { return dictionary } - static func decode(#clazz: T.Type, source: AnyObject) -> T { + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if source is T { return source as! T @@ -68,7 +68,7 @@ class Decoders { } } - static func decodeOptional(#clazz: T.Type, source: AnyObject?) -> T? { + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { if source is NSNull { return nil } @@ -77,7 +77,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [T].Type, source: AnyObject?) -> [T]? { + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { if source is NSNull { return nil } @@ -86,7 +86,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { if source is NSNull { return nil } @@ -113,9 +113,9 @@ class Decoders { // Decoder for {{{classname}}} Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#required}}!{{/required}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{^required}}Optional{{/required}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#required}}!{{/required}}){{/isEnum}}{{/vars}} + let instance = {{classname}}(){{#vars}}{{#isEnum}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index f597a5de688..72fff39d6f6 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 1.3' + s.dependency 'Alamofire', '~> 2.0.0-beta.1' end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 0dd6cd2ecc1..5c2428488d6 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -26,11 +26,11 @@ extension {{projectName}}API { - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} {{/hasParams}}{{#allParams}} - :param: {{paramName}} ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} - :returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} + - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path @@ -43,7 +43,7 @@ extension {{projectName}}API { let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}true{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} }