You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by mr...@apache.org on 2016/09/01 23:52:09 UTC
[48/51] [partial] usergrid-swift git commit: Initial commit of
Usergrid Swift SDK.
http://git-wip-us.apache.org/repos/asf/usergrid-swift/blob/8283a6dd/Source/Usergrid.swift
----------------------------------------------------------------------
diff --git a/Source/Usergrid.swift b/Source/Usergrid.swift
new file mode 100644
index 0000000..063d361
--- /dev/null
+++ b/Source/Usergrid.swift
@@ -0,0 +1,637 @@
+//
+// Usergrid.swift
+// UsergridSDK
+//
+// Created by Robert Walsh on 7/21/15.
+//
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ *
+ */
+
+import Foundation
+
+/// The version number for the Usergrid Swift SDK.
+public let UsergridSDKVersion = "2.1.1"
+
+/**
+ The `Usergrid` class acts as a static shared instance manager for the `UsergridClient` class.
+
+ The methods and variables in this class are all static and therefore you will never need or want to initialize an instance of the `Usergrid` class.
+
+ Use of this class depends on initialization of the shared instance of the `UsergridClient` object. Because of this, before using any of the static methods
+ provided you will need to call one of the shared instance initialization methods. Failure to do so will result in failure from all methods.
+ */
+public class Usergrid: NSObject {
+
+ // MARK: - Static Variables -
+
+ internal static var _sharedClient : UsergridClient!
+
+ /// Used to determine if the shared instance of the `UsergridClient` has been initialized.
+ public static var isInitialized : Bool { return Usergrid._sharedClient != nil }
+
+ /**
+ A shared instance of `UsergridClient`, used by the `Usergrid` static methods and acts as the default `UsergridClient`
+ within the UsergridSDK library.
+
+ - Warning: You must call one of the `Usergrid.initSharedInstance` methods before this or any other `Usergrid` static methods are valid.
+ */
+ public static var sharedInstance : UsergridClient {
+ assert(Usergrid.isInitialized, "Usergrid shared instance is not initalized!")
+ return Usergrid._sharedClient
+ }
+
+ /// The application identifier the shared instance of `UsergridClient`.
+ public static var appId : String { return Usergrid.sharedInstance.appId }
+
+ /// The organization identifier of the shared instance of `UsergridClient`.
+ public static var orgId : String { return Usergrid.sharedInstance.orgId }
+
+ /// The base URL that all calls will be made with of the shared instance of `UsergridClient`.
+ public static var baseUrl : String { return Usergrid.sharedInstance.baseUrl }
+
+ /// The constructed URL string based on the `UsergridClient`'s baseUrl, orgId, and appId of the shared instance of `UsergridClient`.
+ public static var clientAppURL : String { return Usergrid.sharedInstance.clientAppURL }
+
+ /// The currently logged in `UsergridUser` of the shared instance of `UsergridClient`.
+ public static var currentUser: UsergridUser? { return Usergrid.sharedInstance.currentUser }
+
+ /// Whether or not the current user will be saved and restored from the keychain using the shared instance of `UsergridClient`.
+ public static var persistCurrentUserInKeychain: Bool {
+ get { return Usergrid.sharedInstance.persistCurrentUserInKeychain }
+ set(persist) { Usergrid.sharedInstance.persistCurrentUserInKeychain = persist }
+ }
+
+ /// The `UsergridUserAuth` which consists of the token information from the `currentUser` property of the shared instance of `UsergridClient`.
+ public static var userAuth: UsergridUserAuth? { return Usergrid.sharedInstance.userAuth }
+
+ /// The application level `UsergridAppAuth` object of the shared instance of `UsergridClient`.
+ public static var appAuth: UsergridAppAuth? {
+ get { return Usergrid.sharedInstance.appAuth }
+ set(auth) { Usergrid.sharedInstance.appAuth = auth }
+ }
+
+ /// The `UsergridAuthMode` value used to determine what type of token will be sent of the shared instance of `UsergridClient`, if any.
+ public static var authMode: UsergridAuthMode {
+ get { return Usergrid.sharedInstance.authMode }
+ set(mode) { Usergrid.sharedInstance.authMode = mode }
+ }
+
+ // MARK: - Initialization -
+
+ /**
+ Initializes the `Usergrid.sharedInstance` of `UsergridClient`.
+
+ - parameter orgId: The organization identifier.
+ - parameter appId: The application identifier.
+
+ - returns: The shared instance of `UsergridClient`.
+ */
+ public static func initSharedInstance(orgId orgId : String, appId: String) -> UsergridClient {
+ if !Usergrid.isInitialized {
+ Usergrid._sharedClient = UsergridClient(orgId: orgId, appId: appId)
+ } else {
+ print("The Usergrid shared instance was already initialized. All subsequent initialization attempts (including this) will be ignored.")
+ }
+ return Usergrid._sharedClient
+ }
+
+ /**
+ Initializes the `Usergrid.sharedInstance` of `UsergridClient`.
+
+ - parameter orgId: The organization identifier.
+ - parameter appId: The application identifier.
+ - parameter baseUrl: The base URL that all calls will be made with.
+
+ - returns: The shared instance of `UsergridClient`.
+ */
+ public static func initSharedInstance(orgId orgId : String, appId: String, baseUrl: String) -> UsergridClient {
+ if !Usergrid.isInitialized {
+ Usergrid._sharedClient = UsergridClient(orgId: orgId, appId: appId, baseUrl: baseUrl)
+ } else {
+ print("The Usergrid shared instance was already initialized. All subsequent initialization attempts (including this) will be ignored.")
+ }
+ return Usergrid._sharedClient
+ }
+
+ /**
+ Initializes the `Usergrid.sharedInstance` of `UsergridClient`.
+
+ - parameter configuration: The configuration for the client to be set up with.
+
+ - returns: The shared instance of `UsergridClient`.
+ */
+ public static func initSharedInstance(configuration configuration: UsergridClientConfig) -> UsergridClient {
+ if !Usergrid.isInitialized {
+ Usergrid._sharedClient = UsergridClient(configuration: configuration)
+ } else {
+ print("The Usergrid shared instance was already initialized. All subsequent initialization attempts (including this) will be ignored.")
+ }
+ return Usergrid._sharedClient
+ }
+
+ // MARK: - Push Notifications -
+
+ /**
+ Sets the push token for the given notifier ID and performs a PUT request to update the shared `UsergridDevice` instance using the shared instance of `UsergridCient`.
+
+ - parameter pushToken: The push token from Apple.
+ - parameter notifierID: The Usergrid notifier ID.
+ - parameter completion: The completion block.
+ */
+ public static func applyPushToken(pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ Usergrid.sharedInstance.applyPushToken(pushToken, notifierID: notifierID, completion: completion)
+ }
+
+ /**
+ Sets the push token for the given notifier ID and performs a PUT request to update the given `UsergridDevice` instance using the shared instance of `UsergridCient`.
+
+ - parameter device: The `UsergridDevice` object.
+ - parameter pushToken: The push token from Apple.
+ - parameter notifierID: The Usergrid notifier ID.
+ - parameter completion: The completion block.
+ */
+ public static func applyPushToken(device: UsergridDevice, pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) {
+ Usergrid.sharedInstance.applyPushToken(device, pushToken: pushToken, notifierID: notifierID, completion: completion)
+ }
+
+
+ // MARK: - Authorization -
+
+ /**
+ Sets the shared `UsergridClient`'s `tempAuth` property using the passed in `UsergridAuth`.
+
+ This will cause the next CRUD method performed by the client to use the `tempAuth` property once and will then reset.
+
+ - parameter auth: The `UsergridAuth` object to temporarily use for authentication.
+
+ - returns: The shared instance of `UsergridClient`
+ */
+ public static func usingAuth(auth:UsergridAuth) -> UsergridClient {
+ return Usergrid.sharedInstance.usingAuth(auth)
+ }
+
+ /**
+ Sets the shared `UsergridClient`'s `tempAuth` property using the passed in token.
+
+ This will cause the next CRUD method performed by the client to use the `tempAuth` property once and will then reset.
+
+ - parameter auth: The access token to temporarily use for authentication.
+
+ - returns: The shared instance of `UsergridClient`
+ */
+ public static func usingToken(token:String) -> UsergridClient {
+ return Usergrid.sharedInstance.usingToken(token)
+ }
+
+
+ /**
+ Determines the `UsergridAuth` object that will be used for all outgoing requests made by the shared instance of `UsergridClient`.
+
+ If there is a `UsergridUser` logged in and the token of that user is valid then it will return that.
+
+ Otherwise, if the `authMode` is `.App`, and the `UsergridAppAuth` of the client is set and the token is valid it will return that.
+
+ - returns: The `UsergridAuth` if one is found or nil if not.
+ */
+ public static func authForRequests() -> UsergridAuth? {
+ return Usergrid.sharedInstance.authForRequests()
+ }
+
+ /**
+ Authenticates with the `UsergridAppAuth` that is contained within the shared instance of `UsergridCient`.
+
+ - parameter completion: The completion block that will be called after authentication has completed.
+ */
+ public static func authenticateApp(completion: UsergridAppAuthCompletionBlock? = nil) {
+ Usergrid.sharedInstance.authenticateApp(completion)
+ }
+
+ /**
+ Authenticates with the `UsergridAppAuth` that is passed in using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.authenticateApp(auth, completion: completion)
+ }
+
+ /**
+ Authenticates with the `UsergridUserAuth` that is passed in using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.authenticateUser(auth, completion: completion)
+ }
+
+ /**
+ Authenticates with the `UsergridUserAuth` that is passed in using the shared instance of `UsergridCient`.
+
+ - parameter auth: The `UsergridUserAuth` that will be authenticated.
+ - 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) {
+ Usergrid.sharedInstance.authenticateUser(userAuth, setAsCurrentUser: setAsCurrentUser, completion: completion)
+ }
+
+ /**
+ Changes the given `UsergridUser`'s current password with the shared instance of `UsergridClient`.
+
+ - parameter user: The user.
+ - parameter old: The old password.
+ - parameter new: The new password.
+ - parameter completion: The optional completion block.
+ */
+ public static func resetPassword(user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) {
+ Usergrid.sharedInstance.resetPassword(user, old: old, new: new, completion: completion)
+ }
+
+ /**
+ Logs out the current user of the shared instance locally and remotely using the shared instance of `UsergridClient`.
+
+ - parameter completion: The completion block that will be called after logout has completed.
+ */
+ public static func logoutCurrentUser(completion:UsergridResponseCompletion? = nil) {
+ Usergrid.sharedInstance.logoutCurrentUser(completion)
+ }
+
+ /**
+ Logs out the user remotely with the given tokens using the shared instance of `UsergridCient`.
+
+ - parameter completion: The completion block that will be called after logout has completed.
+ */
+ public static func logoutUserAllTokens(uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) {
+ Usergrid.sharedInstance.logoutUserAllTokens(uuidOrUsername, completion: completion)
+ }
+
+ /**
+ Logs out a user with the give UUID or username using the shared instance of `UsergridCient`.
+
+ Passing in a token will log out the user for just that token. Passing in nil for the token will logout the user for all tokens.
+
+ - parameter completion: The completion block that will be called after logout has completed.
+ */
+ public static func logoutUser(uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) {
+ Usergrid.sharedInstance.logoutUser(uuidOrUsername, token: token, completion: completion)
+ }
+
+ // MARK: - Generic Request Methods -
+
+ /**
+ Starts the `UsergridRequest` sending process using the shared instance of `UsergridCient`.
+
+ - Note: This method should only be used when you construct your own `UsergridRequest objects.
+
+ - 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) {
+ Usergrid.sharedInstance.sendRequest(request, completion: completion)
+ }
+
+ // MARK: - GET -
+
+ /**
+ Gets a single `UsergridEntity` of a given type with a specific UUID/name using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - 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) {
+ Usergrid.sharedInstance.GET(type,uuidOrName:uuidOrName,completion:completion)
+ }
+
+ /**
+ Gets a group of `UsergridEntity` objects of a given type using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.GET(type,completion:completion)
+ }
+
+ /**
+ Gets a group of `UsergridEntity` objects with a given query using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.GET(query,queryCompletion:queryCompletion)
+ }
+
+ // MARK: - PUT -
+
+ /**
+ Updates an `UsergridEntity` with the given type and UUID/name specified using the passed in jsonBody using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - parameter uuidOrName: The UUID or name of the `UsergridEntity`.
+ - 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) {
+ Usergrid.sharedInstance.PUT(type, uuidOrName: uuidOrName, jsonBody: jsonBody, completion: completion)
+ }
+
+ /**
+ Updates an `UsergridEntity` with the given type using the jsonBody where the UUID/name is specified inside of the jsonBody using the shared instance of `UsergridCient`.
+
+ - Note: The `jsonBody` must contain a valid value for either `uuid` or `name`.
+
+ - parameter type: The `UsergridEntity` type.
+ - 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) {
+ Usergrid.sharedInstance.PUT(type, jsonBody: jsonBody, completion: completion)
+ }
+
+ /**
+ Updates the passed in `UsergridEntity` using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.PUT(entity, completion: completion)
+ }
+
+ /**
+ Updates the entities that fit the given query using the passed in jsonBody using the shared instance of `UsergridCient`.
+
+ - Note: The query parameter must have a valid `collectionName` before calling this method.
+
+ - parameter query: The query to use when filtering what entities to update.
+ - 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) {
+ Usergrid.sharedInstance.PUT(query, jsonBody: jsonBody, queryCompletion: queryCompletion)
+ }
+
+ // MARK: - POST -
+
+ /**
+ Creates and posts an `UsergridEntity` of the given type with a given name and the given jsonBody using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - parameter name: The name of the `UsergridEntity`.
+ - 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) {
+ Usergrid.sharedInstance.POST(type, name: name, jsonBody: jsonBody, completion: completion)
+ }
+
+ /**
+ Creates and posts an `UsergridEntity` of the given type with the given jsonBody using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - 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) {
+ Usergrid.sharedInstance.POST(type, jsonBody: jsonBody, completion: completion)
+ }
+
+ /**
+ Creates and posts an array of `Entity` objects while assinging the given type to them using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - 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) {
+ Usergrid.sharedInstance.POST(type, jsonBodies: jsonBodies, completion: completion)
+ }
+
+ /**
+ Creates and posts creates an `UsergridEntity` using the shared instance of `UsergridCient`.
+
+ - 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) {
+ Usergrid.sharedInstance.POST(entity, completion: completion)
+ }
+
+ /**
+ Creates and posts an array of `UsergridEntity` objects using the shared instance of `UsergridCient`.
+
+ - Note: Each `UsergridEntity` in the array much already have a type assigned and must be the same.
+
+ - 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) {
+ Usergrid.sharedInstance.POST(entities, entitiesCompletion: entitiesCompletion)
+ }
+
+ // MARK: - DELETE -
+
+ /**
+ Destroys the `UsergridEntity` of a given type with a specific UUID/name using the shared instance of `UsergridCient`.
+
+ - parameter type: The `UsergridEntity` type.
+ - 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) {
+ Usergrid.sharedInstance.DELETE(type, uuidOrName: uuidOrName, completion: completion)
+ }
+
+ /**
+ Destroys the passed `UsergridEntity` using the shared instance of `UsergridCient`.
+
+ - Note: The entity object must have a `uuid` or `name` assigned.
+
+ - 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) {
+ Usergrid.sharedInstance.DELETE(entity, completion:completion)
+ }
+
+ /**
+ Destroys the `UsergridEntity` objects that fit the given `UsergridQuery` using the shared instance of `UsergridCient`.
+
+ - Note: The query parameter must have a valid `collectionName` before calling this method.
+
+ - 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) {
+ Usergrid.sharedInstance.DELETE(query, queryCompletion:queryCompletion)
+ }
+
+ // MARK: - Connection Management -
+
+ /**
+ Connects the `UsergridEntity` objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entity: The entity that will contain the connection.
+ - parameter relationship: The relationship of the two entities.
+ - 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) {
+ Usergrid.sharedInstance.connect(entity, relationship: relationship, to: to, completion: completion)
+ }
+
+ /**
+ Connects the entity objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entityType: The entity type.
+ - parameter entityID: The entity UUID or name.
+ - parameter relationship: The relationship of the connection.
+ - parameter toType: The optional type of the entity you are connecting to.
+ - 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) {
+ Usergrid.sharedInstance.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toID: toID, completion: completion)
+ }
+
+ /**
+ Connects the entity objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entityType: The entity type.
+ - parameter entityID: The entity UUID or name.
+ - parameter relationship: The relationship of the connection.
+ - parameter toType: The type of the entity you are connecting to.
+ - 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) {
+ Usergrid.sharedInstance.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toName: toName, completion: completion)
+ }
+
+
+ /**
+ Disconnects the `UsergridEntity` objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entity: The entity that contains the connection.
+ - parameter relationship: The relationship of the two entities.
+ - 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) {
+ Usergrid.sharedInstance.disconnect(entity, relationship: relationship, from: from, completion: completion)
+ }
+
+ /**
+ Disconnects the entity objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entityType: The entity type.
+ - parameter entityID: The entity UUID or name.
+ - parameter relationship: The relationship of the connection.
+ - parameter fromType: The optional type of the entity you are disconnecting from.
+ - 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) {
+ Usergrid.sharedInstance.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromID: fromID, completion: completion)
+ }
+
+ /**
+ Disconnects the entity objects via the relationship using the shared instance of `UsergridCient`.
+
+ - parameter entityType: The entity type.
+ - parameter entityID: The entity UUID or name.
+ - parameter relationship: The relationship of the connection.
+ - parameter fromType: The type of the entity you are disconnecting from.
+ - 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) {
+ Usergrid.sharedInstance.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromName: fromName, completion: completion)
+ }
+
+ /**
+ Gets the connected entities for the given relationship using the shared instance of `UsergridCient`.
+
+ - parameter direction: The direction of the connection.
+ - parameter entity: The entity that contains the connection.
+ - 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) {
+ Usergrid.sharedInstance.getConnections(direction, entity: entity, relationship: relationship, query:query, completion: completion)
+ }
+
+ /**
+ Gets the connected entities for the given relationship using the shared instance of `UsergridCient`.
+
+ - parameter direction: The direction of the connection.
+ - parameter type: The entity type.
+ - parameter uuidOrName: The entity UUID or name.
+ - parameter relationship: The relationship of the connection.
+ - 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) {
+ Usergrid.sharedInstance.getConnections(direction, type: type, uuidOrName: uuidOrName, relationship: relationship, query:query, completion: completion)
+ }
+
+ /**
+ Gets the connected entities for the given relationship using the shared instance of `UsergridCient`.
+
+ - parameter direction: The direction of the connection.
+ - parameter uuid: The entity UUID.
+ - parameter relationship: The relationship of the connection.
+ - 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) {
+ Usergrid.sharedInstance.getConnections(direction, uuid: uuid, relationship: relationship, query: query, completion: completion)
+ }
+
+ // MARK: - Asset Management -
+
+ /**
+ Uploads the asset and connects the data to the given `UsergridEntity` using the shared instance of `UsergridCient`.
+
+ - parameter entity: The entity to connect the asset to.
+ - parameter asset: The asset to upload.
+ - 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) {
+ Usergrid.sharedInstance.uploadAsset(entity, asset: asset, progress: progress, completion: completion)
+ }
+
+ /**
+ Downloads the asset from the given `UsergridEntity` using the shared instance of `UsergridCient`.
+
+ - parameter entity: The entity to which the asset to.
+ - parameter contentType: The content type of the asset's data.
+ - 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) {
+ Usergrid.sharedInstance.downloadAsset(entity, contentType: contentType, progress: progress, completion: completion)
+ }
+}
http://git-wip-us.apache.org/repos/asf/usergrid-swift/blob/8283a6dd/Source/UsergridAsset.swift
----------------------------------------------------------------------
diff --git a/Source/UsergridAsset.swift b/Source/UsergridAsset.swift
new file mode 100644
index 0000000..9353ec1
--- /dev/null
+++ b/Source/UsergridAsset.swift
@@ -0,0 +1,198 @@
+//
+// UsergridAsset.swift
+// UsergridSDK
+//
+// Created by Robert Walsh on 9/21/15.
+//
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ *
+ */
+
+import Foundation
+
+#if os(iOS) || os(watchOS) || os(tvOS)
+import UIKit
+import MobileCoreServices
+#endif
+
+/// The progress block used in `UsergridAsset` are being uploaded or downloaded.
+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
+
+/// The completion block used in `UsergridAsset` are finished downloading.
+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.
+
+Unless defined, whenever possible, the content-type will be inferred from the data provided, and the attached file (if not already a byte-array representation) will be binary-encoded.
+*/
+public class UsergridAsset: NSObject, NSCoding {
+
+ internal static let DEFAULT_FILE_NAME = "file"
+
+ // MARK: - Instance Properties -
+
+ /// The filename to be used in the multipart/form-data request.
+ public let filename: String
+
+ /// Binary representation of the asset's data.
+ public let data: NSData
+
+ /// A representation of the folder location the asset was loaded from, if it was provided in the initialization.
+ public let originalLocation: String?
+
+ /// The Content-type of the asset to be used when defining content-type inside the multipart/form-data request.
+ public var contentType: String
+
+ /// The content length of the assets data.
+ public var contentLength: Int { return self.data.length }
+
+ // MARK: - Initialization -
+
+ /**
+ Designated initializer for `UsergridAsset` objects.
+
+ - parameter fileName: The file name associated with the file data.
+ - parameter data: The data of the file.
+ - parameter originalLocation: An optional original location of the file.
+ - parameter contentType: The content type of the file.
+
+ - returns: A new instance of `UsergridAsset`.
+ */
+ public init(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, data:NSData, originalLocation:String? = nil, contentType:String) {
+ self.filename = filename ?? UsergridAsset.DEFAULT_FILE_NAME
+ self.data = data
+ self.originalLocation = originalLocation
+ self.contentType = contentType
+ }
+
+ #if os(iOS) || os(watchOS) || os(tvOS)
+ /**
+ Convenience initializer for `UsergridAsset` objects dealing with image data.
+
+ - parameter fileName: The file name associated with the file data.
+ - parameter image: The `UIImage` object to upload.
+ - parameter imageContentType: The content type of the `UIImage`
+
+ - 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?
+ switch(imageContentType) {
+ case .Png :
+ imageData = UIImagePNGRepresentation(image)
+ 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:"")
+ return nil
+ }
+ }
+ #endif
+
+ /**
+ Convenience initializer for `UsergridAsset` objects dealing directly with files on disk.
+
+ - parameter fileName: The file name associated with the file data.
+ - parameter fileURL: The `NSURL` object associated with the file.
+ - parameter contentType: The content type of the `UIImage`. If not specified it will try to figure out the type and if it can't initialization will fail.
+
+ - 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) {
+ var fileNameToUse = filename
+ if fileNameToUse != UsergridAsset.DEFAULT_FILE_NAME, let inferredFileName = fileURL.lastPathComponent {
+ fileNameToUse = inferredFileName
+ }
+ 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:"")
+ return nil
+ }
+ } else {
+ print("Usergrid Error: fileURL parameter must be a file URL.")
+ self.init(filename:"",data:NSData(),contentType:"")
+ return nil
+ }
+ }
+
+ // MARK: - NSCoding -
+
+ /**
+ NSCoding protocol initializer.
+
+ - parameter aDecoder: The decoder.
+
+ - 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
+ else {
+ self.filename = ""
+ self.contentType = ""
+ self.originalLocation = nil
+ self.data = NSData()
+ super.init()
+ return nil
+ }
+ self.filename = filename
+ self.data = assetData
+ self.contentType = contentType
+ self.originalLocation = aDecoder.decodeObjectForKey("originalLocation") as? String
+ super.init()
+ }
+
+ /**
+ NSCoding protocol encoder.
+
+ - 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")
+ }
+
+ private static func MIMEType(fileURL: NSURL) -> String? {
+ if let pathExtension = fileURL.pathExtension {
+ if let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
+ let UTI = UTIRef.takeUnretainedValue()
+ UTIRef.release()
+ if let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType) {
+ let MIMEType = MIMETypeRef.takeUnretainedValue()
+ MIMETypeRef.release()
+ return MIMEType as String
+ }
+ }
+ }
+ return nil
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/usergrid-swift/blob/8283a6dd/Source/UsergridAssetRequestWrapper.swift
----------------------------------------------------------------------
diff --git a/Source/UsergridAssetRequestWrapper.swift b/Source/UsergridAssetRequestWrapper.swift
new file mode 100644
index 0000000..d715652
--- /dev/null
+++ b/Source/UsergridAssetRequestWrapper.swift
@@ -0,0 +1,48 @@
+//
+// UsergridAssetRequestWrapper.swift
+// UsergridSDK
+//
+// Created by Robert Walsh on 10/1/15.
+//
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ *
+ */
+
+import Foundation
+
+typealias UsergridAssetRequestWrapperCompletionBlock = (requestWrapper:UsergridAssetRequestWrapper) -> Void
+
+final class UsergridAssetRequestWrapper {
+ weak var session: NSURLSession?
+ let sessionTask: NSURLSessionTask
+
+ var response: NSURLResponse?
+ var responseData: NSData?
+ var error: NSError?
+
+ var progress: UsergridAssetRequestProgress?
+ let completion: UsergridAssetRequestWrapperCompletionBlock
+
+ init(session:NSURLSession?, sessionTask:NSURLSessionTask, progress:UsergridAssetRequestProgress?, completion:UsergridAssetRequestWrapperCompletionBlock) {
+ self.session = session
+ self.sessionTask = sessionTask
+ self.progress = progress
+ self.completion = completion
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/usergrid-swift/blob/8283a6dd/Source/UsergridAuth.swift
----------------------------------------------------------------------
diff --git a/Source/UsergridAuth.swift b/Source/UsergridAuth.swift
new file mode 100644
index 0000000..e87e9c1
--- /dev/null
+++ b/Source/UsergridAuth.swift
@@ -0,0 +1,276 @@
+//
+// UsergridAuth.swift
+// UsergridSDK
+//
+// Created by Robert Walsh on 9/11/15.
+//
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ *
+ */
+
+import Foundation
+
+/// The completion block used in `UsergridAppAuth` authentication methods.
+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
+
+/**
+ The `UsergridAuth` class functions to create and store authentication information used by Usergrid.
+
+ The `UsergridAuth` sub classes, `UsergridAppAuth` and `UsergridUserAuth`, provide different ways for authentication to be used in creating requests for access tokens through the SDK.
+*/
+public class UsergridAuth : NSObject, NSCoding {
+
+ // MARK: - Instance Properties -
+
+ /// The access token, if this `UsergridAuth` was authorized successfully.
+ 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?
+
+ /// Determines if an access token exists.
+ public var hasToken: Bool { return self.accessToken != nil }
+
+ /// Determines if the token was set explicitly within the init method or not.
+ private var usingToken: Bool = false
+
+ /// Determines if an access token exists and if the token is not expired.
+ public var isValid : Bool { return self.hasToken && !self.isExpired }
+
+ /// Determines if the access token, if one exists, is expired.
+ public var isExpired: Bool {
+ var isExpired = false
+ if let expires = self.expiry {
+ isExpired = expires.timeIntervalSinceNow < 0.0
+ } else {
+ isExpired = !self.usingToken
+ }
+ return isExpired
+ }
+
+ /// The credentials dictionary. Subclasses must override this method and provide an actual dictionary containing the credentials to send with requests.
+ var credentialsJSONDict: [String:AnyObject] {
+ return [:]
+ }
+
+ // MARK: - Initialization -
+
+ /**
+ Internal initialization method. Note this should never be used outside of internal methods.
+
+ - returns: A new instance of `UsergridAuth`.
+ */
+ override private init() {
+ super.init()
+ }
+
+ /**
+ Initializer for a base `UsergridAuth` object that just contains an `accessToken` and an optional `expiry` date.
+
+ - parameter accessToken: The access token.
+ - parameter expiry: The optional expiry date.
+
+ - returns: A new instance of `UsergridAuth`
+ */
+ public init(accessToken:String, expiry:NSDate? = nil) {
+ self.usingToken = true
+ self.accessToken = accessToken
+ self.expiry = expiry
+ }
+
+ // MARK: - NSCoding -
+
+ /**
+ NSCoding protocol initializer.
+
+ - parameter aDecoder: The decoder.
+
+ - 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
+ }
+
+ /**
+ NSCoding protocol encoder.
+
+ - parameter aCoder: The encoder.
+ */
+ public func encodeWithCoder(aCoder: NSCoder) {
+ if let accessToken = self.accessToken {
+ aCoder.encodeObject(accessToken, forKey: "accessToken")
+ }
+ if let expiresAt = self.expiry {
+ aCoder.encodeObject(expiresAt, forKey: "expiry")
+ }
+ }
+
+ // MARK: - Instance Methods -
+
+ /**
+ Destroys/removes the access token and expiry.
+ */
+ public func destroy() {
+ self.accessToken = nil
+ self.expiry = nil
+ }
+}
+
+/// The `UsergridAuth` subclass used for user level authorization.
+public class UsergridUserAuth : UsergridAuth {
+
+ // MARK: - Instance Properties -
+
+ /// The username associated with the User.
+ public let username: String
+
+ /// The password associated with the User.
+ private let password: String
+
+ /// The credentials dictionary constructed with the `UsergridUserAuth`'s `username` and `password`.
+ override var credentialsJSONDict: [String:AnyObject] {
+ return ["grant_type":"password",
+ "username":self.username,
+ "password":self.password]
+ }
+
+ // MARK: - Initialization -
+
+ /**
+ Designated initializer for `UsergridUserAuth` objects.
+
+ - parameter username: The username associated with the User.
+ - parameter password: The password associated with the User.
+
+ - returns: A new instance of `UsergridUserAuth`.
+ */
+ public init(username:String, password: String){
+ self.username = username
+ self.password = password
+ super.init()
+ }
+
+ // MARK: - NSCoding -
+
+ /**
+ NSCoding protocol initializer.
+
+ - parameter aDecoder: The decoder.
+
+ - 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
+ else {
+ self.username = ""
+ self.password = ""
+ super.init(coder: aDecoder)
+ return nil
+ }
+
+ self.username = username
+ self.password = password
+ super.init(coder: aDecoder)
+ }
+
+ /**
+ NSCoding protocol encoder.
+
+ - 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)
+ }
+}
+
+/// The `UsergridAuth` subclass used for application level authorization.
+public class UsergridAppAuth : UsergridAuth {
+
+ // MARK: - Instance Properties -
+
+ /// The client identifier associated with the application.
+ public let clientId: String
+
+ /// The client secret associated with the application.
+ private let clientSecret: String
+
+ /// The credentials dictionary constructed with the `UsergridAppAuth`'s `clientId` and `clientSecret`.
+ override var credentialsJSONDict: [String:AnyObject] {
+ return ["grant_type":"client_credentials",
+ "client_id":self.clientId,
+ "client_secret":self.clientSecret]
+ }
+
+ // MARK: - Initialization -
+
+ /**
+ Designated initializer for `UsergridAppAuth` objects.
+
+ - parameter clientId: The client identifier associated with the application.
+ - parameter clientSecret: The client secret associated with the application.
+
+ - returns: A new instance of `UsergridAppAuth`.
+ */
+ public init(clientId:String,clientSecret:String){
+ self.clientId = clientId
+ self.clientSecret = clientSecret
+ super.init()
+ }
+
+ // MARK: - NSCoding -
+
+ /**
+ NSCoding protocol initializer.
+
+ - parameter aDecoder: The decoder.
+
+ - 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
+ else {
+ self.clientId = ""
+ self.clientSecret = ""
+ super.init(coder: aDecoder)
+ return nil
+ }
+ self.clientId = clientId
+ self.clientSecret = clientSecret
+ super.init(coder: aDecoder)
+ }
+
+ /**
+ NSCoding protocol encoder.
+
+ - 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)
+ }
+}
\ No newline at end of file