Merge branch 'master' into swift_3.0
# Conflicts:
# Tests/ASSET_Tests.swift
# Tests/GET_Tests.swift
diff --git a/Samples/ActivityFeed/ActivityFeed.xcodeproj/project.pbxproj b/Samples/ActivityFeed/ActivityFeed.xcodeproj/project.pbxproj
index 215ca87..61a984b 100644
--- a/Samples/ActivityFeed/ActivityFeed.xcodeproj/project.pbxproj
+++ b/Samples/ActivityFeed/ActivityFeed.xcodeproj/project.pbxproj
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
+ 587A839139502BE0380CD1DA /* Pods_ActivityFeed.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 383F79CDBA14ABFBFE0D157C /* Pods_ActivityFeed.framework */; };
634855401C726AE9005FE016 /* UsergridSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 634855331C726AD3005FE016 /* UsergridSDK.framework */; };
634855411C726AE9005FE016 /* UsergridSDK.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 634855331C726AD3005FE016 /* UsergridSDK.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
634855451C726AF7005FE016 /* UsergridSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 634855351C726AD3005FE016 /* UsergridSDK.framework */; };
@@ -164,6 +165,9 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ 27CE17FF2D4FC59A741243ED /* Pods-ActivityFeed.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ActivityFeed.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ActivityFeed/Pods-ActivityFeed.debug.xcconfig"; sourceTree = "<group>"; };
+ 383F79CDBA14ABFBFE0D157C /* Pods_ActivityFeed.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ActivityFeed.framework; sourceTree = BUILT_PRODUCTS_DIR; };
+ 5F7C629490712A1E96D1C945 /* Pods-ActivityFeed.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ActivityFeed.release.xcconfig"; path = "Pods/Target Support Files/Pods-ActivityFeed/Pods-ActivityFeed.release.xcconfig"; sourceTree = "<group>"; };
634855281C726AD3005FE016 /* UsergridSDK.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = UsergridSDK.xcodeproj; path = ../../UsergridSDK.xcodeproj; sourceTree = "<group>"; };
6348D95B1C4EAC0B005C978C /* WatchSample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WatchSample.app; sourceTree = BUILT_PRODUCTS_DIR; };
6348D95E1C4EAC0B005C978C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
@@ -206,12 +210,28 @@
buildActionMask = 2147483647;
files = (
634855401C726AE9005FE016 /* UsergridSDK.framework in Frameworks */,
+ 587A839139502BE0380CD1DA /* Pods_ActivityFeed.framework in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ A56E0389E87D6C6C996BF007 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
+ 2112A2F4682490176F99F6BA /* Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 383F79CDBA14ABFBFE0D157C /* Pods_ActivityFeed.framework */,
+ );
+ name = Frameworks;
+ sourceTree = "<group>";
+ };
634855291C726AD3005FE016 /* Products */ = {
isa = PBXGroup;
children = (
@@ -255,6 +275,8 @@
6348D95C1C4EAC0B005C978C /* WatchSample */,
6348D96B1C4EAC0B005C978C /* WatchSample Extension */,
6355FEC21BFE4FC600E07170 /* Products */,
+ CDFE621065D6B589E1F28562 /* Pods */,
+ 2112A2F4682490176F99F6BA /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -322,6 +344,15 @@
name = Storyboards;
sourceTree = "<group>";
};
+ CDFE621065D6B589E1F28562 /* Pods */ = {
+ isa = PBXGroup;
+ children = (
+ 27CE17FF2D4FC59A741243ED /* Pods-ActivityFeed.debug.xcconfig */,
+ 5F7C629490712A1E96D1C945 /* Pods-ActivityFeed.release.xcconfig */,
+ );
+ name = Pods;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -331,6 +362,7 @@
buildPhases = (
6348D9591C4EAC0B005C978C /* Resources */,
6348D97B1C4EAC0C005C978C /* Embed App Extensions */,
+ A56E0389E87D6C6C996BF007 /* Frameworks */,
);
buildRules = (
);
@@ -365,11 +397,14 @@
isa = PBXNativeTarget;
buildConfigurationList = 6355FED31BFE4FC600E07170 /* Build configuration list for PBXNativeTarget "ActivityFeed" */;
buildPhases = (
+ 472DB0E2A40503BB734CFCDA /* [CP] Check Pods Manifest.lock */,
6355FEBD1BFE4FC600E07170 /* Sources */,
6355FEBE1BFE4FC600E07170 /* Frameworks */,
6355FEBF1BFE4FC600E07170 /* Resources */,
6348D97D1C4EAC0C005C978C /* Embed Watch Content */,
634855441C726AE9005FE016 /* Embed Frameworks */,
+ A3199695972495C1CCD1CB10 /* [CP] Embed Pods Frameworks */,
+ 91D9D0F42FF78FB16CE0E42F /* [CP] Copy Pods Resources */,
);
buildRules = (
);
@@ -389,17 +424,20 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0720;
- LastUpgradeCheck = 0710;
+ LastUpgradeCheck = 0800;
ORGANIZATIONNAME = "Apigee Inc.";
TargetAttributes = {
6348D95A1C4EAC0B005C978C = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
6348D9661C4EAC0B005C978C = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
6355FEC01BFE4FC600E07170 = {
CreatedOnToolsVersion = 7.1.1;
+ LastSwiftMigration = 0800;
};
};
};
@@ -511,6 +549,54 @@
};
/* End PBXResourcesBuildPhase section */
+/* Begin PBXShellScriptBuildPhase section */
+ 472DB0E2A40503BB734CFCDA /* [CP] Check Pods Manifest.lock */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ );
+ name = "[CP] Check Pods Manifest.lock";
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
+ showEnvVarsInLog = 0;
+ };
+ 91D9D0F42FF78FB16CE0E42F /* [CP] Copy Pods Resources */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ );
+ name = "[CP] Copy Pods Resources";
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ActivityFeed/Pods-ActivityFeed-resources.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+ A3199695972495C1CCD1CB10 /* [CP] Embed Pods Frameworks */ = {
+ isa = PBXShellScriptBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputPaths = (
+ );
+ name = "[CP] Embed Pods Frameworks";
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ActivityFeed/Pods-ActivityFeed-frameworks.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+/* End PBXShellScriptBuildPhase section */
+
/* Begin PBXSourcesBuildPhase section */
6348D9631C4EAC0B005C978C /* Sources */ = {
isa = PBXSourcesBuildPhase;
@@ -597,43 +683,45 @@
6348D9761C4EAC0C005C978C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
IBSC_MODULE = WatchSample_Extension;
INFOPLIST_FILE = WatchSample/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.activityfeed.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
- WATCHOS_DEPLOYMENT_TARGET = 2.1;
+ WATCHOS_DEPLOYMENT_TARGET = 3.0;
};
name = Debug;
};
6348D9771C4EAC0C005C978C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
IBSC_MODULE = WatchSample_Extension;
INFOPLIST_FILE = WatchSample/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.activityfeed.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
- WATCHOS_DEPLOYMENT_TARGET = 2.1;
+ WATCHOS_DEPLOYMENT_TARGET = 3.0;
};
name = Release;
};
6348D9781C4EAC0C005C978C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = "WatchSample Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
@@ -641,15 +729,16 @@
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
- WATCHOS_DEPLOYMENT_TARGET = 2.1;
+ WATCHOS_DEPLOYMENT_TARGET = 3.0;
};
name = Debug;
};
6348D9791C4EAC0C005C978C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = "WatchSample Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
@@ -657,8 +746,10 @@
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
- WATCHOS_DEPLOYMENT_TARGET = 2.1;
+ WATCHOS_DEPLOYMENT_TARGET = 3.0;
};
name = Release;
};
@@ -747,12 +838,13 @@
};
6355FED41BFE4FC600E07170 /* Debug */ = {
isa = XCBuildConfiguration;
+ baseConfigurationReference = 27CE17FF2D4FC59A741243ED /* Pods-ActivityFeed.debug.xcconfig */;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
INFOPLIST_FILE = Source/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.activityfeed;
@@ -761,17 +853,19 @@
SWIFT_INSTALL_OBJC_HEADER = NO;
SWIFT_OBJC_BRIDGING_HEADER = "";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
6355FED51BFE4FC600E07170 /* Release */ = {
isa = XCBuildConfiguration;
+ baseConfigurationReference = 5F7C629490712A1E96D1C945 /* Pods-ActivityFeed.release.xcconfig */;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
- EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
INFOPLIST_FILE = Source/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.activityfeed;
@@ -779,6 +873,8 @@
PROVISIONING_PROFILE = "";
SWIFT_INSTALL_OBJC_HEADER = NO;
SWIFT_OBJC_BRIDGING_HEADER = "";
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
diff --git a/Samples/ActivityFeed/ActivityFeed.xcworkspace/contents.xcworkspacedata b/Samples/ActivityFeed/ActivityFeed.xcworkspace/contents.xcworkspacedata
index 1344aa3..43deff1 100644
--- a/Samples/ActivityFeed/ActivityFeed.xcworkspace/contents.xcworkspacedata
+++ b/Samples/ActivityFeed/ActivityFeed.xcworkspace/contents.xcworkspacedata
@@ -4,4 +4,7 @@
<FileRef
location = "group:ActivityFeed.xcodeproj">
</FileRef>
+ <FileRef
+ location = "group:Pods/Pods.xcodeproj">
+ </FileRef>
</Workspace>
diff --git a/Samples/ActivityFeed/Source/ActivityEntity.swift b/Samples/ActivityFeed/Source/ActivityEntity.swift
index 5ddcf12..4cea1fc 100644
--- a/Samples/ActivityFeed/Source/ActivityEntity.swift
+++ b/Samples/ActivityFeed/Source/ActivityEntity.swift
@@ -45,7 +45,7 @@
UsergridEntity.mapCustomType("activity", toSubclass: ActivityEntity.self)
}
- required public init(type: String, name: String?, propertyDict: [String : AnyObject]?) {
+ required public init(type: String, name: String?, propertyDict: [String : Any]?) {
super.init(type: type, name: name, propertyDict: propertyDict)
}
@@ -53,8 +53,8 @@
super.init(coder: aDecoder)
}
- public override func encodeWithCoder(aCoder: NSCoder) {
- super.encodeWithCoder(aCoder)
+ open override func encode(with aCoder: NSCoder) {
+ super.encode(with:aCoder)
}
-}
\ No newline at end of file
+}
diff --git a/Samples/ActivityFeed/Source/AppDelegate.swift b/Samples/ActivityFeed/Source/AppDelegate.swift
index cca5c41..35d69c0 100644
--- a/Samples/ActivityFeed/Source/AppDelegate.swift
+++ b/Samples/ActivityFeed/Source/AppDelegate.swift
@@ -34,10 +34,10 @@
var window: UIWindow?
- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
+ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
- UINavigationBar.appearance().tintColor = UIColor.whiteColor()
- application.registerUserNotificationSettings(UIUserNotificationSettings( forTypes: [.Alert, .Badge, .Sound], categories: nil))
+ UINavigationBar.appearance().tintColor = UIColor.white
+ application.registerUserNotificationSettings(UIUserNotificationSettings( types: [.alert, .badge, .sound], categories: nil))
application.registerForRemoteNotifications()
// Initialize the Usergrid shared instance.
@@ -48,17 +48,17 @@
if Usergrid.currentUser != nil {
let rootViewController = self.window!.rootViewController as! UINavigationController
let loginViewController = rootViewController.viewControllers.first!
- loginViewController.performSegueWithIdentifier("loginSuccessNonAnimatedSegue", sender: loginViewController)
+ loginViewController.performSegue(withIdentifier: "loginSuccessNonAnimatedSegue", sender: loginViewController)
}
return true
}
- func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Usergrid.applyPushToken(deviceToken, notifierID: UsergridManager.NOTIFIER_ID, completion: nil)
}
- func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Application failed to register for remote notifications")
}
}
diff --git a/Samples/ActivityFeed/Source/FollowViewController.swift b/Samples/ActivityFeed/Source/FollowViewController.swift
index 6362cdb..70d4fb7 100644
--- a/Samples/ActivityFeed/Source/FollowViewController.swift
+++ b/Samples/ActivityFeed/Source/FollowViewController.swift
@@ -32,19 +32,19 @@
@IBOutlet weak var usernameTextField: UITextField!
- @IBAction func addFollowerButtonTouched(sender:AnyObject?) {
- guard let username = usernameTextField.text where !username.isEmpty
+ @IBAction func addFollowerButtonTouched(_ sender:AnyObject?) {
+ guard let username = usernameTextField.text, !username.isEmpty
else {
- self.showAlert(title: "Follow failed.", message: "Please enter a valid username.")
+ self.showAlert("Follow failed.", message: "Please enter a valid username.")
return
}
UsergridManager.followUser(username) { (response) -> Void in
if response.ok {
- self.performSegueWithIdentifier("unwindToChatSegue", sender: self)
+ self.performSegue(withIdentifier: "unwindToChatSegue", sender: self)
} else {
- self.showAlert(title: "Follow failed.", message: "No user with the username \"\(username)\" found.")
+ self.showAlert("Follow failed.", message: "No user with the username \"\(username)\" found.")
}
}
}
-}
\ No newline at end of file
+}
diff --git a/Samples/ActivityFeed/Source/FormTextField.swift b/Samples/ActivityFeed/Source/FormTextField.swift
index fbb9bd6..961098e 100644
--- a/Samples/ActivityFeed/Source/FormTextField.swift
+++ b/Samples/ActivityFeed/Source/FormTextField.swift
@@ -43,29 +43,29 @@
}
func setUp() {
- addTarget(self, action: #selector(FormTextField.actionKeyboardButtonTapped(_:)), forControlEvents: .EditingDidEndOnExit)
+ addTarget(self, action: #selector(FormTextField.actionKeyboardButtonTapped(_:)), for: .editingDidEndOnExit)
}
- func actionKeyboardButtonTapped(sender: UITextField) {
+ func actionKeyboardButtonTapped(_ sender: UITextField) {
switch nextResponderField {
case let button as UIButton:
- if button.enabled {
- button.sendActionsForControlEvents(.TouchUpInside)
+ if button.isEnabled {
+ button.sendActions(for: .touchUpInside)
} else {
resignFirstResponder()
}
- case .Some(let responder):
+ case .some(let responder):
responder.becomeFirstResponder()
default:
resignFirstResponder()
}
}
- override func textRectForBounds(bounds: CGRect) -> CGRect {
- return CGRectInset(bounds, inset, 0)
+ override func textRect(forBounds bounds: CGRect) -> CGRect {
+ return bounds.insetBy(dx: inset, dy: 0)
}
- override func editingRectForBounds(bounds: CGRect) -> CGRect {
- return textRectForBounds(bounds)
+ override func editingRect(forBounds bounds: CGRect) -> CGRect {
+ return textRect(forBounds: bounds)
}
}
diff --git a/Samples/ActivityFeed/Source/LoginViewController.swift b/Samples/ActivityFeed/Source/LoginViewController.swift
index 0e6c0fa..7a8e261 100644
--- a/Samples/ActivityFeed/Source/LoginViewController.swift
+++ b/Samples/ActivityFeed/Source/LoginViewController.swift
@@ -33,45 +33,45 @@
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
- override func viewWillAppear(animated: Bool) {
+ override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.passwordTextField.text = nil
}
- override func viewDidAppear(animated: Bool) {
+ override func viewDidAppear(_ animated: Bool) {
Usergrid.logoutCurrentUser()
super.viewDidAppear(animated)
}
- override func viewWillDisappear(animated: Bool) {
+ override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.view.endEditing(true)
}
- @IBAction func loginButtonTouched(sender: AnyObject) {
- guard let username = usernameTextField.text where !username.isEmpty,
- let password = passwordTextField.text where !password.isEmpty
+ @IBAction func loginButtonTouched(_ sender: AnyObject) {
+ guard let username = usernameTextField.text, !username.isEmpty,
+ let password = passwordTextField.text, !password.isEmpty
else {
- self.showAlert(title: "Error Authenticating User", message: "Username and password must not be empty.")
+ self.showAlert("Error Authenticating User", message: "Username and password must not be empty.")
return;
}
self.loginUser(username, password: password)
}
- func loginUser(username:String, password:String) {
+ func loginUser(_ username:String, password:String) {
UsergridManager.loginUser(username,password: password) { (auth, user, error) -> Void in
if let authErrorDescription = error {
- self.showAlert(title: "Error Authenticating User", message: authErrorDescription.errorDescription)
+ self.showAlert("Error Authenticating User", message: authErrorDescription.errorDescription)
} else if let authenticatedUser = user {
- self.showAlert(title: "Authenticated User Successful", message: "User description: \n \(authenticatedUser.stringValue)") { (action) -> Void in
- self.performSegueWithIdentifier("loginSuccessSegue", sender: self)
+ self.showAlert("Authenticated User Successful", message: "User description: \n \(authenticatedUser.stringValue)") { (action) -> Void in
+ self.performSegue(withIdentifier: "loginSuccessSegue", sender: self)
}
}
}
}
- @IBAction func unwind(segue: UIStoryboardSegue) {
+ @IBAction func unwind(_ segue: UIStoryboardSegue) {
// Used for unwind segues back to this view controller.
}
}
diff --git a/Samples/ActivityFeed/Source/MessageTableViewCell.swift b/Samples/ActivityFeed/Source/MessageTableViewCell.swift
index a77abd8..8e018d3 100644
--- a/Samples/ActivityFeed/Source/MessageTableViewCell.swift
+++ b/Samples/ActivityFeed/Source/MessageTableViewCell.swift
@@ -32,7 +32,7 @@
var titleLabel : UILabel
var bodyLabel : UILabel
var thumbnailView : UIImageView
- var indexPath : NSIndexPath?
+ var indexPath : IndexPath?
public static let kMessageTableViewCellMinimumHeight: CGFloat = 50.0;
public static let kMessageTableViewCellAvatarHeight: CGFloat = 30.0;
@@ -48,8 +48,8 @@
super.init(style: style, reuseIdentifier: reuseIdentifier)
- self.selectionStyle = UITableViewCellSelectionStyle.None
- self.backgroundColor = UIColor.whiteColor()
+ self.selectionStyle = UITableViewCellSelectionStyle.none
+ self.backgroundColor = UIColor.white
self.configureSubviews()
}
@@ -58,30 +58,30 @@
}
override public func prepareForReuse() {
- self.selectionStyle = UITableViewCellSelectionStyle.None
- self.titleLabel.font = UIFont.boldSystemFontOfSize(MessageTableViewCell.defaultFontSize)
- self.bodyLabel.font = UIFont.boldSystemFontOfSize(13)
+ self.selectionStyle = UITableViewCellSelectionStyle.none
+ self.titleLabel.font = UIFont.boldSystemFont(ofSize: MessageTableViewCell.defaultFontSize)
+ self.bodyLabel.font = UIFont.boldSystemFont(ofSize: 13)
self.titleLabel.text = ""
self.bodyLabel.text = ""
}
func configureSubviews() {
self.titleLabel.translatesAutoresizingMaskIntoConstraints = false
- self.titleLabel.backgroundColor = UIColor.clearColor()
- self.titleLabel.userInteractionEnabled = false
+ self.titleLabel.backgroundColor = UIColor.clear
+ self.titleLabel.isUserInteractionEnabled = false
self.titleLabel.numberOfLines = 0
- self.titleLabel.textColor = UIColor.grayColor()
- self.titleLabel.font = UIFont.boldSystemFontOfSize(MessageTableViewCell.defaultFontSize)
+ self.titleLabel.textColor = UIColor.gray
+ self.titleLabel.font = UIFont.boldSystemFont(ofSize: MessageTableViewCell.defaultFontSize)
self.bodyLabel.translatesAutoresizingMaskIntoConstraints = false
- self.bodyLabel.backgroundColor = UIColor.clearColor()
- self.bodyLabel.userInteractionEnabled = false
+ self.bodyLabel.backgroundColor = UIColor.clear
+ self.bodyLabel.isUserInteractionEnabled = false
self.bodyLabel.numberOfLines = 0
- self.bodyLabel.textColor = UIColor.grayColor()
- self.bodyLabel.font = UIFont.boldSystemFontOfSize(13)
+ self.bodyLabel.textColor = UIColor.gray
+ self.bodyLabel.font = UIFont.boldSystemFont(ofSize: 13)
self.thumbnailView.translatesAutoresizingMaskIntoConstraints = false
- self.thumbnailView.userInteractionEnabled = false
+ self.thumbnailView.isUserInteractionEnabled = false
self.thumbnailView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
self.thumbnailView.layer.cornerRadius = 15
self.thumbnailView.layer.masksToBounds = true
@@ -90,12 +90,12 @@
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.bodyLabel)
- let views = ["thumbnailView":self.thumbnailView, "titleLabel":self.titleLabel, "bodyLabel":self.bodyLabel]
+ let views = ["thumbnailView":self.thumbnailView, "titleLabel":self.titleLabel, "bodyLabel":self.bodyLabel] as [String : Any]
let metrics = ["thumbSize":MessageTableViewCell.kMessageTableViewCellAvatarHeight, "padding":15, "right":10, "left":5]
- self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-left-[thumbnailView(thumbSize)]-right-[titleLabel(>=0)]-right-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
- self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-left-[thumbnailView(thumbSize)]-right-[bodyLabel(>=0)]-right-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
- self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-right-[titleLabel(20)]-left-[bodyLabel(>=0@999)]-left-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
- self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-right-[thumbnailView(thumbSize)]-(>=0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
+ self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[thumbnailView(thumbSize)]-right-[titleLabel(>=0)]-right-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
+ self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[thumbnailView(thumbSize)]-right-[bodyLabel(>=0)]-right-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
+ self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-right-[titleLabel(20)]-left-[bodyLabel(>=0@999)]-left-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
+ self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-right-[thumbnailView(thumbSize)]-(>=0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
}
-}
\ No newline at end of file
+}
diff --git a/Samples/ActivityFeed/Source/MessageTextView.swift b/Samples/ActivityFeed/Source/MessageTextView.swift
index 135372e..b8bb464 100644
--- a/Samples/ActivityFeed/Source/MessageTextView.swift
+++ b/Samples/ActivityFeed/Source/MessageTextView.swift
@@ -28,12 +28,12 @@
import SlackTextViewController
class MessageTextView : SLKTextView {
- override func willMoveToSuperview(newSuperview: UIView?) {
- super.willMoveToSuperview(newSuperview)
- self.backgroundColor = UIColor.whiteColor()
- self.placeholderColor = UIColor.lightGrayColor()
+ override func willMove(toSuperview newSuperview: UIView?) {
+ super.willMove(toSuperview: newSuperview)
+ self.backgroundColor = UIColor.white
+ self.placeholderColor = UIColor.lightGray
self.placeholder = "Message"
- self.pastableMediaTypes = .None
- self.layer.borderColor = UIColor(red: 217/255, green: 217/255, blue: 217/255, alpha: 1.0).CGColor
+ self.pastableMediaTypes = []
+ self.layer.borderColor = UIColor(red: 217/255, green: 217/255, blue: 217/255, alpha: 1.0).cgColor
}
}
diff --git a/Samples/ActivityFeed/Source/MessageViewController.swift b/Samples/ActivityFeed/Source/MessageViewController.swift
index b2a152c..a004cfe 100644
--- a/Samples/ActivityFeed/Source/MessageViewController.swift
+++ b/Samples/ActivityFeed/Source/MessageViewController.swift
@@ -36,7 +36,7 @@
private var messageEntities: [ActivityEntity] = []
init() {
- super.init(tableViewStyle:.Plain)
+ super.init(tableViewStyle:.plain)
commonInit()
}
@@ -45,11 +45,11 @@
commonInit()
}
- override static func tableViewStyleForCoder(decoder: NSCoder) -> UITableViewStyle {
- return .Plain
+ override static func tableViewStyle(for decoder: NSCoder) -> UITableViewStyle {
+ return .plain
}
- override func viewWillAppear(animated: Bool) {
+ override func viewWillAppear(_ animated: Bool) {
self.reloadMessages()
if let username = Usergrid.currentUser?.name {
self.navigationItem.title = "\(username)'s Feed"
@@ -60,11 +60,11 @@
func commonInit() {
self.bounces = true
self.shakeToClearEnabled = true
- self.keyboardPanningEnabled = true
+ self.isKeyboardPanningEnabled = true
self.shouldScrollToBottomAfterKeyboardShows = true
- self.inverted = true
+ self.isInverted = true
- self.registerClassForTextView(MessageTextView)
+ self.registerClass(forTextView:MessageTextView.classForCoder())
self.activateWCSession()
}
@@ -78,32 +78,32 @@
override func viewDidLoad() {
super.viewDidLoad()
- self.rightButton.setTitle("Send", forState: .Normal)
+ self.rightButton.setTitle("Send", for: [])
self.textInputbar.autoHideRightButton = true
self.textInputbar.maxCharCount = 256
- self.textInputbar.editorTitle.textColor = UIColor.darkGrayColor()
+ self.textInputbar.editorTitle.textColor = UIColor.darkGray
- self.tableView!.separatorStyle = .None
- self.tableView!.registerClass(MessageTableViewCell.self, forCellReuseIdentifier:MessageViewController.MESSAGE_CELL_IDENTIFIER)
+ self.tableView!.separatorStyle = .none
+ self.tableView!.register(MessageTableViewCell.self, forCellReuseIdentifier:MessageViewController.MESSAGE_CELL_IDENTIFIER)
}
- override func didPressRightButton(sender: AnyObject!) {
+ override func didPressRightButton(_ sender: Any!) {
self.textView.refreshFirstResponder()
UsergridManager.postFeedMessage(self.textView.text) { (response) -> Void in
if let messageEntity = response.entity as? ActivityEntity {
- let indexPath = NSIndexPath(forRow: 0, inSection: 0)
- let rowAnimation: UITableViewRowAnimation = self.inverted ? .Bottom : .Top
- let scrollPosition: UITableViewScrollPosition = self.inverted ? .Bottom : .Top
+ let indexPath = NSIndexPath.init(row: 0, section: 0)
+ let rowAnimation: UITableViewRowAnimation = self.isInverted ? .bottom : .top
+ let scrollPosition: UITableViewScrollPosition = self.isInverted ? .bottom : .top
self.tableView!.beginUpdates()
- self.messageEntities.insert(messageEntity, atIndex: 0)
- self.tableView!.insertRowsAtIndexPaths([indexPath], withRowAnimation: rowAnimation)
+ self.messageEntities.insert(messageEntity, at: 0)
+ self.tableView!.insertRows(at: [indexPath as IndexPath], with: rowAnimation)
self.tableView!.endUpdates()
- self.tableView!.scrollToRowAtIndexPath(indexPath, atScrollPosition: scrollPosition, animated: true)
- self.tableView!.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
+ self.tableView!.scrollToRow(at: indexPath as IndexPath, at: scrollPosition, animated: true)
+ self.tableView!.reloadRows(at: [indexPath as IndexPath], with: .automatic)
self.sendEntitiesToWatch(self.messageEntities)
}
@@ -112,35 +112,37 @@
}
override func keyForTextCaching() -> String? {
- return NSBundle.mainBundle().bundleIdentifier
+ return Bundle.main.bundleIdentifier
}
- override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+
+ override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
- override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+
+ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messageEntities.count
}
- override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
+ override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.messageCellForRowAtIndexPath(indexPath)
}
- @IBAction func unwindToChat(segue: UIStoryboardSegue) {
+ @IBAction func unwindToChat(_ segue: UIStoryboardSegue) {
}
- func populateCell(cell:MessageTableViewCell,feedEntity:ActivityEntity) {
+ func populateCell(_ cell:MessageTableViewCell,feedEntity:ActivityEntity) {
cell.titleLabel.text = feedEntity.displayName
cell.bodyLabel.text = feedEntity.content
cell.thumbnailView.image = nil
- if let imageURLString = feedEntity.imageURL, imageURL = NSURL(string: imageURLString) {
- NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in
- if let imageData = data, image = UIImage(data: imageData) {
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
+ if let imageURLString = feedEntity.imageURL, let imageURL = URL(string: imageURLString) {
+ URLSession.shared.dataTask(with: imageURL) { (data, response, error) in
+ if let imageData = data, let image = UIImage(data: imageData) {
+ DispatchQueue.main.async(execute: { () -> Void in
cell.thumbnailView.image = image
})
}
@@ -148,8 +150,8 @@
}
}
- func messageCellForRowAtIndexPath(indexPath:NSIndexPath) -> MessageTableViewCell {
- let cell = self.tableView!.dequeueReusableCellWithIdentifier(MessageViewController.MESSAGE_CELL_IDENTIFIER) as! MessageTableViewCell
+ func messageCellForRowAtIndexPath(_ indexPath:IndexPath) -> MessageTableViewCell {
+ let cell = self.tableView!.dequeueReusableCell(withIdentifier: MessageViewController.MESSAGE_CELL_IDENTIFIER) as! MessageTableViewCell
self.populateCell(cell, feedEntity: self.messageEntities[indexPath.row])
cell.indexPath = indexPath
@@ -158,30 +160,30 @@
return cell
}
- override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
+ override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- let feedEntity = messageEntities[indexPath.row]
+ let feedEntity = messageEntities[(indexPath as NSIndexPath).row]
- guard let messageText = feedEntity.content where !messageText.isEmpty
+ guard let messageText = feedEntity.content, !messageText.isEmpty
else {
return 0
}
- let messageUsername : NSString = feedEntity.displayName ?? ""
+ let messageUsername : NSString = (feedEntity.displayName ?? "") as NSString
let paragraphStyle = NSMutableParagraphStyle()
- paragraphStyle.lineBreakMode = .ByWordWrapping
- paragraphStyle.alignment = .Left
+ paragraphStyle.lineBreakMode = .byWordWrapping
+ paragraphStyle.alignment = .left
let pointSize = MessageTableViewCell.defaultFontSize
- let attributes = [NSFontAttributeName:UIFont.boldSystemFontOfSize(pointSize),NSParagraphStyleAttributeName:paragraphStyle]
+ let attributes = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: pointSize),NSParagraphStyleAttributeName:paragraphStyle]
- let width: CGFloat = CGRectGetWidth(self.tableView!.frame) - MessageTableViewCell.kMessageTableViewCellAvatarHeight - 25
+ let width: CGFloat = self.tableView!.frame.width - MessageTableViewCell.kMessageTableViewCellAvatarHeight - 25
- let titleBounds = messageUsername.boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
- let bodyBounds = messageText.boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
+ let titleBounds = messageUsername.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
+ let bodyBounds = messageText.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
- var height = CGRectGetHeight(titleBounds) + CGRectGetHeight(bodyBounds) + 40
+ var height = titleBounds.height + bodyBounds.height + 40
if height < MessageTableViewCell.kMessageTableViewCellMinimumHeight {
height = MessageTableViewCell.kMessageTableViewCellMinimumHeight
}
@@ -194,24 +196,47 @@
func activateWCSession() {
if (WCSession.isSupported()) {
- let session = WCSession.defaultSession()
+ let session = WCSession.default()
session.delegate = self
- session.activateSession()
+ session.activate()
}
}
- func sendEntitiesToWatch(messages:[UsergridEntity]) {
- if WCSession.defaultSession().reachable {
- NSKeyedArchiver.setClassName("ActivityEntity", forClass: ActivityEntity.self)
- let data = NSKeyedArchiver.archivedDataWithRootObject(messages)
- WCSession.defaultSession().sendMessageData(data, replyHandler: nil, errorHandler: { (error) -> Void in
- self.showAlert(title: "WCSession Unreachable.", message: "\(error)")
+ @available(iOS 9.3, *)
+ func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
+
+ }
+
+ func sessionDidBecomeInactive(_ session: WCSession) {
+
+ }
+
+ func sessionDidDeactivate(_ session: WCSession) {
+
+ }
+
+ func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Swift.Void) {
+ if let action = message["action"] as? String, action == "getMessages" {
+ UsergridManager.getFeedMessages { (response) -> Void in
+ if let entities = response.entities {
+ self.sendEntitiesToWatch(entities)
+ }
+ }
+ }
+ }
+
+ func sendEntitiesToWatch(_ messages:[UsergridEntity]) {
+ if WCSession.default().isReachable {
+ NSKeyedArchiver.setClassName("ActivityEntity", for: ActivityEntity.self)
+ let data = NSKeyedArchiver.archivedData(withRootObject: messages)
+ WCSession.default().sendMessageData(data, replyHandler: nil, errorHandler: { (error) -> Void in
+ self.showAlert("WCSession Unreachable.", message: "\(error)")
})
}
}
- func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
- if let action = message["action"] as? String where action == "getMessages" {
+ func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
+ if let action = message["action"] as? String, action == "getMessages" {
UsergridManager.getFeedMessages { (response) -> Void in
if let entities = response.entities {
self.sendEntitiesToWatch(entities)
diff --git a/Samples/ActivityFeed/Source/RegisterViewController.swift b/Samples/ActivityFeed/Source/RegisterViewController.swift
index 25cad11..f2cbae5 100644
--- a/Samples/ActivityFeed/Source/RegisterViewController.swift
+++ b/Samples/ActivityFeed/Source/RegisterViewController.swift
@@ -35,27 +35,27 @@
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
- @IBAction func registerButtonTouched(sender: AnyObject) {
- guard let name = nameTextField.text where !name.isEmpty,
- let username = usernameTextField.text where !username.isEmpty,
- let email = emailTextField.text where !email.isEmpty,
- let password = passwordTextField.text where !password.isEmpty
+ @IBAction func registerButtonTouched(_ sender: AnyObject) {
+ guard let name = nameTextField.text, !name.isEmpty,
+ let username = usernameTextField.text, !username.isEmpty,
+ let email = emailTextField.text, !email.isEmpty,
+ let password = passwordTextField.text, !password.isEmpty
else {
- self.showAlert(title: "Error Registering User", message: "Name, username, email, and password fields must not be empty.")
+ self.showAlert("Error Registering User", message: "Name, username, email, and password fields must not be empty.")
return;
}
self.createUser(name, username: username, email: email, password: password)
}
- private func createUser(name:String, username:String, email:String, password:String) {
+ private func createUser(_ name:String, username:String, email:String, password:String) {
UsergridManager.createUser(name, username: username, email: email, password: password) { (response) -> Void in
if let createdUser = response.user {
- self.showAlert(title: "Registering User Successful", message: "User description: \n \(createdUser.stringValue)") { (action) -> Void in
- self.performSegueWithIdentifier("unwindSegue", sender: self)
+ self.showAlert("Registering User Successful", message: "User description: \n \(createdUser.stringValue)") { (action) -> Void in
+ self.performSegue(withIdentifier: "unwindSegue", sender: self)
}
} else {
- self.showAlert(title: "Error Registering User", message: response.error?.errorDescription)
+ self.showAlert("Error Registering User", message: response.error?.errorDescription)
}
}
}
diff --git a/Samples/ActivityFeed/Source/UsergridManager.swift b/Samples/ActivityFeed/Source/UsergridManager.swift
index 99fe4b5..7130490 100644
--- a/Samples/ActivityFeed/Source/UsergridManager.swift
+++ b/Samples/ActivityFeed/Source/UsergridManager.swift
@@ -40,29 +40,29 @@
ActivityEntity.registerSubclass()
}
- static func loginUser(username:String, password:String, completion:UsergridUserAuthCompletionBlock) {
+ static func loginUser(_ username:String, password:String, completion:UsergridUserAuthCompletionBlock) {
let userAuth = UsergridUserAuth(username: username, password: password)
Usergrid.authenticateUser(userAuth, completion: completion)
}
- static func createUser(name:String, username:String, email:String, password:String, completion:UsergridResponseCompletion) {
- let user = UsergridUser(name: name, propertyDict: [UsergridUserProperties.Username.stringValue:username,
- UsergridUserProperties.Email.stringValue:email,
- UsergridUserProperties.Password.stringValue:password])
+ static func createUser(_ name:String, username:String, email:String, password:String, completion:UsergridResponseCompletion) {
+ let user = UsergridUser(name: name, propertyDict: [UsergridUserProperties.username.stringValue:username,
+ UsergridUserProperties.email.stringValue:email,
+ UsergridUserProperties.password.stringValue:password])
user.create(completion)
}
- static func getFeedMessages(completion:UsergridResponseCompletion) {
- Usergrid.GET(UsergridQuery("users/me/feed").desc(UsergridEntityProperties.Created.stringValue), queryCompletion: completion)
+ static func getFeedMessages(_ completion:UsergridResponseCompletion) {
+ Usergrid.GET(UsergridQuery("users/me/feed").desc(UsergridEntityProperties.created.stringValue), queryCompletion: completion)
}
- static func postFeedMessage(text:String,completion:UsergridResponseCompletion) {
+ static func postFeedMessage(_ text:String,completion:UsergridResponseCompletion) {
let currentUser = Usergrid.currentUser!
let verb = "post"
let content = text
- var actorDictionary = [String:AnyObject]()
+ var actorDictionary = [String:Any]()
actorDictionary["displayName"] = currentUser.name ?? currentUser.usernameOrEmail ?? ""
actorDictionary["email"] = currentUser.email ?? ""
if let imageURL = currentUser.picture {
@@ -72,7 +72,7 @@
Usergrid.POST("users/me/activities", jsonBody: ["actor":actorDictionary,"verb":verb,"content":content], completion: completion)
}
- static func followUser(username:String, completion:UsergridResponseCompletion) {
+ static func followUser(_ username:String, completion:UsergridResponseCompletion) {
Usergrid.connect("users", entityID: "me", relationship: "following", toType: "users", toName: username, completion: completion)
}
-}
\ No newline at end of file
+}
diff --git a/Samples/ActivityFeed/Source/ViewControllerExtensions.swift b/Samples/ActivityFeed/Source/ViewControllerExtensions.swift
index ad79741..c81f177 100644
--- a/Samples/ActivityFeed/Source/ViewControllerExtensions.swift
+++ b/Samples/ActivityFeed/Source/ViewControllerExtensions.swift
@@ -27,10 +27,10 @@
import UIKit
extension UIViewController {
- func showAlert(title title: String, message: String?, handler:((UIAlertAction) -> Void)? = nil) {
- let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
- alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: handler))
- self.presentViewController(alert, animated: true, completion: nil)
+ func showAlert(_ title: String, message: String?, handler:((UIAlertAction) -> Void)? = nil) {
+ let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
+ alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: handler))
+ self.present(alert, animated: true, completion: nil)
}
}
diff --git a/Samples/ActivityFeed/WatchSample Extension/InterfaceController.swift b/Samples/ActivityFeed/WatchSample Extension/InterfaceController.swift
index a61192a..18a0adf 100644
--- a/Samples/ActivityFeed/WatchSample Extension/InterfaceController.swift
+++ b/Samples/ActivityFeed/WatchSample Extension/InterfaceController.swift
@@ -34,19 +34,23 @@
@IBOutlet var messageTable: WKInterfaceTable!
var messageEntities: [ActivityEntity] = []
- override func awakeWithContext(context: AnyObject?) {
- super.awakeWithContext(context)
+ override func awake(withContext context: Any?) {
+ super.awake(withContext: context)
if WCSession.isSupported() {
- let session = WCSession.defaultSession()
+ let session = WCSession.default()
session.delegate = self
- session.activateSession()
+ session.activate()
}
}
+ func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
+
+ }
+
override func willActivate() {
self.reloadTable()
- if WCSession.defaultSession().reachable {
- WCSession.defaultSession().sendMessage(["action":"getMessages"], replyHandler: nil) { (error) -> Void in
+ if WCSession.default().isReachable {
+ WCSession.default().sendMessage(["action":"getMessages"], replyHandler: nil) { (error) -> Void in
print(error)
}
}
@@ -56,7 +60,7 @@
func reloadTable() {
self.messageTable.setNumberOfRows(messageEntities.count, withRowType: "MessageRow")
for index in 0..<self.messageTable.numberOfRows {
- if let controller = self.messageTable.rowControllerAtIndex(index) as? MessageRowController {
+ if let controller = self.messageTable.rowController(at: index) as? MessageRowController {
let messageEntity = messageEntities[index]
controller.titleLabel.setText(messageEntity.displayName)
controller.messageLabel.setText(messageEntity.content)
@@ -64,9 +68,9 @@
}
}
- func session(session: WCSession, didReceiveMessageData messageData: NSData) {
+ func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
NSKeyedUnarchiver.setClass(ActivityEntity.self, forClassName: "ActivityEntity")
- if let messageEntities = NSKeyedUnarchiver.unarchiveObjectWithData(messageData) as? [ActivityEntity] {
+ if let messageEntities = NSKeyedUnarchiver.unarchiveObject(with: messageData) as? [ActivityEntity] {
self.messageEntities = messageEntities
self.reloadTable()
}
diff --git a/Samples/Push/Push.xcodeproj/project.pbxproj b/Samples/Push/Push.xcodeproj/project.pbxproj
index f786e4e..414f073 100644
--- a/Samples/Push/Push.xcodeproj/project.pbxproj
+++ b/Samples/Push/Push.xcodeproj/project.pbxproj
@@ -201,6 +201,7 @@
TargetAttributes = {
637A71EF1C5BF7B10056545A = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
};
};
@@ -428,6 +429,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.usergridpushsample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -443,6 +445,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.usergrid.usergridpushsample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
diff --git a/Samples/Push/Source/AppDelegate.swift b/Samples/Push/Source/AppDelegate.swift
index 0ce64dd..e13348b 100644
--- a/Samples/Push/Source/AppDelegate.swift
+++ b/Samples/Push/Source/AppDelegate.swift
@@ -32,21 +32,21 @@
var window: UIWindow?
- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
+ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
UsergridManager.initializeSharedInstance()
- application.registerUserNotificationSettings(UIUserNotificationSettings( forTypes: [.Alert, .Badge, .Sound], categories: nil))
+ application.registerUserNotificationSettings(UIUserNotificationSettings( types: [.alert, .badge, .sound], categories: nil))
application.registerForRemoteNotifications()
return true
}
- func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
UsergridManager.applyPushToken(deviceToken)
}
- func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Application failed to register for remote notifications")
}
}
diff --git a/Samples/Push/Source/UsergridManager.swift b/Samples/Push/Source/UsergridManager.swift
index 00e8ec2..bcdcb98 100644
--- a/Samples/Push/Source/UsergridManager.swift
+++ b/Samples/Push/Source/UsergridManager.swift
@@ -39,7 +39,7 @@
Usergrid.initSharedInstance(configuration: UsergridClientConfig(orgId: UsergridManager.ORG_ID, appId: UsergridManager.APP_ID, baseUrl: UsergridManager.BASE_URL))
}
- static func applyPushToken(deviceToken:NSData) {
+ static func applyPushToken(_ deviceToken:Data) {
Usergrid.applyPushToken(deviceToken, notifierID: UsergridManager.NOTIFIER_ID, completion: { (response) -> Void in
print("Apply token completed successfully : \(response.ok)")
if !response.ok, let errorDescription = response.error?.errorDescription {
@@ -48,8 +48,8 @@
})
}
- static func sendPush(deviceId deviceId:String,message:String) {
- let pushRequest = UsergridRequest(method: .Post,
+ static func sendPush(deviceId:String,message:String) {
+ let pushRequest = UsergridRequest(method: .post,
baseUrl: Usergrid.clientAppURL,
paths: ["devices",deviceId,"notifications"],
auth: Usergrid.authForRequests(),
@@ -69,4 +69,4 @@
static func pushToAllDevices() {
UsergridManager.sendPush(deviceId: "*", message: "Push to all devices message.")
}
-}
\ No newline at end of file
+}
diff --git a/Samples/Push/Source/ViewController.swift b/Samples/Push/Source/ViewController.swift
index d1e3247..ec130d3 100644
--- a/Samples/Push/Source/ViewController.swift
+++ b/Samples/Push/Source/ViewController.swift
@@ -28,11 +28,11 @@
class ViewController: UIViewController {
- @IBAction func pushToThisDevice(sender: AnyObject) {
+ @IBAction func pushToThisDevice(_ sender: AnyObject) {
UsergridManager.pushToThisDevice()
}
- @IBAction func pushToAllDevices(sender: AnyObject) {
+ @IBAction func pushToAllDevices(_ sender: AnyObject) {
UsergridManager.pushToAllDevices()
}
}
diff --git a/Source/Usergrid.swift b/Source/Usergrid.swift
index ac87380..f9807f3 100644
--- a/Source/Usergrid.swift
+++ b/Source/Usergrid.swift
@@ -103,7 +103,8 @@
- returns: The shared instance of `UsergridClient`.
*/
- public static func initSharedInstance(orgId orgId : String, appId: String) -> UsergridClient {
+ @discardableResult
+ public static func initSharedInstance(orgId : String, appId: String) -> UsergridClient {
if !Usergrid.isInitialized {
Usergrid._sharedClient = UsergridClient(orgId: orgId, appId: appId)
} else {
@@ -121,7 +122,8 @@
- returns: The shared instance of `UsergridClient`.
*/
- public static func initSharedInstance(orgId orgId : String, appId: String, baseUrl: String) -> UsergridClient {
+ @discardableResult
+ public static func initSharedInstance(orgId : String, appId: String, baseUrl: String) -> UsergridClient {
if !Usergrid.isInitialized {
Usergrid._sharedClient = UsergridClient(orgId: orgId, appId: appId, baseUrl: baseUrl)
} else {
@@ -137,7 +139,8 @@
- returns: The shared instance of `UsergridClient`.
*/
- public static func initSharedInstance(configuration configuration: UsergridClientConfig) -> UsergridClient {
+ @discardableResult
+ public static func initSharedInstance(configuration: UsergridClientConfig) -> UsergridClient {
if !Usergrid.isInitialized {
Usergrid._sharedClient = UsergridClient(configuration: configuration)
} else {
@@ -155,7 +158,7 @@
- parameter notifierID: The Usergrid notifier ID.
- parameter completion: The completion block.
*/
- public static func applyPushToken(pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ public static func applyPushToken(_ pushToken: Data, notifierID: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.applyPushToken(pushToken, notifierID: notifierID, completion: completion)
}
@@ -167,7 +170,7 @@
- parameter notifierID: The Usergrid notifier ID.
- parameter completion: The completion block.
*/
- public static func applyPushToken(device: UsergridDevice, pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ public static func applyPushToken(_ device: UsergridDevice, pushToken: Data, notifierID: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.applyPushToken(device, pushToken: pushToken, notifierID: notifierID, completion: completion)
}
@@ -183,7 +186,7 @@
- returns: The shared instance of `UsergridClient`
*/
- public static func usingAuth(auth:UsergridAuth) -> UsergridClient {
+ public static func usingAuth(_ auth:UsergridAuth) -> UsergridClient {
return Usergrid.sharedInstance.usingAuth(auth)
}
@@ -196,7 +199,7 @@
- returns: The shared instance of `UsergridClient`
*/
- public static func usingToken(token:String) -> UsergridClient {
+ public static func usingToken(_ token:String) -> UsergridClient {
return Usergrid.sharedInstance.usingToken(token)
}
@@ -219,7 +222,7 @@
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public static func authenticateApp(completion: UsergridAppAuthCompletionBlock? = nil) {
+ public static func authenticateApp(_ completion: UsergridAppAuthCompletionBlock? = nil) {
Usergrid.sharedInstance.authenticateApp(completion)
}
@@ -229,7 +232,7 @@
- parameter auth: The `UsergridAppAuth` that will be authenticated.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public static func authenticateApp(auth: UsergridAppAuth, completion: UsergridAppAuthCompletionBlock? = nil) {
+ public static func authenticateApp(_ auth: UsergridAppAuth, completion: UsergridAppAuthCompletionBlock? = nil) {
Usergrid.sharedInstance.authenticateApp(auth, completion: completion)
}
@@ -239,7 +242,7 @@
- parameter auth: The `UsergridUserAuth` that will be authenticated.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public static func authenticateUser(auth: UsergridUserAuth, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public static func authenticateUser(_ auth: UsergridUserAuth, completion: UsergridUserAuthCompletionBlock? = nil) {
Usergrid.sharedInstance.authenticateUser(auth, completion: completion)
}
@@ -250,7 +253,7 @@
- parameter setAsCurrentUser: If the authenticated user should be set as the `UsergridClient.currentUser`.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public static func authenticateUser(userAuth: UsergridUserAuth, setAsCurrentUser:Bool, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public static func authenticateUser(_ userAuth: UsergridUserAuth, setAsCurrentUser:Bool, completion: UsergridUserAuthCompletionBlock? = nil) {
Usergrid.sharedInstance.authenticateUser(userAuth, setAsCurrentUser: setAsCurrentUser, completion: completion)
}
@@ -262,7 +265,7 @@
- parameter new: The new password.
- parameter completion: The optional completion block.
*/
- public static func resetPassword(user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
+ public static func resetPassword(_ user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
Usergrid.sharedInstance.resetPassword(user, old: old, new: new, completion: completion)
}
@@ -271,7 +274,7 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public static func logoutCurrentUser(completion:UsergridResponseCompletion? = nil) {
+ public static func logoutCurrentUser(_ completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.logoutCurrentUser(completion)
}
@@ -280,7 +283,7 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public static func logoutUserAllTokens(uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) {
+ public static func logoutUserAllTokens(_ uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.logoutUserAllTokens(uuidOrUsername, completion: completion)
}
@@ -291,7 +294,7 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public static func logoutUser(uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) {
+ public static func logoutUser(_ uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.logoutUser(uuidOrUsername, token: token, completion: completion)
}
@@ -305,7 +308,7 @@
- parameter request: The `UsergridRequest` object to send.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public static func sendRequest(request:UsergridRequest, completion:UsergridResponseCompletion? = nil) {
+ public static func sendRequest(_ request:UsergridRequest, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.sendRequest(request, completion: completion)
}
@@ -318,7 +321,7 @@
- parameter uuidOrName: The UUID or name of the `UsergridEntity`.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func GET(type: String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
+ public static func GET(_ type: String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.GET(type,uuidOrName:uuidOrName,completion:completion)
}
@@ -328,7 +331,7 @@
- parameter type: The `UsergridEntity` type.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public static func GET(type: String, completion: UsergridResponseCompletion? = nil) {
+ public static func GET(_ type: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.GET(type,completion:completion)
}
@@ -338,7 +341,7 @@
- parameter query: The query to use when gathering `UsergridEntity` objects.
- parameter queryCompletion: The completion block that will be called once the request has completed.
*/
- public static func GET(query: UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
+ public static func GET(_ query: UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.GET(query,queryCompletion:queryCompletion)
}
@@ -352,7 +355,7 @@
- parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func PUT(type: String, uuidOrName: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
+ public static func PUT(_ type: String, uuidOrName: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.PUT(type, uuidOrName: uuidOrName, jsonBody: jsonBody, completion: completion)
}
@@ -365,7 +368,7 @@
- parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func PUT(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
+ public static func PUT(_ type: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.PUT(type, jsonBody: jsonBody, completion: completion)
}
@@ -375,7 +378,7 @@
- parameter entity: The `UsergridEntity` to update.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func PUT(entity: UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public static func PUT(_ entity: UsergridEntity, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.PUT(entity, completion: completion)
}
@@ -388,7 +391,7 @@
- parameter jsonBody: The valid JSON body dictionary to update with.
- parameter queryCompletion: The completion block that will be called once the request has completed.
*/
- public static func PUT(query: UsergridQuery, jsonBody:[String:AnyObject], queryCompletion: UsergridResponseCompletion? = nil) {
+ public static func PUT(_ query: UsergridQuery, jsonBody:[String:Any], queryCompletion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.PUT(query, jsonBody: jsonBody, queryCompletion: queryCompletion)
}
@@ -402,7 +405,7 @@
- parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func POST(type: String, name: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
+ public static func POST(_ type: String, name: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.POST(type, name: name, jsonBody: jsonBody, completion: completion)
}
@@ -413,7 +416,7 @@
- parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func POST(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
+ public static func POST(_ type: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.POST(type, jsonBody: jsonBody, completion: completion)
}
@@ -424,7 +427,7 @@
- parameter jsonBody: The valid JSON body dictionaries to use when creating the `UsergridEntity` objects.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func POST(type: String, jsonBodies:[[String:AnyObject]], completion: UsergridResponseCompletion? = nil) {
+ public static func POST(_ type: String, jsonBodies:[[String:Any]], completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.POST(type, jsonBodies: jsonBodies, completion: completion)
}
@@ -434,7 +437,7 @@
- parameter entity: The `UsergridEntity` to create.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func POST(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public static func POST(_ entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.POST(entity, completion: completion)
}
@@ -446,7 +449,7 @@
- parameter entities: The `UsergridEntity` objects to create.
- parameter entitiesCompletion: The completion block that will be called once the request has completed.
*/
- public static func POST(entities:[UsergridEntity], entitiesCompletion: UsergridResponseCompletion? = nil) {
+ public static func POST(_ entities:[UsergridEntity], entitiesCompletion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.POST(entities, entitiesCompletion: entitiesCompletion)
}
@@ -459,7 +462,7 @@
- parameter uuidOrName: The UUID or name of the `UsergridEntity`.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func DELETE(type:String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
+ public static func DELETE(_ type:String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.DELETE(type, uuidOrName: uuidOrName, completion: completion)
}
@@ -471,7 +474,7 @@
- parameter entity: The `UsergridEntity` to delete.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func DELETE(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public static func DELETE(_ entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.DELETE(entity, completion:completion)
}
@@ -483,7 +486,7 @@
- parameter query: The query to use when filtering what entities to delete.
- parameter queryCompletion: The completion block that will be called once the request has completed.
*/
- public static func DELETE(query:UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
+ public static func DELETE(_ query:UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.DELETE(query, queryCompletion:queryCompletion)
}
@@ -497,7 +500,7 @@
- parameter to: The entity which is connected.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func connect(entity:UsergridEntity, relationship:String, to:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public static func connect(_ entity:UsergridEntity, relationship:String, to:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.connect(entity, relationship: relationship, to: to, completion: completion)
}
@@ -511,7 +514,7 @@
- parameter toID: The UUID of the entity you are connecting to.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func connect(entityType:String, entityID:String, relationship:String, toType:String?, toID: String, completion: UsergridResponseCompletion? = nil) {
+ public static func connect(_ entityType:String, entityID:String, relationship:String, toType:String?, toID: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toID: toID, completion: completion)
}
@@ -525,7 +528,7 @@
- parameter toName: The name of the entity you are connecting to.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func connect(entityType:String, entityID:String, relationship:String, toType:String, toName: String, completion: UsergridResponseCompletion? = nil) {
+ public static func connect(_ entityType:String, entityID:String, relationship:String, toType:String, toName: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toName: toName, completion: completion)
}
@@ -538,7 +541,7 @@
- parameter connectingEntity: The entity which is connected.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func disconnect(entity:UsergridEntity, relationship:String, from:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public static func disconnect(_ entity:UsergridEntity, relationship:String, from:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.disconnect(entity, relationship: relationship, from: from, completion: completion)
}
@@ -552,7 +555,7 @@
- parameter toID: The UUID of the entity you are disconnecting from.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func disconnect(entityType:String, entityID:String, relationship:String, fromType:String?, fromID: String, completion: UsergridResponseCompletion? = nil) {
+ public static func disconnect(_ entityType:String, entityID:String, relationship:String, fromType:String?, fromID: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromID: fromID, completion: completion)
}
@@ -566,7 +569,7 @@
- parameter fromName: The name of the entity you are disconnecting from.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func disconnect(entityType:String, entityID:String, relationship:String, fromType:String, fromName: String, completion: UsergridResponseCompletion? = nil) {
+ public static func disconnect(_ entityType:String, entityID:String, relationship:String, fromType:String, fromName: String, completion: UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromName: fromName, completion: completion)
}
@@ -578,7 +581,7 @@
- parameter relationship: The relationship.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func getConnections(direction:UsergridDirection, entity:UsergridEntity, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public static func getConnections(_ direction:UsergridDirection, entity:UsergridEntity, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.getConnections(direction, entity: entity, relationship: relationship, query:query, completion: completion)
}
@@ -592,7 +595,7 @@
- parameter query: The optional query.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func getConnections(direction:UsergridDirection, type:String, uuidOrName:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public static func getConnections(_ direction:UsergridDirection, type:String, uuidOrName:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.getConnections(direction, type: type, uuidOrName: uuidOrName, relationship: relationship, query:query, completion: completion)
}
@@ -605,7 +608,7 @@
- parameter query: The optional query.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public static func getConnections(direction:UsergridDirection, uuid:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public static func getConnections(_ direction:UsergridDirection, uuid:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
Usergrid.sharedInstance.getConnections(direction, uuid: uuid, relationship: relationship, query: query, completion: completion)
}
@@ -619,7 +622,7 @@
- parameter progress: The progress block that will be called to update the progress of the upload.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func uploadAsset(entity:UsergridEntity, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
+ public static func uploadAsset(_ entity:UsergridEntity, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
Usergrid.sharedInstance.uploadAsset(entity, asset: asset, progress: progress, completion: completion)
}
@@ -631,7 +634,7 @@
- parameter progress: The progress block that will be called to update the progress of the download.
- parameter completion: The completion block that will be called once the request has completed.
*/
- public static func downloadAsset(entity:UsergridEntity, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
+ public static func downloadAsset(_ entity:UsergridEntity, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
Usergrid.sharedInstance.downloadAsset(entity, contentType: contentType, progress: progress, completion: completion)
}
}
diff --git a/Source/UsergridAsset.swift b/Source/UsergridAsset.swift
index 9353ec1..93c88c7 100644
--- a/Source/UsergridAsset.swift
+++ b/Source/UsergridAsset.swift
@@ -32,13 +32,13 @@
#endif
/// The progress block used in `UsergridAsset` are being uploaded or downloaded.
-public typealias UsergridAssetRequestProgress = (bytesFinished:Int64, bytesExpected: Int64) -> Void
+public typealias UsergridAssetRequestProgress = (_ bytesFinished:Int64, _ bytesExpected: Int64) -> Void
/// The completion block used in `UsergridAsset` are finished uploading.
-public typealias UsergridAssetUploadCompletion = (asset:UsergridAsset?, response: UsergridResponse) -> Void
+public typealias UsergridAssetUploadCompletion = (_ asset:UsergridAsset?, _ response: UsergridResponse) -> Void
/// The completion block used in `UsergridAsset` are finished downloading.
-public typealias UsergridAssetDownloadCompletion = (asset:UsergridAsset?, error: UsergridResponseError?) -> Void
+public typealias UsergridAssetDownloadCompletion = (_ asset:UsergridAsset?, _ error: UsergridResponseError?) -> Void
/**
As Usergrid supports storing binary assets, the SDKs are designed to make uploading assets easier and more robust. Attaching, uploading, and downloading assets is handled by the `UsergridEntity` class.
@@ -55,7 +55,7 @@
public let filename: String
/// Binary representation of the asset's data.
- public let data: NSData
+ public let data: Data
/// A representation of the folder location the asset was loaded from, if it was provided in the initialization.
public let originalLocation: String?
@@ -64,7 +64,7 @@
public var contentType: String
/// The content length of the assets data.
- public var contentLength: Int { return self.data.length }
+ public var contentLength: Int { return self.data.count }
// MARK: - Initialization -
@@ -78,7 +78,7 @@
- returns: A new instance of `UsergridAsset`.
*/
- public init(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, data:NSData, originalLocation:String? = nil, contentType:String) {
+ public init(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, data:Data, originalLocation:String? = nil, contentType:String) {
self.filename = filename ?? UsergridAsset.DEFAULT_FILE_NAME
self.data = data
self.originalLocation = originalLocation
@@ -95,18 +95,18 @@
- returns: A new instance of `UsergridAsset` if the data can be gathered from the passed in `UIImage`, otherwise nil.
*/
- public convenience init?(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, image:UIImage, imageContentType:UsergridImageContentType = .Png) {
- var imageData: NSData?
+ public convenience init?(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, image:UIImage, imageContentType:UsergridImageContentType = .png) {
+ var imageData: Data?
switch(imageContentType) {
- case .Png :
+ case .png :
imageData = UIImagePNGRepresentation(image)
- case .Jpeg :
+ case .jpeg :
imageData = UIImageJPEGRepresentation(image, 1.0)
}
if let assetData = imageData {
self.init(filename:filename,data:assetData,contentType:imageContentType.stringValue)
} else {
- self.init(filename:"",data:NSData(),contentType:"")
+ self.init(filename:"",data:Data(),contentType:"")
return nil
}
}
@@ -121,22 +121,22 @@
- returns: A new instance of `UsergridAsset` if the data can be gathered from the passed in `NSURL`, otherwise nil.
*/
- public convenience init?(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, fileURL:NSURL, contentType:String? = nil) {
- if fileURL.fileURL, let assetData = NSData(contentsOfURL: fileURL) {
+ public convenience init?(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, fileURL:URL, contentType:String? = nil) {
+ if fileURL.isFileURL, let assetData = try? Data(contentsOf: fileURL) {
var fileNameToUse = filename
- if fileNameToUse != UsergridAsset.DEFAULT_FILE_NAME, let inferredFileName = fileURL.lastPathComponent {
- fileNameToUse = inferredFileName
+ if fileNameToUse != UsergridAsset.DEFAULT_FILE_NAME, !fileURL.lastPathComponent.isEmpty {
+ fileNameToUse = fileURL.lastPathComponent
}
if let fileContentType = contentType ?? UsergridAsset.MIMEType(fileURL) {
self.init(filename:fileNameToUse,data:assetData,originalLocation:fileURL.absoluteString,contentType:fileContentType)
} else {
print("Usergrid Error: Failed to imply content type of the asset.")
- self.init(filename:"",data:NSData(),contentType:"")
+ self.init(filename:"",data:Data(),contentType:"")
return nil
}
} else {
print("Usergrid Error: fileURL parameter must be a file URL.")
- self.init(filename:"",data:NSData(),contentType:"")
+ self.init(filename:"",data:Data(),contentType:"")
return nil
}
}
@@ -151,21 +151,21 @@
- returns: A decoded `UsergridUser` object.
*/
required public init?(coder aDecoder: NSCoder) {
- guard let filename = aDecoder.decodeObjectForKey("filename") as? String,
- let assetData = aDecoder.decodeObjectForKey("data") as? NSData,
- let contentType = aDecoder.decodeObjectForKey("contentType") as? String
+ guard let filename = aDecoder.decodeObject(forKey: "filename") as? String,
+ let assetData = aDecoder.decodeObject(forKey: "data") as? Data,
+ let contentType = aDecoder.decodeObject(forKey: "contentType") as? String
else {
self.filename = ""
self.contentType = ""
self.originalLocation = nil
- self.data = NSData()
+ self.data = Data()
super.init()
return nil
}
self.filename = filename
self.data = assetData
self.contentType = contentType
- self.originalLocation = aDecoder.decodeObjectForKey("originalLocation") as? String
+ self.originalLocation = aDecoder.decodeObject(forKey: "originalLocation") as? String
super.init()
}
@@ -174,16 +174,17 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.filename, forKey: "filename")
- aCoder.encodeObject(self.data, forKey: "data")
- aCoder.encodeObject(self.contentType, forKey: "contentType")
- aCoder.encodeObject(self.originalLocation, forKey: "originalLocation")
+ public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.filename, forKey: "filename")
+ aCoder.encode(self.data, forKey: "data")
+ aCoder.encode(self.contentType, forKey: "contentType")
+ aCoder.encode(self.originalLocation, forKey: "originalLocation")
}
- private static func MIMEType(fileURL: NSURL) -> String? {
- if let pathExtension = fileURL.pathExtension {
- if let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
+ private static func MIMEType(_ fileURL: URL) -> String? {
+ let pathExtension = fileURL.pathExtension
+ if !pathExtension.isEmpty {
+ if let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil) {
let UTI = UTIRef.takeUnretainedValue()
UTIRef.release()
if let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType) {
@@ -195,4 +196,4 @@
}
return nil
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridAssetRequestWrapper.swift b/Source/UsergridAssetRequestWrapper.swift
index d715652..37b5288 100644
--- a/Source/UsergridAssetRequestWrapper.swift
+++ b/Source/UsergridAssetRequestWrapper.swift
@@ -26,23 +26,23 @@
import Foundation
-typealias UsergridAssetRequestWrapperCompletionBlock = (requestWrapper:UsergridAssetRequestWrapper) -> Void
+typealias UsergridAssetRequestWrapperCompletionBlock = (_ requestWrapper:UsergridAssetRequestWrapper) -> Void
final class UsergridAssetRequestWrapper {
- weak var session: NSURLSession?
- let sessionTask: NSURLSessionTask
+ weak var session: URLSession?
+ let sessionTask: URLSessionTask
- var response: NSURLResponse?
- var responseData: NSData?
+ var response: URLResponse?
+ var responseData: Data?
var error: NSError?
var progress: UsergridAssetRequestProgress?
let completion: UsergridAssetRequestWrapperCompletionBlock
- init(session:NSURLSession?, sessionTask:NSURLSessionTask, progress:UsergridAssetRequestProgress?, completion:UsergridAssetRequestWrapperCompletionBlock) {
+ init(session:URLSession?, sessionTask:URLSessionTask, progress:UsergridAssetRequestProgress?, completion:UsergridAssetRequestWrapperCompletionBlock) {
self.session = session
self.sessionTask = sessionTask
self.progress = progress
self.completion = completion
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridAuth.swift b/Source/UsergridAuth.swift
index e87e9c1..228a4f4 100644
--- a/Source/UsergridAuth.swift
+++ b/Source/UsergridAuth.swift
@@ -27,10 +27,10 @@
import Foundation
/// The completion block used in `UsergridAppAuth` authentication methods.
-public typealias UsergridAppAuthCompletionBlock = (auth:UsergridAppAuth?, error: UsergridResponseError?) -> Void
+public typealias UsergridAppAuthCompletionBlock = (_ auth:UsergridAppAuth?, _ error: UsergridResponseError?) -> Void
/// The completion block used in `UsergridUserAuth` authentication methods.
-public typealias UsergridUserAuthCompletionBlock = (auth:UsergridUserAuth?, user:UsergridUser?, error: UsergridResponseError?) -> Void
+public typealias UsergridUserAuthCompletionBlock = (_ auth:UsergridUserAuth?, _ user:UsergridUser?, _ error: UsergridResponseError?) -> Void
/**
The `UsergridAuth` class functions to create and store authentication information used by Usergrid.
@@ -45,7 +45,7 @@
public var accessToken : String?
/// The expires at date, if this `UsergridAuth` was authorized successfully and their was a expires in time stamp within the token response.
- public var expiry : NSDate?
+ public var expiry : Date?
/// Determines if an access token exists.
public var hasToken: Bool { return self.accessToken != nil }
@@ -68,7 +68,7 @@
}
/// The credentials dictionary. Subclasses must override this method and provide an actual dictionary containing the credentials to send with requests.
- var credentialsJSONDict: [String:AnyObject] {
+ var credentialsJSONDict: [String:Any] {
return [:]
}
@@ -79,7 +79,7 @@
- returns: A new instance of `UsergridAuth`.
*/
- override private init() {
+ override fileprivate init() {
super.init()
}
@@ -91,7 +91,7 @@
- returns: A new instance of `UsergridAuth`
*/
- public init(accessToken:String, expiry:NSDate? = nil) {
+ public init(accessToken:String, expiry:Date? = nil) {
self.usingToken = true
self.accessToken = accessToken
self.expiry = expiry
@@ -107,8 +107,8 @@
- returns: A decoded `UsergridAuth` object.
*/
required public init?(coder aDecoder: NSCoder) {
- self.accessToken = aDecoder.decodeObjectForKey("accessToken") as? String
- self.expiry = aDecoder.decodeObjectForKey("expiry") as? NSDate
+ self.accessToken = aDecoder.decodeObject(forKey: "accessToken") as? String
+ self.expiry = aDecoder.decodeObject(forKey: "expiry") as? Date
}
/**
@@ -116,12 +116,12 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
+ public func encode(with aCoder: NSCoder) {
if let accessToken = self.accessToken {
- aCoder.encodeObject(accessToken, forKey: "accessToken")
+ aCoder.encode(accessToken, forKey: "accessToken")
}
if let expiresAt = self.expiry {
- aCoder.encodeObject(expiresAt, forKey: "expiry")
+ aCoder.encode(expiresAt, forKey: "expiry")
}
}
@@ -148,7 +148,7 @@
private let password: String
/// The credentials dictionary constructed with the `UsergridUserAuth`'s `username` and `password`.
- override var credentialsJSONDict: [String:AnyObject] {
+ override var credentialsJSONDict: [String:Any] {
return ["grant_type":"password",
"username":self.username,
"password":self.password]
@@ -180,8 +180,8 @@
- returns: A decoded `UsergridUserAuth` object.
*/
required public init?(coder aDecoder: NSCoder) {
- guard let username = aDecoder.decodeObjectForKey("username") as? String,
- password = aDecoder.decodeObjectForKey("password") as? String
+ guard let username = aDecoder.decodeObject(forKey: "username") as? String,
+ let password = aDecoder.decodeObject(forKey: "password") as? String
else {
self.username = ""
self.password = ""
@@ -199,10 +199,10 @@
- parameter aCoder: The encoder.
*/
- override public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.username, forKey: "username")
- aCoder.encodeObject(self.password, forKey: "password")
- super.encodeWithCoder(aCoder)
+ override public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.username, forKey: "username")
+ aCoder.encode(self.password, forKey: "password")
+ super.encode(with: aCoder)
}
}
@@ -218,7 +218,7 @@
private let clientSecret: String
/// The credentials dictionary constructed with the `UsergridAppAuth`'s `clientId` and `clientSecret`.
- override var credentialsJSONDict: [String:AnyObject] {
+ override var credentialsJSONDict: [String:Any] {
return ["grant_type":"client_credentials",
"client_id":self.clientId,
"client_secret":self.clientSecret]
@@ -250,8 +250,8 @@
- returns: A decoded `UsergridAppAuth` object.
*/
required public init?(coder aDecoder: NSCoder) {
- guard let clientId = aDecoder.decodeObjectForKey("clientId") as? String,
- let clientSecret = aDecoder.decodeObjectForKey("clientSecret") as? String
+ guard let clientId = aDecoder.decodeObject(forKey: "clientId") as? String,
+ let clientSecret = aDecoder.decodeObject(forKey: "clientSecret") as? String
else {
self.clientId = ""
self.clientSecret = ""
@@ -268,9 +268,9 @@
- parameter aCoder: The encoder.
*/
- override public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.clientId, forKey: "clientId")
- aCoder.encodeObject(self.clientSecret, forKey: "clientSecret")
- super.encodeWithCoder(aCoder)
+ override public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.clientId, forKey: "clientId")
+ aCoder.encode(self.clientSecret, forKey: "clientSecret")
+ super.encode(with: aCoder)
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridClient.swift b/Source/UsergridClient.swift
index 2b3eb6b..81fe3a6 100644
--- a/Source/UsergridClient.swift
+++ b/Source/UsergridClient.swift
@@ -143,7 +143,7 @@
- returns: A decoded `UsergridClient` object.
*/
public required init?(coder aDecoder: NSCoder) {
- guard let config = aDecoder.decodeObjectForKey("config") as? UsergridClientConfig
+ guard let config = aDecoder.decodeObject(forKey: "config") as? UsergridClientConfig
else {
self.config = UsergridClientConfig(orgId: "", appId: "")
super.init()
@@ -153,7 +153,7 @@
self.config = config
super.init()
- if let currentUser = aDecoder.decodeObjectForKey("currentUser") as? UsergridUser {
+ if let currentUser = aDecoder.decodeObject(forKey: "currentUser") as? UsergridUser {
self.currentUser = currentUser
} else {
if persistCurrentUserInKeychain {
@@ -168,9 +168,9 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.config, forKey: "config")
- aCoder.encodeObject(self.currentUser, forKey: "currentUser")
+ public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.config, forKey: "config")
+ aCoder.encode(self.currentUser, forKey: "currentUser")
}
// MARK: - Device Registration/Push Notifications -
@@ -182,7 +182,7 @@
- parameter notifierID: The Usergrid notifier ID.
- parameter completion: The completion block.
*/
- public func applyPushToken(pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ public func applyPushToken(_ pushToken: Data, notifierID: String, completion: UsergridResponseCompletion? = nil) {
self.applyPushToken(UsergridDevice.sharedDevice, pushToken: pushToken, notifierID: notifierID, completion: completion)
}
@@ -194,13 +194,13 @@
- parameter notifierID: The Usergrid notifier ID.
- parameter completion: The completion block.
*/
- public func applyPushToken(device: UsergridDevice, pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ public func applyPushToken(_ device: UsergridDevice, pushToken: Data, notifierID: String, completion: UsergridResponseCompletion? = nil) {
device.applyPushToken(pushToken, notifierID: notifierID)
self.PUT("devices", jsonBody: device.jsonObjectValue) { (response) in
if let responseEntity = response.entity {
device.copyInternalsFromEntity(responseEntity)
}
- completion?(response: response)
+ completion?(response)
}
}
@@ -226,17 +226,17 @@
self.tempAuth = nil
} else {
switch(self.authMode) {
- case .User:
- if let userAuth = self.userAuth where userAuth.isValid {
+ case .user:
+ if let userAuth = self.userAuth , userAuth.isValid {
usergridAuth = userAuth
}
break
- case .App:
- if let appAuth = self.appAuth where appAuth.isValid {
+ case .app:
+ if let appAuth = self.appAuth , appAuth.isValid {
usergridAuth = appAuth
}
break
- case .None:
+ case .none:
usergridAuth = nil
break
}
@@ -253,7 +253,7 @@
- returns: `Self`
*/
- public func usingAuth(auth:UsergridAuth) -> Self {
+ public func usingAuth(_ auth:UsergridAuth) -> Self {
self.tempAuth = auth
return self
}
@@ -267,7 +267,7 @@
- returns: `Self`
*/
- public func usingToken(token:String) -> Self {
+ public func usingToken(_ token:String) -> Self {
self.tempAuth = UsergridAuth(accessToken: token)
return self
}
@@ -277,11 +277,11 @@
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public func authenticateApp(completion: UsergridAppAuthCompletionBlock? = nil) {
+ public func authenticateApp(_ completion: UsergridAppAuthCompletionBlock? = nil) {
guard let appAuth = self.appAuth
else {
let error = UsergridResponseError(errorName: "Invalid UsergridAppAuth.", errorDescription: "UsergridClient's appAuth is nil.")
- completion?(auth: nil, error: error)
+ completion?(nil, error)
return
}
self.authenticateApp(appAuth, completion: completion)
@@ -293,16 +293,16 @@
- parameter auth: The `UsergridAppAuth` that will be authenticated.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public func authenticateApp(appAuth: UsergridAppAuth, completion: UsergridAppAuthCompletionBlock? = nil) {
- let request = UsergridRequest(method: .Post,
+ public func authenticateApp(_ appAuth: UsergridAppAuth, completion: UsergridAppAuthCompletionBlock? = nil) {
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: ["token"],
auth: self.authForRequests(),
- jsonBody: appAuth.credentialsJSONDict)
+ jsonBody: appAuth.credentialsJSONDict as Any?)
_requestManager.performAppAuthRequest(appAuth, request: request) { [weak self] (auth,error) in
self?.appAuth = auth
- completion?(auth: auth, error: error)
+ completion?(auth, error)
}
}
@@ -312,7 +312,7 @@
- parameter auth: The `UsergridUserAuth` that will be authenticated.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public func authenticateUser(userAuth: UsergridUserAuth, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public func authenticateUser(_ userAuth: UsergridUserAuth, completion: UsergridUserAuthCompletionBlock? = nil) {
self.authenticateUser(userAuth, setAsCurrentUser:true, completion:completion)
}
@@ -323,17 +323,17 @@
- parameter setAsCurrentUser: If the authenticated user should be set as the `UsergridClient.currentUser`.
- parameter completion: The completion block that will be called after authentication has completed.
*/
- public func authenticateUser(userAuth: UsergridUserAuth, setAsCurrentUser: Bool, completion: UsergridUserAuthCompletionBlock? = nil) {
- let request = UsergridRequest(method: .Post,
+ public func authenticateUser(_ userAuth: UsergridUserAuth, setAsCurrentUser: Bool, completion: UsergridUserAuthCompletionBlock? = nil) {
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: ["token"],
auth: self.authForRequests(),
- jsonBody: userAuth.credentialsJSONDict)
+ jsonBody: userAuth.credentialsJSONDict as Any?)
_requestManager.performUserAuthRequest(userAuth, request: request) { [weak self] (auth,user,error) in
if setAsCurrentUser {
self?.currentUser = user
}
- completion?(auth: auth, user: user, error: error)
+ completion?(auth, user, error)
}
}
@@ -345,21 +345,21 @@
- parameter new: The new password.
- parameter completion: The optional completion block.
*/
- public func resetPassword(user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
+ public func resetPassword(_ user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
guard let usernameOrEmail = user.usernameOrEmail
else {
- completion?(error: UsergridResponseError(errorName: "Error resetting password.", errorDescription: "The UsergridUser object must contain a valid username or email to reset the password."), didSucceed: false)
+ completion?(UsergridResponseError(errorName: "Error resetting password.", errorDescription: "The UsergridUser object must contain a valid username or email to reset the password."), false)
return
}
- let request = UsergridRequest(method: .Put,
+ let request = UsergridRequest(method: .put,
baseUrl: self.clientAppURL,
paths: ["users",usernameOrEmail,"password"],
auth: self.authForRequests(),
jsonBody:["oldpassword":old,"newpassword":new])
_requestManager.performRequest(request, completion: { (response) -> Void in
- completion?(error: response.error, didSucceed: response.statusCode == 200)
+ completion?(response.error, response.statusCode == 200)
})
}
@@ -368,11 +368,11 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public func logoutCurrentUser(completion:UsergridResponseCompletion? = nil) {
+ public func logoutCurrentUser(_ completion:UsergridResponseCompletion? = nil) {
guard let uuidOrUsername = self.currentUser?.uuidOrUsername,
let token = self.currentUser?.auth?.accessToken
else {
- completion?(response:UsergridResponse(client: self, errorName: "Logout Failed.", errorDescription: "UsergridClient's currentUser is not valid."))
+ completion?(UsergridResponse(client: self, errorName: "Logout Failed.", errorDescription: "UsergridClient's currentUser is not valid."))
return
}
@@ -384,7 +384,7 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public func logoutUserAllTokens(uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) {
+ public func logoutUserAllTokens(_ uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) {
self.logoutUser(uuidOrUsername, token: nil, completion: completion)
}
@@ -395,7 +395,7 @@
- parameter completion: The completion block that will be called after logout has completed.
*/
- public func logoutUser(uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) {
+ public func logoutUser(_ uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) {
var paths = ["users",uuidOrUsername]
var queryParams: [String: String]?
if let accessToken = token {
@@ -404,7 +404,7 @@
} else {
paths.append("revoketokens")
}
- let request = UsergridRequest(method: .Put,
+ let request = UsergridRequest(method: .put,
baseUrl: self.clientAppURL,
paths: paths,
auth: self.authForRequests(),
@@ -417,7 +417,7 @@
self.currentUser = nil
}
}
- completion?(response: response)
+ completion?(response)
}
}
@@ -431,7 +431,7 @@
- parameter request: The `UsergridRequest` object to send.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func sendRequest(request:UsergridRequest, completion:UsergridResponseCompletion? = nil) {
+ public func sendRequest(_ request:UsergridRequest, completion:UsergridResponseCompletion? = nil) {
_requestManager.performRequest(request, completion: completion)
}
@@ -444,8 +444,8 @@
- parameter uuidOrName: The UUID or name of the `UsergridEntity`.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func GET(type: String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type,uuidOrName], auth:self.authForRequests())
+ public func GET(_ type: String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .get, baseUrl: self.clientAppURL, paths: [type,uuidOrName], auth:self.authForRequests())
self.sendRequest(request, completion: completion)
}
@@ -455,8 +455,8 @@
- parameter type: The `UsergridEntity` type.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func GET(type: String, completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type], query: nil, auth: self.authForRequests())
+ public func GET(_ type: String, completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .get, baseUrl: self.clientAppURL, paths: [type], query: nil, auth: self.authForRequests())
self.sendRequest(request, completion: completion)
}
@@ -466,14 +466,14 @@
- parameter query: The query to use when gathering `UsergridEntity` objects.
- parameter queryCompletion: The optional completion block that will be called once the request has completed.
*/
- public func GET(query: UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
+ public func GET(_ query: UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
guard let type = query.collectionName
else {
- queryCompletion?(response: UsergridResponse(client:self, errorName: "Query collection name missing.", errorDescription: "Query collection name is missing."))
+ queryCompletion?(UsergridResponse(client:self, errorName: "Query collection name missing.", errorDescription: "Query collection name is missing."))
return
}
- let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type], query: query, auth: self.authForRequests())
+ let request = UsergridRequest(method: .get, baseUrl: self.clientAppURL, paths: [type], query: query, auth: self.authForRequests())
self.sendRequest(request, completion: queryCompletion)
}
@@ -487,13 +487,13 @@
- parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func PUT(type: String, uuidOrName: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Put,
+ public func PUT(_ type: String, uuidOrName: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .put,
baseUrl: self.clientAppURL,
paths: [type,uuidOrName],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBody)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBody as Any?)
self.sendRequest(request, completion: completion)
}
@@ -503,7 +503,7 @@
- parameter entity: The `UsergridEntity` to update.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func PUT(entity: UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func PUT(_ entity: UsergridEntity, completion: UsergridResponseCompletion? = nil) {
PUT(entity.type, jsonBody: entity.jsonObjectValue, completion: completion)
}
@@ -516,18 +516,18 @@
- parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func PUT(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
- guard let uuidOrName = (jsonBody[UsergridEntityProperties.UUID.stringValue] ?? jsonBody[UsergridEntityProperties.Name.stringValue]) as? String
+ public func PUT(_ type: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
+ guard let uuidOrName = (jsonBody[UsergridEntityProperties.uuid.stringValue] ?? jsonBody[UsergridEntityProperties.name.stringValue]) as? String
else {
- completion?(response: UsergridResponse(client:self, errorName: "jsonBody not valid.", errorDescription: "The `jsonBody` must contain a valid value for either `uuid` or `name`."))
+ completion?(UsergridResponse(client:self, errorName: "jsonBody not valid.", errorDescription: "The `jsonBody` must contain a valid value for either `uuid` or `name`."))
return
}
- let request = UsergridRequest(method: .Put,
+ let request = UsergridRequest(method: .put,
baseUrl: self.clientAppURL,
paths: [type,uuidOrName],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBody)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBody as Any?)
self.sendRequest(request, completion: completion)
}
@@ -540,19 +540,19 @@
- parameter jsonBody: The valid JSON body dictionary to update with.
- parameter queryCompletion: The optional completion block that will be called once the request has completed.
*/
- public func PUT(query: UsergridQuery, jsonBody:[String:AnyObject], queryCompletion: UsergridResponseCompletion? = nil) {
+ public func PUT(_ query: UsergridQuery, jsonBody:[String:Any], queryCompletion: UsergridResponseCompletion? = nil) {
guard let type = query.collectionName
else {
- queryCompletion?(response: UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name."))
+ queryCompletion?(UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name."))
return
}
- let request = UsergridRequest(method: .Put,
+ let request = UsergridRequest(method: .put,
baseUrl: self.clientAppURL,
paths: [type],
query: query,
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBody)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBody as Any?)
self.sendRequest(request, completion: queryCompletion)
}
@@ -563,13 +563,13 @@
- parameter entity: The `UsergridEntity` to create.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func POST(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Post,
+ public func POST(_ entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: [entity.type],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: entity.jsonObjectValue)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: entity.jsonObjectValue as Any?)
self.sendRequest(request, completion: completion)
}
@@ -581,10 +581,10 @@
- parameter entities: The `UsergridEntity` objects to create.
- parameter entitiesCompletion: The optional completion block that will be called once the request has completed.
*/
- public func POST(entities:[UsergridEntity], entitiesCompletion: UsergridResponseCompletion? = nil) {
+ public func POST(_ entities:[UsergridEntity], entitiesCompletion: UsergridResponseCompletion? = nil) {
guard let type = entities.first?.type
else {
- entitiesCompletion?(response: UsergridResponse(client:self, errorName: "No type found.", errorDescription: "The first entity in the array had no type found."))
+ entitiesCompletion?(UsergridResponse(client:self, errorName: "No type found.", errorDescription: "The first entity in the array had no type found."))
return
}
POST(type, jsonBodies: entities.map { return ($0).jsonObjectValue }, completion: entitiesCompletion)
@@ -597,13 +597,13 @@
- parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func POST(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Post,
+ public func POST(_ type: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: [type],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBody)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBody as Any?)
self.sendRequest(request, completion: completion)
}
@@ -614,13 +614,13 @@
- parameter jsonBody: The valid JSON body dictionaries to use when creating the `UsergridEntity` objects.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func POST(type: String, jsonBodies:[[String:AnyObject]], completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Post,
+ public func POST(_ type: String, jsonBodies:[[String:Any]], completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: [type],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBodies)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBodies as Any?)
self.sendRequest(request, completion: completion)
}
@@ -632,15 +632,15 @@
- parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func POST(type: String, name: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) {
+ public func POST(_ type: String, name: String, jsonBody:[String:Any], completion: UsergridResponseCompletion? = nil) {
var jsonBodyWithName = jsonBody
- jsonBodyWithName[UsergridEntityProperties.Name.stringValue] = name
- let request = UsergridRequest(method: .Post,
+ jsonBodyWithName[UsergridEntityProperties.name.stringValue] = name
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: [type],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER,
- jsonBody: jsonBodyWithName)
+ headers: UsergridRequest.jsonHeaderContentType(),
+ jsonBody: jsonBodyWithName as Any?)
self.sendRequest(request, completion: completion)
}
@@ -655,10 +655,10 @@
- parameter entity: The `UsergridEntity` to delete.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func DELETE(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func DELETE(_ entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
guard let uuidOrName = entity.uuidOrName
else {
- completion?(response: UsergridResponse(client:self, errorName: "No UUID or name found.", errorDescription: "The entity object must have a `uuid` or `name` assigned."))
+ completion?(UsergridResponse(client:self, errorName: "No UUID or name found.", errorDescription: "The entity object must have a `uuid` or `name` assigned."))
return
}
@@ -673,19 +673,19 @@
- parameter query: The query to use when filtering what entities to delete.
- parameter queryCompletion: The optional completion block that will be called once the request has completed.
*/
- public func DELETE(query:UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
+ public func DELETE(_ query:UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) {
guard let type = query.collectionName
else {
- queryCompletion?(response: UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name."))
+ queryCompletion?(UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name."))
return
}
- let request = UsergridRequest(method: .Delete,
+ let request = UsergridRequest(method: .delete,
baseUrl: self.clientAppURL,
paths: [type],
query: query,
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER)
+ headers: UsergridRequest.jsonHeaderContentType())
self.sendRequest(request, completion: queryCompletion)
}
@@ -696,12 +696,12 @@
- parameter uuidOrName: The UUID or name of the `UsergridEntity`.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func DELETE(type:String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Delete,
+ public func DELETE(_ type:String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .delete,
baseUrl: self.clientAppURL,
paths: [type,uuidOrName],
auth: self.authForRequests(),
- headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER)
+ headers: UsergridRequest.jsonHeaderContentType())
self.sendRequest(request, completion: completion)
}
@@ -715,11 +715,11 @@
- parameter to: The `UsergridEntity` which is connected.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func connect(entity:UsergridEntity, relationship:String, to:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func connect(_ entity:UsergridEntity, relationship:String, to:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
guard let entityID = entity.uuidOrName,
let toID = to.uuidOrName
else {
- completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Connection Attempt.", errorDescription: "One or both entities that are attempting to be connected do not contain a valid UUID or Name property."))
+ completion?(UsergridResponse(client: self, errorName: "Invalid Entity Connection Attempt.", errorDescription: "One or both entities that are attempting to be connected do not contain a valid UUID or Name property."))
return
}
self.connect(entity.type, entityID: entityID, relationship: relationship, toType: to.type, toID: toID, completion: completion)
@@ -735,7 +735,7 @@
- parameter toName: The name of the entity you are connecting to.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func connect(entityType:String, entityID:String, relationship:String, toType:String, toName: String, completion: UsergridResponseCompletion? = nil) {
+ public func connect(_ entityType:String, entityID:String, relationship:String, toType:String, toName: String, completion: UsergridResponseCompletion? = nil) {
self.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toID: toName, completion: completion)
}
@@ -749,14 +749,14 @@
- parameter toID: The UUID of the entity you are connecting to.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func connect(entityType:String, entityID:String, relationship:String, toType:String?, toID: String, completion: UsergridResponseCompletion? = nil) {
+ public func connect(_ entityType:String, entityID:String, relationship:String, toType:String?, toID: String, completion: UsergridResponseCompletion? = nil) {
var paths = [entityType,entityID,relationship]
if let toType = toType {
paths.append(toType)
}
paths.append(toID)
- let request = UsergridRequest(method: .Post,
+ let request = UsergridRequest(method: .post,
baseUrl: self.clientAppURL,
paths: paths,
auth: self.authForRequests())
@@ -771,11 +771,11 @@
- parameter from: The `UsergridEntity` which is connected.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func disconnect(entity:UsergridEntity, relationship:String, from:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func disconnect(_ entity:UsergridEntity, relationship:String, from:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
guard let entityID = entity.uuidOrName,
let fromID = from.uuidOrName
else {
- completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Disconnect Attempt.", errorDescription: "The connecting and connected entities must have a `uuid` or `name` assigned."))
+ completion?(UsergridResponse(client: self, errorName: "Invalid Entity Disconnect Attempt.", errorDescription: "The connecting and connected entities must have a `uuid` or `name` assigned."))
return
}
@@ -792,7 +792,7 @@
- parameter fromName: The name of the entity you are disconnecting from.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func disconnect(entityType:String, entityID:String, relationship:String, fromType:String, fromName: String, completion: UsergridResponseCompletion? = nil) {
+ public func disconnect(_ entityType:String, entityID:String, relationship:String, fromType:String, fromName: String, completion: UsergridResponseCompletion? = nil) {
self.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromID: fromName, completion: completion)
}
@@ -806,7 +806,7 @@
- parameter toID: The UUID of the entity you are disconnecting from.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func disconnect(entityType:String, entityID:String, relationship:String, fromType:String?, fromID: String, completion: UsergridResponseCompletion? = nil) {
+ public func disconnect(_ entityType:String, entityID:String, relationship:String, fromType:String?, fromID: String, completion: UsergridResponseCompletion? = nil) {
var paths = [entityType,entityID,relationship]
if let fromType = fromType {
@@ -814,7 +814,7 @@
}
paths.append(fromID)
- let request = UsergridRequest(method: .Delete,
+ let request = UsergridRequest(method: .delete,
baseUrl: self.clientAppURL,
paths: paths,
auth: self.authForRequests())
@@ -829,10 +829,10 @@
- parameter query: The optional query.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func getConnections(direction:UsergridDirection, entity:UsergridEntity, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func getConnections(_ direction:UsergridDirection, entity:UsergridEntity, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
guard let uuidOrName = entity.uuidOrName
else {
- completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Get Connections Attempt.", errorDescription: "The entity must have a `uuid` or `name` assigned."))
+ completion?(UsergridResponse(client: self, errorName: "Invalid Entity Get Connections Attempt.", errorDescription: "The entity must have a `uuid` or `name` assigned."))
return
}
self.getConnections(direction, type: entity.type, uuidOrName: uuidOrName, relationship: relationship, query:query, completion: completion)
@@ -848,8 +848,8 @@
- parameter query: The optional query.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func getConnections(direction:UsergridDirection, type:String, uuidOrName:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Get,
+ public func getConnections(_ direction:UsergridDirection, type:String, uuidOrName:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .get,
baseUrl: self.clientAppURL,
paths: [type, uuidOrName, direction.connectionValue, relationship],
query: query,
@@ -866,8 +866,8 @@
- parameter query: The optional query.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func getConnections(direction:UsergridDirection, uuid:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
- let request = UsergridRequest(method: .Get,
+ public func getConnections(_ direction:UsergridDirection, uuid:String, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ let request = UsergridRequest(method: .get,
baseUrl: self.clientAppURL,
paths: [uuid, direction.connectionValue, relationship],
query: query,
@@ -885,7 +885,7 @@
- parameter progress: The optional progress block that will be called to update the progress of the upload.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func uploadAsset(entity:UsergridEntity, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
+ public func uploadAsset(_ entity:UsergridEntity, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
let assetRequest = UsergridAssetUploadRequest(baseUrl: self.clientAppURL,
paths: [entity.type,entity.uuidOrName!],
auth: self.authForRequests(),
@@ -898,7 +898,7 @@
entity.fileMetaData = responseEntityFileMetaData
}
}
- completion?(asset: asset, response: response)
+ completion?(asset, response)
}
}
@@ -910,14 +910,14 @@
- parameter progress: The optional progress block that will be called to update the progress of the download.
- parameter completion: The optional completion block that will be called once the request has completed.
*/
- public func downloadAsset(entity:UsergridEntity, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
+ public func downloadAsset(_ entity:UsergridEntity, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
guard entity.hasAsset
else {
- completion?(asset: nil, error: UsergridResponseError(errorName: "Download asset failed.", errorDescription: "Entity does not have an asset attached."))
+ completion?(nil, UsergridResponseError(errorName: "Download asset failed.", errorDescription: "Entity does not have an asset attached."))
return
}
- let downloadAssetRequest = UsergridRequest(method: .Get,
+ let downloadAssetRequest = UsergridRequest(method: .get,
baseUrl: self.clientAppURL,
paths: [entity.type,entity.uuidOrName!],
auth: self.authForRequests(),
@@ -925,7 +925,7 @@
_requestManager.performAssetDownload(contentType, usergridRequest: downloadAssetRequest, progress: progress, completion: { (asset, error) -> Void in
entity.asset = asset
- completion?(asset: asset, error: error)
+ completion?(asset, error)
})
}
}
diff --git a/Source/UsergridClientConfig.swift b/Source/UsergridClientConfig.swift
index 64ebd4f..9d1e057 100644
--- a/Source/UsergridClientConfig.swift
+++ b/Source/UsergridClientConfig.swift
@@ -45,7 +45,7 @@
public var baseUrl: String = UsergridClient.DEFAULT_BASE_URL
/// The `UsergridAuthMode` value used to determine what type of token will be sent, if any.
- public var authMode: UsergridAuthMode = .User
+ public var authMode: UsergridAuthMode = .user
/// Whether or not the `UsergridClient` current user will be saved and restored from the keychain.
public var persistCurrentUserInKeychain: Bool = true
@@ -115,9 +115,9 @@
- returns: A decoded `UsergridUser` object.
*/
public required init?(coder aDecoder: NSCoder) {
- guard let appId = aDecoder.decodeObjectForKey("appId") as? String,
- let orgId = aDecoder.decodeObjectForKey("orgId") as? String,
- let baseUrl = aDecoder.decodeObjectForKey("baseUrl") as? String
+ guard let appId = aDecoder.decodeObject(forKey: "appId") as? String,
+ let orgId = aDecoder.decodeObject(forKey: "orgId") as? String,
+ let baseUrl = aDecoder.decodeObject(forKey: "baseUrl") as? String
else {
self.appId = ""
self.orgId = ""
@@ -127,9 +127,9 @@
self.appId = appId
self.orgId = orgId
self.baseUrl = baseUrl
- self.appAuth = aDecoder.decodeObjectForKey("appAuth") as? UsergridAppAuth
- self.persistCurrentUserInKeychain = aDecoder.decodeBoolForKey("persistCurrentUserInKeychain") ?? true
- self.authMode = UsergridAuthMode(rawValue:aDecoder.decodeIntegerForKey("authMode")) ?? .None
+ self.appAuth = aDecoder.decodeObject(forKey: "appAuth") as? UsergridAppAuth
+ self.persistCurrentUserInKeychain = aDecoder.decodeBool(forKey: "persistCurrentUserInKeychain")
+ self.authMode = (UsergridAuthMode(rawValue:aDecoder.decodeInteger(forKey: "authMode")) ?? .none)!
super.init()
}
@@ -138,12 +138,12 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.appId, forKey: "appId")
- aCoder.encodeObject(self.orgId, forKey: "orgId")
- aCoder.encodeObject(self.baseUrl, forKey: "baseUrl")
- aCoder.encodeObject(self.appAuth, forKey: "appAuth")
- aCoder.encodeBool(self.persistCurrentUserInKeychain, forKey: "persistCurrentUserInKeychain")
- aCoder.encodeInteger(self.authMode.rawValue, forKey: "authMode")
+ public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.appId, forKey: "appId")
+ aCoder.encode(self.orgId, forKey: "orgId")
+ aCoder.encode(self.baseUrl, forKey: "baseUrl")
+ aCoder.encode(self.appAuth, forKey: "appAuth")
+ aCoder.encode(self.persistCurrentUserInKeychain, forKey: "persistCurrentUserInKeychain")
+ aCoder.encode(self.authMode.rawValue, forKey: "authMode")
}
}
diff --git a/Source/UsergridDevice.swift b/Source/UsergridDevice.swift
index 004c42c..5eb3850 100644
--- a/Source/UsergridDevice.swift
+++ b/Source/UsergridDevice.swift
@@ -47,13 +47,13 @@
// MARK: - Instance Properties -
/// Property helper method for the `UsergridDevice` objects device model.
- public var model: String { return super[UsergridDeviceProperties.Model.stringValue] as! String }
+ public var model: String { return super[UsergridDeviceProperties.model.stringValue] as! String }
/// Property helper method for the `UsergridDevice` objects device platform.
- public var platform: String { return super[UsergridDeviceProperties.Platform.stringValue] as! String }
+ public var platform: String { return super[UsergridDeviceProperties.platform.stringValue] as! String }
/// Property helper method for the `UsergridDevice` objects device operating system version.
- public var osVersion: String { return super[UsergridDeviceProperties.OSVersion.stringValue] as! String }
+ public var osVersion: String { return super[UsergridDeviceProperties.osVersion.stringValue] as! String }
/// The shared instance of `UsergridDevice`.
public static var sharedDevice: UsergridDevice = UsergridDevice.getOrCreateSharedDeviceFromKeychain()
@@ -80,7 +80,7 @@
- returns: A new `UsergridDevice` object.
*/
- required public init(type:String, name:String? = nil, propertyDict:[String:AnyObject]? = nil) {
+ required public init(type:String, name:String? = nil, propertyDict:[String:Any]? = nil) {
super.init(type: type, name: name, propertyDict: propertyDict)
}
@@ -102,8 +102,8 @@
- parameter aCoder: The encoder.
*/
- public override func encodeWithCoder(aCoder: NSCoder) {
- super.encodeWithCoder(aCoder)
+ public override func encode(with aCoder: NSCoder) {
+ super.encode(with: aCoder)
}
/**
@@ -113,7 +113,7 @@
- parameter completion: An optional completion block that, if successful, will contain the updated/saved `UsergridEntity` object.
*/
- public override func save(completion: UsergridResponseCompletion? = nil) {
+ public override func save(_ completion: UsergridResponseCompletion? = nil) {
self.save(Usergrid.sharedInstance, completion: completion)
}
@@ -126,14 +126,14 @@
- parameter client: The client to use when saving.
- parameter completion: An optional completion block that, if successful, will contain the updated/saved `UsergridEntity` object.
*/
- public override func save(client: UsergridClient, completion: UsergridResponseCompletion? = nil) {
+ public override func save(_ client: UsergridClient, completion: UsergridResponseCompletion? = nil) {
super.save(client) { (response) in
if( response.ok ) {
if( self == UsergridDevice.sharedDevice || self.isEqualToEntity(UsergridDevice.sharedDevice)) {
UsergridDevice.saveSharedDeviceToKeychain()
}
}
- completion?(response:response)
+ completion?(response)
}
}
@@ -154,7 +154,7 @@
let uuid = usergridDevice["uuid"]
```
*/
- override public subscript(propertyName: String) -> AnyObject? {
+ override public subscript(propertyName: String) -> Any? {
get {
return super[propertyName]
}
@@ -172,22 +172,22 @@
- returns: A property dictionary with the common properties set.
*/
- public static func commonDevicePropertyDict() -> [String:AnyObject] {
- var commonDevicePropertyDict: [String:AnyObject] = [:]
- commonDevicePropertyDict[UsergridEntityProperties.EntityType.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE
+ public static func commonDevicePropertyDict() -> [String:Any] {
+ var commonDevicePropertyDict: [String:Any] = [:]
+ commonDevicePropertyDict[UsergridEntityProperties.type.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE
#if os(watchOS)
- commonDevicePropertyDict[UsergridDeviceProperties.Model.stringValue] = WKInterfaceDevice.currentDevice().model
- commonDevicePropertyDict[UsergridDeviceProperties.Platform.stringValue] = WKInterfaceDevice.currentDevice().systemName
- commonDevicePropertyDict[UsergridDeviceProperties.OSVersion.stringValue] = WKInterfaceDevice.currentDevice().systemVersion
+ commonDevicePropertyDict[UsergridDeviceProperties.model.stringValue] = WKInterfaceDevice.current().model
+ commonDevicePropertyDict[UsergridDeviceProperties.platform.stringValue] = WKInterfaceDevice.current().systemName
+ commonDevicePropertyDict[UsergridDeviceProperties.osVersion.stringValue] = WKInterfaceDevice.current().systemVersion
#elseif os(iOS) || os(tvOS)
- commonDevicePropertyDict[UsergridDeviceProperties.Model.stringValue] = UIDevice.currentDevice().model
- commonDevicePropertyDict[UsergridDeviceProperties.Platform.stringValue] = UIDevice.currentDevice().systemName
- commonDevicePropertyDict[UsergridDeviceProperties.OSVersion.stringValue] = UIDevice.currentDevice().systemVersion
+ commonDevicePropertyDict[UsergridDeviceProperties.model.stringValue] = UIDevice.current.model
+ commonDevicePropertyDict[UsergridDeviceProperties.platform.stringValue] = UIDevice.current.systemName
+ commonDevicePropertyDict[UsergridDeviceProperties.osVersion.stringValue] = UIDevice.current.systemVersion
#elseif os(OSX)
- commonDevicePropertyDict[UsergridDeviceProperties.Model.stringValue] = "Mac"
- commonDevicePropertyDict[UsergridDeviceProperties.Platform.stringValue] = "OSX"
- commonDevicePropertyDict[UsergridDeviceProperties.OSVersion.stringValue] = NSProcessInfo.processInfo().operatingSystemVersionString
+ commonDevicePropertyDict[UsergridDeviceProperties.model.stringValue] = "Mac"
+ commonDevicePropertyDict[UsergridDeviceProperties.platform.stringValue] = "OSX"
+ commonDevicePropertyDict[UsergridDeviceProperties.osVersion.stringValue] = ProcessInfo.processInfo.operatingSystemVersionString
#endif
return commonDevicePropertyDict
@@ -205,8 +205,8 @@
- parameter pushToken: The push token from Apple.
- parameter notifierID: The notifier ID.
*/
- internal func applyPushToken(pushToken: NSData, notifierID: String) {
- self[notifierID + USERGRID_NOTIFIER_ID_SUFFIX] = pushToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "")
+ internal func applyPushToken(_ pushToken: Data, notifierID: String) {
+ self[notifierID + USERGRID_NOTIFIER_ID_SUFFIX] = pushToken.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
}
}
diff --git a/Source/UsergridEntity.swift b/Source/UsergridEntity.swift
index dd169ed..7babee4 100644
--- a/Source/UsergridEntity.swift
+++ b/Source/UsergridEntity.swift
@@ -32,16 +32,16 @@
`UsergridEntity` maintains a set of accessor properties for standard Usergrid schema properties (e.g. name, uuid), and supports helper methods for accessing any custom properties that might exist.
*/
-public class UsergridEntity: NSObject, NSCoding {
+open class UsergridEntity: NSObject, NSCoding {
static private var subclassMappings: [String:UsergridEntity.Type] = [UsergridUser.USER_ENTITY_TYPE:UsergridUser.self,UsergridDevice.DEVICE_ENTITY_TYPE:UsergridDevice.self]
// MARK: - Instance Properties -
/// The property dictionary that stores the properties values of the `UsergridEntity` object.
- private var properties: [String : AnyObject] {
+ private var properties: [String : Any] {
didSet {
- if let fileMetaData = properties.removeValueForKey(UsergridFileMetaData.FILE_METADATA) as? [String:AnyObject] {
+ if let fileMetaData = properties.removeValue(forKey: UsergridFileMetaData.FILE_METADATA) as? [String:Any] {
self.fileMetaData = UsergridFileMetaData(fileMetaDataJSON: fileMetaData)
} else {
self.fileMetaData = nil
@@ -55,25 +55,25 @@
/// The `UsergridFileMetaData` of this `UsergridEntity`.
internal(set) public var fileMetaData : UsergridFileMetaData?
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.EntityType`.
- public var type: String { return self.getEntitySpecificProperty(.EntityType) as! String }
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.type`.
+ public var type: String { return self.getEntitySpecificProperty(.type) as! String }
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.UUID`.
- public var uuid: String? { return self.getEntitySpecificProperty(.UUID) as? String }
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.uuid`.
+ public var uuid: String? { return self.getEntitySpecificProperty(.uuid) as? String }
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.Name`.
- public var name: String? { return self.getEntitySpecificProperty(.Name) as? String }
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.name`.
+ public var name: String? { return self.getEntitySpecificProperty(.name) as? String }
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.Created`.
- public var created: NSDate? { return self.getEntitySpecificProperty(.Created) as? NSDate }
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.created`.
+ public var created: Date? { return self.getEntitySpecificProperty(.created) as? Date }
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.Modified`.
- public var modified: NSDate? { return self.getEntitySpecificProperty(.Modified) as? NSDate }
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.modified`.
+ public var modified: Date? { return self.getEntitySpecificProperty(.modified) as? Date }
- /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.Location`.
+ /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.location`.
public var location: CLLocation? {
- get { return self.getEntitySpecificProperty(.Location) as? CLLocation }
- set(newLocation) { self[UsergridEntityProperties.Location.stringValue] = newLocation }
+ get { return self.getEntitySpecificProperty(.location) as? CLLocation }
+ set(newLocation) { self[UsergridEntityProperties.location.stringValue] = newLocation }
}
/// Property helper method to get the UUID or name of the `UsergridEntity`.
@@ -83,21 +83,21 @@
public var isUser: Bool { return self is UsergridUser || self.type == UsergridUser.USER_ENTITY_TYPE }
/// Tells you if there is an asset associated with this entity.
- public var hasAsset: Bool { return self.asset != nil || self.fileMetaData?.contentLength > 0 }
+ public var hasAsset: Bool { return self.asset != nil || (self.fileMetaData?.contentLength ?? 0) > 0 }
/// The JSON object value.
- public var jsonObjectValue : [String:AnyObject] { return self.properties }
+ public var jsonObjectValue : [String:Any] { return self.properties }
/// The string value.
- public var stringValue : String { return NSString(data: try! NSJSONSerialization.dataWithJSONObject(self.jsonObjectValue, options: .PrettyPrinted), encoding: NSUTF8StringEncoding) as! String }
+ public var stringValue : String { return NSString(data: try! JSONSerialization.data(withJSONObject: self.jsonObjectValue, options: .prettyPrinted), encoding: String.Encoding.utf8.rawValue) as! String }
/// The description.
- public override var description : String {
+ open override var description : String {
return "Properties of Entity: \(stringValue)."
}
/// The debug description.
- public override var debugDescription : String {
+ open override var debugDescription : String {
return "Properties of Entity: \(stringValue)."
}
@@ -112,28 +112,28 @@
- returns: A new `UsergridEntity` object.
*/
- required public init(type:String, name:String? = nil, propertyDict:[String:AnyObject]? = nil) {
+ required public init(type:String, name:String? = nil, propertyDict:[String:Any]? = nil) {
self.properties = propertyDict ?? [:]
super.init()
if self is UsergridUser {
- self.properties[UsergridEntityProperties.EntityType.stringValue] = UsergridUser.USER_ENTITY_TYPE
+ self.properties[UsergridEntityProperties.type.stringValue] = UsergridUser.USER_ENTITY_TYPE
} else if self is UsergridDevice {
- self.properties[UsergridEntityProperties.EntityType.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE
+ self.properties[UsergridEntityProperties.type.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE
} else {
- self.properties[UsergridEntityProperties.EntityType.stringValue] = type
+ self.properties[UsergridEntityProperties.type.stringValue] = type
}
if let entityName = name {
- self.properties[UsergridEntityProperties.Name.stringValue] = entityName
+ self.properties[UsergridEntityProperties.name.stringValue] = entityName
}
- if let fileMetaData = self.properties.removeValueForKey(UsergridFileMetaData.FILE_METADATA) as? [String:AnyObject] {
+ if let fileMetaData = self.properties.removeValue(forKey: UsergridFileMetaData.FILE_METADATA) as? [String:Any] {
self.fileMetaData = UsergridFileMetaData(fileMetaDataJSON: fileMetaData)
}
}
- internal func copyInternalsFromEntity(entity:UsergridEntity) {
+ internal func copyInternalsFromEntity(_ entity:UsergridEntity) {
self.properties = entity.properties
}
@@ -143,7 +143,7 @@
- parameter type: The type of the `Usergrid` object.
- parameter toSubclass: The subclass `UsergridEntity.Type` to map it to.
*/
- public static func mapCustomType(type:String,toSubclass:UsergridEntity.Type) {
+ public static func mapCustomType(_ type:String,toSubclass:UsergridEntity.Type) {
UsergridEntity.subclassMappings[type] = toSubclass
}
@@ -154,8 +154,8 @@
- returns: A `UsergridEntity` object provided that the `type` key within the dictionay exists. Otherwise nil.
*/
- public class func entity(jsonDict jsonDict: [String:AnyObject]) -> UsergridEntity? {
- guard let type = jsonDict[UsergridEntityProperties.EntityType.stringValue] as? String
+ public class func entity(jsonDict: [String:Any]) -> UsergridEntity? {
+ guard let type = jsonDict[UsergridEntityProperties.type.stringValue] as? String
else {
return nil
}
@@ -171,7 +171,7 @@
- returns: An array of `UsergridEntity`.
*/
- public class func entities(jsonArray entitiesJSONArray: [[String:AnyObject]]) -> [UsergridEntity] {
+ public class func entities(jsonArray entitiesJSONArray: [[String:Any]]) -> [UsergridEntity] {
var entityArray : [UsergridEntity] = []
for entityJSONDict in entitiesJSONArray {
if let entity = UsergridEntity.entity(jsonDict:entityJSONDict) {
@@ -191,15 +191,15 @@
- returns: A decoded `UsergridUser` object.
*/
required public init?(coder aDecoder: NSCoder) {
- guard let properties = aDecoder.decodeObjectForKey("properties") as? [String:AnyObject]
+ guard let properties = aDecoder.decodeObject(forKey: "properties") as? [String:Any]
else {
self.properties = [:]
super.init()
return nil
}
self.properties = properties
- self.fileMetaData = aDecoder.decodeObjectForKey("fileMetaData") as? UsergridFileMetaData
- self.asset = aDecoder.decodeObjectForKey("asset") as? UsergridAsset
+ self.fileMetaData = aDecoder.decodeObject(forKey: "fileMetaData") as? UsergridFileMetaData
+ self.asset = aDecoder.decodeObject(forKey: "asset") as? UsergridAsset
super.init()
}
@@ -208,10 +208,10 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.properties, forKey: "properties")
- aCoder.encodeObject(self.fileMetaData, forKey: "fileMetaData")
- aCoder.encodeObject(self.asset, forKey: "asset")
+ open func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.properties, forKey: "properties")
+ aCoder.encode(self.fileMetaData, forKey: "fileMetaData")
+ aCoder.encode(self.asset, forKey: "asset")
}
// MARK: - Property Manipulation -
@@ -225,13 +225,13 @@
usergridEntity["propertyName"] = propertyValue
```
*/
- public subscript(propertyName: String) -> AnyObject? {
+ public subscript(propertyName: String) -> Any? {
get {
if let entityProperty = UsergridEntityProperties.fromString(propertyName) {
return self.getEntitySpecificProperty(entityProperty)
} else {
let propertyValue = self.properties[propertyName]
- if propertyValue === NSNull() { // Let's just return nil for properties that have been removed instead of NSNull
+ if propertyValue is NSNull { // Let's just return nil for properties that have been removed instead of NSNull
return nil
} else {
return propertyValue
@@ -242,7 +242,7 @@
if let value = propertyValue {
if let entityProperty = UsergridEntityProperties.fromString(propertyName) {
if entityProperty.isMutableForEntity(self) {
- if entityProperty == .Location {
+ if entityProperty == .location {
if let location = value as? CLLocation {
properties[propertyName] = [ENTITY_LATITUDE:location.coordinate.latitude,
ENTITY_LONGITUDE:location.coordinate.longitude]
@@ -250,7 +250,7 @@
properties[propertyName] = [ENTITY_LATITUDE:location.latitude,
ENTITY_LONGITUDE:location.longitude]
} else if let location = value as? [String:Double] {
- if let lat = location[ENTITY_LATITUDE], long = location[ENTITY_LONGITUDE] {
+ if let lat = location[ENTITY_LATITUDE], let long = location[ENTITY_LONGITUDE] {
properties[propertyName] = [ENTITY_LATITUDE:lat,
ENTITY_LONGITUDE:long]
}
@@ -282,7 +282,7 @@
- parameter name: The name of the property.
- parameter value: The value to update to.
*/
- public func putProperty(name:String,value:AnyObject?) {
+ public func putProperty(_ name:String,value:Any?) {
self[name] = value
}
@@ -291,7 +291,7 @@
- parameter properties: The property dictionary containing the properties names and values.
*/
- public func putProperties(properties:[String:AnyObject]) {
+ public func putProperties(_ properties:[String:Any]) {
for (name,value) in properties {
self.putProperty(name, value: value)
}
@@ -302,7 +302,7 @@
- parameter name: The name of the property.
*/
- public func removeProperty(name:String) {
+ public func removeProperty(_ name:String) {
self[name] = nil
}
@@ -311,7 +311,7 @@
- parameter propertyNames: An array of property names.
*/
- public func removeProperties(propertyNames:[String]) {
+ public func removeProperties(_ propertyNames:[String]) {
for name in propertyNames {
self.removeProperty(name)
}
@@ -323,8 +323,8 @@
- parameter name: The name of the property.
- parameter value: The value or an array of values to append.
*/
- public func append(name:String, value:AnyObject) {
- self.insertArray(name, values:value as? [AnyObject] ?? [value], index: Int.max)
+ public func append(_ name:String, value:Any) {
+ self.insertArray(name, values:value as? [Any] ?? [value], index: Int.max)
}
/**
@@ -334,8 +334,8 @@
- parameter index: The index to insert at.
- parameter value: The value or an array of values to insert.
*/
- public func insert(name:String, value:AnyObject, index:Int = 0) {
- self.insertArray(name, values:value as? [AnyObject] ?? [value], index: index)
+ public func insert(_ name:String, value:Any, index:Int = 0) {
+ self.insertArray(name, values:value as? [Any] ?? [value], index: index)
}
/**
@@ -345,14 +345,14 @@
- parameter index: The index to insert at.
- parameter values: The values to insert.
*/
- private func insertArray(name:String,values:[AnyObject], index:Int = 0) {
+ private func insertArray(_ name:String,values:[Any], index:Int = 0) {
if let propertyValue = self[name] {
- if let arrayValue = propertyValue as? [AnyObject] {
+ if let arrayValue = propertyValue as? [Any] {
var arrayOfValues = arrayValue
if index > arrayValue.count {
- arrayOfValues.appendContentsOf(values)
+ arrayOfValues.append(contentsOf: values)
} else {
- arrayOfValues.insertContentsOf(values, at: index)
+ arrayOfValues.insert(contentsOf: values, at: index)
}
self[name] = arrayOfValues
} else {
@@ -372,8 +372,8 @@
- parameter name: The name of the property.
*/
- public func pop(name:String) {
- if let arrayValue = self[name] as? [AnyObject] where arrayValue.count > 0 {
+ public func pop(_ name:String) {
+ if let arrayValue = self[name] as? [Any] , arrayValue.count > 0 {
var arrayOfValues = arrayValue
arrayOfValues.removeLast()
self[name] = arrayOfValues
@@ -385,25 +385,25 @@
- parameter name: The name of the property.
*/
- public func shift(name:String) {
- if let arrayValue = self[name] as? [AnyObject] where arrayValue.count > 0 {
+ public func shift(_ name:String) {
+ if let arrayValue = self[name] as? [Any] , arrayValue.count > 0 {
var arrayOfValues = arrayValue
arrayOfValues.removeFirst()
self[name] = arrayOfValues
}
}
- private func getEntitySpecificProperty(entityProperty: UsergridEntityProperties) -> AnyObject? {
- var propertyValue: AnyObject? = nil
+ private func getEntitySpecificProperty(_ entityProperty: UsergridEntityProperties) -> Any? {
+ var propertyValue: Any? = nil
switch entityProperty {
- case .UUID,.EntityType,.Name :
+ case .uuid,.type,.name :
propertyValue = self.properties[entityProperty.stringValue]
- case .Created,.Modified :
+ case .created,.modified :
if let milliseconds = self.properties[entityProperty.stringValue] as? Int {
- propertyValue = NSDate(milliseconds: milliseconds.description)
+ propertyValue = Date(milliseconds: milliseconds.description)
}
- case .Location :
- if let locationDict = self.properties[entityProperty.stringValue] as? [String:Double], lat = locationDict[ENTITY_LATITUDE], long = locationDict[ENTITY_LONGITUDE] {
+ case .location :
+ if let locationDict = self.properties[entityProperty.stringValue] as? [String:Double], let lat = locationDict[ENTITY_LATITUDE], let long = locationDict[ENTITY_LONGITUDE] {
propertyValue = CLLocation(latitude: lat, longitude: long)
}
}
@@ -417,7 +417,7 @@
- parameter completion: An optional completion block that, if successful, will contain the reloaded `UsergridEntity` object.
*/
- public func reload(completion: UsergridResponseCompletion? = nil) {
+ public func reload(_ completion: UsergridResponseCompletion? = nil) {
self.reload(Usergrid.sharedInstance, completion: completion)
}
@@ -427,10 +427,10 @@
- parameter client: The client to use when reloading.
- parameter completion: An optional completion block that, if successful, will contain the reloaded `UsergridEntity` object.
*/
- public func reload(client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
+ public func reload(_ client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
guard let uuidOrName = self.uuidOrName
else {
- completion?(response: UsergridResponse(client: client, errorName: "Entity cannot be reloaded.", errorDescription: "Entity has neither an UUID or name specified."))
+ completion?(UsergridResponse(client: client, errorName: "Entity cannot be reloaded.", errorDescription: "Entity has neither an UUID or name specified."))
return
}
@@ -438,7 +438,7 @@
if let responseEntity = response.entity {
self.copyInternalsFromEntity(responseEntity)
}
- completion?(response: response)
+ completion?(response)
}
}
@@ -447,7 +447,7 @@
- parameter completion: An optional completion block that, if successful, will contain the updated/saved `UsergridEntity` object.
*/
- public func save(completion: UsergridResponseCompletion? = nil) {
+ public func save(_ completion: UsergridResponseCompletion? = nil) {
self.save(Usergrid.sharedInstance, completion: completion)
}
@@ -457,20 +457,20 @@
- parameter client: The client to use when saving.
- parameter completion: An optional completion block that, if successful, will contain the updated/saved `UsergridEntity` object.
*/
- public func save(client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
+ public func save(_ client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
if let _ = self.uuid { // If UUID exists we PUT otherwise POST
client.PUT(self) { response in
if let responseEntity = response.entity {
self.copyInternalsFromEntity(responseEntity)
}
- completion?(response: response)
+ completion?(response)
}
} else {
client.POST(self) { response in
if let responseEntity = response.entity {
self.copyInternalsFromEntity(responseEntity)
}
- completion?(response: response)
+ completion?(response)
}
}
}
@@ -480,7 +480,7 @@
- parameter completion: An optional completion block.
*/
- public func remove(completion: UsergridResponseCompletion? = nil) {
+ public func remove(_ completion: UsergridResponseCompletion? = nil) {
self.remove(Usergrid.sharedInstance, completion: completion)
}
@@ -490,7 +490,7 @@
- parameter client: The client to use when removing.
- parameter completion: An optional completion block.
*/
- public func remove(client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
+ public func remove(_ client:UsergridClient, completion: UsergridResponseCompletion? = nil) {
client.DELETE(self, completion: completion)
}
@@ -503,7 +503,7 @@
- parameter progress: An optional progress block to keep track of upload progress.
- parameter completion: An optional completion block.
*/
- public func uploadAsset(asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
+ public func uploadAsset(_ asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
self.uploadAsset(Usergrid.sharedInstance, asset: asset, progress: progress, completion: completion)
}
@@ -515,7 +515,7 @@
- parameter progress: An optional progress block to keep track of upload progress.
- parameter completion: An optional completion block.
*/
- public func uploadAsset(client:UsergridClient, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
+ public func uploadAsset(_ client:UsergridClient, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) {
client.uploadAsset(self, asset: asset, progress:progress, completion:completion)
}
@@ -526,7 +526,7 @@
- parameter progress: An optional progress block to keep track of download progress.
- parameter completion: An optional completion block.
*/
- public func downloadAsset(contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
+ public func downloadAsset(_ contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
self.downloadAsset(Usergrid.sharedInstance, contentType: contentType, progress: progress, completion: completion)
}
@@ -538,7 +538,7 @@
- parameter progress: An optional progress block to keep track of download progress.
- parameter completion: An optional completion block.
*/
- public func downloadAsset(client:UsergridClient, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
+ public func downloadAsset(_ client:UsergridClient, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
client.downloadAsset(self, contentType: contentType, progress:progress, completion: completion)
}
@@ -551,7 +551,7 @@
- parameter toEntity: The entity to connect.
- parameter completion: An optional completion block.
*/
- public func connect(relationship:String, toEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func connect(_ relationship:String, toEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
self.connect(Usergrid.sharedInstance, relationship: relationship, toEntity: toEntity, completion: completion)
}
@@ -563,7 +563,7 @@
- parameter toEntity: The entity to connect.
- parameter completion: An optional completion block.
*/
- public func connect(client:UsergridClient, relationship:String, toEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func connect(_ client:UsergridClient, relationship:String, toEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
client.connect(self, relationship: relationship, to: toEntity, completion: completion)
}
@@ -574,7 +574,7 @@
- parameter fromEntity: The entity to disconnect.
- parameter completion: An optional completion block.
*/
- public func disconnect(relationship:String, fromEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func disconnect(_ relationship:String, fromEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
self.disconnect(Usergrid.sharedInstance, relationship: relationship, fromEntity: fromEntity, completion: completion)
}
@@ -586,7 +586,7 @@
- parameter fromEntity: The entity to disconnect.
- parameter completion: An optional completion block.
*/
- public func disconnect(client:UsergridClient, relationship:String, fromEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
+ public func disconnect(_ client:UsergridClient, relationship:String, fromEntity:UsergridEntity, completion: UsergridResponseCompletion? = nil) {
client.disconnect(self, relationship: relationship, from: fromEntity, completion: completion)
}
@@ -598,7 +598,7 @@
- parameter query: The optional query.
- parameter completion: An optional completion block.
*/
- public func getConnections(direction:UsergridDirection, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func getConnections(_ direction:UsergridDirection, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
self.getConnections(Usergrid.sharedInstance, direction: direction, relationship: relationship, query: query, completion: completion)
}
@@ -611,7 +611,7 @@
- parameter query: The optional query.
- parameter completion: An optional completion block.
*/
- public func getConnections(client:UsergridClient, direction:UsergridDirection, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func getConnections(_ client:UsergridClient, direction:UsergridDirection, relationship:String, query:UsergridQuery? = nil, completion:UsergridResponseCompletion? = nil) {
client.getConnections(direction, entity: self, relationship: relationship, query:query, completion: completion)
}
@@ -624,7 +624,7 @@
- returns: If the two `UsergridEntity` objects are equal. i.e. they have the same non nil uuidOrName.
*/
- public func isEqualToEntity(entity: UsergridEntity?) -> Bool {
+ public func isEqualToEntity(_ entity: UsergridEntity?) -> Bool {
guard let selfUUID = self.uuidOrName,
let entityUUID = entity?.uuidOrName
else {
@@ -632,4 +632,4 @@
}
return selfUUID == entityUUID
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridEnums.swift b/Source/UsergridEnums.swift
index fd0b625..2b32aa1 100644
--- a/Source/UsergridEnums.swift
+++ b/Source/UsergridEnums.swift
@@ -36,21 +36,21 @@
/**
If the API call fails, the activity is treated as a failure with an appropriate HTTP status code.
*/
- case None
+ case none
/**
If a non-expired `UsergridUserAuth` exists in `UsergridClient.currentUser`, this token is used to authenticate all API calls.
If the API call fails, the activity is treated as a failure with an appropriate HTTP status code (This behavior is identical to authMode=.None).
*/
- case User
+ case user
/**
If a non-expired `UsergridAppAuth` exists in `UsergridClient.appAuth`, this token is used to authenticate all API calls.
If the API call fails, the activity is treated as a failure with an appropriate HTTP status code (This behavior is identical to authMode=.None).
*/
- case App
+ case app
}
/**
@@ -61,17 +61,17 @@
// MARK: - Values -
/// Corresponds to the property 'type'
- case EntityType
+ case type
/// Corresponds to the property 'uuid'
- case UUID
+ case uuid
/// Corresponds to the property 'name'
- case Name
+ case name
/// Corresponds to the property 'created'
- case Created
+ case created
/// Corresponds to the property 'modified'
- case Modified
+ case modified
/// Corresponds to the property 'location'
- case Location
+ case location
// MARK: - Methods -
@@ -82,14 +82,14 @@
- returns: The corresponding `UsergridEntityProperties` or nil.
*/
- public static func fromString(stringValue: String) -> UsergridEntityProperties? {
- switch stringValue.lowercaseString {
- case ENTITY_TYPE: return .EntityType
- case ENTITY_UUID: return .UUID
- case ENTITY_NAME: return .Name
- case ENTITY_CREATED: return .Created
- case ENTITY_MODIFIED: return .Modified
- case ENTITY_LOCATION: return .Location
+ public static func fromString(_ stringValue: String) -> UsergridEntityProperties? {
+ switch stringValue.lowercased() {
+ case ENTITY_TYPE: return .type
+ case ENTITY_UUID: return .uuid
+ case ENTITY_NAME: return .name
+ case ENTITY_CREATED: return .created
+ case ENTITY_MODIFIED: return .modified
+ case ENTITY_LOCATION: return .location
default: return nil
}
}
@@ -97,12 +97,12 @@
/// Returns the string value.
public var stringValue: String {
switch self {
- case .EntityType: return ENTITY_TYPE
- case .UUID: return ENTITY_UUID
- case .Name: return ENTITY_NAME
- case .Created: return ENTITY_CREATED
- case .Modified: return ENTITY_MODIFIED
- case .Location: return ENTITY_LOCATION
+ case .type: return ENTITY_TYPE
+ case .uuid: return ENTITY_UUID
+ case .name: return ENTITY_NAME
+ case .created: return ENTITY_CREATED
+ case .modified: return ENTITY_MODIFIED
+ case .location: return ENTITY_LOCATION
}
}
@@ -113,11 +113,11 @@
- returns: If the `UsergridEntityProperties` is mutable for the given entity
*/
- public func isMutableForEntity(entity:UsergridEntity) -> Bool {
+ public func isMutableForEntity(_ entity:UsergridEntity) -> Bool {
switch self {
- case .EntityType,.UUID,.Created,.Modified: return false
- case .Location: return true
- case .Name: return entity.isUser
+ case .type,.uuid,.created,.modified: return false
+ case .location: return true
+ case .name: return entity.isUser
}
}
}
@@ -130,11 +130,11 @@
// MARK: - Values -
/// Corresponds to the property 'deviceModel'
- case Model
+ case model
/// Corresponds to the property 'devicePlatform'
- case Platform
+ case platform
/// Corresponds to the property 'deviceOSVersion'
- case OSVersion
+ case osVersion
// MARK: - Methods -
@@ -145,11 +145,11 @@
- returns: The corresponding `UsergridDeviceProperties` or nil.
*/
- public static func fromString(stringValue: String) -> UsergridDeviceProperties? {
- switch stringValue.lowercaseString {
- case DEVICE_MODEL: return .Model
- case DEVICE_PLATFORM: return .Platform
- case DEVICE_OSVERSION: return .OSVersion
+ public static func fromString(_ stringValue: String) -> UsergridDeviceProperties? {
+ switch stringValue.lowercased() {
+ case DEVICE_MODEL: return .model
+ case DEVICE_PLATFORM: return .platform
+ case DEVICE_OSVERSION: return .osVersion
default: return nil
}
}
@@ -157,9 +157,9 @@
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Model: return DEVICE_MODEL
- case .Platform: return DEVICE_PLATFORM
- case .OSVersion: return DEVICE_OSVERSION
+ case .model: return DEVICE_MODEL
+ case .platform: return DEVICE_PLATFORM
+ case .osVersion: return DEVICE_OSVERSION
}
}
}
@@ -172,21 +172,21 @@
// MARK: - Values -
/// Corresponds to the property 'name'
- case Name
+ case name
/// Corresponds to the property 'username'
- case Username
+ case username
/// Corresponds to the property 'password'
- case Password
+ case password
/// Corresponds to the property 'email'
- case Email
+ case email
/// Corresponds to the property 'age'
- case Age
+ case age
/// Corresponds to the property 'activated'
- case Activated
+ case activated
/// Corresponds to the property 'disabled'
- case Disabled
+ case disabled
/// Corresponds to the property 'picture'
- case Picture
+ case picture
// MARK: - Methods -
@@ -197,16 +197,16 @@
- returns: The corresponding `UsergridUserProperties` or nil.
*/
- public static func fromString(stringValue: String) -> UsergridUserProperties? {
- switch stringValue.lowercaseString {
- case ENTITY_NAME: return .Name
- case USER_USERNAME: return .Username
- case USER_PASSWORD: return .Password
- case USER_EMAIL: return .Email
- case USER_AGE: return .Age
- case USER_ACTIVATED: return .Activated
- case USER_DISABLED: return .Disabled
- case USER_PICTURE: return .Picture
+ public static func fromString(_ stringValue: String) -> UsergridUserProperties? {
+ switch stringValue.lowercased() {
+ case ENTITY_NAME: return .name
+ case USER_USERNAME: return .username
+ case USER_PASSWORD: return .password
+ case USER_EMAIL: return .email
+ case USER_AGE: return .age
+ case USER_ACTIVATED: return .activated
+ case USER_DISABLED: return .disabled
+ case USER_PICTURE: return .picture
default: return nil
}
}
@@ -214,14 +214,14 @@
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Name: return ENTITY_NAME
- case .Username: return USER_USERNAME
- case .Password: return USER_PASSWORD
- case .Email: return USER_EMAIL
- case .Age: return USER_AGE
- case .Activated: return USER_ACTIVATED
- case .Disabled: return USER_DISABLED
- case .Picture: return USER_PICTURE
+ case .name: return ENTITY_NAME
+ case .username: return USER_USERNAME
+ case .password: return USER_PASSWORD
+ case .email: return USER_EMAIL
+ case .age: return USER_AGE
+ case .activated: return USER_ACTIVATED
+ case .disabled: return USER_DISABLED
+ case .picture: return USER_PICTURE
}
}
}
@@ -234,15 +234,15 @@
// MARK: - Values -
/// '='
- case Equal
+ case equal
/// '>'
- case GreaterThan
+ case greaterThan
/// '>='
- case GreaterThanEqualTo
+ case greaterThanEqualTo
/// '<'
- case LessThan
+ case lessThan
/// '<='
- case LessThanEqualTo
+ case lessThanEqualTo
// MARK: - Methods -
@@ -253,13 +253,13 @@
- returns: The corresponding `UsergridQueryOperator` or nil.
*/
- public static func fromString(stringValue: String) -> UsergridQueryOperator? {
- switch stringValue.lowercaseString {
- case UsergridQuery.EQUAL: return .Equal
- case UsergridQuery.GREATER_THAN: return .GreaterThan
- case UsergridQuery.GREATER_THAN_EQUAL_TO: return .GreaterThanEqualTo
- case UsergridQuery.LESS_THAN: return .LessThan
- case UsergridQuery.LESS_THAN_EQUAL_TO: return .LessThanEqualTo
+ public static func fromString(_ stringValue: String) -> UsergridQueryOperator? {
+ switch stringValue.lowercased() {
+ case UsergridQuery.EQUAL: return .equal
+ case UsergridQuery.GREATER_THAN: return .greaterThan
+ case UsergridQuery.GREATER_THAN_EQUAL_TO: return .greaterThanEqualTo
+ case UsergridQuery.LESS_THAN: return .lessThan
+ case UsergridQuery.LESS_THAN_EQUAL_TO: return .lessThanEqualTo
default: return nil
}
}
@@ -267,11 +267,11 @@
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Equal: return UsergridQuery.EQUAL
- case .GreaterThan: return UsergridQuery.GREATER_THAN
- case .GreaterThanEqualTo: return UsergridQuery.GREATER_THAN_EQUAL_TO
- case .LessThan: return UsergridQuery.LESS_THAN
- case .LessThanEqualTo: return UsergridQuery.LESS_THAN_EQUAL_TO
+ case .equal: return UsergridQuery.EQUAL
+ case .greaterThan: return UsergridQuery.GREATER_THAN
+ case .greaterThanEqualTo: return UsergridQuery.GREATER_THAN_EQUAL_TO
+ case .lessThan: return UsergridQuery.LESS_THAN
+ case .lessThanEqualTo: return UsergridQuery.LESS_THAN_EQUAL_TO
}
}
}
@@ -284,9 +284,9 @@
// MARK: - Values -
/// Sort order is ascending.
- case Asc
+ case asc
/// Sort order is descending.
- case Desc
+ case desc
// MARK: - Methods -
@@ -297,10 +297,10 @@
- returns: The corresponding `UsergridQuerySortOrder` or nil.
*/
- public static func fromString(stringValue: String) -> UsergridQuerySortOrder? {
- switch stringValue.lowercaseString {
- case UsergridQuery.ASC: return .Asc
- case UsergridQuery.DESC: return .Desc
+ public static func fromString(_ stringValue: String) -> UsergridQuerySortOrder? {
+ switch stringValue.lowercased() {
+ case UsergridQuery.ASC: return .asc
+ case UsergridQuery.DESC: return .desc
default: return nil
}
}
@@ -308,8 +308,8 @@
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Asc: return UsergridQuery.ASC
- case .Desc: return UsergridQuery.DESC
+ case .asc: return UsergridQuery.ASC
+ case .desc: return UsergridQuery.DESC
}
}
}
@@ -322,17 +322,17 @@
// MARK: - Values -
/// Content type: 'image/png'
- case Png
+ case png
/// Content type: 'image/jpeg'
- case Jpeg
+ case jpeg
// MARK: - Methods -
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Png: return ASSET_IMAGE_PNG
- case .Jpeg: return ASSET_IMAGE_JPEG
+ case .png: return ASSET_IMAGE_PNG
+ case .jpeg: return ASSET_IMAGE_JPEG
}
}
}
@@ -345,18 +345,18 @@
// MARK: - Values -
/// To get the entities that have created a connection to an entity. aka `connecting`
- case In
+ case `in`
/// To get the entities an entity has connected to. aka `connections`
- case Out
+ case out
// MARK: - Methods -
/// Returns the connection value.
public var connectionValue: String {
switch self {
- case .In: return CONNECTION_TYPE_IN
- case .Out: return CONNECTION_TYPE_OUT
+ case .in: return CONNECTION_TYPE_IN
+ case .out: return CONNECTION_TYPE_OUT
}
}
}
@@ -367,24 +367,24 @@
@objc public enum UsergridHttpMethod : Int {
/// GET
- case Get
+ case get
/// PUT
- case Put
+ case put
/// POST
- case Post
+ case post
/// DELETE
- case Delete
+ case delete
/// Returns the string value.
public var stringValue: String {
switch self {
- case .Get: return "GET"
- case .Put: return "PUT"
- case .Post: return "POST"
- case .Delete: return "DELETE"
+ case .get: return "GET"
+ case .put: return "PUT"
+ case .post: return "POST"
+ case .delete: return "DELETE"
}
}
}
diff --git a/Source/UsergridExtensions.swift b/Source/UsergridExtensions.swift
index 30ff3a7..4370808 100644
--- a/Source/UsergridExtensions.swift
+++ b/Source/UsergridExtensions.swift
@@ -29,7 +29,7 @@
private let kUsergrid_Milliseconds_Per_Second = 1000
/// Extension methods to help create and manipulate `NSDate` objects returned by Usergrid.
-public extension NSDate {
+public extension Date {
/**
Creates a new `NSDate` object with the given milliseconds.
@@ -37,8 +37,8 @@
- returns: A new `NSDate` object.
*/
- public convenience init(milliseconds: String) {
- self.init(timeIntervalSince1970: (milliseconds as NSString).doubleValue / Double(kUsergrid_Milliseconds_Per_Second) )
+ public init(milliseconds: String) {
+ self.init(timeIntervalSince1970:(milliseconds as NSString).doubleValue / Double(kUsergrid_Milliseconds_Per_Second))
}
/**
Converts the `NSDate` object to milliseconds.
@@ -54,7 +54,7 @@
- returns: The number of milliseconds corresponding to the date as a string.
*/
public func dateAsMillisecondsString() -> String {
- return NSDate.stringFromMilleseconds(self.dateAsMilliseconds())
+ return Date.stringFromMilleseconds(self.dateAsMilliseconds())
}
/**
Converts the number of milliseconds to a string.
@@ -63,8 +63,8 @@
- returns: The milliseconds as a string.
*/
- public static func stringFromMilleseconds(milliseconds:Int) -> String {
- return NSNumber(longLong: Int64(milliseconds)).stringValue
+ public static func stringFromMilleseconds(_ milliseconds:Int) -> String {
+ return NSNumber(value: Int64(milliseconds)).stringValue
}
/**
Converts the `NSDate` object to the corresponding UNIX time stamp as a string.
@@ -72,7 +72,7 @@
- returns: The UNIX time stamp as a string.
*/
public static func unixTimeStampString() -> String {
- return NSDate.stringFromMilleseconds(NSDate.nowAsMilliseconds())
+ return Date.stringFromMilleseconds(Date.nowAsMilliseconds())
}
/**
Converts the `NSDate` object to the corresponding UNIX time stamp.
@@ -80,7 +80,7 @@
- returns: The UNIX time stamp.
*/
public static func unixTimeStamp() -> Int {
- return NSDate.nowAsMilliseconds()
+ return Date.nowAsMilliseconds()
}
/**
Converts the current date to milliseconds.
@@ -89,9 +89,9 @@
*/
public static func nowAsMilliseconds() -> Int {
var tv = timeval()
- let currentMillisecondTime = withUnsafeMutablePointer(&tv, { (t: UnsafeMutablePointer<timeval>) -> Int in
+ let currentMillisecondTime = withUnsafeMutablePointer(to: &tv, { (t: UnsafeMutablePointer<timeval>) -> Int in
gettimeofday(t, nil)
- return (Int(t.memory.tv_sec) * kUsergrid_Milliseconds_Per_Second) + (Int(t.memory.tv_usec) / kUsergrid_Milliseconds_Per_Second)
+ return (Int(t.pointee.tv_sec) * kUsergrid_Milliseconds_Per_Second) + (Int(t.pointee.tv_usec) / kUsergrid_Milliseconds_Per_Second)
})
return currentMillisecondTime
}
@@ -99,12 +99,12 @@
internal extension String {
func isUuid() -> Bool {
- return (NSUUID(UUIDString: self) != nil) ? true : false
+ return (UUID(uuidString: self) != nil) ? true : false
}
}
internal extension Dictionary {
- mutating func update(other:Dictionary) {
+ mutating func update(_ other:Dictionary) {
for (key,value) in other {
self.updateValue(value, forKey:key)
}
diff --git a/Source/UsergridFileMetaData.swift b/Source/UsergridFileMetaData.swift
index 4908430..b150e2e 100644
--- a/Source/UsergridFileMetaData.swift
+++ b/Source/UsergridFileMetaData.swift
@@ -51,7 +51,7 @@
public let lastModifiedTimeStamp: Int
/// The `NSDate` object corresponding to the last modified time stamp.
- public let lastModifiedDate: NSDate?
+ public let lastModifiedDate: Date?
// MARK: - Initialization -
@@ -62,7 +62,7 @@
- returns: A new instance of `UsergridFileMetaData`.
*/
- public init(fileMetaDataJSON:[String:AnyObject]) {
+ public init(fileMetaDataJSON:[String:Any]) {
self.eTag = fileMetaDataJSON["etag"] as? String
self.checkSum = fileMetaDataJSON["checksum"] as? String
self.contentType = fileMetaDataJSON["content-type"] as? String
@@ -70,7 +70,7 @@
self.lastModifiedTimeStamp = fileMetaDataJSON["last-modified"] as? Int ?? 0
if self.lastModifiedTimeStamp > 0 {
- self.lastModifiedDate = NSDate(milliseconds: self.lastModifiedTimeStamp.description)
+ self.lastModifiedDate = Date(milliseconds: self.lastModifiedTimeStamp.description)
} else {
self.lastModifiedDate = nil
}
@@ -86,14 +86,14 @@
- returns: A decoded `UsergridUser` object.
*/
required public init?(coder aDecoder: NSCoder) {
- self.eTag = aDecoder.decodeObjectForKey("etag") as? String
- self.checkSum = aDecoder.decodeObjectForKey("checksum") as? String
- self.contentType = aDecoder.decodeObjectForKey("content-type") as? String
- self.contentLength = aDecoder.decodeIntegerForKey("content-length") ?? 0
- self.lastModifiedTimeStamp = aDecoder.decodeIntegerForKey("last-modified") ?? 0
+ self.eTag = aDecoder.decodeObject(forKey: "etag") as? String
+ self.checkSum = aDecoder.decodeObject(forKey: "checksum") as? String
+ self.contentType = aDecoder.decodeObject(forKey: "content-type") as? String
+ self.contentLength = aDecoder.decodeInteger(forKey: "content-length")
+ self.lastModifiedTimeStamp = aDecoder.decodeInteger(forKey: "last-modified")
if self.lastModifiedTimeStamp > 0 {
- self.lastModifiedDate = NSDate(milliseconds: self.lastModifiedTimeStamp.description)
+ self.lastModifiedDate = Date(milliseconds: self.lastModifiedTimeStamp.description)
} else {
self.lastModifiedDate = nil
}
@@ -104,11 +104,11 @@
- parameter aCoder: The encoder.
*/
- public func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.eTag, forKey: "etag")
- aCoder.encodeObject(self.checkSum, forKey: "checksum")
- aCoder.encodeObject(self.contentType, forKey: "content-type")
- aCoder.encodeInteger(self.contentLength, forKey: "content-length")
- aCoder.encodeInteger(self.lastModifiedTimeStamp, forKey: "last-modified")
+ public func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.eTag, forKey: "etag")
+ aCoder.encode(self.checkSum, forKey: "checksum")
+ aCoder.encode(self.contentType, forKey: "content-type")
+ aCoder.encode(self.contentLength, forKey: "content-length")
+ aCoder.encode(self.lastModifiedTimeStamp, forKey: "last-modified")
}
}
diff --git a/Source/UsergridKeychainHelpers.swift b/Source/UsergridKeychainHelpers.swift
index 4639832..b363a7f 100644
--- a/Source/UsergridKeychainHelpers.swift
+++ b/Source/UsergridKeychainHelpers.swift
@@ -34,8 +34,8 @@
private let USERGRID_DEVICE_KEYCHAIN_SERVICE = "SharedDevice"
private let USERGRID_CURRENT_USER_KEYCHAIN_SERVICE = "CurrentUser"
-private func usergridGenericKeychainItem() -> [String:AnyObject] {
- var keychainItem: [String:AnyObject] = [:]
+private func usergridGenericKeychainItem() -> [String:Any] {
+ var keychainItem: [String:Any] = [:]
keychainItem[kSecClass as String] = kSecClassGenericPassword as String
keychainItem[kSecAttrAccessible as String] = kSecAttrAccessibleAlways as String
keychainItem[kSecAttrAccount as String] = USERGRID_KEYCHAIN_NAME
@@ -44,7 +44,7 @@
internal extension UsergridDevice {
- static func deviceKeychainItem() -> [String:AnyObject] {
+ static func deviceKeychainItem() -> [String:Any] {
var keychainItem = usergridGenericKeychainItem()
keychainItem[kSecAttrService as String] = USERGRID_DEVICE_KEYCHAIN_SERVICE
return keychainItem
@@ -53,9 +53,9 @@
static func createNewDeviceKeychainUUID() -> String {
#if os(watchOS) || os(OSX)
- let usergridUUID = NSUUID().UUIDString
+ let usergridUUID = NSUUID().uuidString
#elseif os(iOS) || os(tvOS)
- let usergridUUID = UIDevice.currentDevice().identifierForVendor?.UUIDString ?? NSUUID().UUIDString
+ let usergridUUID = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
#endif
return usergridUUID
@@ -63,21 +63,21 @@
private static func createNewSharedDevice() -> UsergridDevice {
var deviceEntityDict = UsergridDevice.commonDevicePropertyDict()
- deviceEntityDict[UsergridEntityProperties.UUID.stringValue] = UsergridDevice.createNewDeviceKeychainUUID()
+ deviceEntityDict[UsergridEntityProperties.uuid.stringValue] = UsergridDevice.createNewDeviceKeychainUUID()
let sharedDevice = UsergridDevice(type: UsergridDevice.DEVICE_ENTITY_TYPE, name: nil, propertyDict: deviceEntityDict)
return sharedDevice
}
static func getOrCreateSharedDeviceFromKeychain() -> UsergridDevice {
var queryAttributes = UsergridDevice.deviceKeychainItem()
- queryAttributes[kSecReturnData as String] = kCFBooleanTrue as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanTrue as Bool
+ queryAttributes[kSecReturnData as String] = (kCFBooleanTrue != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanTrue != nil) as Bool
var result: AnyObject?
- let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(queryAttributes, UnsafeMutablePointer($0)) }
+ let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(queryAttributes as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let resultDictionary = result as? NSDictionary {
- if let resultData = resultDictionary[kSecValueData as String] as? NSData {
- if let sharedDevice = NSKeyedUnarchiver.unarchiveObjectWithData(resultData) as? UsergridDevice {
+ if let resultData = resultDictionary[kSecValueData as String] as? Data {
+ if let sharedDevice = NSKeyedUnarchiver.unarchiveObject(with: resultData) as? UsergridDevice {
return sharedDevice
} else {
UsergridDevice.deleteSharedDeviceKeychainItem()
@@ -92,17 +92,17 @@
}
- static func saveSharedDeviceKeychainItem(device:UsergridDevice) {
+ static func saveSharedDeviceKeychainItem(_ device:UsergridDevice) {
var queryAttributes = UsergridDevice.deviceKeychainItem()
- queryAttributes[kSecReturnData as String] = kCFBooleanTrue as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanTrue as Bool
+ queryAttributes[kSecReturnData as String] = (kCFBooleanTrue != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanTrue != nil) as Bool
- let sharedDeviceData = NSKeyedArchiver.archivedDataWithRootObject(device);
+ let sharedDeviceData = NSKeyedArchiver.archivedData(withRootObject: device);
- if SecItemCopyMatching(queryAttributes,nil) == errSecSuccess // Do we need to update keychain item or add a new one.
+ if SecItemCopyMatching(queryAttributes as CFDictionary,nil) == errSecSuccess // Do we need to update keychain item or add a new one.
{
let attributesToUpdate = [kSecValueData as String:sharedDeviceData]
- let updateStatus = SecItemUpdate(UsergridDevice.deviceKeychainItem(), attributesToUpdate)
+ let updateStatus = SecItemUpdate(UsergridDevice.deviceKeychainItem() as CFDictionary, attributesToUpdate as CFDictionary)
if updateStatus != errSecSuccess {
print("Error updating shared device data to keychain!")
}
@@ -111,7 +111,7 @@
{
var keychainItem = UsergridDevice.deviceKeychainItem()
keychainItem[kSecValueData as String] = sharedDeviceData
- let status = SecItemAdd(keychainItem, nil)
+ let status = SecItemAdd(keychainItem as CFDictionary, nil)
if status != errSecSuccess {
print("Error adding shared device data to keychain!")
}
@@ -120,10 +120,10 @@
static func deleteSharedDeviceKeychainItem() {
var queryAttributes = UsergridDevice.deviceKeychainItem()
- queryAttributes[kSecReturnData as String] = kCFBooleanFalse as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanFalse as Bool
- if SecItemCopyMatching(queryAttributes,nil) == errSecSuccess {
- let deleteStatus = SecItemDelete(queryAttributes)
+ queryAttributes[kSecReturnData as String] = (kCFBooleanFalse != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanFalse != nil) as Bool
+ if SecItemCopyMatching(queryAttributes as CFDictionary,nil) == errSecSuccess {
+ let deleteStatus = SecItemDelete(queryAttributes as CFDictionary)
if deleteStatus != errSecSuccess {
print("Error deleting shared device data to keychain!")
}
@@ -133,23 +133,23 @@
internal extension UsergridUser {
- static func userKeychainItem(client:UsergridClient) -> [String:AnyObject] {
+ static func userKeychainItem(_ client:UsergridClient) -> [String:Any] {
var keychainItem = usergridGenericKeychainItem()
keychainItem[kSecAttrService as String] = USERGRID_CURRENT_USER_KEYCHAIN_SERVICE + "." + client.appId + "." + client.orgId
return keychainItem
}
- static func getCurrentUserFromKeychain(client:UsergridClient) -> UsergridUser? {
+ static func getCurrentUserFromKeychain(_ client:UsergridClient) -> UsergridUser? {
var queryAttributes = UsergridUser.userKeychainItem(client)
- queryAttributes[kSecReturnData as String] = kCFBooleanTrue as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanTrue as Bool
+ queryAttributes[kSecReturnData as String] = (kCFBooleanTrue != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanTrue != nil) as Bool
var result: AnyObject?
- let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(queryAttributes, UnsafeMutablePointer($0)) }
+ let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(queryAttributes as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let resultDictionary = result as? NSDictionary {
- if let resultData = resultDictionary[kSecValueData as String] as? NSData {
- if let currentUser = NSKeyedUnarchiver.unarchiveObjectWithData(resultData) as? UsergridUser {
+ if let resultData = resultDictionary[kSecValueData as String] as? Data {
+ if let currentUser = NSKeyedUnarchiver.unarchiveObject(with: resultData) as? UsergridUser {
return currentUser
}
}
@@ -158,15 +158,15 @@
return nil
}
- static func saveCurrentUserKeychainItem(client:UsergridClient, currentUser:UsergridUser) {
+ static func saveCurrentUserKeychainItem(_ client:UsergridClient, currentUser:UsergridUser) {
var queryAttributes = UsergridUser.userKeychainItem(client)
- queryAttributes[kSecReturnData as String] = kCFBooleanTrue as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanTrue as Bool
+ queryAttributes[kSecReturnData as String] = (kCFBooleanTrue != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanTrue != nil) as Bool
- if SecItemCopyMatching(queryAttributes,nil) == errSecSuccess // Do we need to update keychain item or add a new one.
+ if SecItemCopyMatching(queryAttributes as CFDictionary,nil) == errSecSuccess // Do we need to update keychain item or add a new one.
{
- let attributesToUpdate = [kSecValueData as String:NSKeyedArchiver.archivedDataWithRootObject(currentUser)]
- let updateStatus = SecItemUpdate(UsergridUser.userKeychainItem(client), attributesToUpdate)
+ let attributesToUpdate = [kSecValueData as String:NSKeyedArchiver.archivedData(withRootObject: currentUser)]
+ let updateStatus = SecItemUpdate(UsergridUser.userKeychainItem(client) as CFDictionary, attributesToUpdate as CFDictionary)
if updateStatus != errSecSuccess {
print("Error updating current user data to keychain!")
}
@@ -174,20 +174,20 @@
else
{
var keychainItem = UsergridUser.userKeychainItem(client)
- keychainItem[kSecValueData as String] = NSKeyedArchiver.archivedDataWithRootObject(currentUser)
- let status = SecItemAdd(keychainItem, nil)
+ keychainItem[kSecValueData as String] = NSKeyedArchiver.archivedData(withRootObject: currentUser)
+ let status = SecItemAdd(keychainItem as CFDictionary, nil)
if status != errSecSuccess {
print("Error adding current user data to keychain!")
}
}
}
- static func deleteCurrentUserKeychainItem(client:UsergridClient) {
+ static func deleteCurrentUserKeychainItem(_ client:UsergridClient) {
var queryAttributes = UsergridUser.userKeychainItem(client)
- queryAttributes[kSecReturnData as String] = kCFBooleanFalse as Bool
- queryAttributes[kSecReturnAttributes as String] = kCFBooleanFalse as Bool
- if SecItemCopyMatching(queryAttributes,nil) == errSecSuccess {
- let deleteStatus = SecItemDelete(queryAttributes)
+ queryAttributes[kSecReturnData as String] = (kCFBooleanFalse != nil) as Bool
+ queryAttributes[kSecReturnAttributes as String] = (kCFBooleanFalse != nil) as Bool
+ if SecItemCopyMatching(queryAttributes as CFDictionary,nil) == errSecSuccess {
+ let deleteStatus = SecItemDelete(queryAttributes as CFDictionary)
if deleteStatus != errSecSuccess {
print("Error deleting current user data to keychain!")
}
diff --git a/Source/UsergridQuery.swift b/Source/UsergridQuery.swift
index c2a7000..a5c05bd 100644
--- a/Source/UsergridQuery.swift
+++ b/Source/UsergridQuery.swift
@@ -55,7 +55,7 @@
- returns: Returns a new instance that’s a copy of the receiver.
*/
- public func copyWithZone(zone: NSZone) -> AnyObject {
+ public func copy(with zone: NSZone?) -> Any {
let queryCopy = UsergridQuery(self.collectionName)
queryCopy.requirementStrings = NSArray(array:self.requirementStrings, copyItems: true) as! [String]
queryCopy.urlTerms = NSArray(array:self.urlTerms, copyItems: true) as! [String]
@@ -76,7 +76,7 @@
- returns: The constructed URL query sting.
*/
- public func build(autoURLEncode: Bool = true) -> String {
+ public func build(_ autoURLEncode: Bool = true) -> String {
return self.constructURLAppend(autoURLEncode)
}
@@ -90,7 +90,8 @@
- returns: `Self`
*/
- public func contains(term: String, value: String) -> Self { return self.containsWord(term, value: value) }
+ @discardableResult
+ public func contains(_ term: String, value: String) -> Self { return self.containsWord(term, value: value) }
/**
@@ -101,7 +102,8 @@
- returns: `Self`
*/
- public func containsString(term: String, value: String) -> Self { return self.containsWord(term, value: value) }
+ @discardableResult
+ public func containsString(_ term: String, value: String) -> Self { return self.containsWord(term, value: value) }
/**
Contains. Query: where term contains 'val%'.
@@ -111,7 +113,14 @@
- returns: `Self`
*/
- public func containsWord(term: String, value: String) -> Self { return self.addRequirement(term + UsergridQuery.SPACE + UsergridQuery.CONTAINS + UsergridQuery.SPACE + ((value.isUuid()) ? UsergridQuery.EMPTY_STRING : UsergridQuery.APOSTROPHE) + value + ((value.isUuid()) ? UsergridQuery.EMPTY_STRING : UsergridQuery.APOSTROPHE)) }
+ @discardableResult
+ public func containsWord(_ term: String, value: String) -> Self {
+ var operationValue: String = value
+ if !value.isUuid() {
+ operationValue = UsergridQuery.APOSTROPHE + value + UsergridQuery.APOSTROPHE
+ }
+ return self.addRequirement(term + UsergridQuery.SPACE + UsergridQuery.CONTAINS + UsergridQuery.SPACE + operationValue)
+ }
/**
Sort ascending. Query:. order by term asc.
@@ -120,7 +129,8 @@
- returns: `Self`
*/
- public func ascending(term: String) -> Self { return self.asc(term) }
+ @discardableResult
+ public func ascending(_ term: String) -> Self { return self.asc(term) }
/**
Sort ascending. Query:. order by term asc.
@@ -129,7 +139,8 @@
- returns: `Self`
*/
- public func asc(term: String) -> Self { return self.sort(term, sortOrder: .Asc) }
+ @discardableResult
+ public func asc(_ term: String) -> Self { return self.sort(term, sortOrder: .asc) }
/**
Sort descending. Query: order by term desc
@@ -138,7 +149,8 @@
- returns: `Self`
*/
- public func descending(term: String) -> Self { return self.desc(term) }
+ @discardableResult
+ public func descending(_ term: String) -> Self { return self.desc(term) }
/**
Sort descending. Query: order by term desc
@@ -147,7 +159,8 @@
- returns: `Self`
*/
- public func desc(term: String) -> Self { return self.sort(term, sortOrder: .Desc) }
+ @discardableResult
+ public func desc(_ term: String) -> Self { return self.sort(term, sortOrder: .desc) }
/**
Filter (or Equal-to). Query: where term = 'value'.
@@ -157,7 +170,8 @@
- returns: `Self`
*/
- public func filter(term: String, value: AnyObject) -> Self { return self.eq(term, value: value) }
+ @discardableResult
+ public func filter(_ term: String, value: Any) -> Self { return self.eq(term, value: value) }
/**
Equal-to. Query: where term = 'value'.
@@ -167,7 +181,8 @@
- returns: `Self`
*/
- public func equals(term: String, value: AnyObject) -> Self { return self.eq(term, value: value) }
+ @discardableResult
+ public func equals(_ term: String, value: Any) -> Self { return self.eq(term, value: value) }
/**
Equal-to. Query: where term = 'value'.
@@ -177,7 +192,8 @@
- returns: `Self`
*/
- public func eq(term: String, value: AnyObject) -> Self { return self.addOperationRequirement(term, operation:.Equal, value: value) }
+ @discardableResult
+ public func eq(_ term: String, value: Any) -> Self { return self.addOperationRequirement(term, operation:.equal, value: value) }
/**
Greater-than. Query: where term > 'value'.
@@ -187,7 +203,8 @@
- returns: `Self`
*/
- public func greaterThan(term: String, value: AnyObject) -> Self { return self.gt(term, value: value) }
+ @discardableResult
+ public func greaterThan(_ term: String, value: Any) -> Self { return self.gt(term, value: value) }
/**
Greater-than. Query: where term > 'value'.
@@ -197,7 +214,8 @@
- returns: `Self`
*/
- public func gt(term: String, value: AnyObject) -> Self { return self.addOperationRequirement(term, operation:.GreaterThan, value: value) }
+ @discardableResult
+ public func gt(_ term: String, value: Any) -> Self { return self.addOperationRequirement(term, operation:.greaterThan, value: value) }
/**
Greater-than-or-equal-to. Query: where term >= 'value'.
@@ -207,7 +225,8 @@
- returns: `Self`
*/
- public func greaterThanOrEqual(term: String, value: AnyObject) -> Self { return self.gte(term, value: value) }
+ @discardableResult
+ public func greaterThanOrEqual(_ term: String, value: Any) -> Self { return self.gte(term, value: value) }
/**
Greater-than-or-equal-to. Query: where term >= 'value'.
@@ -217,7 +236,8 @@
- returns: `Self`
*/
- public func gte(term: String, value: AnyObject) -> Self { return self.addOperationRequirement(term, operation:.GreaterThanEqualTo, value: value) }
+ @discardableResult
+ public func gte(_ term: String, value: Any) -> Self { return self.addOperationRequirement(term, operation:.greaterThanEqualTo, value: value) }
/**
Less-than. Query: where term < 'value'.
@@ -227,7 +247,8 @@
- returns: `Self`
*/
- public func lessThan(term: String, value: AnyObject) -> Self { return self.lt(term, value: value) }
+ @discardableResult
+ public func lessThan(_ term: String, value: Any) -> Self { return self.lt(term, value: value) }
/**
Less-than. Query: where term < 'value'.
@@ -237,7 +258,8 @@
- returns: `Self`
*/
- public func lt(term: String, value: AnyObject) -> Self { return self.addOperationRequirement(term, operation:.LessThan, value: value) }
+ @discardableResult
+ public func lt(_ term: String, value: Any) -> Self { return self.addOperationRequirement(term, operation:.lessThan, value: value) }
/**
Less-than-or-equal-to. Query: where term <= 'value'.
@@ -247,7 +269,8 @@
- returns: `Self`
*/
- public func lessThanOrEqual(term: String, value: AnyObject) -> Self { return self.lte(term, value: value) }
+ @discardableResult
+ public func lessThanOrEqual(_ term: String, value: Any) -> Self { return self.lte(term, value: value) }
/**
Less-than-or-equal-to. Query: where term <= 'value'.
@@ -257,7 +280,8 @@
- returns: `Self`
*/
- public func lte(term: String, value: AnyObject) -> Self { return self.addOperationRequirement(term, operation:.LessThanEqualTo, value: value) }
+ @discardableResult
+ public func lte(_ term: String, value: Any) -> Self { return self.addOperationRequirement(term, operation:.lessThanEqualTo, value: value) }
/**
Contains. Query: location within val of lat, long.
@@ -268,7 +292,8 @@
- returns: `Self`
*/
- public func locationWithin(distance: Float, latitude: Float, longitude: Float) -> Self {
+ @discardableResult
+ public func locationWithin(_ distance: Float, latitude: Float, longitude: Float) -> Self {
return self.addRequirement(UsergridQuery.LOCATION + UsergridQuery.SPACE + UsergridQuery.WITHIN + UsergridQuery.SPACE + distance.description + UsergridQuery.SPACE + UsergridQuery.OF + UsergridQuery.SPACE + latitude.description + UsergridQuery.COMMA + longitude.description )
}
@@ -277,10 +302,11 @@
- returns: `Self`
*/
+ @discardableResult
public func or() -> Self {
if !self.requirementStrings.first!.isEmpty {
- self.requirementStrings.insert(UsergridQuery.OR, atIndex: 0)
- self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, atIndex: 0)
+ self.requirementStrings.insert(UsergridQuery.OR, at: 0)
+ self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, at: 0)
}
return self
}
@@ -290,10 +316,11 @@
- returns: `Self`
*/
+ @discardableResult
public func and() -> Self {
if !self.requirementStrings.first!.isEmpty {
- self.requirementStrings.insert(UsergridQuery.AND, atIndex: 0)
- self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, atIndex: 0)
+ self.requirementStrings.insert(UsergridQuery.AND, at: 0)
+ self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, at: 0)
}
return self
}
@@ -303,10 +330,11 @@
- returns: `Self`
*/
+ @discardableResult
public func not() -> Self {
if !self.requirementStrings.first!.isEmpty {
- self.requirementStrings.insert(UsergridQuery.NOT, atIndex: 0)
- self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, atIndex: 0)
+ self.requirementStrings.insert(UsergridQuery.NOT, at: 0)
+ self.requirementStrings.insert(UsergridQuery.EMPTY_STRING, at: 0)
}
return self
}
@@ -319,7 +347,8 @@
- returns: `Self`
*/
- public func sort(term: String, sortOrder: UsergridQuerySortOrder) -> Self {
+ @discardableResult
+ public func sort(_ term: String, sortOrder: UsergridQuerySortOrder) -> Self {
self.orderClauses[term] = sortOrder
return self
}
@@ -331,7 +360,8 @@
- returns: `Self`
*/
- public func collection(collectionName: String) -> Self {
+ @discardableResult
+ public func collection(_ collectionName: String) -> Self {
self.collectionName = collectionName
return self
}
@@ -343,7 +373,8 @@
- returns: `Self`
*/
- public func type(type: String) -> Self {
+ @discardableResult
+ public func type(_ type: String) -> Self {
self.collectionName = type
return self
}
@@ -355,7 +386,8 @@
- returns: `Self`
*/
- public func limit(limit: Int) -> Self {
+ @discardableResult
+ public func limit(_ limit: Int) -> Self {
self.limit = limit
return self
}
@@ -367,7 +399,8 @@
- returns: `Self`
*/
- public func ql(value: String) -> Self {
+ @discardableResult
+ public func ql(_ value: String) -> Self {
return self.addRequirement(value)
}
@@ -378,7 +411,8 @@
- returns: `Self`
*/
- public func cursor(value: String?) -> Self {
+ @discardableResult
+ public func cursor(_ value: String?) -> Self {
self.cursor = value
return self
}
@@ -390,7 +424,8 @@
- returns: `Self`
*/
- public func fromString(value: String?) -> Self {
+ @discardableResult
+ public func fromString(_ value: String?) -> Self {
self.fromStringValue = value
return self
}
@@ -403,11 +438,12 @@
- returns: `Self`
*/
- public func urlTerm(term: String, equalsValue: String) -> Self {
- if (term as NSString).isEqualToString(UsergridQuery.QL) {
- self.ql(equalsValue)
+ @discardableResult
+ public func urlTerm(_ term: String, equalsValue: String) -> Self {
+ if term == UsergridQuery.QL {
+ return self.ql(equalsValue)
} else {
- self.urlTerms.append(term + UsergridQueryOperator.Equal.stringValue + equalsValue)
+ self.urlTerms.append(term + UsergridQueryOperator.equal.stringValue + equalsValue)
}
return self
}
@@ -421,7 +457,8 @@
- returns: `Self`
*/
- public func addOperationRequirement(term: String, operation: UsergridQueryOperator, stringValue: String) -> Self {
+ @discardableResult
+ public func addOperationRequirement(_ term: String, operation: UsergridQueryOperator, stringValue: String) -> Self {
return self.addOperationRequirement(term,operation:operation,value:stringValue)
}
@@ -434,25 +471,32 @@
- returns: `Self`
*/
- public func addOperationRequirement(term: String, operation: UsergridQueryOperator, intValue: Int) -> Self {
+ @discardableResult
+ public func addOperationRequirement(_ term: String, operation: UsergridQueryOperator, intValue: Int) -> Self {
return self.addOperationRequirement(term,operation:operation,value:intValue)
}
-
- private func addRequirement(requirement: String) -> Self {
- var requirementString: String = self.requirementStrings.removeAtIndex(0)
+
+ @discardableResult
+ private func addRequirement(_ requirement: String) -> Self {
+ var requirementString: String = self.requirementStrings.remove(at: 0)
if !requirementString.isEmpty {
requirementString += UsergridQuery.SPACE + UsergridQuery.AND + UsergridQuery.SPACE
}
requirementString += requirement
- self.requirementStrings.insert(requirementString, atIndex: 0)
+ self.requirementStrings.insert(requirementString, at: 0)
return self
}
-
- private func addOperationRequirement(term: String, operation: UsergridQueryOperator, value: AnyObject) -> Self {
- if value is String {
- return self.addRequirement(term + UsergridQuery.SPACE + operation.stringValue + UsergridQuery.SPACE + ((value.description.isUuid()) ? UsergridQuery.EMPTY_STRING : UsergridQuery.APOSTROPHE) + value.description + ((value.description.isUuid()) ? UsergridQuery.EMPTY_STRING : UsergridQuery.APOSTROPHE) )
+
+ @discardableResult
+ private func addOperationRequirement(_ term: String, operation: UsergridQueryOperator, value: Any) -> Self {
+ if let stringValue = value as? String {
+ var operationValue: String = stringValue
+ if !stringValue.isUuid() {
+ operationValue = UsergridQuery.APOSTROPHE + stringValue + UsergridQuery.APOSTROPHE
+ }
+ return self.addRequirement(term + UsergridQuery.SPACE + operation.stringValue + UsergridQuery.SPACE + operationValue)
} else {
- return self.addRequirement(term + UsergridQuery.SPACE + operation.stringValue + UsergridQuery.SPACE + value.description)
+ return self.addRequirement(term + UsergridQuery.SPACE + operation.stringValue + UsergridQuery.SPACE + (value as AnyObject).description )
}
}
@@ -477,7 +521,7 @@
}
private func constructURLTermsString() -> String {
- return (self.urlTerms as NSArray).componentsJoinedByString(UsergridQuery.AMPERSAND)
+ return self.urlTerms.joined(separator: UsergridQuery.AMPERSAND)
}
private func constructRequirementString() -> String {
@@ -485,25 +529,25 @@
var requirementStrings = self.requirementStrings
// If the first requirement is empty lets remove it.
- if let firstRequirement = requirementStrings.first where firstRequirement.isEmpty {
+ if let firstRequirement = requirementStrings.first , firstRequirement.isEmpty {
requirementStrings.removeFirst()
}
// If the first requirement now is a conditional separator then we should remove it so its not placed at the end of the constructed string.
- if let firstRequirement = requirementStrings.first where firstRequirement == UsergridQuery.OR || firstRequirement == UsergridQuery.NOT {
+ if let firstRequirement = requirementStrings.first , firstRequirement == UsergridQuery.OR || firstRequirement == UsergridQuery.NOT {
requirementStrings.removeFirst()
}
- requirementsString = (requirementStrings.reverse() as NSArray).componentsJoinedByString(UsergridQuery.SPACE)
+ requirementsString = requirementStrings.reversed().joined(separator: UsergridQuery.SPACE)
return requirementsString
}
- private func constructURLAppend(autoURLEncode: Bool = true) -> String {
+ private func constructURLAppend(_ autoURLEncode: Bool = true) -> String {
if let fromString = self.fromStringValue {
var requirementsString = fromString
if autoURLEncode {
- if let encodedRequirementsString = fromString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
+ if let encodedRequirementsString = fromString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
requirementsString = encodedRequirementsString
}
}
@@ -521,7 +565,7 @@
}
urlAppend += urlTermsString
}
- if let cursorString = self.cursor where !cursorString.isEmpty {
+ if let cursorString = self.cursor , !cursorString.isEmpty {
if !urlAppend.isEmpty {
urlAppend += UsergridQuery.AMPERSAND
}
@@ -535,7 +579,7 @@
}
if !requirementsString.isEmpty {
if autoURLEncode {
- if let encodedRequirementsString = requirementsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
+ if let encodedRequirementsString = requirementsString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
requirementsString = encodedRequirementsString
}
}
diff --git a/Source/UsergridRequest.swift b/Source/UsergridRequest.swift
index 0a651e2..f0bdf42 100644
--- a/Source/UsergridRequest.swift
+++ b/Source/UsergridRequest.swift
@@ -54,7 +54,7 @@
public let headers: [String:String]?
/// The JSON body that will be set on the request. Can be either a valid JSON object or NSData.
- public let jsonBody: AnyObject?
+ public let jsonBody: Any?
/// The query params that will be set on the request.
public let queryParams: [String:String]?
@@ -81,7 +81,7 @@
query:UsergridQuery? = nil,
auth:UsergridAuth? = nil,
headers:[String:String]? = nil,
- jsonBody:AnyObject? = nil,
+ jsonBody:Any? = nil,
queryParams:[String:String]? = nil) {
self.method = method
self.baseUrl = baseUrl
@@ -90,7 +90,7 @@
self.headers = headers
self.query = query
self.queryParams = queryParams
- if let body = jsonBody where (body is NSData || NSJSONSerialization.isValidJSONObject(body)) {
+ if let body = jsonBody , (body is Data || JSONSerialization.isValidJSONObject(body)) {
self.jsonBody = body
} else {
self.jsonBody = nil
@@ -104,20 +104,20 @@
- returns: An initialized and configured `NSURLRequest` object.
*/
- public func buildNSURLRequest() -> NSURLRequest {
- let request = NSMutableURLRequest(URL: self.buildURL())
- request.HTTPMethod = self.method.stringValue
+ public func buildNSURLRequest() -> URLRequest {
+ let request = NSMutableURLRequest(url: self.buildURL())
+ request.httpMethod = self.method.stringValue
self.applyHeaders(request)
self.applyBody(request)
self.applyAuth(request)
- return request
+ return request as URLRequest
}
- private func buildURL() -> NSURL {
+ private func buildURL() -> URL {
var constructedURLString = self.baseUrl
if let appendingPaths = self.paths {
for pathToAppend in appendingPaths {
- if let encodedPath = pathToAppend.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet()) {
+ if let encodedPath = pathToAppend.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed) {
constructedURLString = "\(constructedURLString)\(UsergridRequest.FORWARD_SLASH)\(encodedPath)"
}
}
@@ -129,19 +129,19 @@
}
}
if let queryParams = self.queryParams {
- if let components = NSURLComponents(string: constructedURLString) {
+ if var components = URLComponents(string: constructedURLString) {
components.queryItems = components.queryItems ?? []
for (key, value) in queryParams {
- let q: NSURLQueryItem = NSURLQueryItem(name: key, value: value)
+ let q: URLQueryItem = URLQueryItem(name: key, value: value)
components.queryItems!.append(q)
}
constructedURLString = components.string!
}
}
- return NSURL(string:constructedURLString)!
+ return URL(string:constructedURLString)!
}
- private func applyHeaders(request:NSMutableURLRequest) {
+ fileprivate func applyHeaders(_ request:NSMutableURLRequest) {
if let httpHeaders = self.headers {
for (key,value) in httpHeaders {
request.setValue(value, forHTTPHeaderField: key)
@@ -149,14 +149,14 @@
}
}
- private func applyBody(request:NSMutableURLRequest) {
- if let jsonBody = self.jsonBody, httpBody = UsergridRequest.jsonBodyToData(jsonBody) {
- request.HTTPBody = httpBody
- request.setValue(String(format: "%lu", httpBody.length), forHTTPHeaderField: UsergridRequest.CONTENT_LENGTH)
+ private func applyBody(_ request:NSMutableURLRequest) {
+ if let jsonBody = self.jsonBody, let httpBody = UsergridRequest.jsonBodyToData(jsonBody) {
+ request.httpBody = httpBody
+ request.setValue(String(format: "%lu", httpBody.count), forHTTPHeaderField: UsergridRequest.CONTENT_LENGTH)
}
}
- private func applyAuth(request:NSMutableURLRequest) {
+ private func applyAuth(_ request:NSMutableURLRequest) {
if let usergridAuth = self.auth {
if usergridAuth.isValid, let accessToken = usergridAuth.accessToken {
request.setValue("\(UsergridRequest.BEARER) \(accessToken)", forHTTPHeaderField: UsergridRequest.AUTHORIZATION)
@@ -164,26 +164,28 @@
}
}
- private static func jsonBodyToData(jsonBody:AnyObject) -> NSData? {
- if let jsonBodyAsNSData = jsonBody as? NSData {
+ private static func jsonBodyToData(_ jsonBody:Any) -> Data? {
+ if let jsonBodyAsNSData = jsonBody as? Data {
return jsonBodyAsNSData
} else {
- var jsonBodyAsNSData: NSData? = nil
- do { jsonBodyAsNSData = try NSJSONSerialization.dataWithJSONObject(jsonBody, options: NSJSONWritingOptions(rawValue: 0)) }
+ var jsonBodyAsNSData: Data? = nil
+ do { jsonBodyAsNSData = try JSONSerialization.data(withJSONObject: jsonBody, options: JSONSerialization.WritingOptions(rawValue: 0)) }
catch { print(error) }
return jsonBodyAsNSData
}
}
- private static let AUTHORIZATION = "Authorization"
- private static let ACCESS_TOKEN = "access_token"
- private static let APPLICATION_JSON = "application/json; charset=utf-8"
- private static let BEARER = "Bearer"
- private static let CONTENT_LENGTH = "Content-Length"
- private static let CONTENT_TYPE = "Content-Type"
- private static let FORWARD_SLASH = "/"
+ fileprivate static let AUTHORIZATION = "Authorization"
+ fileprivate static let ACCESS_TOKEN = "access_token"
+ fileprivate static let APPLICATION_JSON = "application/json; charset=utf-8"
+ fileprivate static let BEARER = "Bearer"
+ fileprivate static let CONTENT_LENGTH = "Content-Length"
+ fileprivate static let CONTENT_TYPE = "Content-Type"
+ fileprivate static let FORWARD_SLASH = "/"
- static let JSON_CONTENT_TYPE_HEADER = [UsergridRequest.CONTENT_TYPE:UsergridRequest.APPLICATION_JSON]
+ static func jsonHeaderContentType() -> [String:String] {
+ return [UsergridRequest.CONTENT_TYPE:UsergridRequest.APPLICATION_JSON]
+ }
}
/**
@@ -197,15 +199,16 @@
public let asset: UsergridAsset
/// A constructed multipart http body for requests to upload.
- public var multiPartHTTPBody: NSData {
+ public var multiPartHTTPBody: Data {
let httpBodyString = UsergridAssetUploadRequest.MULTIPART_START +
"\(UsergridAssetUploadRequest.CONTENT_DISPOSITION):\(UsergridAssetUploadRequest.FORM_DATA); name=file; filename=\(self.asset.filename)\r\n" +
- "\(UsergridRequest.CONTENT_TYPE): \(self.asset.contentType)\r\n\r\n" as NSString
+ "\(UsergridRequest.CONTENT_TYPE): \(self.asset.contentType)\r\n\r\n"
- let httpBody = NSMutableData()
- httpBody.appendData(httpBodyString.dataUsingEncoding(NSUTF8StringEncoding)!)
- httpBody.appendData(self.asset.data)
- httpBody.appendData(UsergridAssetUploadRequest.MULTIPART_END.dataUsingEncoding(NSUTF8StringEncoding)!)
+
+ var httpBody = Data()
+ httpBody.append(httpBodyString.data(using: String.Encoding.utf8)!)
+ httpBody.append(self.asset.data)
+ httpBody.append(UsergridAssetUploadRequest.MULTIPART_END.data(using: String.Encoding.utf8)!)
return httpBody
}
@@ -227,19 +230,19 @@
auth:UsergridAuth? = nil,
asset:UsergridAsset) {
self.asset = asset
- super.init(method: .Put, baseUrl: baseUrl, paths: paths, auth: auth)
+ super.init(method: .put, baseUrl: baseUrl, paths: paths, auth: auth)
}
- private override func applyHeaders(request: NSMutableURLRequest) {
+ fileprivate override func applyHeaders(_ request: NSMutableURLRequest) {
super.applyHeaders(request)
request.setValue(UsergridAssetUploadRequest.ASSET_UPLOAD_CONTENT_HEADER, forHTTPHeaderField: UsergridRequest.CONTENT_TYPE)
- request.setValue(String(format: "%lu", self.multiPartHTTPBody.length), forHTTPHeaderField: UsergridRequest.CONTENT_LENGTH)
+ request.setValue(String(format: "%lu", self.multiPartHTTPBody.count), forHTTPHeaderField: UsergridRequest.CONTENT_LENGTH)
}
private static let ASSET_UPLOAD_BOUNDARY = "usergrid-asset-upload-boundary"
private static let ASSET_UPLOAD_CONTENT_HEADER = "multipart/form-data; boundary=\(UsergridAssetUploadRequest.ASSET_UPLOAD_BOUNDARY)"
private static let CONTENT_DISPOSITION = "Content-Disposition"
private static let MULTIPART_START = "--\(UsergridAssetUploadRequest.ASSET_UPLOAD_BOUNDARY)\r\n"
- private static let MULTIPART_END = "\r\n--\(UsergridAssetUploadRequest.ASSET_UPLOAD_BOUNDARY)--\r\n" as NSString
+ private static let MULTIPART_END = "\r\n--\(UsergridAssetUploadRequest.ASSET_UPLOAD_BOUNDARY)--\r\n"
private static let FORM_DATA = "form-data"
}
diff --git a/Source/UsergridRequestManager.swift b/Source/UsergridRequestManager.swift
index 46a4213..a876f81 100644
--- a/Source/UsergridRequestManager.swift
+++ b/Source/UsergridRequestManager.swift
@@ -30,7 +30,7 @@
unowned let client: UsergridClient
- let session: NSURLSession
+ let session: URLSession
var sessionDelegate : UsergridSessionDelegate {
return session.delegate as! UsergridSessionDelegate
@@ -39,19 +39,19 @@
init(client:UsergridClient) {
self.client = client
- let config = NSURLSessionConfiguration.defaultSessionConfiguration()
+ let config = URLSessionConfiguration.default
#if os(tvOS)
- config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-tvOS/v\(UsergridSDKVersion)"]
+ config.httpAdditionalHeaders = ["User-Agent": "usergrid-tvOS/v\(UsergridSDKVersion)"]
#elseif os(iOS)
- config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-ios/v\(UsergridSDKVersion)"]
+ config.httpAdditionalHeaders = ["User-Agent": "usergrid-ios/v\(UsergridSDKVersion)"]
#elseif os(watchOS)
- config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-watchOS/v\(UsergridSDKVersion)"]
+ config.httpAdditionalHeaders = ["User-Agent": "usergrid-watchOS/v\(UsergridSDKVersion)"]
#elseif os(OSX)
- config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-osx/v\(UsergridSDKVersion)"]
+ config.httpAdditionalHeaders = ["User-Agent": "usergrid-osx/v\(UsergridSDKVersion)"]
#endif
- self.session = NSURLSession(configuration: config,
+ self.session = URLSession(configuration: config,
delegate: UsergridSessionDelegate(),
delegateQueue: nil)
}
@@ -60,11 +60,11 @@
session.invalidateAndCancel()
}
- func performRequest(request:UsergridRequest, completion:UsergridResponseCompletion?) {
- session.dataTaskWithRequest(request.buildNSURLRequest()) { [weak self] (data, response, error) -> Void in
- let response = UsergridResponse(client:self?.client, data: data, response: response as? NSHTTPURLResponse, error: error)
- dispatch_async(dispatch_get_main_queue()) {
- completion?(response: response)
+ func performRequest(_ request:UsergridRequest, completion:UsergridResponseCompletion?) {
+ session.dataTask(with: request.buildNSURLRequest()) { [weak self] (data, response, error) -> Void in
+ let usergridResponse = UsergridResponse(client:self?.client, data: data, response: response as? HTTPURLResponse, error: error as NSError?)
+ DispatchQueue.main.async {
+ completion?(usergridResponse)
}
}.resume()
}
@@ -74,32 +74,32 @@
// MARK: - Authentication -
extension UsergridRequestManager {
- static func getTokenAndExpiryFromResponseJSON(jsonDict:[String:AnyObject]) -> (token:String?,expiry:NSDate?) {
+ static func getTokenAndExpiryFromResponseJSON(_ jsonDict:[String:Any]) -> (token:String?,expiry:Date?) {
var token: String? = nil
- var expiry: NSDate? = nil
+ var expiry: Date? = nil
if let accessToken = jsonDict["access_token"] as? String {
token = accessToken
}
if let expiresIn = jsonDict["expires_in"] as? Int {
let expiresInAdjusted = expiresIn - 5000
- expiry = NSDate(timeIntervalSinceNow: NSTimeInterval(expiresInAdjusted))
+ expiry = Date(timeIntervalSinceNow: TimeInterval(expiresInAdjusted))
}
return (token,expiry)
}
- func performUserAuthRequest(userAuth:UsergridUserAuth, request:UsergridRequest, completion:UsergridUserAuthCompletionBlock?) {
- session.dataTaskWithRequest(request.buildNSURLRequest()) { (data, response, error) -> Void in
- let dataAsJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
+ func performUserAuthRequest(_ userAuth:UsergridUserAuth, request:UsergridRequest, completion:UsergridUserAuthCompletionBlock?) {
+ session.dataTask(with: request.buildNSURLRequest()) { (data, response, error) -> Void in
+ let dataAsJSON = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
var createdUser: UsergridUser? = nil
var responseError: UsergridResponseError? = nil
- if let jsonDict = dataAsJSON as? [String:AnyObject] {
+ if let jsonDict = dataAsJSON as? [String:Any] {
let tokenAndExpiry = UsergridRequestManager.getTokenAndExpiryFromResponseJSON(jsonDict)
userAuth.accessToken = tokenAndExpiry.token
userAuth.expiry = tokenAndExpiry.expiry
- if let userDict = jsonDict[UsergridUser.USER_ENTITY_TYPE] as? [String:AnyObject] {
+ if let userDict = jsonDict[UsergridUser.USER_ENTITY_TYPE] as? [String:Any] {
if let newUser = UsergridEntity.entity(jsonDict: userDict) as? UsergridUser {
newUser.auth = userAuth
createdUser = newUser
@@ -112,19 +112,19 @@
responseError = UsergridResponseError(errorName: "Auth Failed.", errorDescription: "Error Description: \(error?.localizedDescription).")
}
- dispatch_async(dispatch_get_main_queue()) {
- completion?(auth: userAuth, user: createdUser, error: responseError)
+ DispatchQueue.main.async {
+ completion?(userAuth, createdUser, responseError)
}
}.resume()
}
- func performAppAuthRequest(appAuth: UsergridAppAuth, request: UsergridRequest, completion: UsergridAppAuthCompletionBlock?) {
- session.dataTaskWithRequest(request.buildNSURLRequest()) { (data, response, error) -> Void in
- let dataAsJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
+ func performAppAuthRequest(_ appAuth: UsergridAppAuth, request: UsergridRequest, completion: UsergridAppAuthCompletionBlock?) {
+ session.dataTask(with: request.buildNSURLRequest()) { (data, response, error) -> Void in
+ let dataAsJSON = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
var responseError: UsergridResponseError? = nil
- if let jsonDict = dataAsJSON as? [String:AnyObject] {
+ if let jsonDict = dataAsJSON as? [String:Any] {
let tokenAndExpiry = UsergridRequestManager.getTokenAndExpiryFromResponseJSON(jsonDict)
appAuth.accessToken = tokenAndExpiry.token
appAuth.expiry = tokenAndExpiry.expiry
@@ -132,8 +132,8 @@
responseError = UsergridResponseError(errorName: "Auth Failed.", errorDescription: "Error Description: \(error?.localizedDescription).")
}
- dispatch_async(dispatch_get_main_queue()) {
- completion?(auth: appAuth, error: responseError)
+ DispatchQueue.main.async {
+ completion?(appAuth, responseError)
}
}.resume()
}
@@ -142,35 +142,35 @@
// MARK: - Asset Management -
extension UsergridRequestManager {
- func performAssetDownload(contentType:String, usergridRequest:UsergridRequest, progress: UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
- let downloadTask = session.downloadTaskWithRequest(usergridRequest.buildNSURLRequest())
+ func performAssetDownload(_ contentType:String, usergridRequest:UsergridRequest, progress: UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) {
+ let downloadTask = session.downloadTask(with: usergridRequest.buildNSURLRequest())
let requestWrapper = UsergridAssetRequestWrapper(session: self.session, sessionTask: downloadTask, progress: progress) { (request) -> Void in
var asset: UsergridAsset? = nil
var responseError: UsergridResponseError? = nil
- if let assetData = request.responseData where assetData.length > 0 {
+ if let assetData = request.responseData , assetData.count > 0 {
asset = UsergridAsset(data: assetData, contentType: contentType)
} else {
responseError = UsergridResponseError(errorName: "Download Failed.", errorDescription: "Downloading asset failed. No data was recieved.")
}
- dispatch_async(dispatch_get_main_queue()) {
- completion?(asset: asset, error: responseError)
+ DispatchQueue.main.async {
+ completion?(asset, responseError)
}
}
self.sessionDelegate.addRequestDelegate(requestWrapper.sessionTask, requestWrapper:requestWrapper)
requestWrapper.sessionTask.resume()
}
- func performAssetUpload(usergridRequest:UsergridAssetUploadRequest, progress:UsergridAssetRequestProgress? = nil, completion: UsergridAssetUploadCompletion? = nil) {
- let uploadTask = session.uploadTaskWithRequest(usergridRequest.buildNSURLRequest(), fromData: usergridRequest.multiPartHTTPBody)
+ func performAssetUpload(_ usergridRequest:UsergridAssetUploadRequest, progress:UsergridAssetRequestProgress? = nil, completion: UsergridAssetUploadCompletion? = nil) {
+ let uploadTask = session.uploadTask(with: usergridRequest.buildNSURLRequest() as URLRequest, from: usergridRequest.multiPartHTTPBody as Data)
let requestWrapper = UsergridAssetRequestWrapper(session: self.session, sessionTask: uploadTask, progress: progress) { [weak self] (request) -> Void in
- let response = UsergridResponse(client: self?.client, data: request.responseData, response: request.response as? NSHTTPURLResponse, error: request.error)
- dispatch_async(dispatch_get_main_queue()) {
- completion?(asset: usergridRequest.asset, response: response)
+ let response = UsergridResponse(client: self?.client, data: request.responseData, response: request.response as? HTTPURLResponse, error: request.error)
+ DispatchQueue.main.async {
+ completion?(usergridRequest.asset, response)
}
}
self.sessionDelegate.addRequestDelegate(requestWrapper.sessionTask, requestWrapper:requestWrapper)
requestWrapper.sessionTask.resume()
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridResponse.swift b/Source/UsergridResponse.swift
index b9e58ec..525bfde 100644
--- a/Source/UsergridResponse.swift
+++ b/Source/UsergridResponse.swift
@@ -27,7 +27,7 @@
import Foundation
/// The completion block used in for most `UsergridClient` requests.
-public typealias UsergridResponseCompletion = (response: UsergridResponse) -> Void
+public typealias UsergridResponseCompletion = (_ response: UsergridResponse) -> Void
/**
`UsergridResponse` is the core class that handles both successful and unsuccessful HTTP responses from Usergrid.
@@ -44,7 +44,7 @@
public weak var client: UsergridClient?
/// The raw response JSON.
- internal(set) public var responseJSON: [String:AnyObject]?
+ internal(set) public var responseJSON: [String:Any]?
/// The query used on the request.
internal(set) public var query: UsergridQuery?
@@ -97,7 +97,7 @@
/// The string value.
public var stringValue : String {
if let responseJSON = self.responseJSON {
- return NSString(data: try! NSJSONSerialization.dataWithJSONObject(responseJSON, options: .PrettyPrinted), encoding: NSUTF8StringEncoding) as? String ?? ""
+ return NSString(data: try! JSONSerialization.data(withJSONObject: responseJSON, options: .prettyPrinted), encoding: String.Encoding.utf8.rawValue) as? String ?? ""
} else {
return error?.description ?? ""
}
@@ -142,10 +142,10 @@
- returns: A new instance of `UsergridResponse`.
*/
- public init(client:UsergridClient?, data:NSData?, response:NSHTTPURLResponse?, error:NSError?, query:UsergridQuery? = nil) {
+ public init(client:UsergridClient?, data:Data?, response:HTTPURLResponse?, error:NSError?, query:UsergridQuery? = nil) {
self.client = client
self.statusCode = response?.statusCode
- self.headers = response?.allHeaderFields as? [String:String]
+// self.headers = response?.allHeaderFields as? [String:String]
if let sessionError = error {
self.error = UsergridResponseError(errorName: sessionError.domain, errorDescription: sessionError.localizedDescription)
@@ -157,16 +157,16 @@
if let jsonData = data {
do {
- let dataAsJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers)
- if let jsonDict = dataAsJSON as? [String:AnyObject] {
+ let dataAsJSON = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers)
+ if let jsonDict = dataAsJSON as? [String:Any] {
self.responseJSON = jsonDict
if let responseError = UsergridResponseError(jsonDictionary: jsonDict) {
self.error = responseError
} else {
- if let entitiesJSONArray = jsonDict[UsergridResponse.ENTITIES] as? [[String:AnyObject]] where entitiesJSONArray.count > 0 {
+ if let entitiesJSONArray = jsonDict[UsergridResponse.ENTITIES] as? [[String:Any]] , entitiesJSONArray.count > 0 {
self.entities = UsergridEntity.entities(jsonArray: entitiesJSONArray)
}
- if let cursor = jsonDict[UsergridResponse.CURSOR] as? String where !cursor.isEmpty {
+ if let cursor = jsonDict[UsergridResponse.CURSOR] as? String , !cursor.isEmpty {
self.cursor = cursor
}
}
@@ -186,7 +186,7 @@
- parameter completion: The completion block that is called once the request for the next page has finished.
*/
- public func loadNextPage(completion: UsergridResponseCompletion) {
+ public func loadNextPage(_ completion: UsergridResponseCompletion) {
if self.hasNextPage, let type = (self.responseJSON?["path"] as? NSString)?.lastPathComponent {
if let query = self.query?.copy() as? UsergridQuery {
self.client?.GET(query.cursor(self.cursor), queryCompletion:completion)
@@ -194,7 +194,7 @@
self.client?.GET(UsergridQuery(type).cursor(self.cursor), queryCompletion:completion)
}
} else {
- completion(response: UsergridResponse(client: self.client, errorName: "No next page.", errorDescription: "No next page was found."))
+ completion(UsergridResponse(client: self.client, errorName: "No next page.", errorDescription: "No next page was found."))
}
}
diff --git a/Source/UsergridResponseError.swift b/Source/UsergridResponseError.swift
index eda8a30..f4dbc4a 100644
--- a/Source/UsergridResponseError.swift
+++ b/Source/UsergridResponseError.swift
@@ -74,9 +74,9 @@
- returns: A new instance of `UsergridResponseError` if the JSON dictionary did indeed contain error information.
*/
- public convenience init?(jsonDictionary:[String:AnyObject]) {
+ public convenience init?(jsonDictionary:[String:Any]) {
if let errorName = jsonDictionary[USERGRID_ERROR] as? String,
- errorDescription = jsonDictionary[USERGRID_ERROR_DESCRIPTION] as? String {
+ let errorDescription = jsonDictionary[USERGRID_ERROR_DESCRIPTION] as? String {
self.init(errorName:errorName,errorDescription:errorDescription,exception:jsonDictionary[USERGRID_EXCEPTION] as? String)
} else {
self.init(errorName:"",errorDescription:"")
@@ -87,4 +87,4 @@
let USERGRID_ERROR = "error"
let USERGRID_ERROR_DESCRIPTION = "error_description"
-let USERGRID_EXCEPTION = "exception"
\ No newline at end of file
+let USERGRID_EXCEPTION = "exception"
diff --git a/Source/UsergridSessionDelegate.swift b/Source/UsergridSessionDelegate.swift
index cb36fb7..7866c26 100644
--- a/Source/UsergridSessionDelegate.swift
+++ b/Source/UsergridSessionDelegate.swift
@@ -28,63 +28,63 @@
final class UsergridSessionDelegate: NSObject {
- private var requestDelegates: [Int:UsergridAssetRequestWrapper] = [:]
+ fileprivate var requestDelegates: [Int:UsergridAssetRequestWrapper] = [:]
- func addRequestDelegate(task:NSURLSessionTask,requestWrapper:UsergridAssetRequestWrapper) {
+ func addRequestDelegate(_ task:URLSessionTask,requestWrapper:UsergridAssetRequestWrapper) {
requestDelegates[task.taskIdentifier] = requestWrapper
}
- func removeRequestDelegate(task:NSURLSessionTask) {
+ func removeRequestDelegate(_ task:URLSessionTask) {
requestDelegates[task.taskIdentifier] = nil
}
}
-extension UsergridSessionDelegate : NSURLSessionTaskDelegate {
+extension UsergridSessionDelegate : URLSessionTaskDelegate {
- func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
+ func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let progressBlock = requestDelegates[task.taskIdentifier]?.progress {
- progressBlock(bytesFinished:totalBytesSent, bytesExpected: totalBytesExpectedToSend)
+ progressBlock(totalBytesSent, totalBytesExpectedToSend)
}
}
- func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let requestWrapper = requestDelegates[task.taskIdentifier] {
- requestWrapper.error = error
- requestWrapper.completion(requestWrapper: requestWrapper)
+ requestWrapper.error = error as? NSError // WTF
+ requestWrapper.completion(requestWrapper)
}
self.removeRequestDelegate(task)
}
}
-extension UsergridSessionDelegate : NSURLSessionDataDelegate {
+extension UsergridSessionDelegate : URLSessionDataDelegate {
- func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
+ public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void) {
if let requestWrapper = requestDelegates[dataTask.taskIdentifier] {
requestWrapper.response = response
}
- completionHandler(NSURLSessionResponseDisposition.Allow)
+ completionHandler(Foundation.URLSession.ResponseDisposition.allow)
}
- func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
+ public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let requestWrapper = requestDelegates[dataTask.taskIdentifier] {
- let mutableData = requestWrapper.responseData != nil ? NSMutableData(data: requestWrapper.responseData!) : NSMutableData()
- mutableData.appendData(data)
+ var mutableData = requestWrapper.responseData != nil ? (NSMutableData(data: requestWrapper.responseData!) as Data) : Data()
+ mutableData.append(data)
requestWrapper.responseData = mutableData
}
}
}
-extension UsergridSessionDelegate : NSURLSessionDownloadDelegate {
+extension UsergridSessionDelegate : URLSessionDownloadDelegate {
- func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let progressBlock = requestDelegates[downloadTask.taskIdentifier]?.progress {
- progressBlock(bytesFinished:totalBytesWritten, bytesExpected: totalBytesExpectedToWrite)
+ progressBlock(totalBytesWritten, totalBytesExpectedToWrite)
}
}
- func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let requestWrapper = requestDelegates[downloadTask.taskIdentifier] {
- requestWrapper.responseData = NSData(contentsOfURL: location)!
+ requestWrapper.responseData = try! Data(contentsOf: location)
}
}
-}
\ No newline at end of file
+}
diff --git a/Source/UsergridUser.swift b/Source/UsergridUser.swift
index 17415ba..f01430b 100644
--- a/Source/UsergridUser.swift
+++ b/Source/UsergridUser.swift
@@ -27,10 +27,10 @@
import Foundation
/// The completion block used for checking email and/or username availablity for new `UsergridUser` objects.
-public typealias UsergridUserAvailabilityCompletion = (error: UsergridResponseError?, available:Bool) -> Void
+public typealias UsergridUserAvailabilityCompletion = (_ error: UsergridResponseError?, _ available:Bool) -> Void
/// The completion block used for changing the password of `UsergridUser` objects.
-public typealias UsergridUserResetPasswordCompletion = (error: UsergridResponseError?, didSucceed:Bool) -> Void
+public typealias UsergridUserResetPasswordCompletion = (_ error: UsergridResponseError?, _ didSucceed:Bool) -> Void
/**
`UsergridUser` is a special subclass of `UsergridEntity` that supports functions and properties unique to users.
@@ -50,32 +50,32 @@
Unlike `UsergridEntity` objects, `UsergridUser`'s can change their name property which is why we provide a getter here.
*/
override public var name: String? {
- set(name) { self[UsergridUserProperties.Name.stringValue] = name }
+ set(name) { self[UsergridUserProperties.name.stringValue] = name }
get{ return super.name }
}
/// Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Username`.
public var username: String? {
- set(username) { self[UsergridUserProperties.Username.stringValue] = username }
- get { return self.getUserSpecificProperty(.Username) as? String }
+ set(username) { self[UsergridUserProperties.username.stringValue] = username }
+ get { return self.getUserSpecificProperty(.username) as? String }
}
/// Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Password`.
public var password: String? {
- set(password) { self[UsergridUserProperties.Password.stringValue] = password }
- get { return self.getUserSpecificProperty(.Password) as? String }
+ set(password) { self[UsergridUserProperties.password.stringValue] = password }
+ get { return self.getUserSpecificProperty(.password) as? String }
}
/// Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Email`.
public var email: String? {
- set(email) { self[UsergridUserProperties.Email.stringValue] = email }
- get { return self.getUserSpecificProperty(.Email) as? String }
+ set(email) { self[UsergridUserProperties.email.stringValue] = email }
+ get { return self.getUserSpecificProperty(.email) as? String }
}
/// Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Age`.
public var age: NSNumber? {
- set(age) { self[UsergridUserProperties.Age.stringValue] = age }
- get { return self.getUserSpecificProperty(.Age) as? NSNumber }
+ set(age) { self[UsergridUserProperties.age.stringValue] = age }
+ get { return self.getUserSpecificProperty(.age) as? NSNumber }
}
/// Property helper method to get the username or email of the `UsergridUser`.
@@ -87,14 +87,14 @@
Indicates whether the user account has been activated or not.
*/
public var activated: Bool {
- set(activated) { self[UsergridUserProperties.Activated.stringValue] = activated }
- get { return self.getUserSpecificProperty(.Activated) as? Bool ?? false }
+ set(activated) { self[UsergridUserProperties.activated.stringValue] = activated }
+ get { return self.getUserSpecificProperty(.activated) as? Bool ?? false }
}
/// Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Disabled`.
public var disabled: Bool {
- set(disabled) { self[UsergridUserProperties.Disabled.stringValue] = disabled }
- get { return self.getUserSpecificProperty(.Disabled) as? Bool ?? false }
+ set(disabled) { self[UsergridUserProperties.disabled.stringValue] = disabled }
+ get { return self.getUserSpecificProperty(.disabled) as? Bool ?? false }
}
/**
@@ -103,8 +103,8 @@
URL path to user’s profile picture. Defaults to Gravatar for email address.
*/
public var picture: String? {
- set(picture) { self[UsergridUserProperties.Picture.stringValue] = picture }
- get { return self.getUserSpecificProperty(.Picture) as? String }
+ set(picture) { self[UsergridUserProperties.picture.stringValue] = picture }
+ get { return self.getUserSpecificProperty(.picture) as? String }
}
/// The UUID or username property value if found.
@@ -132,7 +132,7 @@
- returns: A new `UsergridUser` object.
*/
- required public init(type: String, name: String?, propertyDict: [String : AnyObject]?) {
+ required public init(type: String, name: String?, propertyDict: [String : Any]?) {
super.init(type: type, name: name, propertyDict: propertyDict)
}
@@ -144,7 +144,7 @@
- returns: A new instance of `UsergridUser`.
*/
- public init(name:String,propertyDict:[String:AnyObject]? = nil) {
+ public init(name:String,propertyDict:[String:Any]? = nil) {
super.init(type: UsergridUser.USER_ENTITY_TYPE, name:name, propertyDict:propertyDict)
}
@@ -225,7 +225,7 @@
- returns: A decoded `UsergridUser` object.
*/
required public init?(coder aDecoder: NSCoder) {
- self.auth = aDecoder.decodeObjectForKey("auth") as? UsergridUserAuth
+ self.auth = aDecoder.decodeObject(forKey: "auth") as? UsergridUserAuth
super.init(coder: aDecoder)
}
@@ -234,9 +234,9 @@
- parameter aCoder: The encoder.
*/
- public override func encodeWithCoder(aCoder: NSCoder) {
- aCoder.encodeObject(self.auth, forKey: "auth")
- super.encodeWithCoder(aCoder)
+ public override func encode(with aCoder: NSCoder) {
+ aCoder.encode(self.auth, forKey: "auth")
+ super.encode(with: aCoder)
}
// MARK: - Class Methods -
@@ -248,7 +248,7 @@
- parameter username: The optional username.
- parameter completion: The completion block.
*/
- public static func checkAvailable(email:String?, username:String?, completion:UsergridUserAvailabilityCompletion) {
+ public static func checkAvailable(_ email:String?, username:String?, completion:UsergridUserAvailabilityCompletion) {
self.checkAvailable(Usergrid.sharedInstance, email: email, username: username, completion: completion)
}
@@ -260,16 +260,16 @@
- parameter username: The optional username.
- parameter completion: The completion block.
*/
- public static func checkAvailable(client: UsergridClient, email:String?, username:String?, completion:UsergridUserAvailabilityCompletion) {
+ public static func checkAvailable(_ client: UsergridClient, email:String?, username:String?, completion:UsergridUserAvailabilityCompletion) {
let query = UsergridQuery(USER_ENTITY_TYPE)
if let emailValue = email {
- query.eq(UsergridUserProperties.Email.stringValue, value: emailValue)
+ query.eq(UsergridUserProperties.email.stringValue, value: emailValue)
}
if let usernameValue = username {
- query.or().eq(UsergridUserProperties.Username.stringValue, value: usernameValue)
+ query.or().eq(UsergridUserProperties.username.stringValue, value: usernameValue)
}
client.GET(query) { (response) -> Void in
- completion(error: response.error, available: response.entity == nil)
+ completion(response.error, response.entity == nil)
}
}
@@ -280,7 +280,7 @@
- parameter completion: The optional completion block.
*/
- public func create(completion: UsergridResponseCompletion? = nil) {
+ public func create(_ completion: UsergridResponseCompletion? = nil) {
self.create(Usergrid.sharedInstance, completion: completion)
}
@@ -290,12 +290,12 @@
- parameter client: The client to use for creation.
- parameter completion: The optional completion block.
*/
- public func create(client: UsergridClient, completion: UsergridResponseCompletion? = nil) {
+ public func create(_ client: UsergridClient, completion: UsergridResponseCompletion? = nil) {
client.POST(self) { (response) -> Void in
if response.ok, let createdUser = response.user {
self.copyInternalsFromEntity(createdUser)
}
- completion?(response: response)
+ completion?(response)
}
}
@@ -308,7 +308,7 @@
- parameter password: The password.
- parameter completion: The optional completion block.
*/
- public func login(username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public func login(_ username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) {
self.login(Usergrid.sharedInstance, username: username, password: password, completion: completion)
}
@@ -322,11 +322,11 @@
- parameter password: The password.
- parameter completion: The optional completion block.
*/
- public func login(client: UsergridClient, username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public func login(_ client: UsergridClient, username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) {
let userAuth = UsergridUserAuth(username: username, password: password)
client.authenticateUser(userAuth,setAsCurrentUser:false) { (auth, user, error) -> Void in
self.auth = userAuth
- completion?(auth: userAuth, user: user, error: error)
+ completion?(userAuth, user, error)
}
}
@@ -337,7 +337,7 @@
- parameter new: The new password.
- parameter completion: The optional completion block.
*/
- public func resetPassword(old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
+ public func resetPassword(_ old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
self.resetPassword(Usergrid.sharedInstance, old: old, new: new, completion: completion)
}
@@ -349,7 +349,7 @@
- parameter new: The new password.
- parameter completion: The optional completion block
*/
- public func resetPassword(client: UsergridClient, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
+ public func resetPassword(_ client: UsergridClient, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
client.resetPassword(self, old: old, new: new, completion: completion)
}
@@ -358,7 +358,7 @@
- parameter completion: The optional completion block.
*/
- public func reauthenticate(completion: UsergridUserAuthCompletionBlock? = nil) {
+ public func reauthenticate(_ completion: UsergridUserAuthCompletionBlock? = nil) {
self.reauthenticate(Usergrid.sharedInstance, completion: completion)
}
@@ -368,10 +368,10 @@
- parameter client: The client to use for reauthentication.
- parameter completion: The optional completion block.
*/
- public func reauthenticate(client: UsergridClient, completion: UsergridUserAuthCompletionBlock? = nil) {
+ public func reauthenticate(_ client: UsergridClient, completion: UsergridUserAuthCompletionBlock? = nil) {
guard let userAuth = self.auth
else {
- completion?(auth: nil, user: self, error: UsergridResponseError(errorName: "Invalid UsergridUserAuth.", errorDescription: "No UsergridUserAuth found on the UsergridUser."))
+ completion?(nil, self, UsergridResponseError(errorName: "Invalid UsergridUserAuth.", errorDescription: "No UsergridUserAuth found on the UsergridUser."))
return
}
@@ -383,7 +383,7 @@
- parameter completion: The optional completion block.
*/
- public func logout(completion:UsergridResponseCompletion? = nil) {
+ public func logout(_ completion:UsergridResponseCompletion? = nil) {
self.logout(Usergrid.sharedInstance,completion:completion)
}
@@ -393,17 +393,17 @@
- parameter client: The client to use for logout.
- parameter completion: The optional completion block.
*/
- public func logout(client: UsergridClient, completion:UsergridResponseCompletion? = nil) {
+ public func logout(_ client: UsergridClient, completion:UsergridResponseCompletion? = nil) {
guard let uuidOrUsername = self.uuidOrUsername,
let accessToken = self.auth?.accessToken
else {
- completion?(response: UsergridResponse(client:client, errorName:"Logout Failed.", errorDescription:"UUID or Access Token not found on UsergridUser object."))
+ completion?(UsergridResponse(client:client, errorName:"Logout Failed.", errorDescription:"UUID or Access Token not found on UsergridUser object."))
return
}
client.logoutUser(uuidOrUsername, token: accessToken) { (response) in
self.auth = nil
- completion?(response: response)
+ completion?(response)
}
}
@@ -413,7 +413,7 @@
- parameter device: The device to connect to. If nil it will use the `UsergridDevice.sharedDevice` instance.
- parameter completion: The optional completion block.
*/
- public func connectToDevice(device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func connectToDevice(_ device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
self.connectToDevice(Usergrid.sharedInstance, device: device, completion: completion)
}
@@ -424,11 +424,11 @@
- parameter device: The device to connect to. If nil it will use the `UsergridDevice.sharedDevice` instance.
- parameter completion: The optional completion block.
*/
- public func connectToDevice(client:UsergridClient, device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func connectToDevice(_ client:UsergridClient, device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
let deviceToConnect = device ?? UsergridDevice.sharedDevice
guard let _ = deviceToConnect.uuidOrName
else {
- completion?(response: UsergridResponse(client: client, errorName: "Device cannot be connected to User.", errorDescription: "Device has neither an UUID or name specified."))
+ completion?(UsergridResponse(client: client, errorName: "Device cannot be connected to User.", errorDescription: "Device has neither an UUID or name specified."))
return
}
@@ -440,7 +440,7 @@
- parameter completion: The optional completion block.
*/
- public func getConnectedDevice(completion:UsergridResponseCompletion? = nil) {
+ public func getConnectedDevice(_ completion:UsergridResponseCompletion? = nil) {
self.getConnectedDevice(Usergrid.sharedInstance, completion: completion)
}
@@ -450,8 +450,8 @@
- parameter client: The `UsergridClient` object to use for connecting.
- parameter completion: The optional completion block.
*/
- public func getConnectedDevice(client:UsergridClient, completion:UsergridResponseCompletion? = nil) {
- client.getConnections(.Out, entity: self, relationship: "device", completion: completion)
+ public func getConnectedDevice(_ client:UsergridClient, completion:UsergridResponseCompletion? = nil) {
+ client.getConnections(.out, entity: self, relationship: "device", completion: completion)
}
/**
@@ -460,7 +460,7 @@
- parameter device: The device to connect to. If nil it will use the `UsergridDevice.sharedDevice` instance.
- parameter completion: The optional completion block.
*/
- public func disconnectFromDevice(device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func disconnectFromDevice(_ device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
self.disconnectFromDevice(Usergrid.sharedInstance, device: device, completion: completion)
}
@@ -471,26 +471,25 @@
- parameter device: The device to connect to.
- parameter completion: The optional completion block.
*/
- public func disconnectFromDevice(client:UsergridClient, device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
+ public func disconnectFromDevice(_ client:UsergridClient, device:UsergridDevice? = nil, completion:UsergridResponseCompletion? = nil) {
let deviceToDisconnectFrom = device ?? UsergridDevice.sharedDevice
guard let _ = deviceToDisconnectFrom.uuidOrName
else {
- completion?(response: UsergridResponse(client: client, errorName: "Device cannot be disconnected from User.", errorDescription: "Device has neither an UUID or name specified."))
+ completion?(UsergridResponse(client: client, errorName: "Device cannot be disconnected from User.", errorDescription: "Device has neither an UUID or name specified."))
return
}
self.disconnect(client, relationship: "", fromEntity: deviceToDisconnectFrom, completion: completion)
}
- private func getUserSpecificProperty(userProperty: UsergridUserProperties) -> AnyObject? {
- var propertyValue: AnyObject? = super[userProperty.stringValue]
- NSJSONReadingOptions.AllowFragments
+ private func getUserSpecificProperty(_ userProperty: UsergridUserProperties) -> Any? {
+ var propertyValue: Any? = super[userProperty.stringValue]
switch userProperty {
- case .Activated,.Disabled :
- propertyValue = propertyValue?.boolValue
- case .Age :
- propertyValue = propertyValue?.integerValue
- case .Name,.Username,.Password,.Email,.Picture :
+ case .activated,.disabled :
+ propertyValue = (propertyValue as AnyObject) as? Bool ?? false
+ case .age :
+ propertyValue = (propertyValue as AnyObject) as? Int ?? 0 // TODO: Check these conversions
+ case .name,.username,.password,.email,.picture :
break
}
return propertyValue
@@ -508,7 +507,7 @@
usergridUser["name"] = someName
```
*/
- override public subscript(propertyName: String) -> AnyObject? {
+ override public subscript(propertyName: String) -> Any? {
get {
if let userProperty = UsergridUserProperties.fromString(propertyName) {
return self.getUserSpecificProperty(userProperty)
@@ -520,4 +519,4 @@
super[propertyName] = propertyValue
}
}
-}
\ No newline at end of file
+}
diff --git a/Tests/ASSET_Tests.swift b/Tests/ASSET_Tests.swift
index a8c8344..0bbeb92 100644
--- a/Tests/ASSET_Tests.swift
+++ b/Tests/ASSET_Tests.swift
@@ -25,6 +25,7 @@
*/
import XCTest
+import Foundation
@testable import UsergridSDK
class ASSET_Tests: XCTestCase {
@@ -46,8 +47,8 @@
super.tearDown()
}
- func getFullPathOfFile(fileLocation:String) -> String {
- return (NSBundle(forClass: object_getClass(self)).resourcePath! as NSString).stringByAppendingPathComponent(fileLocation)
+ func getFullPathOfFile(_ fileLocation:String) -> String {
+ return (Bundle(for: object_getClass(self)).resourcePath!) + "/\(fileLocation)"
}
func test_ASSET_INIT() {
@@ -57,28 +58,28 @@
XCTAssertNotNil(asset)
XCTAssertNotNil(asset!.data)
XCTAssertNotNil(asset!.filename)
- XCTAssertEqual(asset!.contentType, UsergridImageContentType.Png.stringValue)
+ XCTAssertEqual(asset!.contentType, UsergridImageContentType.png.stringValue)
XCTAssertTrue(asset!.contentLength > 0)
- asset = UsergridAsset(filename:ASSET_Tests.imageName, fileURL: NSURL(fileURLWithPath: filePath))
+ asset = UsergridAsset(filename:ASSET_Tests.imageName, fileURL: URL(fileURLWithPath: filePath))
XCTAssertNotNil(asset)
XCTAssertNotNil(asset!.data)
XCTAssertNotNil(asset!.filename)
- XCTAssertEqual(asset!.contentType, UsergridImageContentType.Png.stringValue)
+ XCTAssertEqual(asset!.contentType, UsergridImageContentType.png.stringValue)
XCTAssertTrue(asset!.contentLength > 0)
filePath = self.getFullPathOfFile(ASSET_Tests.jpgLocation)
image = UIImage(contentsOfFile: filePath)
- asset = UsergridAsset(filename:nil,image: image!, imageContentType:.Jpeg)
+ asset = UsergridAsset(filename:nil,image: image!, imageContentType:.jpeg)
XCTAssertNotNil(asset)
XCTAssertNotNil(asset!.data)
XCTAssertEqual(asset!.filename,UsergridAsset.DEFAULT_FILE_NAME)
- XCTAssertEqual(asset!.contentType, UsergridImageContentType.Jpeg.stringValue)
+ XCTAssertEqual(asset!.contentType, UsergridImageContentType.jpeg.stringValue)
XCTAssertTrue(asset!.contentLength > 0)
}
func test_IMAGE_UPLOAD() {
- let getExpect = self.expectationWithDescription("\(#function)")
+ let getExpect = self.expectation(description: "\(#function)")
let uploadProgress : UsergridAssetRequestProgress = { (bytes,expected) in
print("UPLOAD PROGRESS BLOCK: BYTES:\(bytes) --- EXPECTED:\(expected)")
}
@@ -87,7 +88,7 @@
}
Usergrid.GET(ASSET_Tests.collectionName, uuidOrName:ASSET_Tests.entityUUID) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
let entity = response.first!
XCTAssertNotNil(entity)
@@ -103,7 +104,7 @@
XCTAssertNotNil(asset)
entity.uploadAsset(asset!, progress:uploadProgress) { uploadedAsset,response in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(response.ok)
XCTAssertNil(response.error)
@@ -120,9 +121,9 @@
XCTAssertEqual(entity.asset!.contentLength, entity.fileMetaData!.contentLength)
XCTAssertEqual(entity.asset!.contentType, entity.fileMetaData!.contentType)
- entity.downloadAsset(UsergridImageContentType.Png.stringValue, progress:downloadProgress)
+ entity.downloadAsset(UsergridImageContentType.png.stringValue, progress:downloadProgress)
{ (downloadedAsset, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(downloadedAsset)
XCTAssertNil(error)
let downloadedImage = UIImage(data: downloadedAsset!.data)
@@ -132,12 +133,12 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
- func deleteUser(user:UsergridUser,expectation:XCTestExpectation) {
+ func deleteUser(_ user:UsergridUser,expectation:XCTestExpectation) {
user.remove() { removeResponse in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(removeResponse)
XCTAssertTrue(removeResponse.ok)
XCTAssertNotNil(removeResponse.user)
@@ -148,7 +149,7 @@
}
func test_ATTACH_ASSET_TO_CURRENT_USER() {
- let userAssetExpect = self.expectationWithDescription("\(#function)")
+ let userAssetExpect = self.expectation(description: "\(#function)")
let user = UsergridUser(name:User_Tests.name, email:User_Tests.email, username:User_Tests.username, password:User_Tests.password)
let uploadProgress : UsergridAssetRequestProgress = { (bytes,expected) in
@@ -160,12 +161,12 @@
UsergridUser.checkAvailable(user.email, username: user.username) { error,available in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertTrue(available)
user.create() { (createResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(createResponse)
XCTAssertTrue(createResponse.ok)
XCTAssertNotNil(createResponse.user)
@@ -173,14 +174,14 @@
XCTAssertNotNil(user.uuid)
user.login(user.username!, password:User_Tests.password) { (auth, loggedInUser, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertNotNil(loggedInUser)
XCTAssertEqual(auth, user.auth!)
Usergrid.authenticateUser(user.auth!) { auth,currentUser,error in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertEqual(auth, user.auth!)
@@ -199,7 +200,7 @@
XCTAssertNotNil(asset)
Usergrid.currentUser!.uploadAsset(asset!, progress:uploadProgress) { uploadedAsset,response in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(response.ok)
XCTAssertNil(response.error)
@@ -216,9 +217,9 @@
XCTAssertEqual(Usergrid.currentUser!.asset!.contentLength, Usergrid.currentUser!.fileMetaData!.contentLength)
XCTAssertEqual(Usergrid.currentUser!.asset!.contentType, Usergrid.currentUser!.fileMetaData!.contentType)
- Usergrid.currentUser!.downloadAsset(UsergridImageContentType.Png.stringValue, progress:downloadProgress)
+ Usergrid.currentUser!.downloadAsset(UsergridImageContentType.png.stringValue, progress:downloadProgress)
{ (downloadedAsset, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(downloadedAsset)
XCTAssertNil(error)
let downloadedImage = UIImage(data: downloadedAsset!.data)
@@ -231,7 +232,7 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
@@ -240,12 +241,12 @@
"etag":"dfa7421ea4f35d33e12ba93979a46b7e",
"checkSum":"dfa7421ea4f35d33e12ba93979a46b7e",
"content-length":1417896,
- "last-modified":Int(NSDate().timeIntervalSince1970 * Double(1000))]
+ "last-modified":Int(Date().timeIntervalSince1970 * Double(1000))] as [String : Any]
- let fileMetaData = UsergridFileMetaData(fileMetaDataJSON:fileMetaDataDict as! [String : AnyObject])
+ let fileMetaData = UsergridFileMetaData(fileMetaDataJSON:fileMetaDataDict)
- let fileMetaDataCodingData = NSKeyedArchiver.archivedDataWithRootObject(fileMetaData)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(fileMetaDataCodingData) as? UsergridFileMetaData
+ let fileMetaDataCodingData = NSKeyedArchiver.archivedData(withRootObject: fileMetaData)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: fileMetaDataCodingData) as? UsergridFileMetaData
XCTAssertNotNil(newInstanceFromData)
if let newInstance = newInstanceFromData {
@@ -259,12 +260,12 @@
func test_ASSET_NSCODING() {
let imagePath = self.getFullPathOfFile(ASSET_Tests.pngLocation)
- let asset = UsergridAsset(filename:ASSET_Tests.imageName,fileURL: NSURL(fileURLWithPath: imagePath))
+ let asset = UsergridAsset(filename:ASSET_Tests.imageName,fileURL: URL(fileURLWithPath: imagePath))
XCTAssertNotNil(asset)
if let originalAsset = asset {
- let assetCodingData = NSKeyedArchiver.archivedDataWithRootObject(originalAsset)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(assetCodingData) as? UsergridAsset
+ let assetCodingData = NSKeyedArchiver.archivedData(withRootObject: originalAsset)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: assetCodingData) as? UsergridAsset
XCTAssertNotNil(newInstanceFromData)
diff --git a/Tests/AUTH_Tests.swift b/Tests/AUTH_Tests.swift
index 80ec695..d77bcae 100644
--- a/Tests/AUTH_Tests.swift
+++ b/Tests/AUTH_Tests.swift
@@ -32,8 +32,8 @@
var appAuth: UsergridAppAuth!
var userAuth: UsergridUserAuth!
- private static let collectionName = "publicevent"
- private static let entityUUID = "fa015eaa-fe1c-11e3-b94b-63b29addea01"
+ fileprivate static let collectionName = "publicevent"
+ fileprivate static let entityUUID = "fa015eaa-fe1c-11e3-b94b-63b29addea01"
override func setUp() {
super.setUp()
@@ -49,10 +49,10 @@
func test_CLIENT_AUTH() {
- let authExpect = self.expectationWithDescription("\(#function)")
- Usergrid.authMode = .App
+ let authExpect = self.expectation(description: "\(#function)")
+ Usergrid.authMode = .app
Usergrid.authenticateApp(appAuth) { auth,error in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(Usergrid.appAuth)
@@ -63,7 +63,7 @@
XCTAssertNotNil(appAuth.isValid)
Usergrid.GET(AUTH_Tests.collectionName) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.hasNextPage)
XCTAssertEqual(response.entities!.count, 10)
@@ -73,7 +73,7 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_DESTROY_AUTH() {
@@ -93,10 +93,10 @@
func test_APP_AUTH_NSCODING() {
appAuth.accessToken = "YWMt91Q2YtWaEeW_Ki2uDueMEwAAAVMUTVSPeOdX-oradxdqirEFz5cPU3GWybs"
- appAuth.expiry = NSDate.distantFuture()
+ appAuth.expiry = Date.distantFuture
- let authCodingData = NSKeyedArchiver.archivedDataWithRootObject(appAuth)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(authCodingData) as? UsergridAppAuth
+ let authCodingData = NSKeyedArchiver.archivedData(withRootObject: appAuth)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: authCodingData) as? UsergridAppAuth
XCTAssertNotNil(newInstanceFromData)
@@ -112,10 +112,10 @@
func test_USER_AUTH_NSCODING() {
userAuth.accessToken = "YWMt91Q2YtWaEeW_Ki2uDueMEwAAAVMUTVSPeOdX-oradxdqirEFz5cPU3GWybs"
- userAuth.expiry = NSDate.distantFuture()
+ userAuth.expiry = Date.distantFuture
- let authCodingData = NSKeyedArchiver.archivedDataWithRootObject(userAuth)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(authCodingData) as? UsergridUserAuth
+ let authCodingData = NSKeyedArchiver.archivedData(withRootObject: userAuth)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: authCodingData) as? UsergridUserAuth
XCTAssertNotNil(newInstanceFromData)
diff --git a/Tests/CONNECTION_Tests.swift b/Tests/CONNECTION_Tests.swift
index 2640778..e824088 100644
--- a/Tests/CONNECTION_Tests.swift
+++ b/Tests/CONNECTION_Tests.swift
@@ -30,7 +30,7 @@
class CONNECTION_Tests: XCTestCase {
let clientAuth = UsergridAppAuth(clientId: "b3U6THNcevskEeOQZLcUROUUVA", clientSecret: "b3U6RZHYznP28xieBzQPackFPmmnevU")
- private static let collectionName = "publicevent"
+ fileprivate static let collectionName = "publicevent"
override func setUp() {
super.setUp()
@@ -44,10 +44,10 @@
func test_CLIENT_AUTH() {
- let authExpect = self.expectationWithDescription("\(#function)")
- Usergrid.authMode = .App
+ let authExpect = self.expectation(description: "\(#function)")
+ Usergrid.authMode = .app
Usergrid.authenticateApp(clientAuth) { auth,error in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(Usergrid.appAuth)
@@ -57,7 +57,7 @@
XCTAssertNotNil(appAuth.expiry)
Usergrid.GET(CONNECTION_Tests.collectionName) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertTrue(response.hasNextPage)
@@ -68,12 +68,12 @@
XCTAssertEqual(entity.type, CONNECTION_Tests.collectionName)
entity.connect("likes", toEntity: entityToConnect) { (response) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
- entity.getConnections(.Out, relationship: "likes", query:nil) { (response) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ entity.getConnections(.out, relationship: "likes", query:nil) { (response) -> Void in
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
@@ -82,12 +82,12 @@
XCTAssertEqual(connectedEntity.uuidOrName, entityToConnect.uuidOrName)
entity.disconnect("likes", fromEntity: connectedEntity) { (response) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
- entity.getConnections(.Out, relationship: "likes", query:nil) { (response) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ entity.getConnections(.out, relationship: "likes", query:nil) { (response) -> Void in
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
authExpect.fulfill()
@@ -100,6 +100,6 @@
authExpect.fulfill()
}
}
- self.waitForExpectationsWithTimeout(20, handler: nil)
+ self.waitForExpectations(timeout: 20, handler: nil)
}
}
diff --git a/Tests/ClientCreationTests.swift b/Tests/ClientCreationTests.swift
index 40a7de1..6776cb4 100644
--- a/Tests/ClientCreationTests.swift
+++ b/Tests/ClientCreationTests.swift
@@ -50,7 +50,7 @@
func test_CLIENT_PROPERTIES() {
XCTAssertEqual(Usergrid.appId, ClientCreationTests.appId)
XCTAssertEqual(Usergrid.orgId, ClientCreationTests.orgId)
- XCTAssertEqual(Usergrid.authMode, UsergridAuthMode.User)
+ XCTAssertEqual(Usergrid.authMode, UsergridAuthMode.user)
XCTAssertEqual(Usergrid.persistCurrentUserInKeychain, false)
XCTAssertEqual(Usergrid.baseUrl, UsergridClient.DEFAULT_BASE_URL)
XCTAssertEqual(Usergrid.clientAppURL, "\(UsergridClient.DEFAULT_BASE_URL)/\(ClientCreationTests.orgId)/\(ClientCreationTests.appId)" )
@@ -59,8 +59,8 @@
}
func test_CLIENT_NSCODING() {
- let sharedInstanceAsData = NSKeyedArchiver.archivedDataWithRootObject(Usergrid.sharedInstance)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(sharedInstanceAsData) as? UsergridClient
+ let sharedInstanceAsData = NSKeyedArchiver.archivedData(withRootObject: Usergrid.sharedInstance)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: sharedInstanceAsData) as? UsergridClient
XCTAssertNotNil(newInstanceFromData)
diff --git a/Tests/GET_Tests.swift b/Tests/GET_Tests.swift
index 76ca828..b6698e5 100644
--- a/Tests/GET_Tests.swift
+++ b/Tests/GET_Tests.swift
@@ -46,36 +46,36 @@
func test_GET_WITHOUT_QUERY() {
- let getExpect = self.expectationWithDescription("\(#function)")
+ let getExpect = self.expectation(description: "\(#function)")
Usergrid.GET(GET_Tests.collectionName) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertTrue(response.hasNextPage)
XCTAssertEqual(response.count, 10)
getExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
func test_GET_WITH_QUERY() {
- let getExpect = self.expectationWithDescription("\(#function)")
+ let getExpect = self.expectation(description: "\(#function)")
Usergrid.GET(self.query) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertEqual(response.count, 1)
getExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
func test_GET_WITH_UUID() {
- let getExpect = self.expectationWithDescription("\(#function)")
+ let getExpect = self.expectation(description: "\(#function)")
Usergrid.GET(GET_Tests.collectionName, uuidOrName:GET_Tests.entityUUID) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
let entity = response.first!
@@ -85,29 +85,29 @@
XCTAssertEqual(entity.uuid!, GET_Tests.entityUUID)
getExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
func test_GET_NEXT_PAGE_WITH_NO_QUERY() {
- let getExpect = self.expectationWithDescription("\(#function)")
+ let getExpect = self.expectation(description: "\(#function)")
Usergrid.GET(GET_Tests.collectionName) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertTrue(response.hasNextPage)
XCTAssertEqual(response.count, 10)
response.loadNextPage() { (nextPageResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(nextPageResponse.ok)
XCTAssertNotNil(nextPageResponse)
- XCTAssertTrue(nextPageResponse.hasNextPage)
+ XCTAssertFalse(!nextPageResponse.hasNextPage)
XCTAssertEqual(nextPageResponse.entities!.count, 10)
getExpect.fulfill()
}
}
- self.waitForExpectationsWithTimeout(20, handler: nil)
+ self.waitForExpectations(timeout: 20, handler: nil)
}
}
diff --git a/Tests/PUT_Tests.swift b/Tests/PUT_Tests.swift
index b1ff3e7..ff67738 100644
--- a/Tests/PUT_Tests.swift
+++ b/Tests/PUT_Tests.swift
@@ -51,10 +51,10 @@
let propertyNameToUpdate = "\(#function)"
let propertiesNewValue = "\(propertyNameToUpdate)_VALUE"
- let putExpect = self.expectationWithDescription(propertyNameToUpdate)
+ let putExpect = self.expectation(description: propertyNameToUpdate)
Usergrid.PUT(PUT_Tests.collectionName, uuidOrName: PUT_Tests.entityUUID, jsonBody:[propertyNameToUpdate : propertiesNewValue]) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertEqual(response.entities!.count, 1)
@@ -68,19 +68,19 @@
XCTAssertEqual(updatedPropertyValue!,propertiesNewValue)
putExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
func test_PUT_BY_SPECIFYING_UUID_WITHIN_JSON_BODY() {
let propertyNameToUpdate = "\(#function)"
let propertiesNewValue = "\(propertyNameToUpdate)_VALUE"
- let putExpect = self.expectationWithDescription(propertyNameToUpdate)
+ let putExpect = self.expectation(description: propertyNameToUpdate)
- let jsonDictToPut = [UsergridEntityProperties.UUID.stringValue : PUT_Tests.entityUUID, propertyNameToUpdate : propertiesNewValue]
+ let jsonDictToPut = [UsergridEntityProperties.uuid.stringValue : PUT_Tests.entityUUID, propertyNameToUpdate : propertiesNewValue]
Usergrid.PUT(PUT_Tests.collectionName, jsonBody: jsonDictToPut) { (response) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertEqual(response.entities!.count, 1)
@@ -94,16 +94,16 @@
XCTAssertEqual(updatedPropertyValue!,propertiesNewValue)
putExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
func test_PUT_WITH_ENTITY_OBJECT() {
let propertyNameToUpdate = "\(#function)"
let propertiesNewValue = "\(propertyNameToUpdate)_VALUE"
- let putExpect = self.expectationWithDescription(propertyNameToUpdate)
+ let putExpect = self.expectation(description: propertyNameToUpdate)
Usergrid.GET(PUT_Tests.collectionName, uuidOrName: PUT_Tests.entityUUID) { (getResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(getResponse)
XCTAssertTrue(getResponse.ok)
XCTAssertEqual(getResponse.entities!.count, 1)
@@ -116,7 +116,7 @@
responseEntity[propertyNameToUpdate] = propertiesNewValue
Usergrid.PUT(responseEntity) { (putResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(putResponse)
XCTAssertTrue(putResponse.ok)
XCTAssertEqual(putResponse.entities!.count, 1)
@@ -131,16 +131,16 @@
putExpect.fulfill()
}
}
- self.waitForExpectationsWithTimeout(20, handler: nil)
+ self.waitForExpectations(timeout: 20, handler: nil)
}
func test_PUT_WITH_QUERY() {
let propertyNameToUpdate = "\(#function)"
let propertiesNewValue = "\(propertyNameToUpdate)_VALUE"
- let putExpect = self.expectationWithDescription(propertyNameToUpdate)
+ let putExpect = self.expectation(description: propertyNameToUpdate)
Usergrid.PUT(self.query, jsonBody: [propertyNameToUpdate : propertiesNewValue]) { (putResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(putResponse)
XCTAssertTrue(putResponse.ok)
XCTAssertEqual(putResponse.entities!.count, 1)
@@ -153,6 +153,6 @@
XCTAssertEqual(updatedPropertyValue!,propertiesNewValue)
putExpect.fulfill()
}
- self.waitForExpectationsWithTimeout(10, handler: nil)
+ self.waitForExpectations(timeout: 10, handler: nil)
}
}
diff --git a/Tests/User_Tests.swift b/Tests/User_Tests.swift
index dcb5545..aeea8c3 100644
--- a/Tests/User_Tests.swift
+++ b/Tests/User_Tests.swift
@@ -34,8 +34,8 @@
static let name = "Robert Walsh"
static let age = 29
- static let email = "handsomeRob741@yahoo.com"
- static let username = "rwalsh"
+ static let email = "handsomeRob741www@yahoo.com"
+ static let username = "rwalshwww"
static let password = "password"
static let resetPassword = "password111"
static let picture = "http://www.gravatar.com/avatar/e466d447df831ddce35fbc50763fb03a"
@@ -46,11 +46,13 @@
super.setUp()
Usergrid.initSharedInstance(orgId:ClientCreationTests.orgId, appId: ClientCreationTests.appId)
+ Usergrid.authMode = .user
Usergrid.persistCurrentUserInKeychain = false
user = UsergridUser(name:"a_bogus_name", email:User_Tests.email, username:User_Tests.username, password:User_Tests.password)
user.name = User_Tests.name
- user.age = User_Tests.age
+ user.password = User_Tests.password
+ user.age = User_Tests.age as NSNumber
user.location = CLLocation(latitude: -90, longitude: 100)
user.picture = User_Tests.picture
user.activated = User_Tests.activated
@@ -134,7 +136,7 @@
XCTAssertNil(user.uuid)
XCTAssertEqual(user.name!, User_Tests.name)
- XCTAssertEqual(user.age!, User_Tests.age)
+ XCTAssertEqual(user.age!, User_Tests.age as NSNumber)
XCTAssertEqual(user.username!, User_Tests.username)
XCTAssertEqual(user.email!, User_Tests.email)
XCTAssertEqual(user.password!, User_Tests.password)
@@ -144,19 +146,19 @@
}
func test_USER_PROPERTIES_WITHOUT_HELPERS() {
- XCTAssertEqual(user[UsergridUserProperties.Name.stringValue]! as? String, User_Tests.name)
- XCTAssertEqual(user[UsergridUserProperties.Age.stringValue]! as? Int, User_Tests.age)
- XCTAssertEqual(user[UsergridUserProperties.Username.stringValue]! as? String, User_Tests.username)
- XCTAssertEqual(user[UsergridUserProperties.Email.stringValue]! as? String, User_Tests.email)
- XCTAssertEqual(user[UsergridUserProperties.Password.stringValue]! as? String, User_Tests.password)
- XCTAssertEqual(user[UsergridUserProperties.Picture.stringValue]! as? String, User_Tests.picture)
- XCTAssertTrue(user[UsergridUserProperties.Activated.stringValue]! as! Bool)
- XCTAssertFalse(user[UsergridUserProperties.Disabled.stringValue]! as! Bool)
+ XCTAssertEqual(user[UsergridUserProperties.name.stringValue]! as? String, User_Tests.name)
+ XCTAssertEqual(user[UsergridUserProperties.age.stringValue]! as? Int, User_Tests.age)
+ XCTAssertEqual(user[UsergridUserProperties.username.stringValue]! as? String, User_Tests.username)
+ XCTAssertEqual(user[UsergridUserProperties.email.stringValue]! as? String, User_Tests.email)
+ XCTAssertEqual(user[UsergridUserProperties.password.stringValue]! as? String, User_Tests.password)
+ XCTAssertEqual(user[UsergridUserProperties.picture.stringValue]! as? String, User_Tests.picture)
+ XCTAssertTrue(user[UsergridUserProperties.activated.stringValue]! as! Bool)
+ XCTAssertFalse(user[UsergridUserProperties.disabled.stringValue]! as! Bool)
}
- func deleteUser(expectation:XCTestExpectation) {
+ func deleteUser(_ expectation:XCTestExpectation) {
self.user.remove() { removeResponse in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(removeResponse)
XCTAssertTrue(removeResponse.ok)
XCTAssertNotNil(removeResponse.user)
@@ -167,10 +169,10 @@
}
func test_CREATE_AND_DELETE_USER() {
- let userExpect = self.expectationWithDescription("\(#function)")
+ let userExpect = self.expectation(description: "\(#function)")
user.save() { (createResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(createResponse)
XCTAssertTrue(createResponse.ok)
XCTAssertNotNil(createResponse.user)
@@ -183,7 +185,7 @@
XCTAssertNotNil(createdUser.modified)
XCTAssertNotNil(createdUser.location)
XCTAssertEqual(createdUser.name!, User_Tests.name)
- XCTAssertEqual(createdUser.age!, User_Tests.age)
+ XCTAssertEqual(createdUser.age!.intValue, User_Tests.age)
XCTAssertEqual(createdUser.username!, User_Tests.username)
XCTAssertEqual(createdUser.email!, User_Tests.email)
XCTAssertEqual(createdUser.picture!, User_Tests.picture)
@@ -194,20 +196,22 @@
self.deleteUser(userExpect)
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_AUTHENTICATE_USER() {
- let userExpect = self.expectationWithDescription("\(#function)")
+ let userExpect = self.expectation(description: "\(#function)")
UsergridUser.checkAvailable(user.email, username: user.username) { error,available in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertTrue(available)
+// self.deleteUser(userExpect)
+
self.user.create() { (createResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(createResponse)
XCTAssertTrue(createResponse.ok)
XCTAssertNotNil(createResponse.user)
@@ -215,14 +219,14 @@
XCTAssertNotNil(self.user.uuid)
self.user.login(self.user.username!, password:User_Tests.password) { (auth, loggedInUser, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertNotNil(loggedInUser)
XCTAssertEqual(auth, self.user.auth!)
Usergrid.authenticateUser(self.user.auth!) { auth,currentUser,error in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertEqual(auth, self.user.auth!)
@@ -232,7 +236,7 @@
XCTAssertEqual(currentUser, Usergrid.currentUser!)
self.user.reauthenticate() { auth, reauthedUser, error in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertEqual(auth, self.user.auth!)
@@ -241,7 +245,7 @@
XCTAssertNotNil(Usergrid.currentUser)
self.user.logout() { response in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(response)
XCTAssertTrue(response.ok)
XCTAssertNil(response.error)
@@ -253,14 +257,14 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_RESET_USER_PASSWORD() {
- let userExpect = self.expectationWithDescription("\(#function)")
+ let userExpect = self.expectation(description: "\(#function)")
user.create() { (createResponse) in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(createResponse)
XCTAssertTrue(createResponse.ok)
XCTAssertNotNil(createResponse.user)
@@ -268,19 +272,19 @@
XCTAssertNotNil(self.user.uuid)
self.user.login(self.user.username!, password:User_Tests.password) { (auth, loggedInUser, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertNotNil(loggedInUser)
XCTAssertEqual(auth, self.user.auth!)
self.user.resetPassword(User_Tests.password, new: User_Tests.resetPassword) { error,didSucceed in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(didSucceed)
XCTAssertNil(error)
self.user.login(self.user.username!, password:User_Tests.resetPassword) { (auth, loggedInUser, error) -> Void in
- XCTAssertTrue(NSThread.isMainThread())
+ XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(error)
XCTAssertNotNil(auth)
XCTAssertNotNil(loggedInUser)
@@ -291,11 +295,11 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_DEVICE_CONNECTION() {
- let userExpect = self.expectationWithDescription("\(#function)")
+ let userExpect = self.expectation(description: "\(#function)")
user.create() { createResponse in
XCTAssertNotNil(createResponse)
@@ -329,11 +333,11 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_DEVICE_CONNECT_FAIL() {
- let userExpect = self.expectationWithDescription("\(#function)")
+ let userExpect = self.expectation(description: "\(#function)")
user.create() { createResponse in
XCTAssertNotNil(createResponse)
@@ -367,13 +371,13 @@
}
}
}
- self.waitForExpectationsWithTimeout(100, handler: nil)
+ self.waitForExpectations(timeout: 100, handler: nil)
}
func test_USER_NSCODING() {
- let userData = NSKeyedArchiver.archivedDataWithRootObject(user)
- let newInstanceFromData = NSKeyedUnarchiver.unarchiveObjectWithData(userData) as? UsergridUser
+ let userData = NSKeyedArchiver.archivedData(withRootObject: user)
+ let newInstanceFromData = NSKeyedUnarchiver.unarchiveObject(with: userData) as? UsergridUser
XCTAssertNotNil(newInstanceFromData)
@@ -396,4 +400,4 @@
XCTAssertEqual(user.hasAsset,newInstance.hasAsset)
}
}
-}
\ No newline at end of file
+}
diff --git a/UsergridSDK.xcodeproj/project.pbxproj b/UsergridSDK.xcodeproj/project.pbxproj
index 338835c..af92c89 100644
--- a/UsergridSDK.xcodeproj/project.pbxproj
+++ b/UsergridSDK.xcodeproj/project.pbxproj
@@ -498,23 +498,34 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0720;
- LastUpgradeCheck = 0720;
+ LastUpgradeCheck = 0800;
ORGANIZATIONNAME = "Apigee Inc.";
TargetAttributes = {
630A219E1C49BFFC008BE87F = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
630A21B71C49C473008BE87F = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
+ };
+ 6319202A1C48436500F99E86 = {
+ LastSwiftMigration = 0800;
};
6319204A1C49BC0700F99E86 = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
639B4BEA1C3DD6CF005E26E7 = {
CreatedOnToolsVersion = 7.2;
+ LastSwiftMigration = 0800;
};
63AF0E871BBC38FB009D4196 = {
CreatedOnToolsVersion = 7.0.1;
+ LastSwiftMigration = 0800;
+ };
+ 63EE60F11C406E1600AFC2CF = {
+ LastSwiftMigration = 0800;
};
};
};
@@ -777,6 +788,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-OSX-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -791,6 +803,8 @@
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-OSX-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -802,6 +816,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-iOS-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -813,6 +828,8 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-iOS-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -831,11 +848,13 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+ MACOSX_DEPLOYMENT_TARGET = 10.11;
PRODUCT_BUNDLE_IDENTIFIER = org.apache.usergrid.swift;
PRODUCT_NAME = UsergridSDK;
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -854,10 +873,13 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+ MACOSX_DEPLOYMENT_TARGET = 10.11;
PRODUCT_BUNDLE_IDENTIFIER = org.apache.usergrid.swift;
PRODUCT_NAME = UsergridSDK;
SDKROOT = macosx;
SKIP_INSTALL = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -869,8 +891,9 @@
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-TVOS-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 3;
- TVOS_DEPLOYMENT_TARGET = 9.2;
+ TVOS_DEPLOYMENT_TARGET = 10.0;
};
name = Debug;
};
@@ -882,8 +905,10 @@
PRODUCT_BUNDLE_IDENTIFIER = "org.apache.usergrid.swift-TVOS-Tests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 3;
- TVOS_DEPLOYMENT_TARGET = 9.2;
+ TVOS_DEPLOYMENT_TARGET = 10.0;
};
name = Release;
};
@@ -902,6 +927,7 @@
PRODUCT_NAME = UsergridSDK;
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 2.1;
};
@@ -922,6 +948,8 @@
PRODUCT_NAME = UsergridSDK;
SDKROOT = watchos;
SKIP_INSTALL = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 2.1;
};
@@ -1035,6 +1063,7 @@
PRODUCT_NAME = UsergridSDK;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -1054,6 +1083,8 @@
PRODUCT_BUNDLE_IDENTIFIER = org.apache.usergrid.swift;
PRODUCT_NAME = UsergridSDK;
SKIP_INSTALL = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -1074,6 +1105,7 @@
SDKROOT = appletvos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 3;
};
name = Debug;
@@ -1094,6 +1126,8 @@
PRODUCT_NAME = UsergridSDK;
SDKROOT = appletvos;
SKIP_INSTALL = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 3;
};
name = Release;
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK OSX.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK OSX.xcscheme
index 591624c..7cb7a01 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK OSX.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK OSX.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK iOS.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK iOS.xcscheme
index 2c81a49..87f3d97 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK iOS.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK iOS.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK tvOS.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK tvOS.xcscheme
index 0c2ae38..ed7fbc6 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK tvOS.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK tvOS.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK watchOS.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK watchOS.xcscheme
index 7ba8b2a..66d0592 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK watchOS.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK watchOS.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_OSX_Tests.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_OSX_Tests.xcscheme
index 4e01ef0..27f424a 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_OSX_Tests.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_OSX_Tests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_TVOS_Tests.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_TVOS_Tests.xcscheme
index bae88d1..ca1fb5e 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_TVOS_Tests.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_TVOS_Tests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_iOS_Tests.xcscheme b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_iOS_Tests.xcscheme
index a6ebb1d..95beda8 100644
--- a/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_iOS_Tests.xcscheme
+++ b/UsergridSDK.xcodeproj/xcshareddata/xcschemes/UsergridSDK_iOS_Tests.xcscheme
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
- LastUpgradeVersion = "0720"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"