http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridRequestManager.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridRequestManager.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridRequestManager.swift deleted file mode 100644 index ccd41e5..0000000 --- a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridRequestManager.swift +++ /dev/null @@ -1,156 +0,0 @@ -// -// UsergridRequestManager.swift -// UsergridSDK -// -// Created by Robert Walsh on 9/22/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 - -final class UsergridRequestManager { - - unowned let client: UsergridClient - - let session: NSURLSession - - var sessionDelegate : UsergridSessionDelegate { - return session.delegate as! UsergridSessionDelegate - } - - init(client:UsergridClient) { - self.client = client - - let config = NSURLSessionConfiguration.defaultSessionConfiguration() - - #if os(tvOS) - config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-tvOS/v\(UsergridSDKVersion)"] - #elseif os(iOS) - config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-ios/v\(UsergridSDKVersion)"] - #elseif os(watchOS) - config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-watchOS/v\(UsergridSDKVersion)"] - #elseif os(OSX) - config.HTTPAdditionalHeaders = ["User-Agent": "usergrid-osx/v\(UsergridSDKVersion)"] - #endif - - self.session = NSURLSession(configuration: config, - delegate: UsergridSessionDelegate(), - delegateQueue: NSOperationQueue.mainQueue()) - } - - deinit { - session.invalidateAndCancel() - } - - func performRequest(request:UsergridRequest, completion:UsergridResponseCompletion?) { - session.dataTaskWithRequest(request.buildNSURLRequest()) { [weak self] (data, response, error) -> Void in - completion?(response: UsergridResponse(client:self?.client, data: data, response: response as? NSHTTPURLResponse, error: error)) - }.resume() - } -} - - -// MARK: - Authentication - -extension UsergridRequestManager { - - static func getTokenAndExpiryFromResponseJSON(jsonDict:[String:AnyObject]) -> (String?,NSDate?) { - var token: String? = nil - var expiry: NSDate? = 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: Double(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) - if let jsonDict = dataAsJSON as? [String:AnyObject] { - let tokenAndExpiry = UsergridRequestManager.getTokenAndExpiryFromResponseJSON(jsonDict) - userAuth.accessToken = tokenAndExpiry.0 - userAuth.expiry = tokenAndExpiry.1 - - var user: UsergridUser? - if let userDict = jsonDict[UsergridUser.USER_ENTITY_TYPE] as? [String:AnyObject] { - if let createdUser = UsergridEntity.entity(jsonDict: userDict) as? UsergridUser { - createdUser.auth = userAuth - user = createdUser - } - } - if let createdUser = user { - completion?(auth: userAuth, user:createdUser, error: nil) - } else { - let error = UsergridResponseError(jsonDictionary: jsonDict) ?? UsergridResponseError(errorName: "Auth Failed.", errorDescription: "Error Description: \(error?.localizedDescription).") - completion?(auth: userAuth, user:nil, error:error) - } - } else { - let error = UsergridResponseError(errorName: "Auth Failed.", errorDescription: "Error Description: \(error?.localizedDescription).") - completion?(auth: userAuth, user:nil, error: error) - } - }.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) - if let jsonDict = dataAsJSON as? [String:AnyObject] { - let tokenAndExpiry = UsergridRequestManager.getTokenAndExpiryFromResponseJSON(jsonDict) - appAuth.accessToken = tokenAndExpiry.0 - appAuth.expiry = tokenAndExpiry.1 - completion?(auth: appAuth, error: nil) - } else { - let error = UsergridResponseError(errorName: "Auth Failed.", errorDescription: "Error Description: \(error?.localizedDescription).") - completion?(auth: nil, error: error) - } - }.resume() - } -} - -// MARK: - Asset Management - -extension UsergridRequestManager { - - func performAssetDownload(contentType:String, usergridRequest:UsergridRequest, progress: UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) { - let downloadTask = session.downloadTaskWithRequest(usergridRequest.buildNSURLRequest()) - let requestWrapper = UsergridAssetRequestWrapper(session: self.session, sessionTask: downloadTask, progress: progress) { (request) -> Void in - if let assetData = request.responseData where assetData.length > 0 { - let asset = UsergridAsset(data: assetData, contentType: contentType) - completion?(asset: asset, error:nil) - } else { - completion?(asset: nil, error: "Downloading asset failed. No data was recieved.") - } - } - 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) - let requestWrapper = UsergridAssetRequestWrapper(session: self.session, sessionTask: uploadTask, progress: progress) { [weak self] (request) -> Void in - completion?(response: UsergridResponse(client: self?.client, data: request.responseData, response: request.response as? NSHTTPURLResponse, error: request.error),asset:usergridRequest.asset,error:nil) - } - self.sessionDelegate.addRequestDelegate(requestWrapper.sessionTask, requestWrapper:requestWrapper) - requestWrapper.sessionTask.resume() - } -} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponse.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponse.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponse.swift deleted file mode 100644 index 012c82f..0000000 --- a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponse.swift +++ /dev/null @@ -1,203 +0,0 @@ -// -// UsergridResponse.swift -// UsergridSDK -// -// Created by Robert Walsh on 9/2/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 for most `UsergridClient` requests. -public typealias UsergridResponseCompletion = (response: UsergridResponse) -> Void - -/** -`UsergridResponse` is the core class that handles both successful and unsuccessful HTTP responses from Usergrid. - -If a request is successful, any entities returned in the response will be automatically parsed into `UsergridEntity` objects and pushed to the `entities` property. - -If a request fails, the `errorName` and `errorDescription` will contain information about the problem encountered. -*/ -public class UsergridResponse: NSObject { - - // MARK: - Instance Properties - - - /// The client that was responsible for the request. - public weak var client: UsergridClient? - - /// The raw response JSON. - internal(set) public var responseJSON: [String:AnyObject]? - - /// The query used on the request. - internal(set) public var query: UsergridQuery? - - /// The cursor from the response. - internal(set) public var cursor: String? - - /// The entities created from the response JSON. - internal(set) public var entities: [UsergridEntity]? - - /// The response headers. - internal(set) public var headers: [String:String]? - - /// The response status code. - internal(set) public var statusCode: Int? - - /// The error object containing error information if one occurred. - internal(set) public var error: UsergridResponseError? - - /// Returns true if the HTTP status code from the response is less than 400. - public var ok : Bool { - var isOk = false - if let statusCode = self.statusCode { - isOk = (statusCode < 400) - } - return isOk - } - - /// The count of `entities`. - public var count: Int { return self.entities?.count ?? 0 } - - /// The first entity in `entities`. - public var first: UsergridEntity? { return self.entities?.first } - - /// The last entity in `entities`. - public var last: UsergridEntity? { return self.entities?.last } - - /// The first entity in `entities`. - public var entity: UsergridEntity? { return self.first } - - /// The `UsergridUser` entity. - public var user: UsergridUser? { return self.entities?.first as? UsergridUser } - - /// An array of `UsergridUser` entities. - public var users: [UsergridUser]? { return self.entities as? [UsergridUser] } - - /// Does the response have a cursor. - public var hasNextPage: Bool { return self.cursor != nil } - - /// The string value. - public var stringValue : String? { - if let responseJSON = self.responseJSON { - return NSString(data: try! NSJSONSerialization.dataWithJSONObject(responseJSON, options: .PrettyPrinted), encoding: NSASCIIStringEncoding) as? String - } else { - return error?.description - } - } - - /// The description. - public override var description : String { - return "Response Description: \(stringValue)." - } - - /// The debug description. - public override var debugDescription : String { - return "Properties of Entity: \(stringValue)." - } - - // MARK: - Initialization - - - /** - Designated initializer for `UsergridResponse` objects that contain errors. - - These types of responses are usually created because request conditions are not met. - - - parameter client: The client responsible for the request. - - parameter errorName: The error name. - - parameter errorDescription: The error description. - - - returns: A new instance of `UsergridResponse`. - */ - public init(client: UsergridClient?, errorName: String, errorDescription: String) { - self.client = client - self.error = UsergridResponseError(errorName: errorName, errorDescription: errorDescription, exception: nil) - } - - /** - Designated initializer for `UsergridResponse` objects finished but still may contain errors. - - - parameter client: The client responsible for the request. - - parameter data: The response data. - - parameter response: The `NSHTTPURLResponse` object. - - parameter error: The `NSError` object. - - parameter query: The query when making the request. - - - returns: A new instance of `UsergridResponse`. - */ - public init(client:UsergridClient?, data:NSData?, response:NSHTTPURLResponse?, error:NSError?, query:UsergridQuery? = nil) { - self.client = client - self.statusCode = response?.statusCode - self.headers = response?.allHeaderFields as? [String:String] - - if let sessionError = error { - self.error = UsergridResponseError(errorName: sessionError.domain, errorDescription: sessionError.localizedDescription) - } - - if let responseQuery = query { - self.query = responseQuery.copy() as? UsergridQuery - } - - if let jsonData = data { - do { - let dataAsJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) - if let jsonDict = dataAsJSON as? [String:AnyObject] { - 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 { - self.entities = UsergridEntity.entities(jsonArray: entitiesJSONArray) - } - if let cursor = jsonDict[UsergridResponse.CURSOR] as? String where !cursor.isEmpty { - self.cursor = cursor - } - } - } - } catch { - print(error) - } - } - } - - // MARK: - Instance Methods - - - /** - Attempts to load the next page of `UsergridEntity` objects. - - This requires a `cursor` to be valid as well as a `path` key within the response JSON. - - - parameter completion: The completion block that is called once the request for the next page has finished. - */ - 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(type, query: query.cursor(self.cursor), completion:completion) - } else { - self.client?.GET(type, query: UsergridQuery(type).cursor(self.cursor), completion:completion) - } - } else { - completion(response: UsergridResponse(client: self.client, errorName: "No next page.", errorDescription: "No next page was found.")) - } - } - - static let CURSOR = "cursor" - static let ENTITIES = "entities" -} http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponseError.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponseError.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponseError.swift deleted file mode 100644 index eda8a30..0000000 --- a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridResponseError.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// UsergridResponseError.swift -// UsergridSDK -// -// Created by Robert Walsh on 1/8/16. -// -/* - * - * 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 - -/// A standard error object that contains details about a request failure. -public class UsergridResponseError: NSObject { - - // MARK: - Instance Properties - - - /// The error's name. - public let errorName : String - - /// The error's description. - public let errorDescription: String - - /// The exception. - public var exception: String? - - /// The description. - public override var description : String { - return "Error Name: \(errorName). Error Description: \(errorDescription). Exception: \(exception)." - } - - /// The debug description. - public override var debugDescription : String { - return "Error Name: \(errorName). Error Description: \(errorDescription). Exception: \(exception)." - } - - // MARK: - Initialization - - - /** - Designated initializer for `UsergridResponseError`. - - - parameter errorName: The error's name. - - parameter errorDescription: The error's description. - - parameter exception: The exception. - - - returns: A new instance of `UsergridResponseError` - */ - public init(errorName:String, errorDescription:String, exception:String? = nil) { - self.errorName = errorName - self.errorDescription = errorDescription - self.exception = exception - } - - /** - Convenience initializer for `UsergridResponseError` that determines if the given `jsonDictionary` contains an error. - - - parameter jsonDictionary: The JSON dictionary that may contain error information. - - - returns: A new instance of `UsergridResponseError` if the JSON dictionary did indeed contain error information. - */ - public convenience init?(jsonDictionary:[String:AnyObject]) { - if let errorName = jsonDictionary[USERGRID_ERROR] as? String, - errorDescription = jsonDictionary[USERGRID_ERROR_DESCRIPTION] as? String { - self.init(errorName:errorName,errorDescription:errorDescription,exception:jsonDictionary[USERGRID_EXCEPTION] as? String) - } else { - self.init(errorName:"",errorDescription:"") - return nil - } - } -} - -let USERGRID_ERROR = "error" -let USERGRID_ERROR_DESCRIPTION = "error_description" -let USERGRID_EXCEPTION = "exception" \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridSessionDelegate.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridSessionDelegate.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridSessionDelegate.swift deleted file mode 100644 index cb36fb7..0000000 --- a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridSessionDelegate.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// UsergridSessionDelegate.swift -// UsergridSDK -// -// Created by Robert Walsh on 9/30/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 - -final class UsergridSessionDelegate: NSObject { - - private var requestDelegates: [Int:UsergridAssetRequestWrapper] = [:] - - func addRequestDelegate(task:NSURLSessionTask,requestWrapper:UsergridAssetRequestWrapper) { - requestDelegates[task.taskIdentifier] = requestWrapper - } - - func removeRequestDelegate(task:NSURLSessionTask) { - requestDelegates[task.taskIdentifier] = nil - } -} - -extension UsergridSessionDelegate : NSURLSessionTaskDelegate { - - func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { - if let progressBlock = requestDelegates[task.taskIdentifier]?.progress { - progressBlock(bytesFinished:totalBytesSent, bytesExpected: totalBytesExpectedToSend) - } - } - - func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { - if let requestWrapper = requestDelegates[task.taskIdentifier] { - requestWrapper.error = error - requestWrapper.completion(requestWrapper: requestWrapper) - } - self.removeRequestDelegate(task) - } -} - -extension UsergridSessionDelegate : NSURLSessionDataDelegate { - - func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { - if let requestWrapper = requestDelegates[dataTask.taskIdentifier] { - requestWrapper.response = response - } - completionHandler(NSURLSessionResponseDisposition.Allow) - } - - func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { - if let requestWrapper = requestDelegates[dataTask.taskIdentifier] { - let mutableData = requestWrapper.responseData != nil ? NSMutableData(data: requestWrapper.responseData!) : NSMutableData() - mutableData.appendData(data) - requestWrapper.responseData = mutableData - } - } -} - -extension UsergridSessionDelegate : NSURLSessionDownloadDelegate { - - func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { - if let progressBlock = requestDelegates[downloadTask.taskIdentifier]?.progress { - progressBlock(bytesFinished:totalBytesWritten, bytesExpected: totalBytesExpectedToWrite) - } - } - - func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { - if let requestWrapper = requestDelegates[downloadTask.taskIdentifier] { - requestWrapper.responseData = NSData(contentsOfURL: location)! - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridUser.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridUser.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridUser.swift deleted file mode 100644 index b1eedcc..0000000 --- a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridUser.swift +++ /dev/null @@ -1,441 +0,0 @@ -// -// User.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 completion block used for checking email and/or username availablity for new `UsergridUser` objects. -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 - -/** -`UsergridUser` is a special subclass of `UsergridEntity` that supports functions and properties unique to users. -*/ -public class UsergridUser : UsergridEntity { - - static let USER_ENTITY_TYPE = "user" - - // MARK: - Instance Properties - - - /// The `UsergridUserAuth` object if this user was authenticated. - public var auth: UsergridUserAuth? - - /** - Property helper method for the `UsergridUser` objects `UsergridUserProperties.Name`. - - 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 } - 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 } - } - - /// 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 } - } - - /// 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 } - } - - /// 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 } - } - - /// Property helper method to get the username or email of the `UsergridUser`. - public var usernameOrEmail: String? { return self.username ?? self.email } - - /** - Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Activated`. - - 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 } - } - - /// 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 } - } - - /** - Property getter and setter helpers for the `UsergridUser` objects `UsergridUserProperties.Picture`. - - 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 } - } - - /// The UUID or username property value if found. - public var uuidOrUsername: String? { return self.uuid ?? self.username } - - // MARK: - Initialization - - - /** - Designated initializer for `UsergridUser` objects. - - - parameter name: The name of the user. Note this is different from the `username` property. - - - returns: A new instance of `UsergridUser`. - */ - public init(name:String? = nil) { - super.init(type: UsergridUser.USER_ENTITY_TYPE, name:name, propertyDict:nil) - } - - /** - The required public initializer for `UsergridEntity` subclasses. - - - parameter type: The type associated with the `UsergridEntity` object. - - parameter name: The optional name associated with the `UsergridEntity` object. - - parameter propertyDict: The optional property dictionary that the `UsergridEntity` object will start out with. - - - returns: A new `UsergridUser` object. - */ - required public init(type: String, name: String?, propertyDict: [String : AnyObject]?) { - super.init(type: type, name: name, propertyDict: propertyDict) - } - - /** - Designated initializer for `UsergridUser` objects. - - - parameter name: The name of the user. Note this is different from the `username` property. - - parameter propertyDict: The optional property dictionary that the `UsergridEntity` object will start out with. - - - returns: A new instance of `UsergridUser`. - */ - public init(name:String,propertyDict:[String:AnyObject]? = nil) { - super.init(type: UsergridUser.USER_ENTITY_TYPE, name:name, propertyDict:propertyDict) - } - - /** - Convenience initializer for `UsergridUser` objects. - - - parameter name: The name of the user. Note this is different from the `username` property. - - parameter email: The user's email. - - parameter password: The optional user's password. - - - returns: A new instance of `UsergridUser`. - */ - public convenience init(name:String, email:String, password:String? = nil) { - self.init(name:name,email:email,username:nil,password:password) - } - - /** - Convenience initializer for `UsergridUser` objects. - - - parameter email: The user's email. - - parameter password: The optional user's password. - - - returns: A new instance of `UsergridUser`. - */ - public convenience init(email:String, password:String? = nil) { - self.init(name:nil,email:email,username:nil,password:password) - } - - /** - Convenience initializer for `UsergridUser` objects. - - - parameter name: The name of the user. Note this is different from the `username` property. - - parameter username: The username of the user. - - parameter password: The optional user's password. - - - returns: A new instance of `UsergridUser`. - */ - public convenience init(name:String, username:String, password:String? = nil) { - self.init(name:name,email:nil,username:username,password:password) - } - - /** - Convenience initializer for `UsergridUser` objects. - - - parameter username: The username of the user. - - parameter password: The optional user's password. - - - returns: A new instance of `UsergridUser`. - */ - public convenience init(username:String, password:String? = nil) { - self.init(name:nil,email:nil,username:username,password:password) - } - - /** - Convenience initializer for `UsergridUser` objects. - - - parameter name: The optional name of the user. Note this is different from the `username` property. - - parameter email: The optional user's email. - - parameter username: The optional username of the user. - - parameter password: The optional user's password. - - - returns: A new instance of `UsergridUser`. - */ - public convenience init(name:String?, email:String?, username:String?, password:String? = nil) { - self.init(name:name) - self.email = email - self.username = username - self.password = password - } - - // MARK: - NSCoding - - - /** - NSCoding protocol initializer. - - - parameter aDecoder: The decoder. - - - returns: A decoded `UsergridUser` object. - */ - required public init?(coder aDecoder: NSCoder) { - self.auth = aDecoder.decodeObjectForKey("auth") as? UsergridUserAuth - super.init(coder: aDecoder) - } - - /** - NSCoding protocol encoder. - - - parameter aCoder: The encoder. - */ - public override func encodeWithCoder(aCoder: NSCoder) { - aCoder.encodeObject(self.auth, forKey: "auth") - super.encodeWithCoder(aCoder) - } - - // MARK: - Class Methods - - - /** - Checks the given email and/or username availablity for new `UsergridUser` objects using the shared instance of `UsergridClient`. - - - parameter email: The optional email address. - - parameter username: The optional username. - - parameter completion: The completion block. - */ - public static func checkAvailable(email:String?, username:String?, completion:UsergridUserAvailabilityCompletion) { - self.checkAvailable(Usergrid.sharedInstance, email: email, username: username, completion: completion) - } - - /** - Checks the given email and/or username availablity for new `UsergridUser` objects using with the given `UsergridClient`. - - - parameter client: The client to use for checking availability. - - parameter email: The optional email address. - - parameter username: The optional username. - - parameter completion: The completion block. - */ - 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) - } - if let usernameValue = username { - query.or().eq(UsergridUserProperties.Username.stringValue, value: usernameValue) - } - client.GET(USER_ENTITY_TYPE, query: query) { (response) -> Void in - completion(error: response.error, available: response.entity == nil) - } - } - - // MARK: - Instance Methods - - - /** - Creates the user object in Usergrid if the user does not already exist with the shared instance of `UsergridClient`. - - - parameter completion: The optional completion block. - */ - public func create(completion: UsergridResponseCompletion? = nil) { - self.create(Usergrid.sharedInstance, completion: completion) - } - - /** - Creates the user object in Usergrid if the user does not already exist with the given `UsergridClient`. - - - parameter client: The client to use for creation. - - parameter completion: The optional completion block. - */ - public func create(client: UsergridClient, completion: UsergridResponseCompletion? = nil) { - client.POST(self,completion:completion) - } - - /** - Authenticates the specified user using the provided username and password with the shared instance of `UsergridClient`. - - While functionally similar to `UsergridClient.authenticateUser(auth)`, this method does not automatically assign this user to `UsergridClient.currentUser`: - - - parameter username: The username. - - parameter password: The password. - - parameter completion: The optional completion block. - */ - public func login(username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) { - self.login(Usergrid.sharedInstance, username: username, password: password, completion: completion) - } - - /** - Authenticates the specified user using the provided username and password. - - While functionally similar to `UsergridClient.authenticateUser(auth)`, this method does not automatically assign this user to `UsergridClient.currentUser`: - - - parameter client: The client to use for login. - - parameter username: The username. - - parameter password: The password. - - parameter completion: The optional completion block. - */ - public func login(client: UsergridClient, username:String, password:String, completion: UsergridUserAuthCompletionBlock? = nil) { - let userAuth = UsergridUserAuth(username: username, password: password) - client.authenticateUser(userAuth,setAsCurrentUser:false) { [weak self] (auth, user, error) -> Void in - self?.auth = userAuth - completion?(auth: userAuth, user: user, error: error) - } - } - - /** - Changes the User's current password with the shared instance of `UsergridClient`. - - - parameter old: The old password. - - parameter new: The new password. - - parameter completion: The optional completion block. - */ - public func resetPassword(old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) { - self.resetPassword(Usergrid.sharedInstance, old: old, new: new, completion: completion) - } - - /** - Changes the User's current password with the shared instance of `UsergridClient`. - - - parameter client: The client to use for resetting the password. - - parameter old: The old password. - - parameter new: The new password. - - parameter completion: The optional completion block - */ - public func resetPassword(client: UsergridClient, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) { - client.resetPassword(self, old: old, new: new, completion: completion) - } - - /** - Attmepts to reauthenticate using the user's `UsergridUserAuth` instance property with the shared instance of `UsergridClient`. - - - parameter completion: The optional completion block. - */ - public func reauthenticate(completion: UsergridUserAuthCompletionBlock? = nil) { - self.reauthenticate(Usergrid.sharedInstance, completion: completion) - } - - /** - Attmepts to reauthenticate using the user's `UsergridUserAuth` instance property. - - - parameter client: The client to use for reauthentication. - - parameter completion: The optional completion block. - */ - public func reauthenticate(client: UsergridClient, completion: UsergridUserAuthCompletionBlock? = nil) { - if let userAuth = self.auth { - client.authenticateUser(userAuth, completion: completion) - } else { - let error = UsergridResponseError(errorName: "Invalid UsergridUserAuth.", errorDescription: "No UsergridUserAuth found on the UsergridUser.") - completion?(auth: nil, user: self, error: error) - } - } - - /** - Invalidates the user token locally and remotely. - - - parameter completion: The optional completion block. - */ - public func logout(completion:UsergridResponseCompletion? = nil) { - self.logout(Usergrid.sharedInstance,completion:completion) - } - - /** - Invalidates the user token locally and remotely. - - - parameter client: The client to use for logout. - - parameter completion: The optional completion block. - */ - public func logout(client: UsergridClient, completion:UsergridResponseCompletion? = nil) { - if self === client.currentUser { - client.logoutCurrentUser(completion) - } else if let uuidOrUsername = self.uuidOrUsername, accessToken = self.auth?.accessToken { - client.logoutUser(uuidOrUsername, token: accessToken) { (response) in - self.auth = nil - completion?(response: response) - } - } else { - completion?(response: UsergridResponse(client:client, errorName:"Logout Failed.", errorDescription:"UUID or Access Token not found on UsergridUser object.")) - } - } - - private func getUserSpecificProperty(userProperty: UsergridUserProperties) -> AnyObject? { - var propertyValue: AnyObject? = super[userProperty.stringValue] - NSJSONReadingOptions.AllowFragments - switch userProperty { - case .Activated,.Disabled : - propertyValue = propertyValue?.boolValue - case .Age : - propertyValue = propertyValue?.integerValue - case .Name,.Username,.Password,.Email,.Picture : - break - } - return propertyValue - } - - /** - Subscript for the `UsergridUser` class. - - - Warning: When setting a properties value must be a valid JSON object. - - - Example usage: - ``` - let someName = usergridUser["name"] - - usergridUser["name"] = someName - ``` - */ - override public subscript(propertyName: String) -> AnyObject? { - get { - if let userProperty = UsergridUserProperties.fromString(propertyName) { - return self.getUserSpecificProperty(userProperty) - } else { - return super[propertyName] - } - } - set(propertyValue) { - super[propertyName] = propertyValue - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Push.xcodeproj/project.pbxproj ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Push.xcodeproj/project.pbxproj b/sdks/swift/Samples/Push/Push.xcodeproj/project.pbxproj index cbd1e3e..f786e4e 100644 --- a/sdks/swift/Samples/Push/Push.xcodeproj/project.pbxproj +++ b/sdks/swift/Samples/Push/Push.xcodeproj/project.pbxproj @@ -7,17 +7,91 @@ objects = { /* Begin PBXBuildFile section */ + 634855231C726A3B005FE016 /* UsergridSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 634855161C726A2D005FE016 /* UsergridSDK.framework */; }; + 634855241C726A3B005FE016 /* UsergridSDK.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 634855161C726A2D005FE016 /* UsergridSDK.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 637A720E1C5BF8160056545A /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 637A72061C5BF8160056545A /* AppDelegate.swift */; }; 637A720F1C5BF8160056545A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 637A72071C5BF8160056545A /* Assets.xcassets */; }; 637A72101C5BF8160056545A /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 637A72081C5BF8160056545A /* LaunchScreen.storyboard */; }; 637A72111C5BF8160056545A /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 637A720A1C5BF8160056545A /* Main.storyboard */; }; 637A72131C5BF8160056545A /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 637A720D1C5BF8160056545A /* ViewController.swift */; }; 637A72161C5C06270056545A /* UsergridManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 637A72151C5C06270056545A /* UsergridManager.swift */; }; - 93F1FDA07B9F97BFB25A2B6A /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73F3E0733C90D8FB3A70AF1A /* Pods.framework */; }; /* End PBXBuildFile section */ +/* Begin PBXContainerItemProxy section */ + 634855151C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 63AF0E881BBC38FB009D4196; + remoteInfo = "UsergridSDK iOS"; + }; + 634855171C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 639B4BEB1C3DD6CF005E26E7; + remoteInfo = "UsergridSDK watchOS"; + }; + 634855191C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 63EE610B1C406E1600AFC2CF; + remoteInfo = "UsergridSDK tvOS"; + }; + 6348551B1C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 631920451C48436500F99E86; + remoteInfo = "UsergridSDK OSX"; + }; + 6348551D1C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 6319204B1C49BC0700F99E86; + remoteInfo = UsergridSDK_TVOS_Tests; + }; + 6348551F1C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 630A219F1C49BFFC008BE87F; + remoteInfo = UsergridSDK_OSX_Tests; + }; + 634855211C726A2D005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 630A21B81C49C473008BE87F; + remoteInfo = UsergridSDK_iOS_Tests; + }; + 634855251C726A3B005FE016 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 63AF0E871BBC38FB009D4196; + remoteInfo = "UsergridSDK iOS"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 634855271C726A3B005FE016 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 634855241C726A3B005FE016 /* UsergridSDK.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileReference section */ - 40784BA539B3C7FC7074887B /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = "<group>"; }; + 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = UsergridSDK.xcodeproj; path = ../../UsergridSDK.xcodeproj; sourceTree = "<group>"; }; 637A71F01C5BF7B10056545A /* Push.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Push.app; sourceTree = BUILT_PRODUCTS_DIR; }; 637A72061C5BF8160056545A /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; }; 637A72071C5BF8160056545A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; }; @@ -26,8 +100,6 @@ 637A720C1C5BF8160056545A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 637A720D1C5BF8160056545A /* ViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; }; 637A72151C5C06270056545A /* UsergridManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UsergridManager.swift; sourceTree = "<group>"; }; - 73F3E0733C90D8FB3A70AF1A /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9BB4D667087D6CF002BECEB1 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -35,37 +107,33 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 93F1FDA07B9F97BFB25A2B6A /* Pods.framework in Frameworks */, + 634855231C726A3B005FE016 /* UsergridSDK.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 11B1DE4765D09F54EEAA5FB4 /* Pods */ = { + 6348550C1C726A2D005FE016 /* Products */ = { isa = PBXGroup; children = ( - 40784BA539B3C7FC7074887B /* Pods.debug.xcconfig */, - 9BB4D667087D6CF002BECEB1 /* Pods.release.xcconfig */, + 634855161C726A2D005FE016 /* UsergridSDK.framework */, + 634855181C726A2D005FE016 /* UsergridSDK.framework */, + 6348551A1C726A2D005FE016 /* UsergridSDK.framework */, + 6348551C1C726A2D005FE016 /* UsergridSDK.framework */, + 6348551E1C726A2D005FE016 /* UsergridSDK_TVOS_Tests.xctest */, + 634855201C726A2D005FE016 /* UsergridSDK_OSX_Tests.xctest */, + 634855221C726A2D005FE016 /* UsergridSDK_iOS_Tests.xctest */, ); - name = Pods; - sourceTree = "<group>"; - }; - 40B8DB4D5F8684F52D86AD13 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 73F3E0733C90D8FB3A70AF1A /* Pods.framework */, - ); - name = Frameworks; + name = Products; sourceTree = "<group>"; }; 637A71E71C5BF7B10056545A = { isa = PBXGroup; children = ( + 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */, 637A72051C5BF8160056545A /* Source */, 637A71F11C5BF7B10056545A /* Products */, - 11B1DE4765D09F54EEAA5FB4 /* Pods */, - 40B8DB4D5F8684F52D86AD13 /* Frameworks */, ); sourceTree = "<group>"; }; @@ -106,16 +174,15 @@ isa = PBXNativeTarget; buildConfigurationList = 637A72021C5BF7B10056545A /* Build configuration list for PBXNativeTarget "Push" */; buildPhases = ( - 07DB92FBF16075B01449F26B /* Check Pods Manifest.lock */, 637A71EC1C5BF7B10056545A /* Sources */, 637A71ED1C5BF7B10056545A /* Frameworks */, 637A71EE1C5BF7B10056545A /* Resources */, - 9A01B8F77A9D4469391D8826 /* Embed Pods Frameworks */, - EA12798F3DFFB01F69B53C53 /* Copy Pods Resources */, + 634855271C726A3B005FE016 /* Embed Frameworks */, ); buildRules = ( ); dependencies = ( + 634855261C726A3B005FE016 /* PBXTargetDependency */, ); name = Push; productName = Push; @@ -148,6 +215,12 @@ mainGroup = 637A71E71C5BF7B10056545A; productRefGroup = 637A71F11C5BF7B10056545A /* Products */; projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 6348550C1C726A2D005FE016 /* Products */; + ProjectRef = 6348550B1C726A2D005FE016 /* UsergridSDK.xcodeproj */; + }, + ); projectRoot = ""; targets = ( 637A71EF1C5BF7B10056545A /* Push */, @@ -155,6 +228,58 @@ }; /* End PBXProject section */ +/* Begin PBXReferenceProxy section */ + 634855161C726A2D005FE016 /* UsergridSDK.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = UsergridSDK.framework; + remoteRef = 634855151C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 634855181C726A2D005FE016 /* UsergridSDK.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = UsergridSDK.framework; + remoteRef = 634855171C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 6348551A1C726A2D005FE016 /* UsergridSDK.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = UsergridSDK.framework; + remoteRef = 634855191C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 6348551C1C726A2D005FE016 /* UsergridSDK.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = UsergridSDK.framework; + remoteRef = 6348551B1C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 6348551E1C726A2D005FE016 /* UsergridSDK_TVOS_Tests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = UsergridSDK_TVOS_Tests.xctest; + remoteRef = 6348551D1C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 634855201C726A2D005FE016 /* UsergridSDK_OSX_Tests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = UsergridSDK_OSX_Tests.xctest; + remoteRef = 6348551F1C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 634855221C726A2D005FE016 /* UsergridSDK_iOS_Tests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = UsergridSDK_iOS_Tests.xctest; + remoteRef = 634855211C726A2D005FE016 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + /* Begin PBXResourcesBuildPhase section */ 637A71EE1C5BF7B10056545A /* Resources */ = { isa = PBXResourcesBuildPhase; @@ -168,54 +293,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 07DB92FBF16075B01449F26B /* Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "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; - }; - 9A01B8F77A9D4469391D8826 /* Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Embed Pods Frameworks"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - EA12798F3DFFB01F69B53C53 /* Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Copy Pods Resources"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 637A71EC1C5BF7B10056545A /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -229,6 +306,14 @@ }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */ + 634855261C726A3B005FE016 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "UsergridSDK iOS"; + targetProxy = 634855251C726A3B005FE016 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + /* Begin PBXVariantGroup section */ 637A72081C5BF8160056545A /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; @@ -266,6 +351,7 @@ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; @@ -310,6 +396,7 @@ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -332,10 +419,10 @@ }; 637A72031C5BF7B10056545A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 40784BA539B3C7FC7074887B /* Pods.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_IDENTITY = "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.usergridpushsample; @@ -346,11 +433,11 @@ }; 637A72041C5BF7B10056545A /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9BB4D667087D6CF002BECEB1 /* Pods.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 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.usergridpushsample; http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Push.xcworkspace/contents.xcworkspacedata ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Push.xcworkspace/contents.xcworkspacedata b/sdks/swift/Samples/Push/Push.xcworkspace/contents.xcworkspacedata index d4ed8a6..268a2da 100644 --- a/sdks/swift/Samples/Push/Push.xcworkspace/contents.xcworkspacedata +++ b/sdks/swift/Samples/Push/Push.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ <FileRef location = "group:Push.xcodeproj"> </FileRef> - <FileRef - location = "group:Pods/Pods.xcodeproj"> - </FileRef> </Workspace> http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Push.xcworkspace/xcshareddata/Push.xcscmblueprint ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Push.xcworkspace/xcshareddata/Push.xcscmblueprint b/sdks/swift/Samples/Push/Push.xcworkspace/xcshareddata/Push.xcscmblueprint deleted file mode 100644 index bec49ab..0000000 --- a/sdks/swift/Samples/Push/Push.xcworkspace/xcshareddata/Push.xcscmblueprint +++ /dev/null @@ -1,30 +0,0 @@ -{ - "DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" : "E28DB29D4B8B9FB468FB340D2257B16682332D89", - "DVTSourceControlWorkspaceBlueprintWorkingCopyRepositoryLocationsKey" : { - - }, - "DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" : { - "E28DB29D4B8B9FB468FB340D2257B16682332D89" : 0, - "AD57BFF635DD66DF5DF78257082332592EB51D31" : 0 - }, - "DVTSourceControlWorkspaceBlueprintIdentifierKey" : "ADB99685-1C5E-4D1B-99F9-59253396C726", - "DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" : { - "E28DB29D4B8B9FB468FB340D2257B16682332D89" : "swift\/", - "AD57BFF635DD66DF5DF78257082332592EB51D31" : ".." - }, - "DVTSourceControlWorkspaceBlueprintNameKey" : "Push", - "DVTSourceControlWorkspaceBlueprintVersion" : 204, - "DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" : "Samples\/Push\/Push.xcworkspace", - "DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" : [ - { - "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "github.com:RobertWalsh\/usergrid.git", - "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", - "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "AD57BFF635DD66DF5DF78257082332592EB51D31" - }, - { - "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "github.com:RobertWalsh\/UsergridSDK.git", - "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", - "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "E28DB29D4B8B9FB468FB340D2257B16682332D89" - } - ] -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Push/Readme.md ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Readme.md b/sdks/swift/Samples/Push/Readme.md new file mode 100644 index 0000000..488509c --- /dev/null +++ b/sdks/swift/Samples/Push/Readme.md @@ -0,0 +1,21 @@ +#Push + +## Running the Sample + +To run the sample app, simply open the `Push.xcworkspace` file in Xcode. + +Two targets in Xcode specific to this application will be available: + +- **Push Target** + + This will run the iOS sample application. + +##Configuring the Sample Apps + +Before running the sample applications you will need to configure each sample application. + +Each sample application should include a source file named `UsergridManager.swift`. This source file is used to contain interaction with the UsergridSDK within a single source file. In doing so, the interactions within the sample apps can be easily seen and examined. + +Within the `UsergridManager.swift` source there will be at least two different static vars named `ORG_ID` and `APP_ID`. You will need to configure those values in order to run the applications in your environment. + +Applications which utilize push notifications will require a valid provisioning profile and device for the push services to work correctly. http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Samples/Readme.md ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Readme.md b/sdks/swift/Samples/Readme.md index 4c5601f..fbfacdb 100644 --- a/sdks/swift/Samples/Readme.md +++ b/sdks/swift/Samples/Readme.md @@ -2,7 +2,7 @@ The sample apps in this directory are intended to show basic usage of some of the major features of the UsergridSDK. -Each sample application utilizes `Cocoapods` to interact with the UsergridSDK. +> Each sample application installs the UsergridSDK by embedding the framework directly. A sample application integrating the UsergridSDK via `Cocoapods` will be coming in the near future. ##Samples Apps @@ -10,6 +10,12 @@ Each sample application utilizes `Cocoapods` to interact with the UsergridSDK. * **Push** - An app that registers for and sends push notifications. +## Running the Sample Apps + +To run the sample apps, simply open the `<SAMPLE APP NAME>.xcworkspace` file in Xcode, then run the app. + +> Note that some applications utilize `Cocoapods` (such as the `ActivityFeed` sample) and you will need to run the `$ pod install` command from within the root folder of the sample project in order for the sample to run properly. + ##Configuring the Sample Apps Before running the sample applications you will need to configure each sample application. @@ -19,7 +25,3 @@ Each sample application should include a source file named `UsergridManager.swif Within the `UsergridManager.swift` source there will be at least two different static vars named `ORG_ID` and `APP_ID`. You will need to configure those values in order to run the applications in your environment. Applications which utilize push notifications will require a valid provisioning profile and device for the push services to work correctly. - -## Running the Sample Apps - -To run the sample apps, simply open the <SAMPLE APP NAME>.xcworkspace file in Xcode, then run the app. \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Source/Usergrid.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Source/Usergrid.swift b/sdks/swift/Source/Usergrid.swift index 78769ae..1049a62 100644 --- a/sdks/swift/Source/Usergrid.swift +++ b/sdks/swift/Source/Usergrid.swift @@ -72,13 +72,25 @@ public class Usergrid: NSObject { /// 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{ Usergrid.sharedInstance.appAuth = newValue } + get { return Usergrid.sharedInstance.appAuth } + set(auth) { Usergrid.sharedInstance.appAuth = auth } + } + + /// The `UsergridAuthFallback` value used to determine what type of token will be sent of the shared instance of `UsergridClient`, if any. + public static var authFallback: UsergridAuthFallback { + get { return Usergrid.sharedInstance.authFallback } + set(authFallback) { Usergrid.sharedInstance.authFallback = authFallback } } // MARK: - Initialization - @@ -162,12 +174,6 @@ public class Usergrid: NSObject { // MARK: - Authorization - - /// The `UsergridAuthFallback` value used to determine what type of token will be sent of the shared instance of `UsergridClient`, if any. - public static var authFallback: UsergridAuthFallback { - get{ return Usergrid.sharedInstance.authFallback } - set { Usergrid.sharedInstance.authFallback = newValue } - } - /** Sets the shared `UsergridClient`'s `tempAuth` property using the passed in `UsergridAuth`. @@ -305,14 +311,23 @@ public class Usergrid: NSObject { } /** - Gets a group of `UsergridEntity` objects of a given type with an optional query using the shared instance of `UsergridCient`. + Gets a group of `UsergridEntity` objects of a given type using the shared instance of `UsergridCient`. - - parameter type: The `UsergridEntity` type. - - parameter query: The optional query to use when gathering `UsergridEntity` objects. - - parameter completion: The completion block that will be called once the request has completed. + - 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(type: String, query: UsergridQuery? = nil, completion: UsergridResponseCompletion? = nil) { - Usergrid.sharedInstance.GET(type,query:query,completion:completion) + public static func GET(query: UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) { + Usergrid.sharedInstance.GET(query,queryCompletion:queryCompletion) } // MARK: - PUT - http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Source/UsergridClient.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Source/UsergridClient.swift b/sdks/swift/Source/UsergridClient.swift index cbb416f..9cb6aa7 100644 --- a/sdks/swift/Source/UsergridClient.swift +++ b/sdks/swift/Source/UsergridClient.swift @@ -53,13 +53,21 @@ public class UsergridClient: NSObject, NSCoding { /// The constructed URL string based on the `UsergridClient`'s `baseUrl`, `orgId`, and `appId`. internal var clientAppURL : String { return "\(baseUrl)/\(orgId)/\(appId)" } + /// Whether or not the current user will be saved and restored from the keychain. + public var persistCurrentUserInKeychain: Bool { + get { return config.persistCurrentUserInKeychain } + set(persist) { config.persistCurrentUserInKeychain = persist } + } + /// The currently logged in `UsergridUser`. internal(set) public var currentUser: UsergridUser? = nil { didSet { - if let newUser = self.currentUser { - UsergridUser.saveCurrentUserKeychainItem(self,currentUser:newUser) - } else if oldValue != nil { - UsergridUser.deleteCurrentUserKeychainItem(self) + if persistCurrentUserInKeychain { + if let newUser = self.currentUser { + UsergridUser.saveCurrentUserKeychainItem(self,currentUser:newUser) + } else if oldValue != nil { + UsergridUser.deleteCurrentUserKeychainItem(self) + } } } } @@ -72,14 +80,14 @@ public class UsergridClient: NSObject, NSCoding { /// The application level `UsergridAppAuth` object. Can be set manually but must call `authenticateApp` to retrive token. public var appAuth: UsergridAppAuth? { - set { config.appAuth = newValue } get { return config.appAuth } + set(auth) { config.appAuth = auth } } /// The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. public var authFallback: UsergridAuthFallback { - set { config.authFallback = newValue } get { return config.authFallback } + set(fallback) { config.authFallback = fallback } } // MARK: - Initialization - @@ -119,7 +127,10 @@ public class UsergridClient: NSObject, NSCoding { public init(configuration:UsergridClientConfig) { self.config = configuration super.init() - self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) // Attempt to get the current user from the saved keychain data. + if persistCurrentUserInKeychain { + self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) // Attempt to get the current user from the saved keychain data. + } + UsergridDevice.sharedDevice.save(self) } // MARK: - NSCoding - @@ -145,9 +156,11 @@ public class UsergridClient: NSObject, NSCoding { if let currentUser = aDecoder.decodeObjectForKey("currentUser") as? UsergridUser { self.currentUser = currentUser } else { - // If we didn't decode a current user, attempt to get the current user from the saved keychain data. - self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) + if persistCurrentUserInKeychain { + self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) + } } + UsergridDevice.sharedDevice.save(self) } /** @@ -183,7 +196,7 @@ public class UsergridClient: NSObject, NSCoding { */ public func applyPushToken(device: UsergridDevice, pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) { device.applyPushToken(pushToken, notifierID: notifierID) - PUT(UsergridDevice.DEVICE_ENTITY_TYPE, jsonBody: device.jsonObjectValue, completion: completion) + device.save(self, completion: completion) } // MARK: - Authorization and User Management - @@ -415,15 +428,31 @@ public class UsergridClient: NSObject, NSCoding { } /** - Gets a group of `UsergridEntity` objects of a given type with an optional query. + Gets a group of `UsergridEntity` objects of a given type. - - parameter type: The `UsergridEntity` type. - - parameter query: The optional query to use when gathering `UsergridEntity` objects. - - parameter completion: The optional completion block that will be called once the request has completed. + - 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()) + self.sendRequest(request, completion: completion) + } + + /** + Gets a group of `UsergridEntity` objects using a given query. + + - 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(type: String, query: UsergridQuery? = nil, completion: 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.")) + return + } + let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type], query: query, auth: self.authForRequests()) - self.sendRequest(request, completion: completion) + self.sendRequest(request, completion: queryCompletion) } // MARK: - PUT - http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Source/UsergridClientConfig.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Source/UsergridClientConfig.swift b/sdks/swift/Source/UsergridClientConfig.swift index c79b6b2..2719610 100644 --- a/sdks/swift/Source/UsergridClientConfig.swift +++ b/sdks/swift/Source/UsergridClientConfig.swift @@ -45,9 +45,12 @@ public class UsergridClientConfig : NSObject, NSCoding { public var baseUrl: String = UsergridClient.DEFAULT_BASE_URL /// The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. - public var authFallback: UsergridAuthFallback = .App + public var authFallback: UsergridAuthFallback = .None - /** + /// Whether or not the `UsergridClient` current user will be saved and restored from the keychain. + public var persistCurrentUserInKeychain: Bool = true + + /** The application level `UsergridAppAuth` object. Note that you still need to call the authentication methods within `UsergridClient` once it has been initialized. @@ -86,16 +89,18 @@ public class UsergridClientConfig : NSObject, NSCoding { /** Convenience initializer for `UsergridClientConfig`. - - parameter orgId: The organization identifier. - - parameter appId: The application identifier. - - parameter baseUrl: The base URL that all calls will be made with. - - parameter authFallback: The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. - - parameter appAuth: The application level `UsergridAppAuth` object. + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + - parameter baseUrl: The base URL that all calls will be made with. + - parameter authFallback: The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. + - parameter persistCurrentUserInKeychain: Whether or not the `UsergridClient` current user will be saved and restored from the keychain. + - parameter appAuth: The application level `UsergridAppAuth` object. - returns: A new instance of `UsergridClientConfig`. */ - public convenience init(orgId: String, appId: String, baseUrl:String, authFallback:UsergridAuthFallback, appAuth:UsergridAppAuth? = nil) { + public convenience init(orgId: String, appId: String, baseUrl:String, authFallback:UsergridAuthFallback, persistCurrentUserInKeychain: Bool = true, appAuth:UsergridAppAuth? = nil) { self.init(orgId:orgId,appId:appId,baseUrl:baseUrl) + self.persistCurrentUserInKeychain = persistCurrentUserInKeychain self.authFallback = authFallback self.appAuth = appAuth } @@ -123,6 +128,7 @@ public class UsergridClientConfig : NSObject, NSCoding { self.orgId = orgId self.baseUrl = baseUrl self.appAuth = aDecoder.decodeObjectForKey("appAuth") as? UsergridAppAuth + self.persistCurrentUserInKeychain = aDecoder.decodeBoolForKey("persistCurrentUserInKeychain") ?? true self.authFallback = UsergridAuthFallback(rawValue:aDecoder.decodeIntegerForKey("authFallback")) ?? .App super.init() } @@ -137,6 +143,7 @@ public class UsergridClientConfig : NSObject, NSCoding { 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.authFallback.rawValue, forKey: "authFallback") } } http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Source/UsergridDevice.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Source/UsergridDevice.swift b/sdks/swift/Source/UsergridDevice.swift index c08fcf6..995470c 100644 --- a/sdks/swift/Source/UsergridDevice.swift +++ b/sdks/swift/Source/UsergridDevice.swift @@ -58,10 +58,10 @@ public class UsergridDevice : UsergridEntity { /// Property helper method for the `UsergridDevice` objects device operating system version. public var osVersion: String { return super[UsergridDeviceProperties.OSVersion.stringValue] as! String } - // MARK: - Initialization - - /// The shared instance of `UsergridDevice`. - public static var sharedDevice: UsergridDevice = UsergridDevice() + public static var sharedDevice: UsergridDevice = UsergridDevice.getOrCreateSharedDeviceFromKeychain() + + // MARK: - Initialization - /** Designated Initializer for `UsergridDevice` objects @@ -71,25 +71,7 @@ public class UsergridDevice : UsergridEntity { - returns: A new instance of `UsergridDevice`. */ public init() { - var deviceEntityDict: [String:AnyObject] = [:] - deviceEntityDict[UsergridEntityProperties.EntityType.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE - deviceEntityDict[UsergridEntityProperties.UUID.stringValue] = UsergridDevice.usergridDeviceUUID() - - #if os(watchOS) - deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = WKInterfaceDevice.currentDevice().model - deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = WKInterfaceDevice.currentDevice().systemName - deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = WKInterfaceDevice.currentDevice().systemVersion - #elseif os(iOS) || os(tvOS) - deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = UIDevice.currentDevice().model - deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = UIDevice.currentDevice().systemName - deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = UIDevice.currentDevice().systemVersion - #elseif os(OSX) - deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = "Mac" - deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = "OSX" - deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = NSProcessInfo.processInfo().operatingSystemVersionString - #endif - - super.init(type: UsergridDevice.DEVICE_ENTITY_TYPE, propertyDict: deviceEntityDict) + super.init(type: UsergridDevice.DEVICE_ENTITY_TYPE, propertyDict: UsergridDevice.commonDevicePropertyDict()) } /** @@ -101,7 +83,7 @@ public class UsergridDevice : UsergridEntity { - returns: A new `UsergridDevice` object. */ - required public init(type: String, name: String?, propertyDict: [String : AnyObject]?) { + required public init(type:String, name:String? = nil, propertyDict:[String:AnyObject]? = nil) { super.init(type: type, name: name, propertyDict: propertyDict) } @@ -148,6 +130,34 @@ public class UsergridDevice : UsergridEntity { } } + // MARK: - Class Helper Methods - + + /** + Creates a property dictionary that contains the common properties for `UsergridDevice` objects. + + - 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 + + #if os(watchOS) + commonDevicePropertyDict[UsergridDeviceProperties.Model.stringValue] = WKInterfaceDevice.currentDevice().model + commonDevicePropertyDict[UsergridDeviceProperties.Platform.stringValue] = WKInterfaceDevice.currentDevice().systemName + commonDevicePropertyDict[UsergridDeviceProperties.OSVersion.stringValue] = WKInterfaceDevice.currentDevice().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 + #elseif os(OSX) + commonDevicePropertyDict[UsergridDeviceProperties.Model.stringValue] = "Mac" + commonDevicePropertyDict[UsergridDeviceProperties.Platform.stringValue] = "OSX" + commonDevicePropertyDict[UsergridDeviceProperties.OSVersion.stringValue] = NSProcessInfo.processInfo().operatingSystemVersionString + #endif + + return commonDevicePropertyDict + } + // MARK: - Push Token Handling - /** http://git-wip-us.apache.org/repos/asf/usergrid/blob/c638c774/sdks/swift/Source/UsergridEntity.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Source/UsergridEntity.swift b/sdks/swift/Source/UsergridEntity.swift index 4b6fe8f..5baaba4 100644 --- a/sdks/swift/Source/UsergridEntity.swift +++ b/sdks/swift/Source/UsergridEntity.swift @@ -73,7 +73,7 @@ public class UsergridEntity: NSObject, NSCoding { /// Property helper method for the `UsergridEntity` objects `UsergridEntityProperties.Location`. public var location: CLLocation? { get { return self.getEntitySpecificProperty(.Location) as? CLLocation } - set { self[UsergridEntityProperties.Location.stringValue] = newValue } + set(newLocation) { self[UsergridEntityProperties.Location.stringValue] = newLocation } } /// Property helper method to get the UUID or name of the `UsergridEntity`. @@ -89,7 +89,7 @@ public class UsergridEntity: NSObject, NSCoding { public var jsonObjectValue : [String:AnyObject] { return self.properties } /// The string value. - public var stringValue : String { return NSString(data: try! NSJSONSerialization.dataWithJSONObject(self.jsonObjectValue, options: .PrettyPrinted), encoding: NSASCIIStringEncoding) as! String } + public var stringValue : String { return NSString(data: try! NSJSONSerialization.dataWithJSONObject(self.jsonObjectValue, options: .PrettyPrinted), encoding: NSUTF8StringEncoding) as! String } /// The description. public override var description : String { @@ -127,12 +127,10 @@ public class UsergridEntity: NSObject, NSCoding { } } - private func copyInternalsFromEntity(entity:UsergridEntity) { + internal func copyInternalsFromEntity(entity:UsergridEntity) { self.properties = entity.properties - self.asset = entity.asset ?? self.asset } - /** Used for custom mapping subclasses to a given `Usergrid` type. @@ -434,7 +432,7 @@ public class UsergridEntity: NSObject, NSCoding { completion?(response: response) } } else { - completion?(response: UsergridResponse(client: client, errorName: "Entity cannot be reloaded.", errorDescription: "Entity has neither an UUID or specified.")) + completion?(response: UsergridResponse(client: client, errorName: "Entity cannot be reloaded.", errorDescription: "Entity has neither an UUID or name specified.")) } }