Skip to content

Commit

Permalink
Swift 4 migration & allowing self signed certs in debug mode.
Browse files Browse the repository at this point in the history
  • Loading branch information
johnny-zumper committed Oct 11, 2018
1 parent 044339c commit 07edc49
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 34 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -17,6 +17,7 @@ DerivedData/
*.perspectivev3
!default.perspectivev3
xcuserdata/
*.xcworkspace

## Other
*.moved-aside
Expand Down
14 changes: 9 additions & 5 deletions Bridge.xcodeproj/project.pbxproj
Expand Up @@ -29,7 +29,7 @@

/* Begin PBXFileReference section */
D033A6AE1B85848600AEBBA0 /* Bridge.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Bridge.h; sourceTree = "<group>"; };
D03446821CB65A0A00052BB5 /* BridgeExamples.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = BridgeExamples.playground; sourceTree = "<group>"; };
D03446821CB65A0A00052BB5 /* BridgeExamples.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = BridgeExamples.playground; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.swift; };
E77A6DDD1B6A690800070837 /* Bridge.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Bridge.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E77A6DE21B6A690800070837 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../Info.plist; sourceTree = "<group>"; };
E77A6DE81B6A695100070837 /* Bridge.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Bridge.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -116,12 +116,12 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0900;
LastUpgradeCheck = 1000;
ORGANIZATIONNAME = Zumper;
TargetAttributes = {
E77A6DDC1B6A690800070837 = {
CreatedOnToolsVersion = 7.0;
LastSwiftMigration = 0800;
LastSwiftMigration = 1000;
};
E77A6DEE1B6A698800070837 = {
CreatedOnToolsVersion = 7.0;
Expand Down Expand Up @@ -198,12 +198,14 @@
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
Expand Down Expand Up @@ -254,12 +256,14 @@
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
Expand Down Expand Up @@ -308,7 +312,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Debug;
};
Expand All @@ -328,7 +332,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Release;
};
Expand Down
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "1000"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand All @@ -26,7 +26,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
Expand All @@ -37,7 +36,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
Expand Down
4 changes: 1 addition & 3 deletions Bridge.xcodeproj/xcshareddata/xcschemes/Bridge.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "1000"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand All @@ -26,7 +26,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
Expand All @@ -37,7 +36,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
Expand Down
48 changes: 28 additions & 20 deletions Bridge/Bridge.swift
Expand Up @@ -8,29 +8,29 @@

import Foundation

public class Bridge {
public class Bridge: NSObject, URLSessionDelegate {
public var responseInterceptors: Array<ResponseInterceptor> = []
public var requestInterceptors: Array<RequestInterceptor> = []
public var tasksByTag: NSMapTable<NSString, AnyObject> = NSMapTable<NSString, AnyObject>(keyOptions: NSPointerFunctions.Options(), valueOptions: NSPointerFunctions.Options.weakMemory)
static let tasksLockQueue: DispatchQueue = DispatchQueue(label: "com.Bridge.TasksByTagLockQueue", attributes: [])

// Debug Settings
var debugMode: Bool = false
var acceptableStatusCodes = Set<Int>(200...299)
public var isDebugMode: Bool = false

private let acceptableStatusCodes = Set<Int>(200...299)
public var baseURL: URL?

let session: URLSession = {
var sessionConfig = URLSessionConfiguration.default
private lazy var session: URLSession = {
var sessionConfig: URLSessionConfiguration = .default
sessionConfig.httpAdditionalHeaders = ["Content-Type": "application/json"]

var urlSession = URLSession(configuration: sessionConfig)
let urlSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
return urlSession
}()

public static let sharedInstance: Bridge = {
return Bridge()
}()
}()

public func cancelWithTag(_ tag: String) {
Bridge.tasksLockQueue.sync {
Expand All @@ -57,11 +57,7 @@ public class Bridge {
}
}

public func enableDebugLogging() {
self.debugMode = true
}

func execute<ReturnType>(_ endpoint: Endpoint<ReturnType>) {
internal func execute<ReturnType>(_ endpoint: Endpoint<ReturnType>) {
let mutableRequest = NSMutableURLRequest(url: URL(string: endpoint.route, relativeTo: self.baseURL!)!)
mutableRequest.httpShouldHandleCookies = endpoint.acceptsCookies
mutableRequest.httpMethod = endpoint.method.rawValue
Expand All @@ -73,7 +69,7 @@ public class Bridge {
request = processRequestInterceptors(endpoint, mutableRequest: &request)
let dataTask = self.createDataTask(endpoint, request: request.copy() as! URLRequest)

if self.debugMode {
if self.isDebugMode {
print("Making request to: \(endpoint.method.rawValue) \(endpoint.requestPath())")
if let requestParams = endpoint.params {
print("with parameters: \(requestParams.description)")
Expand All @@ -90,7 +86,7 @@ public class Bridge {
}
}

func createDataTask<ReturnType>(_ endpoint: Endpoint<ReturnType>, request: URLRequest) -> URLSessionDataTask {
private func createDataTask<ReturnType>(_ endpoint: Endpoint<ReturnType>, request: URLRequest) -> URLSessionDataTask {
var dataTask: URLSessionDataTask
dataTask = Bridge.sharedInstance.session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, err: Error?) -> Void in
do {
Expand All @@ -107,7 +103,7 @@ public class Bridge {
if let serializedObject = try self.processResponse(endpoint, responseObject: responseObject, response: response, error: err as NSError?) {
DispatchQueue.main.async(execute: { () -> Void in

if self.debugMode {
if self.isDebugMode {
print("Request Completed with response: \(response!)")
print("\(serializedObject)")
if let returnData = data {
Expand All @@ -126,7 +122,7 @@ public class Bridge {

DispatchQueue.main.async(execute: { () -> Void in

if self.debugMode {
if self.isDebugMode {
print("Request Failed with errorType: \(error)")
if let returnData = data {
if let dataString = endpoint.encoding.serializeToString(returnData) {
Expand All @@ -151,7 +147,7 @@ public class Bridge {
return dataTask
}

func processResponse<ReturnType>(_ endpoint: Endpoint<ReturnType>, responseObject: ResponseObject, response: URLResponse?, error: NSError?) throws -> ReturnType? {
private func processResponse<ReturnType>(_ endpoint: Endpoint<ReturnType>, responseObject: ResponseObject, response: URLResponse?, error: NSError?) throws -> ReturnType? {

let processResults = self.processResponseInterceptors(endpoint, response: response as? HTTPURLResponse, responseObject: responseObject)

Expand Down Expand Up @@ -181,15 +177,15 @@ public class Bridge {
}


func attemptCustomResponseInterceptor<ReturnType>(_ endpoint: Endpoint<ReturnType>, response: HTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults {
private func attemptCustomResponseInterceptor<ReturnType>(_ endpoint: Endpoint<ReturnType>, response: HTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults {
if let after = endpoint.responseInterceptor {
return after(endpoint, response, responseObject)
} else {
return ProcessResults(true, nil)
}
}

func processResponseInterceptors<ReturnType>(_ endpoint: Endpoint<ReturnType>, response: HTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults {
private func processResponseInterceptors<ReturnType>(_ endpoint: Endpoint<ReturnType>, response: HTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults {
for Bridge in self.responseInterceptors {
let processResults = Bridge.process(endpoint, response: response, responseObject: responseObject)
let shouldContinueProcessing = (processResults.bridgeError != nil || processResults.shouldContinue)
Expand All @@ -202,13 +198,25 @@ public class Bridge {
return attemptCustomResponseInterceptor(endpoint, response: response, responseObject: responseObject)
}

func processRequestInterceptors<ReturnType>(_ endpoint: Endpoint<ReturnType>, mutableRequest: inout NSMutableURLRequest) -> NSMutableURLRequest {
private func processRequestInterceptors<ReturnType>(_ endpoint: Endpoint<ReturnType>, mutableRequest: inout NSMutableURLRequest) -> NSMutableURLRequest {
var processedRequest: NSMutableURLRequest = mutableRequest.mutableCopy() as! NSMutableURLRequest
for Bridge in self.requestInterceptors {
Bridge.process(endpoint, mutableRequest: &processedRequest)
}
return processedRequest
}

// MARK: - URLSessionDelegate

public func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
if self.isDebugMode, let trust = challenge.protectionSpace.serverTrust {
completionHandler(.useCredential, URLCredential(trust: trust))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}

// MARK - Bridges
Expand Down
4 changes: 2 additions & 2 deletions Bridge/Encoding.swift
Expand Up @@ -26,7 +26,7 @@ public enum Encoding {
// Encode params in the URL of the request
let mappedParameters: Array<(key: String, value: String)> = (parameters).map({ (key, value) in
if let collection = value as? [Any] {
return (key, self.escapeString("\(key)") + "=" + (collection.reduce("", { $0 + ($0.characters.isEmpty ? "" : ",") + self.escapeString("\($1)")})))
return (key, self.escapeString("\(key)") + "=" + (collection.reduce("", { $0 + ($0.isEmpty ? "" : ",") + self.escapeString("\($1)")})))
} else {
return (key, self.escapeString("\(key)") + "=" + self.escapeString("\(value)") )
}
Expand All @@ -35,7 +35,7 @@ public enum Encoding {

// Append the leading `?` character for url encoded requests
// and drop the trailing `&` from the reduce
let queryString = "?" + String(flattenedString.characters.dropLast())
let queryString = "?" + String(flattenedString.dropLast())

let baseURL = mutableRequest.url
mutableRequest.url = URL(string: queryString, relativeTo: baseURL!)
Expand Down
2 changes: 1 addition & 1 deletion BridgeExamples.playground/contents.xcplayground
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<playground version='5.0' target-platform='ios' last-migration='1000'>
<timeline fileName='timeline.xctimeline'/>
</playground>

0 comments on commit 07edc49

Please sign in to comment.