Update to 7/5 Swift 3 syntax
diff --git a/OpenWhisk.xcodeproj/project.pbxproj b/OpenWhisk.xcodeproj/project.pbxproj
index a580429..d3ca263 100644
--- a/OpenWhisk.xcodeproj/project.pbxproj
+++ b/OpenWhisk.xcodeproj/project.pbxproj
@@ -7,7 +7,6 @@
objects = {
/* Begin PBXBuildFile section */
- 92BBA3A71D64D0660026EC66 /* OpenWhisk.h in Headers */ = {isa = PBXBuildFile; fileRef = D6E3E6391C72592300843E16 /* OpenWhisk.h */; settings = {ATTRIBUTES = (Public, ); }; };
D64559FC1C8F49A600AA6840 /* OpenWhiskButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6E3E6511C72760C00843E16 /* OpenWhiskButton.swift */; };
D6C9C3B71C8F53C9002BDB13 /* Config.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6C9C3B41C8F53C9002BDB13 /* Config.swift */; };
D6C9C3B81C8F53C9002BDB13 /* OpenWhiskConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = D6C9C3B51C8F53C9002BDB13 /* OpenWhiskConfig.plist */; };
@@ -211,9 +210,11 @@
TargetAttributes = {
D6E3E6351C72592300843E16 = {
CreatedOnToolsVersion = 7.2.1;
+ LastSwiftMigration = 0800;
};
D6E3E63F1C72592300843E16 = {
CreatedOnToolsVersion = 7.2.1;
+ LastSwiftMigration = 0800;
};
D6F56ADE1C76471B00F047B6 = {
CreatedOnToolsVersion = 7.2.1;
@@ -411,6 +412,7 @@
PRODUCT_NAME = OpenWhisk;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -429,6 +431,7 @@
PRODUCT_BUNDLE_IDENTIFIER = org.openwhisk.OpenWhisk;
PRODUCT_NAME = OpenWhisk;
SKIP_INSTALL = YES;
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -438,7 +441,8 @@
INFOPLIST_FILE = OpenWhiskTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.ibm.mobile.openwhisk.OpenWhiskTests;
- PRODUCT_NAME = "OpenWhisk Tests";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -448,7 +452,8 @@
INFOPLIST_FILE = OpenWhiskTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.ibm.mobile.openwhisk.OpenWhiskTests;
- PRODUCT_NAME = "OpenWhisk Tests";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
diff --git a/OpenWhisk/Config.swift b/OpenWhisk/Config.swift
index 085a4c5..b102657 100644
--- a/OpenWhisk/Config.swift
+++ b/OpenWhisk/Config.swift
@@ -21,14 +21,18 @@
*/
public class Config {
+<<<<<<< 42847cb29eb244df0cfcf5c29bb8229ad700e604
static let ApiKeyName = "OPENWHISK_TESTAPIKEY"
static let ApiSecretName = "OPENWHISK_TESTAPISECRET"
public class func getHostAndPath(type type:String) -> String? {
+=======
+ public class func getHostAndPath(type:String) -> String? {
+>>>>>>> Update to 7/5 Swift 3 syntax
var url: String? = nil
if let dict = getConfigDictionary() {
- url = dict.valueForKey(type) as? String
+ url = dict.value(forKey: type) as? String
} else {
print("Configuration file missing, cannot config network call")
}
@@ -41,10 +45,10 @@
// Attempt 1, load the bundle from a local reference to this classes bundle
// I'am assuming the WhiskResources bundle is in the framework's root bundle
- let frameworkBundle = NSBundle(forClass: Config.self)
+ let frameworkBundle = Bundle(for: Config.self)
if let bundlePath = frameworkBundle.pathForResource("OpenWhiskResources", ofType: "bundle") {
- if let bundle = NSBundle(path: bundlePath) {
+ if let bundle = Bundle(path: bundlePath) {
let configFile = bundle.pathForResource("OpenWhiskConfig", ofType: "plist")
if let configFile = configFile {
@@ -56,7 +60,7 @@
}
}
} else if let bundlePath = frameworkBundle.pathForResource("OpenWhiskWatchResources", ofType: "bundle") {
- if let bundle = NSBundle(path: bundlePath) {
+ if let bundle = Bundle(path: bundlePath) {
let configFile = bundle.pathForResource("OpenWhiskConfig", ofType: "plist")
if let configFile = configFile {
@@ -91,11 +95,17 @@
*/
public class func getAuthToken() -> (apiKey: String?, apiSecret: String?)? {
+<<<<<<< 42847cb29eb244df0cfcf5c29bb8229ad700e604
let dict = NSProcessInfo.processInfo().environment
let key = dict[Config.ApiKeyName]
let secret = dict[Config.ApiSecretName]
+=======
+ let dict = ProcessInfo.processInfo.environment
+ let key = dict["TESTAPIKEY"]
+ let secret = dict["TESTAPISECRET"]
+>>>>>>> Update to 7/5 Swift 3 syntax
return(key, secret)
}
-}
\ No newline at end of file
+}
diff --git a/OpenWhisk/OpenWhiskButton.swift b/OpenWhisk/OpenWhiskButton.swift
index ddbfca8..84b73f7 100644
--- a/OpenWhisk/OpenWhiskButton.swift
+++ b/OpenWhisk/OpenWhiskButton.swift
@@ -1,30 +1,30 @@
/*
-* Copyright 2015-2016 IBM Corporation
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Copyright 2015-2016 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
import UIKit
/*
-
-Convenience UI element that allows you to invoke whisk actions. You can use like a normal UIButton and handle all the press events yourself, or you can have the button "self-contained". If you set listenForPressEvents = true it will listen for its own press events and invoke the the configured action.
-
-*/
+
+ Convenience UI element that allows you to invoke whisk actions. You can use like a normal UIButton and handle all the press events yourself, or you can have the button "self-contained". If you set listenForPressEvents = true it will listen for its own press events and invoke the the configured action.
+
+ */
@objc(WhiskButton) public class WhiskButton: UIButton {
var whisk: Whisk?
- var urlSession: NSURLSession?
+ var urlSession: URLSession?
var actionParameters: Dictionary<String,AnyObject>?
var actionHasResult: Bool = false
@@ -48,9 +48,9 @@
set {
if newValue == true {
- self.addTarget(self, action: #selector(WhiskButton.buttonPressed), forControlEvents: .TouchUpInside)
+ self.addTarget(self, action: #selector(WhiskButton.buttonPressed), for: .touchUpInside)
} else {
- self.removeTarget(self, action: #selector(WhiskButton.buttonPressed), forControlEvents: .TouchUpInside)
+ self.removeTarget(self, action: #selector(WhiskButton.buttonPressed), for: .touchUpInside)
}
isListeningToSelf = newValue
@@ -63,14 +63,14 @@
invokeAction(parameters: nil, actionCallback: actionButtonCallback)
}
- public func setupWhiskAction(qualifiedName qName:String, credentials: WhiskCredentials, hasResult: Bool = false,parameters: Dictionary<String, AnyObject>? = nil, urlSession: NSURLSession? = nil, baseUrl: String? = nil) throws {
+ public func setupWhiskAction(qualifiedName qName:String, credentials: WhiskCredentials, hasResult: Bool = false,parameters: Dictionary<String, AnyObject>? = nil, urlSession: URLSession? = nil, baseUrl: String? = nil) throws {
let pathParts = try Whisk.processQualifiedName(qName)
setupWhiskAction(pathParts.name, package: pathParts.package, namespace: pathParts.namespace, credentials: credentials, hasResult: hasResult, parameters: parameters, urlSession: urlSession, baseUrl: baseUrl)
}
- public func setupWhiskAction(name: String, package: String? = nil, namespace: String = "_", credentials: WhiskCredentials, hasResult: Bool = false,parameters: Dictionary<String, AnyObject>? = nil, urlSession: NSURLSession? = nil, baseUrl: String? = nil) {
+ public func setupWhiskAction(_ name: String, package: String? = nil, namespace: String = "_", credentials: WhiskCredentials, hasResult: Bool = false,parameters: Dictionary<String, AnyObject>? = nil, urlSession: URLSession? = nil, baseUrl: String? = nil) {
whisk = Whisk(credentials: credentials)
@@ -89,12 +89,12 @@
actionHasResult = hasResult
}
- public func invokeAction(parameters parameters: [String:AnyObject]? = nil, actionCallback: ((reply: Dictionary<String,AnyObject>?, error: WhiskError?) -> Void)?) {
+ public func invokeAction(parameters: [String:AnyObject]? = nil, actionCallback: ((reply: Dictionary<String,AnyObject>?, error: WhiskError?) -> Void)?) {
if let whisk = whisk, actionName = actionName, actionNamespace = actionNamespace {
-
- dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
+ let queue = DispatchQueue(label:"com.ibm.mobilefirst.openwhisk.invokeAction")
+ queue.async(qos: .userInitiated) {
do {
var params:[String:AnyObject]?
diff --git a/OpenWhisk/OpenWhiskSDK.swift b/OpenWhisk/OpenWhiskSDK.swift
index 9dd6449..ce5120e 100644
--- a/OpenWhisk/OpenWhiskSDK.swift
+++ b/OpenWhisk/OpenWhiskSDK.swift
@@ -44,18 +44,18 @@
}
/* Error types for Whisk calls */
-public enum WhiskError: ErrorType {
- case HTTPError(description: String, statusCode: Int, url: String) // something went wrong with the http call
- case JsonError(description: String) // json wasn't right
- case CredentialError(description: String) // something is wrong with the whisk credentials
- case QualifiedNameFormat(description: String) // something is wrong in qualified name
- case WhiskProcessingError(description: String, errorCode: Int) // something went wrong on the whisk side.
+public enum WhiskError: ErrorProtocol {
+ case httpError(description: String, statusCode: Int) // something went wrong with the http call
+ case jsonError(description: String) // json wasn't right
+ case credentialError(description: String) // something is wrong with the whisk credentials
+ case qualifiedNameFormat(description: String) // something is wrong in qualified name
+ case whiskProcessingError(description: String, errorCode: Int) // something went wrong on the whisk side.
}
/* Type of Whisk operation requested */
enum WhiskType {
- case Action
- case Trigger
+ case action
+ case trigger
}
/* Main class to hold the calls to invoke Actions and fire Triggers */
@@ -71,7 +71,7 @@
public var whiskBaseURL: String?
// set to non-nil if using a custom session
- public var urlSession: NSURLSession?
+ public var urlSession: URLSession?
public var verboseReplies: Bool = false
@@ -114,14 +114,14 @@
/* Base function to fire Whisk Trigger identified by qualified name */
- public func fireTrigger(qualifiedName qualifiedName: String, parameters: AnyObject? = nil, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
+ public func fireTrigger(qualifiedName: String, parameters: AnyObject? = nil, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
let pathParts = try Whisk.processQualifiedName(qualifiedName)
try fireTrigger(name: pathParts.name, package: pathParts.package, namespace: pathParts.namespace, parameters: parameters, callback: callback)
}
/* Base function to invoke Whisk Action identified by qualified name */
- public func invokeAction(qualifiedName qualifiedName: String, parameters: AnyObject?, hasResult: Bool = false, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
+ public func invokeAction(qualifiedName: String, parameters: AnyObject?, hasResult: Bool = false, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
let pathParts = try Whisk.processQualifiedName(qualifiedName)
try invokeAction(name: pathParts.name, package: pathParts.package, namespace: pathParts.namespace, parameters: parameters, hasResult: hasResult, callback: callback)
@@ -129,10 +129,10 @@
/* Base function to fire Whisk Trigger identified by components */
- public func fireTrigger(name name: String, package: String? = nil, namespace: String = "_", parameters: AnyObject? = nil, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
+ public func fireTrigger(name: String, package: String? = nil, namespace: String = "_", parameters: AnyObject? = nil, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?)->Void) throws {
if let accessKey = AccessKey, accessToken = AccessToken {
- try httpRequestWhiskAPI(accessKey: accessKey, accessToken: accessToken, namespace: namespace, verb: "POST", type: .Trigger, package: package, name:name, parameters: parameters, isSync: false, callback: { (jsonArray, error) in
+ try httpRequestWhiskAPI(accessKey: accessKey, accessToken: accessToken, namespace: namespace, verb: "POST", type: .trigger, package: package, name:name, parameters: parameters, isSync: false, callback: { (jsonArray, error) in
if let error = error {
callback(reply: nil, error: error)
} else {
@@ -140,17 +140,17 @@
}
})
} else {
- throw WhiskError.CredentialError(description: "Access key and token not set")
+ throw WhiskError.credentialError(description: "Access key and token not set")
}
}
/* Base function to invoke Whisk Action identified by components */
- public func invokeAction(name name: String, package: String? = nil, namespace: String = "_", parameters: AnyObject?, hasResult:Bool = false, callback: (reply: Dictionary<String,AnyObject>?, error: WhiskError?)-> Void) throws {
+ public func invokeAction(name: String, package: String? = nil, namespace: String = "_", parameters: AnyObject?, hasResult:Bool = false, callback: (reply: Dictionary<String,AnyObject>?, error: WhiskError?)-> Void) throws {
if let accessKey = AccessKey, accessToken = AccessToken {
- try httpRequestWhiskAPI(accessKey: accessKey, accessToken: accessToken, namespace: namespace, verb: "POST", type: .Action, package: package, name: name, parameters: parameters, isSync: hasResult, callback: {(jsonDict, error) in
+ try httpRequestWhiskAPI(accessKey: accessKey, accessToken: accessToken, namespace: namespace, verb: "POST", type: .action, package: package, name: name, parameters: parameters, isSync: hasResult, callback: {(jsonDict, error) in
if let error = error {
callback(reply: nil, error: error)
} else {
@@ -159,13 +159,13 @@
})
} else {
- throw WhiskError.CredentialError(description: "Access key and token not set")
+ throw WhiskError.credentialError(description: "Access key and token not set")
}
}
/* can redirect call here, e.g. if mocking */
- func httpRequestWhiskAPI(accessKey accessKey: String, accessToken: String, namespace: String, verb: String, type: WhiskType, package: String?, name: String, parameters: AnyObject?, isSync: Bool, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?) ->Void) throws {
+ func httpRequestWhiskAPI(accessKey: String, accessToken: String, namespace: String, verb: String, type: WhiskType, package: String?, name: String, parameters: AnyObject?, isSync: Bool, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?) ->Void) throws {
if useMock {
callback(reply:mockReply, error: mockError)
@@ -177,7 +177,7 @@
/* Network call */
- func whiskAPI(accessKey accessKey: String, accessToken: String, namespace: String, verb: String, type: WhiskType, package: String?, name: String, parameters: AnyObject?, isSync: Bool, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?) ->Void) throws {
+ func whiskAPI(accessKey: String, accessToken: String, namespace: String, verb: String, type: WhiskType, package: String?, name: String, parameters: AnyObject?, isSync: Bool, callback: (reply: Dictionary<String,AnyObject>?, error:WhiskError?) ->Void) throws {
// set parameters
var paramsIsDict = false
@@ -189,22 +189,22 @@
// set authorization string
let loginString = NSString(format: "%@:%@", accessKey, accessToken)
- let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
- let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
+ let loginData: Data = loginString.data(using: String.Encoding.utf8.rawValue)!
+ let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let typeStr: String!
// set type
switch type {
- case .Action:
+ case .action:
typeStr = "actions"
- case .Trigger:
+ case .trigger:
typeStr = "triggers"
}
// get base URL
guard let actionURL = baseURL != nil ? baseURL : Config.getHostAndPath(type: typeStr) else {
- callback(reply: nil, error: WhiskError.HTTPError(description: "Base URL not set, try using whisk.baseUrl setting", statusCode: 400, url: "Undefined"))
+ callback(reply: nil, error: WhiskError.httpError(description: "Base URL not set, try using whisk.baseUrl setting", statusCode: 400))
return
}
@@ -232,44 +232,41 @@
syncName += "?blocking=true"
}
- // use this for verbose replies
- let restCall = actionURL+syncName
-
- guard let encodedPath = syncName.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) else {
- callback(reply: nil, error: WhiskError.HTTPError(description: "URL Encode error \(syncName)", statusCode: 400, url: restCall))
+ guard let encodedPath = syncName.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
+ callback(reply: nil, error: WhiskError.httpError(description: "URL Encode error \(syncName)", statusCode: 400))
return
}
syncName = encodedPath
// create request
- guard let url = NSURL(string:actionURL+syncName) else {
+ guard let url = URL(string:actionURL+syncName) else {
// send back error on main queue
- callback(reply: nil, error: WhiskError.HTTPError(description: "Malformed url", statusCode: 400, url: restCall))
+ callback(reply: nil, error: WhiskError.httpError(description: "Malformed url \(actionURL+syncName)", statusCode: 400))
return
}
- let request = NSMutableURLRequest(URL: url)
+ var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
- request.HTTPMethod = verb
+ request.httpMethod = verb
// create JSON from parameters dictionary
do {
if let parameters = parameters {
if paramsIsDict {
- request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
+ request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
} else {
if parameters is String {
let str = "{\"payload\":\"\(parameters as! String)\"}"
- request.HTTPBody = str.dataUsingEncoding(NSUTF8StringEncoding)
+ request.httpBody = str.data(using: String.Encoding.utf8)
} else {
let str = "{\"payload\": \(parameters)}"
- request.HTTPBody = str.dataUsingEncoding(NSUTF8StringEncoding)
+ request.httpBody = str.data(using: String.Encoding.utf8)
}
}
}
@@ -280,36 +277,36 @@
// retrieve session as default or use developer specified session
- let sess: NSURLSession!
+ let sess: URLSession!
if let _ = urlSession {
sess = urlSession
} else {
- let sessConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
- sess = NSURLSession(configuration: sessConfig)
+ let sessConfig = URLSessionConfiguration.default
+ sess = URLSession(configuration: sessConfig)
}
// perform network request
- let task = sess.dataTaskWithRequest(request) {
+ let task = sess.dataTask(with: request) {
data, response, error in
let statusCode: Int!
if let error = error {
- if let httpResponse = response as? NSHTTPURLResponse {
+ if let httpResponse = response as? HTTPURLResponse {
statusCode = httpResponse.statusCode
} else {
statusCode = -1
}
// return network transport error call on main queue
- dispatch_async(dispatch_get_main_queue()) {
- callback(reply: nil, error: WhiskError.HTTPError(description: "\(error.localizedDescription)", statusCode: statusCode, url: restCall))
+ DispatchQueue.main.async {
+ callback(reply: nil, error: WhiskError.httpError(description: "\(error.localizedDescription)", statusCode: statusCode))
}
return
} else {
- if let httpResponse = response as? NSHTTPURLResponse {
+ if let httpResponse = response as? HTTPURLResponse {
statusCode = httpResponse.statusCode
do {
// success
@@ -320,7 +317,7 @@
case "POST":
var jsonDict = [String:AnyObject]()
- let respDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>
+ let respDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, AnyObject>
jsonDict = respDict
@@ -331,8 +328,8 @@
errorCode = code
}
// send back error on main queue
- dispatch_async(dispatch_get_main_queue()) {
- callback(reply: nil, error: WhiskError.WhiskProcessingError(description: "errorCode:\(errorCode), \(whiskError)", errorCode: errorCode))
+ DispatchQueue.main.async {
+ callback(reply: nil, error: WhiskError.whiskProcessingError(description: "errorCode:\(errorCode), \(whiskError)", errorCode: errorCode))
}
} else {
@@ -364,7 +361,9 @@
let payload:AnyObject? = actionResult
if payload is String {
do {
- let payloadObj:AnyObject? = try NSJSONSerialization.JSONObjectWithData(payload!.dataUsingEncoding(NSUTF8StringEncoding)!, options:[])
+
+ let payloadObj = try JSONSerialization.jsonObject(with: (payload as! String).data(using: String.Encoding.utf8)!, options: [])
+
whiskReply["result"] = (payloadObj as? [String:AnyObject])!
} catch {
print("Error parsing payload into JSON, defaulting to string")
@@ -380,7 +379,7 @@
}
// send back successful response on main queue
- dispatch_async(dispatch_get_main_queue()) {
+ DispatchQueue.main.async {
callback(reply: whiskReply, error: nil)
}
}
@@ -388,10 +387,10 @@
// get info about actions/triggers
// not used right now
case "GET":
- let jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
+ let jsonArray = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
let jsonDict:Dictionary<String, AnyObject> = ["array":jsonArray]
- dispatch_async(dispatch_get_main_queue()) {
+ DispatchQueue.main.async {
callback(reply: jsonDict, error: nil)
}
@@ -400,15 +399,15 @@
}
} else {
- dispatch_async(dispatch_get_main_queue()) {
- callback(reply: nil, error: WhiskError.HTTPError(description: "Whisk returned HTTP error code", statusCode: statusCode, url:restCall))
+ DispatchQueue.main.async {
+ callback(reply: nil, error: WhiskError.httpError(description: "Whisk returned HTTP error code", statusCode: statusCode))
}
}
} catch {
print("Error parsing JSON from Whisk response: \(error)")
- dispatch_async(dispatch_get_main_queue()) {
- callback(reply: nil, error: WhiskError.JsonError(description: "\(error)"))
+ DispatchQueue.main.async {
+ callback(reply: nil, error: WhiskError.jsonError(description: "\(error)"))
}
}
}
@@ -421,7 +420,7 @@
}
/* Convert qualified name string into component parts of action or trigger call */
- class func processQualifiedName(qName: String) throws -> (namespace:String, package: String?, name: String) {
+ class func processQualifiedName(_ qName: String) throws -> (namespace:String, package: String?, name: String) {
var namespace = "_"
var package: String? = nil
var name = ""
@@ -442,7 +441,7 @@
package = pathParts[1]
name = pathParts[2]
} else {
- throw WhiskError.QualifiedNameFormat(description: "Cannot parse \(qName)")
+ throw WhiskError.qualifiedNameFormat(description: "Cannot parse \(qName)")
}
} else {
if pathParts.count == 1 {
@@ -451,7 +450,7 @@
package = pathParts[0]
name = pathParts[1]
} else {
- throw WhiskError.QualifiedNameFormat(description: "Cannot parse \(qName)")
+ throw WhiskError.qualifiedNameFormat(description: "Cannot parse \(qName)")
}
}
diff --git a/OpenWhiskTests/OpenWhiskTests.swift b/OpenWhiskTests/OpenWhiskTests.swift
index a764c04..012cacb 100644
--- a/OpenWhiskTests/OpenWhiskTests.swift
+++ b/OpenWhiskTests/OpenWhiskTests.swift
@@ -1,32 +1,32 @@
/*
- * Copyright 2015-2016 IBM Corporation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+* Copyright 2015-2016 IBM Corporation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
import XCTest
import OpenWhisk
-class NetworkUtilsDelegate: NSObject, NSURLSessionDelegate {
- func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
+class NetworkUtilsDelegate: NSObject, URLSessionDelegate {
+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
- completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
+ completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(forTrust: challenge.protectionSpace.serverTrust!))
}
}
class OpenWhiskTests: XCTestCase {
- let Timeout:NSTimeInterval = 100 // time to wait for whisk action to complete
+ let Timeout:TimeInterval = 100 // time to wait for whisk action to complete
var apiKey: String?
var apiSecret: String?
@@ -52,49 +52,49 @@
if let apiKey = apiKey, apiSecret = apiSecret {
// allow for self-signed certificates
- let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue())
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: NetworkUtilsDelegate(), delegateQueue:OperationQueue.main)
let credentials = WhiskCredentials(accessKey: apiKey, accessToken: apiSecret)
let whisk = Whisk(credentials: credentials)
whisk.urlSession = session
// setup for async testing
- let expectation = expectationWithDescription("Whisk Callback")
+ let expectation = self.expectation(withDescription: "Whisk Callback")
do {
try whisk.invokeAction(name: "date", package: "util", namespace: "whisk.system", parameters: nil, hasResult: true,
- callback: {(reply, error) in
-
- if let error = error {
- if case let WhiskError.HTTPError(description, statusCode, "default") = error {
-
- print("Error: \(description) statusCode: \(statusCode))")
-
- if statusCode != 401 && statusCode != 404 && statusCode != 408 && statusCode != 500 {
- XCTFail("Error: \(description) statusCode: \(statusCode))")
- }
-
- }
- }
-
- if let reply = reply {
-
- print("Reply is \(reply)")
- XCTAssertNotNil(reply["activationId"])
- let id = reply["activationId"] as! String
- print("Got id \(id)")
- }
-
- expectation.fulfill()
-
-
+ callback: {(reply, error) in
+
+ if let error = error {
+ if case let WhiskError.httpError(description, statusCode) = error {
+
+ print("Error: \(description) statusCode: \(statusCode))")
+
+ if statusCode != 401 && statusCode != 404 && statusCode != 408 && statusCode != 500 {
+ XCTFail("Error: \(description) statusCode: \(statusCode))")
+ }
+
+ }
+ }
+
+ if let reply = reply {
+
+ print("Reply is \(reply)")
+ XCTAssertNotNil(reply["activationId"])
+ let id = reply["activationId"] as! String
+ print("Got id \(id)")
+ }
+
+ expectation.fulfill()
+
+
})
} catch {
print(error)
XCTFail("Error invoking action \(error)")
}
- waitForExpectationsWithTimeout(Timeout, handler: { error in
+ waitForExpectations(withTimeout: Timeout, handler: { error in
if let error = error {
print("Error: \(error)")
@@ -109,9 +109,9 @@
if let apiKey = apiKey, apiSecret = apiSecret {
// setup for async testing
- let expectation = expectationWithDescription("Whisk Callback")
+ let expectation = self.expectation(withDescription: "Whisk Callback")
// allow for self-signed certificates
- let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue())
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: NetworkUtilsDelegate(), delegateQueue:OperationQueue.main)
let credentials = WhiskCredentials(accessKey: apiKey, accessToken: apiSecret)
let whisk = Whisk(credentials: credentials)
@@ -120,7 +120,7 @@
try whisk.invokeAction(qualifiedName: "/whisk.system/util/date", parameters: nil, hasResult: true, callback: {(reply, error) in
if let error = error {
- if case let WhiskError.HTTPError(description, statusCode, "default") = error {
+ if case let WhiskError.httpError(description, statusCode) = error {
print("Error: \(description) statusCode: \(statusCode))")
@@ -148,7 +148,7 @@
XCTFail("Error invoking action \(error)")
}
- waitForExpectationsWithTimeout(Timeout, handler: { error in
+ waitForExpectations(withTimeout: Timeout, handler: { error in
if let error = error {
print("Error: \(error)")
@@ -163,10 +163,10 @@
if let apiKey = apiKey, apiSecret = apiSecret {
// setup for async testing
- let expectation = expectationWithDescription("Whisk Callback")
+ let expectation = self.expectation(withDescription: "Whisk Callback")
// allow for self-signed certificates
- let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue())
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: NetworkUtilsDelegate(), delegateQueue:OperationQueue.main)
let credentials = WhiskCredentials(accessKey: apiKey, accessToken: apiSecret)
let whisk = Whisk(credentials: credentials)
@@ -178,7 +178,7 @@
try whisk.invokeAction(qualifiedName: "/whisk.system/util/date", parameters: nil, hasResult: true, callback: {(reply, error) in
if let error = error {
- if case let WhiskError.HTTPError(description, statusCode, "default") = error {
+ if case let WhiskError.httpError(description, statusCode) = error {
print("Error: \(description) statusCode: \(statusCode))")
@@ -206,7 +206,7 @@
XCTFail("Error invoking action \(error)")
}
- waitForExpectationsWithTimeout(Timeout, handler: { error in
+ waitForExpectations(withTimeout: Timeout, handler: { error in
if let error = error {
print("Error: \(error)")
@@ -222,10 +222,10 @@
if let apiKey = apiKey, apiSecret = apiSecret {
// setup for async testing
- let expectation = expectationWithDescription("Whisk Callback")
+ let expectation = self.expectation(withDescription: "Whisk Callback")
// allow for self-signed certificates
- let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue())
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: NetworkUtilsDelegate(), delegateQueue:OperationQueue.main)
let credentials = WhiskCredentials(accessKey: apiKey, accessToken: apiSecret)
let whisk = Whisk(credentials: credentials)
@@ -238,7 +238,7 @@
try whisk.invokeAction(qualifiedName: "/whisk.system/util/date", parameters: nil, hasResult: true, callback: {(reply, error) in
if let error = error {
- if case let WhiskError.HTTPError(description, statusCode, "default") = error {
+ if case let WhiskError.httpError(description, statusCode) = error {
print("Error: \(description) statusCode: \(statusCode))")
@@ -266,7 +266,7 @@
XCTFail("Error invoking action \(error)")
}
- waitForExpectationsWithTimeout(Timeout, handler: { error in
+ waitForExpectations(withTimeout: Timeout, handler: { error in
if let error = error {
print("Error: \(error)")
@@ -282,10 +282,10 @@
if let apiKey = apiKey, apiSecret = apiSecret {
// setup for async testing
- let expectation = expectationWithDescription("Whisk Callback")
+ let expectation = self.expectation(withDescription: "Whisk Callback")
// allow for self-signed certificates
- let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue())
+ let session = URLSession(configuration: URLSessionConfiguration.default, delegate: NetworkUtilsDelegate(), delegateQueue:OperationQueue.main)
let credentials = WhiskCredentials(accessKey: apiKey, accessToken: apiSecret)
let whisk = Whisk(credentials: credentials)
@@ -321,7 +321,7 @@
XCTFail("Error invoking trigger \(error)")
}
- waitForExpectationsWithTimeout(Timeout, handler: { error in
+ waitForExpectations(withTimeout: Timeout, handler: { error in
if let error = error {
print("Error: \(error)")