repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GENG-GitHub/weibo-gd
refs/heads/master
GDWeibo/Class/Module/Home/View/RefreshControl/GDRefreshControl.swift
apache-2.0
1
// // GDRefreshControl.swift // GDWeibo // // Created by geng on 15/11/5. // Copyright © 2015年 geng. All rights reserved. // import UIKit class GDRefreshControl: UIRefreshControl { //MARK: - 属性 private let RefreshControlOffest: CGFloat = -60 //MARK: - 记录箭头的指向 private var isUp = false //重写父类的frame属性 override var frame:CGRect { didSet{ if frame.origin.y >= 0 { return } //如果当前菊花在转 if refreshing { refreshView.startLoading() } if frame.origin.y > RefreshControlOffest && !isUp { print("箭头向上") isUp = true refreshView.startRotateTipView(isUp) return }else if frame.origin.y < RefreshControlOffest && isUp { print("箭头向下") isUp = false refreshView.startRotateTipView(isUp) return } } } //MARK: - 重写endRefreshingfangf override func endRefreshing() { //停止系统的菊花 super.endRefreshing() //停止自己定义的菊花转动 refreshView.stopRotating() } //MARK: - 重写构造方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init() { super.init() //设置菊花的颜色 tintColor = UIColor.clearColor() //设置子控件 prepareUI() } //准备子控件 func prepareUI() { //设置子控件 self.addSubview(refreshView) //添加约束,这里的size必须要设置,否则出现意想不到的结果 refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size) } //MARK: - 懒加载 private lazy var refreshView: GDRefreshView = GDRefreshView.refreshView() } //MARK: - 自定义 class GDRefreshView: UIView { //下拉刷新View @IBOutlet weak var tipView: UIView! //箭头 @IBOutlet weak var tipIcon: UIImageView! //加载圆圈 @IBOutlet weak var loadingIcon: UIImageView! //MARK: - 类方法加载xib class func refreshView() -> GDRefreshView { return NSBundle.mainBundle().loadNibNamed("GDRefreshView", owner: nil, options: nil).last as! GDRefreshView } //开始转动箭头 func startRotateTipView(isUp: Bool) { //动画移动箭头 UIView.animateWithDuration(0.25) { () -> Void in self.tipIcon.transform = isUp ? CGAffineTransformIdentity : CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) } } //停止转动 func stopRotating() { //显示下拉刷新View tipView.hidden = false //移除动画 loadingIcon.layer.removeAllAnimations() } //开始加载 func startLoading(){ let animKey = "animKey" //如果当前有动画在执行就返回 if let _ = loadingIcon.layer.animationForKey(animKey) { return } //隐藏箭头View tipView.hidden = true //动画旋转圆圈 let animation = CABasicAnimation(keyPath: "transform.rotation") //设置动画时间 animation.duration = 0.25 //设置动画次数 animation.repeatCount = MAXFLOAT //设置动画范围 animation.toValue = 2 * M_PI //仿真切换控制器动画被停止 animation.removedOnCompletion = false //添加动画到layer上 loadingIcon.layer.addAnimation(animation, forKey: animKey) } }
a50038f270095040c86e5a156c7be503
19.032609
123
0.514107
false
false
false
false
polenoso/TMDBiOS
refs/heads/master
theiostmdb/theiostmdb/SidePanelViewController.swift
mit
1
// // SidePanelViewController.swift // theiostmdb // // Created by bbva on 23/3/17. // // import UIKit @objc protocol SidePanelViewControllerDelegate { func optionSelected(vc: UIViewController) } class SidePanelViewController: UIViewController { var delegate: SidePanelViewControllerDelegate? let optionArray = [String](arrayLiteral: "Discover","Search") @IBOutlet weak var optionsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() optionsTable.delegate = self optionsTable.dataSource = self optionsTable.register(UINib.init(nibName: "OptionCell", bundle: nil), forCellReuseIdentifier: "optionCell") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension SidePanelViewController: UITableViewDelegate, UITableViewDataSource{ public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 2 } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) @available(iOS 2.0, *) public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell", for: indexPath) as! OptionCell cell.titleforIndex(title: self.optionArray[indexPath.row]) return cell } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableView.frame.size.height/2.0 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: delegate?.optionSelected(vc: ViewController()) break case 1: let svc = SearchViewController(nibName: "SearchViewController", bundle: nil) delegate?.optionSelected(vc: svc) default: return } } } class OptionCell: UITableViewCell{ @IBOutlet weak var optionLabel: UILabel! func titleforIndex(title: String){ self.optionLabel.text = title } }
ab5aa0f4a290821160e43823f5b19ff3
30.202128
188
0.684282
false
false
false
false
handsomecode/InteractiveSideMenu
refs/heads/master
Sample/Sample/Menu Controllers/TweakViewController.swift
apache-2.0
1
// // TweakViewController.swift // Sample // // Created by Eric Miller on 2/9/18. // Copyright © 2018 Handsome. All rights reserved. // import UIKit import InteractiveSideMenu class TweakViewController: UIViewController, SideMenuItemContent, Storyboardable { @IBOutlet private weak var animationDurationValueLabel: UILabel! @IBOutlet private weak var contentScaleValueLabel: UILabel! @IBOutlet private weak var visibilityValueLabel: UILabel! @IBOutlet private weak var visibilitySlider: UISlider! override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func viewDidLoad() { super.viewDidLoad() visibilitySlider.maximumValue = Float(UIScreen.main.bounds.width) if let navController = parent as? UINavigationController, let menuContainerController = navController.parent as? MenuContainerViewController { visibilitySlider.value = Float(menuContainerController.transitionOptions.visibleContentWidth) visibilityValueLabel.text = "\(menuContainerController.transitionOptions.visibleContentWidth)" } } @IBAction func openMenu(_ sender: UIBarButtonItem) { showSideMenu() } @IBAction func animationDurationDidChange(_ slider: UISlider) { animationDurationValueLabel.text = "\(TimeInterval(slider.value))" if let navController = parent as? UINavigationController, let menuContainerController = navController.parent as? MenuContainerViewController { menuContainerController.transitionOptions.duration = TimeInterval(slider.value) } } @IBAction func contentScaleDidChange(_ slider: UISlider) { contentScaleValueLabel.text = "\(CGFloat(slider.value))" if let navController = parent as? UINavigationController, let menuContainerController = navController.parent as? MenuContainerViewController { menuContainerController.transitionOptions.contentScale = CGFloat(slider.value) } } @IBAction func visibilityDidChange(_ slider: UISlider) { visibilityValueLabel.text = "\(CGFloat(slider.value))" if let navController = parent as? UINavigationController, let menuContainerController = navController.parent as? MenuContainerViewController { menuContainerController.transitionOptions.visibleContentWidth = CGFloat(slider.value) } } }
c27c8ac5d266c93496f8d0d04a4e8217
39.114754
106
0.724561
false
false
false
false
mgireesh05/leetcode
refs/heads/master
LeetCodeSwiftPlayground.playground/Sources/integer-replacement.swift
mit
1
/** * Solution to the problem: https://leetcode.com/problems/integer-replacement/ */ //Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground. public class Solution397 { public init() { } var dict = [Int: Int]() public func integerReplacement(_ n: Int) -> Int { if(n == 1){ return 0 } if(dict[n] != nil){ return dict[n]! } /* The logic is very similar to solving fibonacci using DP. Save the computed subproblems (f(n/2) or f(n-1) or f(n+1)) in a dictionary and look them up when encountered instead of recomputing. This will solve the problem in linear time which would otherwise will be exponential. */ var minVal = 0 if(n%2 == 0){ let min0 = integerReplacement(n/2) dict[n/2] = min0 minVal = min0 + 1 }else{ let min0 = integerReplacement(n+1) dict[n+1] = min0 let min1 = integerReplacement(n-1) dict[n-1] = min1 minVal = min(min0, min1) + 1 } return minVal } }
b63110c07973a432a4b37cb3ee092971
20.770833
143
0.647847
false
false
false
false
bustoutsolutions/siesta
refs/heads/main
Source/Siesta/Request/NetworkRequest.swift
mit
1
// // NetworkRequest.swift // Siesta // // Created by Paul on 2015/12/15. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation internal final class NetworkRequestDelegate: RequestDelegate { // Basic metadata private let resource: Resource internal var config: Configuration { resource.configuration(for: underlyingRequest) } internal let requestDescription: String // Networking private let requestBuilder: () -> URLRequest // so repeated() can re-read config private let underlyingRequest: URLRequest internal var networking: RequestNetworking? // present only after start() // Progress private var progressComputation: RequestProgressComputation // MARK: Managing request init(resource: Resource, requestBuilder: @escaping () -> URLRequest) { self.resource = resource self.requestBuilder = requestBuilder underlyingRequest = requestBuilder() requestDescription = SiestaLog.Category.enabled.contains(.network) || SiestaLog.Category.enabled.contains(.networkDetails) ? debugStr([underlyingRequest.httpMethod, underlyingRequest.url]) : "NetworkRequest" progressComputation = RequestProgressComputation(isGet: underlyingRequest.httpMethod == "GET") } func startUnderlyingOperation(passingResponseTo completionHandler: RequestCompletionHandler) { let networking = resource.service.networkingProvider.startRequest(underlyingRequest) { res, data, err in DispatchQueue.main.async { self.responseReceived( underlyingResponse: res, body: data, error: err, completionHandler: completionHandler) } } self.networking = networking } func cancelUnderlyingOperation() { networking?.cancel() } func repeated() -> RequestDelegate { NetworkRequestDelegate(resource: resource, requestBuilder: requestBuilder) } // MARK: Progress func computeProgress() -> Double { if let networking = networking { progressComputation.update(from: networking.transferMetrics) } return progressComputation.fractionDone } var progressReportingInterval: TimeInterval { config.progressReportingInterval } // MARK: Response handling // Entry point for response handling. Triggered by RequestNetworking completion callback. private func responseReceived( underlyingResponse: HTTPURLResponse?, body: Data?, error: Error?, completionHandler: RequestCompletionHandler) { DispatchQueue.mainThreadPrecondition() SiestaLog.log(.network, ["Response: ", underlyingResponse?.statusCode ?? error, "←", requestDescription]) SiestaLog.log(.networkDetails, ["Raw response headers:", underlyingResponse?.allHeaderFields]) SiestaLog.log(.networkDetails, ["Raw response body:", body?.count ?? 0, "bytes"]) let responseInfo = interpretResponse(underlyingResponse, body, error) if completionHandler.willIgnore(responseInfo) { return } progressComputation.complete() transformResponse(responseInfo, then: completionHandler.broadcastResponse) } private func isError(httpStatusCode: Int?) -> Bool { guard let httpStatusCode = httpStatusCode else { return false } return httpStatusCode >= 400 } private func interpretResponse( _ underlyingResponse: HTTPURLResponse?, _ body: Data?, _ error: Error?) -> ResponseInfo { if isError(httpStatusCode: underlyingResponse?.statusCode) || error != nil { return ResponseInfo( response: .failure(RequestError(response: underlyingResponse, content: body, cause: error))) } else if underlyingResponse?.statusCode == 304 { if let entity = resource.latestData { return ResponseInfo(response: .success(entity), isNew: false) } else { return ResponseInfo( response: .failure(RequestError( userMessage: NSLocalizedString("No data available", comment: "userMessage"), cause: RequestError.Cause.NoLocalDataFor304()))) } } else { return ResponseInfo(response: .success(Entity<Any>(response: underlyingResponse, content: body ?? Data()))) } } private func transformResponse( _ rawInfo: ResponseInfo, then afterTransformation: @escaping (ResponseInfo) -> Void) { let processor = config.pipeline.makeProcessor(rawInfo.response, resource: resource) DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { let processedInfo = rawInfo.isNew ? ResponseInfo(response: processor(), isNew: true) : rawInfo DispatchQueue.main.async { afterTransformation(processedInfo) } } } }
1c3c6e36f6865e12d03839830ce08abf
32.814815
119
0.608251
false
false
false
false
IBM-MIL/BluePic
refs/heads/master
BluePic-iOS/BluePic/ViewModels/ProfileViewModel.swift
apache-2.0
1
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit class ProfileViewModel: NSObject { //array that holds all that pictures that are displayed in the collection view var pictureDataArray = [Picture]() //callback used to tell the ProfileViewController when to refresh its collection view var refreshVCCallback : (()->())! //state variable to keep try of if the view model has receieved data from cloudant yet var hasRecievedDataFromCloudant = false //constant that represents the number of sections in the collection view let kNumberOfSectionsInCollectionView = 1 //constant that represents the height of the info view in the collection view cell that shows the photos caption and photographer name let kCollectionViewCellInfoViewHeight : CGFloat = 60 //constant that represents the limit of how big the colection view cell height can be let kCollectionViewCellHeightLimit : CGFloat = 480 //constant that represents a value added to the height of the EmptyFeedCollectionViewCell when its given a size in the sizeForItemAtIndexPath method, this value allows the collection view to scroll let kEmptyFeedCollectionViewCellBufferToAllowForScrolling : CGFloat = 1 //constant that represents the number of cells in the collection view when there is no photos let kNumberOfCellsWhenUserHasNoPhotos = 1 /** Method called upon init, it sets up the callback to refresh the profile collection view - parameter refreshVCCallback: (()->()) - returns: */ init(refreshVCCallback : (()->())){ super.init() self.refreshVCCallback = refreshVCCallback DataManagerCalbackCoordinator.SharedInstance.addCallback(handleDataManagerNotifications) getPictureObjects() } /** Method handles notifications when there are DataManagerNotifications, it passes DataManagerNotifications to the Profile VC - parameter dataManagerNotification: DataManagerNotification */ func handleDataManagerNotifications(dataManagerNotification : DataManagerNotification){ if (dataManagerNotification == DataManagerNotification.UserDecidedToPostPhoto){ getPictureObjects() } if (dataManagerNotification == DataManagerNotification.CloudantPullDataSuccess){ getPictureObjects() } else if(dataManagerNotification == DataManagerNotification.ObjectStorageUploadImageAndCloudantCreatePictureDocSuccess){ getPictureObjects() } } /** Method adds a locally stored version of the image the user just posted to the pictureDataArray */ func addUsersLastPhotoTakenToPictureDataArrayAndRefreshCollectionView(){ let lastPhotoTaken = CameraDataManager.SharedInstance.lastPictureObjectTaken var lastPhotoTakenArray = [Picture]() lastPhotoTakenArray.append(lastPhotoTaken) pictureDataArray = lastPhotoTakenArray + pictureDataArray callRefreshCallBack() } /** Method gets the picture objects from cloudant based on the facebook unique user id. When this completes it tells the profile view controller to refresh its collection view */ func getPictureObjects(){ pictureDataArray = CloudantSyncDataManager.SharedInstance!.getPictureObjects(FacebookDataManager.SharedInstance.fbUniqueUserID!) hasRecievedDataFromCloudant = true dispatch_async(dispatch_get_main_queue()) { self.callRefreshCallBack() } } /** method repulls for new data from cloudant */ func repullForNewData(){ do { try CloudantSyncDataManager.SharedInstance!.pullFromRemoteDatabase() } catch { print("repullForNewData error: \(error)") DataManagerCalbackCoordinator.SharedInstance.sendNotification(DataManagerNotification.CloudantPullDataFailure) } } /** Method returns the number of sections in the collection view - returns: Int */ func numberOfSectionsInCollectionView() -> Int { return kNumberOfSectionsInCollectionView } /** Method returns the number of items in a section - parameter section: Int - returns: Int */ func numberOfItemsInSection(section : Int) -> Int { if(pictureDataArray.count == 0 && hasRecievedDataFromCloudant == true) { return kNumberOfCellsWhenUserHasNoPhotos } else { return pictureDataArray.count } } /** Method returns the size for item at indexPath - parameter indexPath: NSIndexPath - parameter collectionView: UICollectionView - parameter heightForEmptyProfileCollectionViewCell: CGFloat - returns: CGSize */ func sizeForItemAtIndexPath(indexPath : NSIndexPath, collectionView : UICollectionView, heightForEmptyProfileCollectionViewCell : CGFloat) -> CGSize { if(pictureDataArray.count == 0) { return CGSize(width: collectionView.frame.width, height: heightForEmptyProfileCollectionViewCell + kEmptyFeedCollectionViewCellBufferToAllowForScrolling) } else{ let picture = pictureDataArray[indexPath.row] if let width = picture.width, let height = picture.height { let ratio = height / width var height = collectionView.frame.width * ratio if(height > kCollectionViewCellHeightLimit){ height = kCollectionViewCellHeightLimit } return CGSize(width: collectionView.frame.width, height: height + kCollectionViewCellInfoViewHeight) } else{ return CGSize(width: collectionView.frame.width, height: collectionView.frame.width + kCollectionViewCellInfoViewHeight) } } } /** Method sets up the collection view cell for indexPath. If the pictureDataArray.count is equal to 0 then we return an instance EmptyfeedCollectionviewCell - parameter indexPath: NSIndexPath - parameter collectionView: UICollectionViewCell - returns: UICollectionViewCell */ func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView : UICollectionView) -> UICollectionViewCell { if(pictureDataArray.count == 0){ let cell: EmptyFeedCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("EmptyFeedCollectionViewCell", forIndexPath: indexPath) as! EmptyFeedCollectionViewCell return cell } else{ let cell: ProfileCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProfileCollectionViewCell", forIndexPath: indexPath) as! ProfileCollectionViewCell let picture = pictureDataArray[indexPath.row] cell.setupData(picture.url, image: picture.image, displayName: picture.displayName, timeStamp: picture.timeStamp, fileName: picture.fileName ) cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.mainScreen().scale return cell } } /** Method sets up the section header for the indexPath parameter - parameter indexPath: NSIndexPath - parameter kind: String - parameter collectionView: UICollectionView - returns: TripDetailSupplementaryView */ func setUpSectionHeaderViewForIndexPath(indexPath : NSIndexPath, kind: String, collectionView : UICollectionView) -> ProfileHeaderCollectionReusableView { let header : ProfileHeaderCollectionReusableView header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "ProfileHeaderCollectionReusableView", forIndexPath: indexPath) as! ProfileHeaderCollectionReusableView header.setupData(FacebookDataManager.SharedInstance.fbUserDisplayName, numberOfShots: pictureDataArray.count, profilePictureURL : FacebookDataManager.SharedInstance.getUserFacebookProfilePictureURL()) return header } /** Method tells the profile view controller to reload its collectionView */ func callRefreshCallBack(){ if let callback = refreshVCCallback { callback() } } }
744a921fb85196543ffede8ff84b7477
33.927007
208
0.658203
false
false
false
false
MaeseppTarvo/FullScreenAlert
refs/heads/master
Example/FullScreenAlert/ViewController.swift
mit
1
// // ViewController.swift // FullScreenAlert // // Created by MaeseppTarvo on 06/16/2017. // Copyright (c) 2017 MaeseppTarvo. All rights reserved. // import UIKit import FullScreenAlert class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //WITHOUT ACTION @IBAction func didTapSuccess(_ sender: Any) { let successAlert = AlertView(type: .Success, title: "Success", message: "You just opened this \"Success\" type alert without action", config: nil) successAlert.present(on: self) } @IBAction func didTapWarning(_ sender: Any) { let warningAlert = AlertView(type: .Warning, title: "Warning", message: "You just opened this \"Warning\" type alert without action", config: nil) warningAlert.present(on: self) } @IBAction func didTapError(_ sender: Any) { let errorAlert = AlertView(type: .Error, title: "Error", message: "You just opened this \"Error\" type alert without action", config: nil) errorAlert.present(on: self) } //WITH ACTION @IBAction func didTapSuccessWithAction(_ sender: Any) { var fullScreenALertConfig = AlertView.Config() fullScreenALertConfig.alertBackgroundColor = UIColor.blue.withAlphaComponent(0.7) let successAlertWithAction = AlertView(type: .Success, title: "Success", message: "You just opened this \"Success\" type alert with action", config: fullScreenALertConfig) { print("SOME ACTION") } successAlertWithAction.present(on: self) } @IBAction func didTapWarningWithAction(_ sender: Any) { } @IBAction func didTapErrorWithWarning(_ sender: Any) { } }
2f0a92500001b0b6d8b0dda2b41f87de
32.711864
181
0.660131
false
true
false
false
terflogag/FacebookImagePicker
refs/heads/master
GBHFacebookImagePicker/Classes/Utils/Reusable.swift
mit
1
// // Reusable.swift // GBHFacebookImagePicker // // Created by Florian Gabach on 21/11/2018. // import UIKit public protocol Reusable: class { static var reuseIdentifier: String { get } } public extension Reusable { static var reuseIdentifier: String { return String(describing: self) } } extension UITableView { final func register<T: UITableViewCell>(cellType: T.Type) where T: Reusable { self.register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier) } final func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T where T: Reusable { guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else { fatalError( "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + "and that you registered the cell beforehand" ) } return cell } } extension UICollectionView { func register<T: UICollectionViewCell>(cellType: T.Type) where T: Reusable { self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T where T: Reusable { let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) guard let cell = bareCell as? T else { fatalError( "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + "and that you registered the cell beforehand" ) } return cell } }
2ef44d50ad4e23cbe2f84ac81d74a639
35.912281
124
0.627376
false
false
false
false
dutchcoders/stacktray
refs/heads/v2
StackTray/Models/Account.swift
mit
1
// // Account.swift // stacktray // // Created by Ruben Cagnie on 3/4/15. // Copyright (c) 2015 dutchcoders. All rights reserved. // import Cocoa public enum AccountType : Int, Printable { case AWS, DUMMY, Unknown /** Name of the thumbnail that should be show */ public var imageName: String { switch self{ case .AWS: return "AWS" case .DUMMY: return "DUMMY" case .Unknown: return "UNKNOWN" } } /** Description */ public var description: String { switch self{ case .AWS: return "Amazon Web Service" case .DUMMY: return "DUMMY Web Service" case .Unknown: return "Unknown Web Service" } } } public protocol AccountDelegate { func didAddAccountInstance(account: Account, instanceIndex: Int) func didUpdateAccountInstance(account: Account, instanceIndex: Int) func didDeleteAccountInstance(account: Account, instanceIndex: Int) func instanceDidStart(account: Account, instanceIndex: Int) func instanceDidStop(account: Account, instanceIndex: Int) } /** An account object represents the connection to a web service */ public class Account : NSObject, NSCoding { /** Meta Data */ public var name: String = "" /** Account Type */ public var accountType: AccountType = .Unknown /** Delegate */ public var delegate : AccountDelegate? func sortOnName(this:Instance, that:Instance) -> Bool { return this.name > that.name } /** Instances */ public var instances : [Instance] = [] { didSet{ if let d = delegate { let oldInstanceIds = oldValue.map{ $0.instanceId } let newInstanceIds = instances.map{ $0.instanceId } for instance in instances { if contains(oldInstanceIds, instance.instanceId) && contains(newInstanceIds, instance.instanceId) { d.didUpdateAccountInstance(self, instanceIndex: find(instances, instance)!) } else if contains(oldInstanceIds, instance.instanceId){ d.didDeleteAccountInstance(self, instanceIndex: find(instances, instance)!) } else if contains(newInstanceIds, instance.instanceId){ d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!) } } } } } /** Init an Account Object */ public init(name: String, accountType: AccountType){ self.name = name self.accountType = accountType super.init() } required public init(coder aDecoder: NSCoder) { if let name = aDecoder.decodeObjectForKey("name") as? String { self.name = name } if let accountTypeNumber = aDecoder.decodeObjectForKey("accountType") as? NSNumber { if let accountType = AccountType(rawValue: accountTypeNumber.integerValue){ self.accountType = accountType } } if let data = aDecoder.decodeObjectForKey("instances") as? NSData { if let instances = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Instance] { self.instances = instances } } super.init() } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(NSNumber(integer: accountType.rawValue), forKey: "accountType") aCoder.encodeObject(NSKeyedArchiver.archivedDataWithRootObject(instances), forKey: "instances") } public func addInstance(instance: Instance){ instances.append(instance) if let d = delegate { d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!) } } public func updateInstanceAtIndex(index: Int, instance: Instance){ let existingInstance = instances[index] let beforeState = existingInstance.state existingInstance.mergeInstance(instance) if let d = delegate { d.didUpdateAccountInstance(self, instanceIndex: index) if instance.lastUpdate != nil && instance.state != beforeState { if instance.state == .Running { d.instanceDidStart(self, instanceIndex: index) } else if instance.state == .Stopped { d.instanceDidStop(self, instanceIndex: index) } } } } public func removeInstances(instanceIds: [String]){ var toRemove = instances.filter { (instance) -> Bool in return contains(instanceIds, instance.instanceId) } for instance in toRemove { if let index = find(instances, instance){ instances.removeAtIndex(index) if let d = delegate { d.didDeleteAccountInstance(self, instanceIndex: index) } } } } } public class AWSAccount : Account { /** AWS Specific Keys */ public var accessKey: String = "" public var secretKey: String = "" public var region: String = "" /** Init an AWS Account Object */ public init(name: String, accessKey: String, secretKey: String, region: String){ self.accessKey = accessKey self.secretKey = secretKey self.region = region super.init(name: name, accountType: .AWS) } required public init(coder aDecoder: NSCoder) { if let accessKey = aDecoder.decodeObjectForKey("accessKey") as? String { self.accessKey = accessKey } if let secretKey = aDecoder.decodeObjectForKey("secretKey") as? String { self.secretKey = secretKey } if let region = aDecoder.decodeObjectForKey("region") as? String{ self.region = region } super.init(coder: aDecoder) } public override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(accessKey, forKey: "accessKey") aCoder.encodeObject(secretKey, forKey: "secretKey") aCoder.encodeObject(region, forKey: "region") super.encodeWithCoder(aCoder) } }
e01d6949642f32784d3abed440b363df
32.282723
119
0.596665
false
false
false
false
tiagobsbraga/HotmartTest
refs/heads/master
HotmartTest/MessageCollectionViewCell.swift
mit
1
// // MessageCollectionViewCell.swift // HotmartTest // // Created by Tiago Braga on 08/02/17. // Copyright © 2017 Tiago Braga. All rights reserved. // import UIKit class MessageCollectionViewCell: UICollectionViewCell { @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var firstCharNameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() self.firstCharNameLabel.isHidden = true } // Public Methods func populateMessage(_ message: Message) { self.photoImageView.image = UIImage() self.photoImageView.cicleMask(message.photo, withBackgroundColor: Style.randomColor()) self.nameLabel.text = message.name self.firstCharNameLabel.text = String(message.firstChar()) self.firstCharNameLabel.isHidden = !(message.photo == nil) } }
f7954cea358080acbbfaadda4ae4a0b5
28
94
0.696329
false
false
false
false
innominds-mobility/swift-custom-ui-elements
refs/heads/master
swift-custom-ui/InnoUI/InnoProgressViewCircle.swift
gpl-3.0
1
// // InnoProgressView.swift // swift-custom-ui // // Created by Deepthi Muramshetty on 09/05/17. // Copyright © 2017 Innominds Mobility. All rights reserved. // import UIKit /// The purpose of this class is to provide custom view for showing progress in a circle. /// The `InnoProgressViewCircle` class is a subclass of the `UIView`. @IBDesignable public class InnoProgressViewCircle: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ /// IBInspectable for Progress color of InnoProgressViewCircle. @IBInspectable public var progressColor: UIColor = UIColor.orange { didSet { setNeedsDisplay() } } /// IBInspectable for Progress default color of InnoProgressViewCircle. @IBInspectable public var progressDefaultColor: UIColor = UIColor.lightGray { didSet { setNeedsDisplay() } } /// IBInspectable for Progress width of InnoProgressViewCircle. @IBInspectable public var progressWidth: CGFloat = 0.0 /// IBInspectable for Progress value of InnoProgressViewCircle. @IBInspectable public var progress: CGFloat = 0.0 { didSet { self.drawProgressCircleViewLayer(progressVal:progress, strokeColor: self.progressColor) } } /// IBInspectable for show title bool of InnoProgressViewCircle @IBInspectable public var showTitle: Bool = false /// IBInspectable for progress title of InnoProgressViewCircle @IBInspectable public var progressTitle: NSString = "Progress" /// Performing custom drawing for progress circle. /// /// - Parameter rect: The portion of the view’s bounds that needs to be updated. override public func draw(_ rect: CGRect) { // Add ARCs self.drawDefaultCircleLayer() self.drawProgressCircleViewLayer(progressVal: self.progress, strokeColor: self.progressColor) } /// Shape layer for default circle. var defaultCircleLayer: CAShapeLayer = CAShapeLayer() /// Shape layer for progress circle. let progressCircleLayer: CAShapeLayer = CAShapeLayer() // MARK: Drawing default circle layer method /// This method draws default circle layer on a bezier path and adds a stroke color to it. func drawDefaultCircleLayer() { /// Center point of circle. let center = CGPoint(x:bounds.width/2, y: bounds.height/2) /// Radius of arc. let radius: CGFloat = max(bounds.width, bounds.height) /// Arc width. let arcWidth: CGFloat = self.progressWidth /// Start angle. let startAngle: CGFloat = 3 * 3.14/2// 3* π / 4 /// End angle. let endAngle: CGFloat = startAngle + CGFloat(2 * 3.14 * 1.0)//π / 4 /// Path for default circle. let defaultPath = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) defaultPath.lineWidth = arcWidth self.progressDefaultColor.setStroke() defaultPath.stroke() defaultPath.close() defaultCircleLayer.path = defaultPath.cgPath defaultCircleLayer.fillColor = UIColor.clear.cgColor defaultCircleLayer.strokeEnd = 0 self.layer.addSublayer(defaultCircleLayer) } // MARK: Drawing Progress circle layer Method /// This method draws/redraws progress circle layer on bezier path and adds a stroke color to it. /// This layer is added as a sublayer for 'defaultCircleLayer'. /// For every change in progress value, this method is called. /// /// - Parameters: /// - progressVal: Progress value for circle. /// - strokeColor: color of circle. func drawProgressCircleViewLayer(progressVal: CGFloat, strokeColor: UIColor) { progressCircleLayer.removeFromSuperlayer() /// Center point of arc. let center = CGPoint(x:bounds.width/2, y: bounds.height/2) /// Radius of arc. let radius: CGFloat = max(bounds.width, bounds.height) /// Arc width. let arcWidth: CGFloat = self.progressWidth /// Start angle. let startAngle: CGFloat = 3 * 3.14/2// 3* π / 4 /// End angle. let endAngle: CGFloat = startAngle + CGFloat(2 * 3.14 * progressVal)//π / 4 /// Path for progress circle let pCirclePath = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) pCirclePath.lineWidth = arcWidth strokeColor.setStroke() pCirclePath.stroke() pCirclePath.close() progressCircleLayer.path = pCirclePath.cgPath progressCircleLayer.fillColor = UIColor.clear.cgColor defaultCircleLayer.addSublayer(progressCircleLayer) for subview in self.subviews { subview.removeFromSuperview() } if showTitle { /// Title view let datailsView = UIView() datailsView.frame = CGRect(x: self.bounds.origin.x+10, y: self.bounds.height/2-30, width: self.bounds.width-20, height: 60) /// Title label let nameLabel = UILabel() nameLabel.font = UIFont(name: "Helvetica-Bold", size: 20) nameLabel.frame = CGRect(x: 0, y: 0, width: datailsView.frame.size.width, height: 30) nameLabel.text = progressTitle as String nameLabel.textAlignment = NSTextAlignment.center nameLabel.textColor = strokeColor datailsView.addSubview(nameLabel) /// Progress value label let valLabel = UILabel() valLabel.font = UIFont(name: "Helvetica-Bold", size: 30) valLabel.frame = CGRect(x: 5, y: nameLabel.frame.origin.y+nameLabel.frame.size.height+5, width: datailsView.frame.size.width-10, height: 30) valLabel.text = "\(Int(progressVal*100))%" valLabel.textAlignment = NSTextAlignment.center valLabel.textColor = strokeColor datailsView.addSubview(valLabel) self.addSubview(datailsView) } } }
1058c7d8a73c50855c6edee04723c1c4
43.763514
101
0.618868
false
false
false
false
whereuat/whereuat-ios
refs/heads/master
whereuat-ios/Database/ContactRequestTable.swift
apache-2.0
1
// // ContactRequestTable.swift // whereuat // // Created by Raymond Jacobson on 5/16/16. // Copyright © 2016 whereuat. All rights reserved. // import Foundation import SQLite /* * ContactRequestTable is the SQLite database tables for pending requests that have * not been added as contacts */ class ContactRequestTable: Table { static let sharedInstance = ContactRequestTable(databaseFilePath: "database.sqlite") private var databaseFilePath: String! var contactRequests: SQLite.Table var db: SQLite.Connection? var idColumn: SQLite.Expression<Int64> var firstNameColumn: SQLite.Expression<String> var lastNameColumn: SQLite.Expression<String> var phoneNumberColumn: SQLite.Expression<String> /* * Init sets up the SQLite connection and constructs the schema */ init(databaseFilePath: String) { self.databaseFilePath = databaseFilePath if let dirs: [NSString] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as [NSString] { let dir = dirs[0] self.databaseFilePath = dir.stringByAppendingPathComponent(self.databaseFilePath); } do { self.db = try SQLite.Connection(self.databaseFilePath) } catch { print("Unable to connect to the Database") } self.contactRequests = SQLite.Table("contactRequests") self.idColumn = SQLite.Expression<Int64>("id") self.firstNameColumn = SQLite.Expression<String>("firstName") self.lastNameColumn = SQLite.Expression<String>("lastName") self.phoneNumberColumn = SQLite.Expression<String>("phoneNumber") } /* * setUpTable instantiates the schema */ func setUpTable() { do { try (self.db!).run(self.contactRequests.create(ifNotExists: true) { t in t.column(self.idColumn, primaryKey: true) t.column(self.firstNameColumn) t.column(self.lastNameColumn) t.column(self.phoneNumberColumn, unique: true) }) } catch { print("Unable to set up Database") } } /* * dropTable drops the database table */ func dropTable() { // Clean the database do { try (self.db)!.run(self.contactRequests.drop()) } catch { print ("Unable to drop the database") } } /* * generateMockData fills the table with 5 mock contacts */ func generateMockData() { let contact1 = Contact(firstName: "Damian", lastName: "Mastylo", phoneNumber: "+19133700735", autoShare: true, requestedCount: 0, color: ColorWheel.randomColor()) let contact2 = Contact(firstName: "Yingjie", lastName: "Shu", phoneNumber: "+12029552443", autoShare: false, requestedCount: 0, color: ColorWheel.randomColor()) let contact3 = Contact(firstName: "", lastName: "", phoneNumber: "+12077348728", autoShare: false, requestedCount: 0, color: ColorWheel.randomColor()) // Insert mock data insert(contact1) insert(contact2) insert(contact3) } /* * insert inserts a row into the database * @param - contact to insert */ func insert(contact: Model) { let c = contact as! Contact let insert = self.contactRequests.insert(self.firstNameColumn <- c.firstName, self.lastNameColumn <- c.lastName, self.phoneNumberColumn <- c.phoneNumber) do { try (self.db!).run(insert) } catch { print("Unable to insert contact") } } /* * getAll returns all of the rows in the table, a SELECT * FROM * @return - Array of Model type */ func getAll() -> Array<Model> { var contactRequestArray = Array<Contact>() do { for contact in (try (self.db!).prepare(self.contactRequests)) { contactRequestArray.append(Contact(firstName: contact[self.firstNameColumn], lastName: contact[self.lastNameColumn], phoneNumber: contact[self.phoneNumberColumn])) } } catch { print("Unable to get pending requests") return Array<Contact>() } return contactRequestArray } /* * dropContactRequest retrieves a particular pending request by phone number and removes * it from the table. * @param - phoneNumber is the phone number for the pending request lookup */ func dropContactRequest(phoneNumber: String) { let query = contactRequests.filter(phoneNumberColumn == phoneNumber) do { try db!.run(query.delete()) } catch { print("Unable to delete contactRequest") } } /* * getContactRequest retrives a particular pending request by phone number. * @param - phoneNumber is the phone number for the pending request lookup * @return the contact found */ func getContactRequest(phoneNumber: String) -> Contact? { do { let query = contactRequests.filter(phoneNumberColumn == phoneNumber) let c = try (db!).prepare(query) for contact in c { return Contact(firstName: contact[self.firstNameColumn], lastName: contact[self.lastNameColumn], phoneNumber: contact[self.phoneNumberColumn]) } return nil } catch { print("Unable to get contact") return nil } } }
a6a865eda5e5fd5063c929974d9cd9f0
34.664804
130
0.545198
false
false
false
false
mxcl/PromiseKit
refs/heads/v6
Tests/JS-A+/JSPromise.swift
mit
1
// // JSPromise.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/1/18. // import Foundation import XCTest import PromiseKit import JavaScriptCore @objc protocol JSPromiseProtocol: JSExport { func then(_: JSValue, _: JSValue) -> JSPromise } class JSPromise: NSObject, JSPromiseProtocol { let promise: Promise<JSValue> init(promise: Promise<JSValue>) { self.promise = promise } func then(_ onFulfilled: JSValue, _ onRejected: JSValue) -> JSPromise { // Keep a reference to the returned promise so we can comply to 2.3.1 var returnedPromiseRef: Promise<JSValue>? let afterFulfill = promise.then { value -> Promise<JSValue> in // 2.2.1: ignored if not a function guard JSUtils.isFunction(value: onFulfilled) else { return .value(value) } // Call `onFulfilled` // 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value) guard let returnValue = try JSUtils.call(function: onFulfilled, arguments: [JSUtils.undefined, value]) else { return .value(value) } // Extract JSPromise.promise if available, or use plain return value if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise { // 2.3.1: if returned value is the promise that `then` returned, throw TypeError if jsPromise.promise === returnedPromiseRef { throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self")) } return jsPromise.promise } else { return .value(returnValue) } } let afterReject = promise.recover { error -> Promise<JSValue> in // 2.2.1: ignored if not a function guard let jsError = error as? JSUtils.JSError, JSUtils.isFunction(value: onRejected) else { throw error } // Call `onRejected` // 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value) guard let returnValue = try JSUtils.call(function: onRejected, arguments: [JSUtils.undefined, jsError.reason]) else { throw error } // Extract JSPromise.promise if available, or use plain return value if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise { // 2.3.1: if returned value is the promise that `then` returned, throw TypeError if jsPromise.promise === returnedPromiseRef { throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self")) } return jsPromise.promise } else { return .value(returnValue) } } let newPromise = Promise<Result<JSValue>> { resolver in _ = promise.tap(resolver.fulfill) }.then(on: nil) { result -> Promise<JSValue> in switch result { case .fulfilled: return afterFulfill case .rejected: return afterReject } } returnedPromiseRef = newPromise return JSPromise(promise: newPromise) } }
1b7a6c72a59ea374be42d7ef6ef44a1f
35.585106
129
0.562954
false
false
false
false
SahilDhawan/On-The-Map
refs/heads/master
OnTheMap/AddLocationViewController.swift
mit
1
// // AddLocationViewController.swift // OnTheMap // // Created by Sahil Dhawan on 05/04/17. // Copyright © 2017 Sahil Dhawan. All rights reserved. // import UIKit import CoreLocation class AddLocationViewController: UIViewController { @IBOutlet weak var locationTextField: UITextField! @IBOutlet weak var websiteTextField: UITextField! //Current User Details static var mapString : String = "" static var webURL : String = "" static var studentLocation : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0) override func viewDidLoad() { super.viewDidLoad() locationTextField.delegate = self websiteTextField.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tabBarController?.tabBar.isHidden = false Alert().activityView(false, self.view) } @IBAction func FindLocationPressed(_ sender: Any) { guard locationTextField.text == nil, websiteTextField.text == nil else { //ActivityIndicatorView Alert().activityView(true, self.view) let geocoder = CLGeocoder() let text = websiteTextField.text! if(text.contains("https://www.") || (text.contains("http://www.")) && (text.contains(".com"))) { AddLocationViewController.webURL = websiteTextField.text! geocoder.geocodeAddressString(locationTextField.text!, completionHandler: { (placemark, error) in if error != nil { Alert().showAlert("Invalid Location",self) Alert().activityView(false, self.view) } else { if let place = placemark, (placemark?.count)! > 0 { var location : CLLocation? location = place.first?.location AddLocationViewController.studentLocation = location!.coordinate AddLocationViewController.mapString = self.locationTextField.text! Alert().activityView(false, self.view) self.performSegue(withIdentifier: "UserCoordinate", sender: location) } } }) } else { Alert().showAlert("website link is not valid",self) Alert().activityView(false, self.view) return } return } } @IBAction func cancelButtonPressed(_ sender: Any) { let controller = storyboard?.instantiateViewController(withIdentifier: "tabController") self.present(controller!, animated: true, completion: nil) } } extension AddLocationViewController:UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
a15a00714332def04a981b8bae486ff7
32.795918
113
0.57035
false
false
false
false
byu-oit-appdev/ios-byuSuite
refs/heads/dev
byuSuite/Apps/LockerRental/model/LockerRentalAgreement.swift
apache-2.0
2
// // LockerRentalAgreement.swift // byuSuite // // Created by Erik Brady on 7/18/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let dateFormat = DateFormatter.defaultDateFormat("MMM dd, yyyy") class LockerRentalAgreement: NSObject, Comparable { var personId: String? var lockerId: Int? var agreementDateTime: Date? var expirationDate: Date? var agreedToTerms: Bool var fee: Int? var dateCharged: Date? var locker: LockerRentalLocker? init(dict: [String: Any]) { personId = dict["personId"] as? String lockerId = dict["lockerId"] as? Int agreementDateTime = dateFormat.date(from: dict["agreementDateTime"] as? String) expirationDate = dateFormat.date(from: dict["expirationDate"] as? String) agreedToTerms = dict["agreedToTerms"] as? Bool ?? false fee = dict["fee"] as? Int dateCharged = dateFormat.date(from: dict["dateCharged"] as? String) } func expirationDateString() -> String { if let expirationDate = expirationDate { return dateFormat.string(from: expirationDate) } else { return "" } } //MARK: Comparable Methods static func <(lhs: LockerRentalAgreement, rhs: LockerRentalAgreement) -> Bool { return lhs.expirationDate ?? Date() < rhs.expirationDate ?? Date() } static func ==(lhs: LockerRentalAgreement, rhs: LockerRentalAgreement) -> Bool { return lhs.expirationDate == rhs.expirationDate } }
ebd9525b4af8f254f7fed7facebd46ea
30.979592
87
0.644544
false
false
false
false
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/Demo/Modules/Demos/Components/QDSingleImagePickerPreviewViewController.swift
mit
1
// // QDSingleImagePickerPreviewViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/5/14. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit protocol QDSingleImagePickerPreviewViewControllerDelegate: QMUIImagePickerPreviewViewControllerDelegate { func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QDSingleImagePickerPreviewViewController, didSelectImageWithImagesAsset imagesAsset: QMUIAsset) } class QDSingleImagePickerPreviewViewController: QMUIImagePickerPreviewViewController { weak var singleDelegate: QDSingleImagePickerPreviewViewControllerDelegate? { get { return delegate as? QDSingleImagePickerPreviewViewControllerDelegate } set { delegate = newValue } } var assetsGroup: QMUIAssetsGroup? private var confirmButton: QMUIButton! override func initSubviews() { super.initSubviews() confirmButton = QMUIButton() confirmButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) confirmButton.setTitle("使用", for: .normal) confirmButton.setTitleColor(toolBarTintColor, for: .normal) confirmButton.sizeToFit() confirmButton.addTarget(self, action: #selector(handleUserAvatarButtonClick(_:)), for: .touchUpInside) topToolBarView.addSubview(confirmButton) } override var downloadStatus: QMUIAssetDownloadStatus { didSet { switch downloadStatus { case .succeed: confirmButton.isHidden = false case .downloading: confirmButton.isHidden = true case .canceled: confirmButton.isHidden = false case .failed: confirmButton.isHidden = true } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() confirmButton.frame = confirmButton.frame.setXY(topToolBarView.frame.width - confirmButton.frame.width - 10, backButton.frame.minY + backButton.frame.height.center(confirmButton.frame.height)) } @objc private func handleUserAvatarButtonClick(_ sender: Any) { navigationController?.dismiss(animated: true, completion: { if let imagePreviewView = self.imagePreviewView { let imageAsset = self.imagesAssetArray[imagePreviewView.currentImageIndex] self.singleDelegate?.imagePickerPreviewViewController(self, didSelectImageWithImagesAsset: imageAsset) } }) } }
b6bf613894647d38ab33730036d1211b
34.821918
200
0.677247
false
false
false
false
GalinaCode/Nutriction-Cal
refs/heads/master
NutritionCal/Nutrition Cal/NDBConvenience.swift
apache-2.0
1
// // NDBConvenience.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // // United States Department of Agriculture // Agricultural Research Service // National Nutrient Database for Standard Reference Release 28 // visit to: http://ndb.nal.usda.gov/ndb/doc/index for documentation and help import Foundation import CoreData extension NDBClient { func NDBItemsFromString(searchString: String, type: NDBSearchType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) { let escapedSearchString = searchString.stringByReplacingOccurrencesOfString(" ", withString: "+").stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!.lowercaseString var searchType: String { switch type { case .ByFoodName: return "n" case .ByRelevance: return "r" } } let params: [String : AnyObject] = [ NDBParameterKeys.format : NDBParameterValues.json, NDBParameterKeys.searchTerm : escapedSearchString, NDBParameterKeys.sort : searchType, NDBParameterKeys.limit : NDBConstants.resultsLimit, NDBParameterKeys.offset : 0, NDBParameterKeys.apiKey : NDBConstants.apiKey ] let urlString = NDBConstants.baseURL + NDBMethods.search + NDBClient.escapedParameters(params) let request = NSURLRequest(URL: NSURL(string: urlString)!) print(request.URL!) let session = NSURLSession.sharedSession() sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error!.localizedDescription)") completionHandler(success: false, result: nil, errorString: error?.localizedDescription) return } var parsedResults: AnyObject? NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in /* GUARD: Was there an error? */ guard (error == nil) else { print("Error parsing JSON: \(error!.localizedDescription)") completionHandler(success: false, result: nil, errorString: error?.localizedDescription) return } parsedResults = result }) if let errors = parsedResults?.valueForKey("errors") { if let error = errors.valueForKey("error") { if let message = error.valueForKey("message") { let errorMessage = message.firstObject as! NSString completionHandler(success: false, result: nil, errorString: errorMessage as String) return } } } if let error = parsedResults!.valueForKey("error") { if let message = error.valueForKey("message") { let errorMessage = message as! NSString completionHandler(success: false, result: nil, errorString: errorMessage as String) return } } guard let list = parsedResults?.valueForKey("list") as? [String: AnyObject] else { print("Couldn't find list in: \(parsedResults)") completionHandler(success: false, result: nil, errorString: "Couldn't find list in parsedResults") return } guard let items = list["item"] as? NSArray else { print("Couldn't find item in: \(list)") completionHandler(success: false, result: nil, errorString: "Couldn't find item in list") return } completionHandler(success: true, result: items, errorString: nil) } sharedTask!.resume() } func NDBReportForItem(ndbNo: String, type: NDBReportType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) { var reportType: String { switch type { case .Basic: return "b" case .Full: return "f" } } let params: [String : AnyObject] = [ NDBParameterKeys.format : NDBParameterValues.json, NDBParameterKeys.NDBNo : ndbNo, NDBParameterKeys.reportType : reportType, NDBParameterKeys.apiKey : NDBConstants.apiKey ] let urlString = NDBConstants.baseURL + NDBMethods.reports + NDBClient.escapedParameters(params) let request = NSURLRequest(URL: NSURL(string: urlString)!) print(request.URL!) let session = NSURLSession.sharedSession() sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error!.localizedDescription)") completionHandler(success: false, result: nil, errorString: error?.localizedDescription) return } var parsedResults: AnyObject? NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in /* GUARD: Was there an error? */ guard (error == nil) else { print("Error parsing JSON: \(error!.localizedDescription)") completionHandler(success: false, result: nil, errorString: error?.localizedDescription) return } parsedResults = result }) if let errors = parsedResults?.valueForKey("errors") { if let error = errors.valueForKey("error") { if let message = error.valueForKey("message") { let errorMessage = message.firstObject as! NSString completionHandler(success: false, result: nil, errorString: errorMessage as String) return } } completionHandler(success: false, result: nil, errorString: nil) return } if let error = parsedResults?.valueForKey("error") { if let message = error.valueForKey("message") { let errorMessage = message as! NSString completionHandler(success: false, result: nil, errorString: errorMessage as String) return } } guard let report = parsedResults?.valueForKey("report") as? [String: AnyObject] else { print("Error finding report") completionHandler(success: false, result: nil, errorString: "Error finding report") return } guard let food = report["food"] as? [String: AnyObject] else { print("Error finding food") completionHandler(success: false, result: nil, errorString: "Error finding food") return } guard let nutrients = food["nutrients"] as? NSArray else { print("Error finding nutrients") completionHandler(success: false, result: nil, errorString: "Error finding nutrients") return } completionHandler(success: true, result: nutrients, errorString: nil) } sharedTask!.resume() } }
9e94b2bb22026270057e087114031b38
30.950739
213
0.689485
false
false
false
false
EdenShapiro/tip-calculator-with-yelp-review
refs/heads/master
SuperCoolTipCalculator/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // SuperCoolTipCalculator // // Created by Eden on 2/3/17. // Copyright © 2017 Eden Shapiro. All rights reserved. // import UIKit class SettingsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var picker1: UIPickerView! @IBOutlet weak var picker2: UIPickerView! @IBOutlet weak var picker3: UIPickerView! var pickerData = [Int]() let defaults = UserDefaults.standard var tipPercentages: [Double]! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { tipPercentages = defaults.object(forKey: "tipPercentages") as! [Double] pickerData += 1...100 picker1.dataSource = self picker1.delegate = self picker1.tag = 1 picker2.dataSource = self picker2.delegate = self picker2.tag = 2 picker3.dataSource = self picker3.delegate = self picker3.tag = 3 picker1.selectRow(Int(tipPercentages[0]*100)-1, inComponent: 0, animated: true) picker2.selectRow(Int(tipPercentages[1]*100)-1, inComponent: 0, animated: true) picker3.selectRow(Int(tipPercentages[2]*100)-1, inComponent: 0, animated: true) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let attributedString = NSAttributedString(string: String(pickerData[row]), attributes: [NSForegroundColorAttributeName : UIColor.lightGray]) return attributedString } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { tipPercentages[pickerView.tag - 1] = Double(pickerData[row])/100.0 defaults.set(tipPercentages, forKey: "tipPercentages") defaults.synchronize() } }
05137c898c8364ee969ef35c9c0647eb
33.238095
148
0.672694
false
false
false
false
frograin/FluidValidator
refs/heads/master
Example/Tests/ValidationTests.swift
mit
1
// // TestValidatorTests.swift // TestValidatorTests // // Created by FrogRain on 05/02/16. // Copyright © 2016 FrogRain. All rights reserved. // import XCTest import FluidValidator class ValidationTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testValidation() { let validation = Validation(name: "isTrue") { (context:Example) -> (Any?) in return context.isTrue } let rule = BeNotNil() validation.addRule(rule) let example = Example() let result = validation.runValidation(example) let failMessage = validation.allErrors XCTAssertFalse(result) XCTAssertTrue(failMessage.errors.count > 0) } func testConditionalValidation() { let validation = Validation(name: "test") { (context:Example) -> (Any?) in return context.testProperty } validation.when { (context) -> (Bool) in return context.number == 0 } validation.addRule(BeNotEmpty()) let example = Example() example.number = 5 example.testProperty = "" // It's empty! let result = validation.runValidation(example) XCTAssertTrue(result) } }
eafbfd7e4ea8e42fa28928ca85aeda50
26.016667
111
0.586058
false
true
false
false
num42/RxUserDefaults
refs/heads/master
Examples/Sources/ViewController.swift
apache-2.0
1
import UIKit import RxUserDefaults import RxSwift class ViewController: UIViewController { let settings: RxSettings let reactiveSetting: Setting<String> var disposeBag = DisposeBag() lazy var valueLabel: UILabel = { let valueLabel = UILabel() valueLabel.textColor = .blue return valueLabel }() lazy var textField: UITextField = { let textField = UITextField() textField.backgroundColor = .white textField.borderStyle = .line textField.text = "Enter new value here" textField.textColor = .black return textField }() lazy var saveButton: UIButton = { let saveButton = UIButton() saveButton.setTitle("Save", for: .normal) saveButton.setTitleColor(.blue, for: .normal) saveButton.setTitleColor(.lightGray, for: .highlighted) return saveButton }() init() { settings = RxSettings(userDefaults: UserDefaults.standard) reactiveSetting = settings.setting(key: "the_settings_key", defaultValue: "The Default Value") super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("init(nibNameOrNil:nibBundleOrNil:) has not been implemented") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupView() setupRxSettingsBinding() } private func setupView() { view.backgroundColor = .white let stackView = UIStackView() stackView.axis = .vertical stackView.addArrangedSubview(textField) stackView.addArrangedSubview(saveButton) stackView.addArrangedSubview(UIView()) stackView.addArrangedSubview(valueLabel) view.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true stackView.widthAnchor.constraint(equalToConstant: 250).isActive = true stackView.heightAnchor.constraint(equalToConstant: 250).isActive = true } private func setupRxSettingsBinding(){ // Setup Saving to Settings saveButton.rx.tap .subscribe(onNext: { [weak self] _ in guard let text = self?.textField.text else { self?.reactiveSetting.remove() return } self?.reactiveSetting.value = text } ) .disposed(by: disposeBag) // Setup Displaying value when settings change reactiveSetting.asObservable() .asDriver(onErrorJustReturn: "Error") .drive(valueLabel.rx.text) .disposed(by: disposeBag) } }
48c6e7a3b74b6e810d7c01dd9a4ec3ab
31.247423
102
0.611573
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Playground.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import PlaygroundSupport import NotAutoLayout let controller = IPhoneXScreenController() controller.rotate(to: .portrait) PlaygroundPage.current.liveView = controller.view let appView = LayoutInfoStoredView() appView.backgroundColor = .white controller.view.addSubview(appView) controller.view.nal.layout(appView) { $0 .stickOnParent() } let padding: NotAutoLayout.Float = 10 let summaryView = ProfileSummaryView() let contentsView = ContentsView() let replyView = ReplyView() summaryView.avatar = #imageLiteral(resourceName: "avatar.png") summaryView.mainTitle = "星野恵瑠@今日も1日フレンズ㌠" summaryView.subTitle = "@lovee" contentsView.contents = """ Hello, NotAutoLayout! The new NotAutoLayout 3.0 now has even better syntax which is: - Easy to write (thanks to method-chain structures) - Easy to read (thanks to more natural English-like statements) - Capable with dynamic view sizes (with commands like `fitSize()`) - Even better closure support to help you set various kinds of layouts with various kinds of properties! - And one more thing: an experienmental sequencial layout engine! """ contentsView.timeStamp = Date() appView.nal.setupSubview(summaryView) { $0 .setDefaultLayout { $0 .setLeft(by: { $0.layoutMarginsGuide.left }) .setRight(by: { $0.layoutMarginsGuide.right }) .setTop(by: { $0.layoutMarginsGuide.top }) .setHeight(to: 50) } .addToParent() } appView.nal.setupSubview(contentsView) { $0 .setDefaultLayout({ $0 .setLeft(by: { $0.layoutMarginsGuide.left }) .setRight(by: { $0.layoutMarginsGuide.right }) .pinTop(to: summaryView, with: { $0.bottom + padding }) .fitHeight() }) .setDefaultOrder(to: 1) .addToParent() } appView.nal.setupSubview(replyView) { $0 .setDefaultLayout({ $0 .setBottomLeft(by: { $0.layoutMarginsGuide.bottomLeft }) .setRight(by: { $0.layoutMarginsGuide.right }) .setHeight(to: 30) }) .addToParent() } let imageViews = (0 ..< 3).map { (_) -> UIImageView in let image = #imageLiteral(resourceName: "avatar.png") let view = UIImageView(image: image) appView.addSubview(view) return view } appView.nal.layout(imageViews) { $0 .setMiddle(by: { $0.vertical(at: 0.7) }) .fitSize() .setHorizontalInsetsEqualingToMargin() }
3a475339e7833a968f34d790499c3db7
28.723684
105
0.736609
false
false
false
false
pabloroca/PR2StudioSwift
refs/heads/master
Source/Networking/AuthorizationJWT.swift
mit
1
// // AuthorizationJWT.swift // PR2StudioSwift // // Created by Pablo Roca on 28/02/2019. // Copyright © 2019 PR2Studio. All rights reserved. // import Foundation public final class AuthorizationJWT: Authorization { public private(set) var authEndPoint: String public private(set) var parameters: [String: String] public init(authEndPoint: String, parameters: [String: String]) { self.authEndPoint = authEndPoint self.parameters = parameters } public func loadCredentials() -> String { return KeyChainService.load(withKey: "jwt") ?? "" } public func authorize(completionHandler: @escaping (Result<Any, AnyError>) -> Void) { let requestOptional = URLRequest(authEndPoint, method: .post, parameters: parameters, encoding: .json) guard let request = requestOptional else { completionHandler(.failure(AnyError( NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed)))) return } NetworkSession.shared.dataTask(request, parserType: .data, toType: String.self, authorization: nil) { (result) in if case let .success(value) = result { guard let token = value as? String else { completionHandler(.failure(AnyError( NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed)))) return } if !KeyChainService.save(token, forKey: "jwt") { completionHandler(.failure(AnyError( NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed)))) } else { completionHandler(result) } } else { completionHandler(result) } } } }
83d72a6c8477f3921ccec73a23d82cdc
35.269231
121
0.613998
false
false
false
false
mseemann/D2Layers
refs/heads/master
Example/D2Layers/ViewController.swift
mit
1
// // ViewController.swift // TestGraphics // // Created by Michael Seemann on 04.11.15. // Copyright © 2015 Michael Seemann. All rights reserved. // import UIKit import D2Layers class D2LayerView: UIView { var root: Graph? override init(frame: CGRect) { super.init(frame: frame) rootInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) rootInit() } func rootInit() { root = Graph(layer: self.layer, parent: nil) // self.layer.shadowRadius = 10.0 // self.layer.shadowOffset = CGSize(width: 0, height: 0) // self.layer.shadowColor = UIColor.grayColor().CGColor // self.layer.masksToBounds = false // self.layer.shadowOpacity = 1.0 } override func layoutSubviews() { root?.needsLayout() } } class ViewController: UIViewController { @IBOutlet weak var vPieChart: D2LayerView! var switcher = false var pieLayout:PieLayout? var normalizedValues : [Double] = [] let colorScale = OrdinalScale<Int, UIColor>.category20c() var count = 5 override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let root = vPieChart.root { let circle = root.circle{ (parentGraph: Graph) in let parentSize = parentGraph.layer.bounds.size let at = CGPoint(x: parentSize.width/2, y: parentSize.height/2) let r = min(parentSize.width, parentSize.height)/CGFloat(2.0) return (at:at, r:r) }.fillColor(UIColor.grayColor().brighter()) pieLayout = circle.pieLayout{ (parentGraph: Graph) in let outerRadius = (min(parentGraph.layer.bounds.width, parentGraph.layer.bounds.height)/2) - 1 return (innerRadius:outerRadius*0.75, outerRadius:outerRadius, startAngle:CGFloat(0), endAngle:CGFloat(2*M_PI)) } .data(updateSlices()){ (pieSlice:PieSlice, normalizedValue:Double, index:Int) in pieSlice.fillColor(self.colorScale.scale(index)!.brighter()) pieSlice.strokeColor(UIColor(white: 0.25, alpha: 1.0)) pieSlice.strokeWidth(0.25) } } } @IBAction func doit(sender: AnyObject) { if let pieLayout = pieLayout { pieLayout.data(updateSlices()) let scale = (1.0 - CGFloat(arc4random_uniform(128))/255.0) let selection = pieLayout.selectAll(PieSlice.self) for g in selection.all() { g.innerRadius(scale * g.outerRadius()) } } } internal func updateSlices() -> [Double]{ var sliceValues:[Double] = [] for(var i=0; i < count; i++) { sliceValues.append(Double(arc4random_uniform(100))) } return sliceValues } }
a3d6f0ee7787232d956ff325671a8d5e
26.627119
131
0.528221
false
false
false
false
lingostar/PilotPlant
refs/heads/master
PilotPlant/CHViews.swift
agpl-3.0
1
// // CHViews.swift // PilotPlantCatalog // // Created by Lingostar on 2017. 5. 2.. // Copyright © 2017년 LingoStar. All rights reserved. // import Foundation import UIKit @IBDesignable open class AnimationImageView:UIImageView { @IBInspectable open var imageBaseName:String = "" @IBInspectable open var duration:Double = 1.0 @IBInspectable open var repeatCount:Int = 0 open override func awakeFromNib() { super.awakeFromNib() var images = [UIImage]() for i in 1 ..< 32000 { let imageFileName = self.imageBaseName + "_\(i)" if let image = UIImage(named: imageFileName) { images.append(image) } else { break } } self.animationImages = images self.contentMode = .scaleAspectFit self.animationRepeatCount = self.repeatCount self.animationDuration = duration self.image = images.first self.startAnimating() } }
42cf198edb938cd7c63c5d50d0bfca18
25.421053
60
0.60757
false
false
false
false
taqun/HBR
refs/heads/master
HBR/Classes/ViewController/FeedTableViewController.swift
mit
1
// // FeedTableViewController.swift // HBR // // Created by taqun on 2014/09/12. // Copyright (c) 2014年 envoixapp. All rights reserved. // import UIKit import CoreData class FeedTableViewController: SegmentedDisplayTableViewController, NSFetchedResultsControllerDelegate { var channel: Channel! private var fetchedResultController: NSFetchedResultsController! /* * Initialize */ convenience init(channel: Channel) { self.init(style: UITableViewStyle.Plain) self.channel = channel } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewStyle) { super.init(style: style) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() // navigation bar let backBtn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil) self.navigationItem.backBarButtonItem = backBtn let checkBtn = UIBarButtonItem(image: UIImage(named: "IconCheckmark"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("didCheckmark")) self.navigationItem.rightBarButtonItem = checkBtn // tableview self.clearsSelectionOnViewWillAppear = true self.tableView.separatorInset = UIEdgeInsetsZero self.tableView.registerNib(UINib(nibName: "FeedTableViewCell", bundle: nil), forCellReuseIdentifier: "FeedCell") self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: Selector("didRefreshControlChanged"), forControlEvents: UIControlEvents.ValueChanged) NSFetchedResultsController.deleteCacheWithName(self.channel.title + "Cache") self.initFetchedResultsController() var error:NSError? if !self.fetchedResultController.performFetch(&error) { println(error) } } /* * Private Method */ private func initFetchedResultsController() { if self.fetchedResultController != nil{ return } var fetchRequest = Item.requestAllSortBy("date", ascending: false) fetchRequest.predicate = NSPredicate(format: "ANY channels = %@", self.channel) let context = CoreDataManager.sharedInstance.managedObjectContext! self.fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: self.channel.title + "Cache") self.fetchedResultController.delegate = self } @objc private func feedLoaded(notification: NSNotification){ if let userInfo = notification.userInfo { if let channelID = userInfo["channelID"] as? NSManagedObjectID { if self.channel.objectID != channelID { return } } } allItemNum = channel.items.count self.tableView.reloadData() self.updateTitle() self.refreshControl?.endRefreshing() } @objc private func didRefreshControlChanged() { FeedController.sharedInstance.loadFeed(channel.objectID) } @objc private func didCheckmark() { channel.markAsReadAllItems() self.updateTitle() self.updateVisibleCells() } private func updateVisibleCells() { var cells = self.tableView.visibleCells() as! [FeedTableViewCell] for cell: FeedTableViewCell in cells { cell.updateView() } } private func updateTitle() { let unreadCount = channel.unreadItemCount if unreadCount == 0 { self.title = channel.title } else { self.title = channel.title + " (" + String(unreadCount) + ")" } } /* * UIViewController Method */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // navigationbar self.updateTitle() // toolbar self.navigationController?.toolbarHidden = true if let indexPath = self.tableView?.indexPathForSelectedRow() { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } // tableView self.updateVisibleCells() allItemNum = channel.items.count NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("feedLoaded:"), name: Notification.FEED_LOADED, object: nil) Logger.sharedInstance.trackFeedList(self.channel) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } /* * UITableViewDataSoruce Protocol */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("FeedCell") as! FeedTableViewCell! if cell == nil { cell = FeedTableViewCell() } let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item cell.setFeedItem(item) return cell } /* * UITableViewDelegate Protocol */ override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item let webViewController = WebViewController(item: item) self.navigationController?.pushViewController(webViewController, animated: true) } /* * NSFetchedResultsControllerDelegate Protocol */ func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } }
48939b8ad0d4135636b97778439945cd
30.203791
190
0.640644
false
false
false
false
imfree-jdcastro/Evrythng-iOS-SDK
refs/heads/master
Evrythng-iOS/EvrythngNetworkService.swift
apache-2.0
1
// // EvrythngNetworkService.swift // EvrythngiOS // // Created by JD Castro on 26/04/2017. // Copyright © 2017 ImFree. All rights reserved. // import Foundation import Moya import MoyaSugar public enum EvrythngNetworkService { case url(String) // User case createUser(user: User?, isAnonymous: Bool) case deleteUser(operatorApiKey: String, userId: String) case authenticateUser(credentials: Credentials) case validateUser(userId: String, activationCode: String) case logout(apiKey: String) case editIssue(owner: String, repo: String, number: Int, title: String?, body: String?) // Thng case readThng(thngId: String) // Scan case identify(scanType: EvrythngScanTypes, scanMethod: EvrythngScanMethods, value: String) } extension EvrythngNetworkService: EvrythngNetworkTargetType { public var sampleResponseClosure: (() -> EndpointSampleResponse) { return { return EndpointSampleResponse.networkResponse(200, self.sampleData) } } public var baseURL: URL { return URL(string: "https://api.evrythng.com")! } //public var baseURL: URL { return URL(string: "https://www.jsonblob.com/api")! } /// method + path public var route: Route { switch self { case .url(let urlString): return .get(urlString) case .createUser: return .post("/auth/evrythng/users") case .deleteUser(_, let userId): return .delete("/users/\(userId)") case .authenticateUser: return .post("/auth/evrythng") case .validateUser(let userId, _): return .post("/users/\(userId)/validate") case .logout: return .post("/auth/all/logout") case .editIssue(let owner, let repo, let number, _, _): return .patch("/repos/\(owner)/\(repo)/issues/\(number)") case .readThng(let thngId): return .get("/thngs/\(thngId)") case .identify: return .get("/scan/identifications") } } // override default url building behavior public var url: URL { switch self { case .url(let urlString): return URL(string: urlString)! default: return self.defaultURL } } /// encoding + parameters public var params: Parameters? { switch self { case .createUser(let user, let anonymous): if(anonymous == true) { var params:[String: Any] = [:] params[EvrythngNetworkServiceConstants.REQUEST_URL_PARAMETER_KEY] = ["anonymous": "true"] params[EvrythngNetworkServiceConstants.REQUEST_BODY_PARAMETER_KEY] = [:] return CompositeEncoding() => params } else { return JSONEncoding() => user!.jsonData!.dictionaryObject! } /* [ "firstName": "Test First1", "lastName": "Test Last1", "email": "validemail1@email.com", "password": "testPassword1" ] */ case .validateUser(_, let activationCode): return JSONEncoding() => ["activationCode": activationCode] case .authenticateUser(let credentials): return JSONEncoding() => ["email": credentials.email!, "password": credentials.password!] case .logout: return JSONEncoding() => [:] case .identify(let scanType, let scanMethod, let value): let urlEncodedFilter = "type=\(scanType.rawValue)&value=\(value)" let encoding = URLEncoding() => ["filter": urlEncodedFilter] print("Encoding: \(encoding.values.description)") return encoding case .editIssue(_, _, _, let title, let body): // Use `URLEncoding()` as default when not specified return [ "title": title, "body": body, ] default: return JSONEncoding() => [:] } } public var sampleData: Data { switch self { case .editIssue(_, let owner, _, _, _): return "{\"id\": 100, \"owner\": \"\(owner)}".utf8Encoded default: return "{}".utf8Encoded } } public var httpHeaderFields: [String: String]? { var headers: [String:String] = [:] headers[EvrythngNetworkServiceConstants.HTTP_HEADER_ACCEPTS] = "application/json" headers[EvrythngNetworkServiceConstants.HTTP_HEADER_CONTENT_TYPE] = "application/json" var authorization: String? switch(self) { case .deleteUser(let operatorApiKey, _): // Operator API Key //authorization = "hohzaKH7VbVp659Pnr5m3xg2DpKBivg9rFh6PttT5AnBtEn3s17B8OPAOpBjNTWdoRlosLTxJmUrpjTi" authorization = operatorApiKey case .logout(let apiKey): authorization = apiKey default: authorization = UserDefaultsUtils.get(key: "pref_key_authorization") as? String if let authorization = UserDefaultsUtils.get(key: "pref_key_authorization") as? String{ headers[EvrythngNetworkServiceConstants.HTTP_HEADER_AUTHORIZATION] = authorization } } if let auth = authorization { if(!auth.isEmpty) { headers[EvrythngNetworkServiceConstants.HTTP_HEADER_AUTHORIZATION] = auth } } print("Headers: \(headers)") return headers } public var task: Task { switch self { case .editIssue, .createUser, .url: fallthrough default: return .request } } } internal struct EvrythngNetworkServiceConstants { static let AppToken = "evrythng_app_token" static let EVRYTHNG_OPERATOR_API_KEY = "evrythng_operator_api_key" static let EVRYTHNG_APP_API_KEY = "evrythng_app_api_key" static let EVRYTHNG_APP_USER_API_KEY = "evrythng_app_user_api_key" static let HTTP_HEADER_AUTHORIZATION = "Authorization" static let HTTP_HEADER_ACCEPTS = "Accept" static let HTTP_HEADER_CONTENT_TYPE = "Content-Type" static let REQUEST_URL_PARAMETER_KEY = "query" static let REQUEST_BODY_PARAMETER_KEY = "body" } // MARK: - Helpers private extension String { var urlEscaped: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } var utf8Encoded: Data { return self.data(using: .utf8)! } }
e910340b83c9121db1e9897614290d43
32.851282
131
0.589759
false
false
false
false
tgu/HAP
refs/heads/master
Sources/HAP/Endpoints/root().swift
mit
1
import func Evergreen.getLogger fileprivate let logger = getLogger("hap.endpoints") typealias Route = (path: String, application: Application) func root(device: Device) -> Application { return logger(router([ // Unauthenticated endpoints ("/", { _, _ in Response(status: .ok, text: "Nothing to see here. Pair this Homekit" + "Accessory with an iOS device.") }), ("/pair-setup", pairSetup(device: device)), ("/pair-verify", pairVerify(device: device)), // Authenticated endpoints ("/identify", protect(identify(device: device))), ("/accessories", protect(accessories(device: device))), ("/characteristics", protect(characteristics(device: device))), ("/pairings", protect(pairings(device: device))) ])) } func logger(_ application: @escaping Application) -> Application { return { connection, request in let response = application(connection, request) // swiftlint:disable:next line_length logger.info("\(connection.socket?.remoteHostname ?? "-") \(request.method) \(request.urlURL.path) \(request.urlURL.query ?? "-") \(response.status.rawValue) \(response.body?.count ?? 0)") logger.debug("- Response Messagea: \(String(data: response.serialized(), encoding: .utf8) ?? "-")") return response } } func router(_ routes: [Route]) -> Application { return { connection, request in guard let route = routes.first(where: { $0.path == request.urlURL.path }) else { return Response(status: .notFound) } return route.application(connection, request) } } func protect(_ application: @escaping Application) -> Application { return { connection, request in guard connection.isAuthenticated else { logger.warning("Unauthorized request to \(request.urlURL.path)") return .forbidden } return application(connection, request) } }
17cc9f314bf031e145d10742fb110c2c
40.265306
195
0.619683
false
false
false
false
ixx1232/swift-Tour
refs/heads/master
swiftTour/swiftTour/tour.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit /** 本页内容包括: 简单值(Simple Value) 控制流(control Flow) 函数和闭包(Functions and Closures) 对象和类(Objects and classes) 枚举和结构体(Enumerations and Structures) 协议和扩展(Protocols and Extensions) 错误处理(Error Handling) 泛型(Generics) */ print("Hello, world!") /* 简单值 */ var myVariable = 42 myVariable = 50 let myConstant = 42 let implicitInteger = 70 let implcitDouble = 70.0 let explictiDoublt: Double = 70 // EXPERIMENT: Create a constant with an explicit type of float and a value of 4 let explicitDouble: Double = 4 let label = "The width is " let width = 94 let widthLabel = label + String(width) // EXPERIMENT: Try removing the conversion to string from the last line. What error do you get? // binary operator '+' cannot be applied to operands of type 'String' and 'Int' let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." // EXPERMENT: Use \() to include a float-point calculation in a string and to include someone's name in a greeting. let revenue: Float = 160.0 let cost: Float = 70.0 let profit: String = "Today my lemonade stand made \(revenue-cost)" let personName: String = "Josh" let greetJosh = "Hi \(personName)" var shoppingList = ["catfish", "water", "tulips","blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm":"Captain", "Kaylee":"Mechanic", ] occupations["Jayne"] = "Public Relations" let emptyArray = [String]() let emptyDictionary = [String: Float]() shoppingList = [] occupations = [:] /** 控制流 */ let individualScore = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScore { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore) var optionalString: String? = "Hello" print(optionalString == nil) var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalString { greeting = "Hello, \(name)" } // EXPERMENT: Change optional to nil. What greeting do you get? Add an else clause that sets a different greeting if optionalName is nil optionalName = nil if let name = optionalName { greeting = "Hello, \(name)" } else { greeting = "Hello stranger" } let nickName: String? = nil let fullName: String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)" let vegetable = "red repper" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber","watercress": print("That would make a good tea sandwich") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup.") } // EXPERIMENT: Try removing the default case. What error do you get? // switch must be exhaustive, consider adding a default clause let interestingNumbers = [ "prime":[2, 3, 5, 7, 11, 13], "Fibonacci":[1, 1, 2, 3, 5, 8], "Square":[1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } print(largest) // EXPERIMENT: Add another variable to keep track o which kind of number was the largest, as well as what that largest number was. let interestingNumber1 = [ "prime":[2, 3, 5, 7, 11, 13], "Fibonacci":[1, 1, 2, 3, 5, 8], "Square":[1, 4, 9, 16, 25], ] var largest1 = 0 var largestKind: String = "" for (kind, numbers) in interestingNumber1 { for number in numbers { if number > largest1 { largest1 = number largestKind = kind } } } print(largest1) print(largestKind) var n = 2 while n < 100 { n = n * 2 } print(n) var m = 2 repeat { m = m * 2 }while m < 100 print(m) var total = 0 for i in 0..<4 { total += i } print(total) /** Functions and Closures */ func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } greet(person: "Bob", day: "Tuesday") // EXPERIMENT: Remove the day parameter. Add a parameter to include today's lunch special in the greeting. func greet(name: String, tadaysLunch: String) -> String { return "Hello \(name), today's lunch is \(tadaysLunch)" } greet(name: "Bob", tadaysLunch: "Turkey Sandwich") func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." } greet("John", on: "Wednesday") func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9]) print(statistics.sum) print(statistics.min) func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(numbers: 42, 597, 12) // EXPERIMENT: Write a function that calculates the average of its arguments func average(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum/numbers.count } average(numbers: 2, 10) func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(list: numbers, condition: lessThanTen) numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) // EXPERIMENT: Rewrite the closure to return zero for all odd numbers. var number1 = [20 , 19, 7, 12] number1.map({ (number : Int) -> Int in if number % 2 == 0 { return number } else { return 0 } }) let mappedNumbers = numbers.map({ number in 3 * number }) print(mappedNumbers) let sortedNumbers = numbers.sorted{ $0 > $1 } print(sortedNumbers) /** Objects and Classes */ class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } // EXPERIMENT: Add a constant property with let, and add another method that takes an argument. class Shape1 { var numberOfSides = 0 let dimension = "2d" func simpleDescription() -> String { return "A shape with \(numberOfSides) sides" } func notSoSimpleDescription() -> String { return "That is a \(dimension) shape." } } let myShape1 = Shape1() myShape1.notSoSimpleDescription() var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() class NameShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } class Square: NameShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)" } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription() // EXPERIMENT: Make another subclass of NameShape called Circle that takes a radius and a name as arguments to its initializer. class NameShape1 { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } class Circle: NameShape1 { var radius: Double init(name: String, radius: Double) { self.radius = radius super.init(name: name) self.name = name } override func simpleDescription() -> String { return "A circle with a radius of \(radius)" } func area() -> Double { return 3.14159265 * radius * radius } } let myCircle = Circle(name: "Example circle", radius: 6.0) myCircle.name myCircle.area() myCircle.simpleDescription() class EquilateralTriangle: NameShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimter) triangle.perimter = 9.9 print(triangle.sideLength) class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") print(triangleAndSquare.square.sideLength) print(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "large square") print(triangleAndSquare.triangle.sideLength) let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength /** Enumerations and Structrures */ enum Rank: Int { case ace = 1 case two, three, four, five, six, seven, eight, nine, ten case jack, queen, king func simpleDescription() -> String { switch self { case .ace: return "ace" case .jack: return "jack" case .queen: return "queen" case .king: return "king" default: return String(self.rawValue) } } } let ace = Rank.ace let aceRawValue = ace.rawValue // EXPERIMENT: Write a function that compares two Rank values by comparing their raw values. enum Rank2: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } let ac = Rank2.Ace let two = Rank2.Two let aceRawValu = ace.rawValue func compare(rank11: Rank2, rank12: Rank2) -> String { var higher: Rank2 = rank11 if rank12.rawValue > rank11.rawValue { var higher = rank12 } return "The higher of the two is \(higher.simpleDescription())" } compare(rank11: ac, rank12: two) if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } enum Suit { case spades, hearts, diamonds, clubs func simpleDescription() -> String { switch self { case .spades: return "spades" case .hearts: return "hearts" case .diamonds: return "diamonds" case .clubs: return "clubs" } } } let hearts = Suit.hearts let heartsDescription = hearts.simpleDescription() // EXPERIMENT: Add a color() method to Suit that returns "black" for spades and clubs, and returns "red" for hearts and diamonds. enum Suit1: Int { case Spades = 1 case Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } func color() -> String { switch self { case .Spades, .Clubs: return "black" case .Hearts, .Diamonds: return "red" } } } let heartsDescription1 = Suit1.Hearts.simpleDescription() let heartsColor = Suit1.Hearts.color() enum ServerResponse { case result(String, String) case failure(String) } let success = ServerResponse.result(" 6:00 am", "8:09 pm") let failure = ServerResponse.failure("Out of cheese") switch success { case let .result(sunrise, sunset): print("Sunrise is at \(sunrise) and sunset is at \(sunset).") case let .failure(message): print("Failure... \(message)") } // EXPERRMENT: Add a third case to ServerResponse and to the switch. enum ServerResponse1 { case Result(String, String) case Error(String) case ThirdCase(String) } struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .three, suit: .spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() // EXPERIMENT: Add a method to Card that creates a full deck of cards,with one card of each combination of rank and suit //class Card12 { // var rank: Rank // var suit: Suit // // init(cardRank: Rank, cardSuit: Suit) { // self.rank = cardRank // self.suit = cardSuit // } // // func simpleDescription() -> String { // return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" // } // // func Deck() -> String { // var stringTogether = "" // for i in 0..<14 { // if let convertedRank = Rank.init(rawValue: i) { // self.rank = convertedRank // // for y in 0..<14 { // if let convertedSuit = Suit.init(rawValue: y) { // self.suit = convertedSuit // stringTogether = "\(stringTogether) \(self.simpleDescription())" // } // } // } // } // return stringTogether // } //} /** Protocols and Extensions */ protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription // EXPERIMENT: Write an enumeration that conforms to this protocol. protocol ExampleProtocol22 { var simpleDescription: String { get } mutating func adjust() } class SimpleClass22: ExampleProtocol22 { var simpleDescription: String = "A VERY simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += "Now 100% adjusted." } } class ConformingClass: ExampleProtocol22 { var simpleDescription: String = "A very simple class." var carModel: String = "The toyota corolla" func adjust() { carModel += " is the best car ever" } } let conformingClass = ConformingClass() conformingClass.adjust() let whichCarIsBest = conformingClass.carModel extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } print(7.simpleDescription) // EXPERIMENT: Write an extension for the Double type that adds an absoluteValue property. extension Double { var absoluteValue: Double { return abs(self) } } let exampleDouble: Double = -40.0 let exampleAbsoluteValue = exampleDouble.absoluteValue let protocolValue: ExampleProtocol = a protocolValue.simpleDescription /** Error Handing */ enum PrinterError: Error { case outOfPaper case noToner case onFire } func send(job: Int, toPrinter printerName: String) throws -> String { if printerName == "Never Has Toner" { throw PrinterError.noToner } return "Job sent" } do { let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng") print(printerResponse) } catch { print(error) } // EXPERIMENT: Change the printer name to "Never Has Toner", so that the send(job: toPrinter:)function throws an error. do { let printerResponse = try send(job: 1440, toPrinter: "Gutenberg") print(printerResponse) } catch PrinterError.onFire { print("I'll just put this over here, with the rest of the fire.") } catch let printerError as PrinterError { print("Printer error: \(printerError)") } catch { print(error) } // EXPERMENT: Add code to throw an error inside the do block. What kind of error do you need to throw so that the error is handled by the first catch block? What about the second and third blocks? let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler") let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner") var fridgeIsOpen = false let fridgeContent = ["milk", "eggs", "leftovers"] func fridgeContains(_ food: String) -> Bool { fridgeIsOpen = true defer { fridgeIsOpen = false } let result = fridgeContent.contains(food) return result } fridgeContains("banana") print(fridgeIsOpen) /** Generics */ func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] { var result = [Item]() for _ in 0..<numberOfTimes { result.append(item) } return result } makeArray(repeating: "knock", numberOfTimes: 4) enum OptionalValue<Wrapped> { case none case some(Wrapped) } var possibleInteger: Optional<Int> = .none possibleInteger = .some(100) func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3]) // EXPERIMENT: Modify the anyCommonElements(_:_:)function to make a function that returns an array of the elements that any two sequences have in common // 练习: 修改 anyCommonElements 函数来创建一个函数, 返回一个数组, 内容是两个序列的共有元素. //func anyCommonElements1<T: Sequence, U:Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element //{ // for lhsItem in lhs { // for rhsItem in rhs { // if lhsItem == rhsItem { // return true // } // } // } // return false //} //anyCommonElements1([1, 2, 3], [3]) // // //func whichCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element:Equatable, T.GeneratorType.Element == U.GeneratorType.Element>(lhs: T, rhs: U) -> Array<T.GeneratorType.Element> //{ // var toReturn = Array<T.GeneratorType.Element>() // // for lhsItem in lhs { // for rhsItem in rhs { // if lhsItem == rhsItem { // toReturn.append(lhsItem) // } // } // } // return toReturn //} //whichCommonElements(lhs: [1, 2, 3], rhs: [3, 2]) // Write<T: Equatable> is the same as writing<T>...where T:Equatable>.
9578a16fcb6a68cb80f3210e403c9493
23.32494
201
0.628678
false
false
false
false
lemberg/obd2-swift-lib
refs/heads/master
OBD2-Swift/Classes/Classes/SensorList.swift
mit
1
// // SensorList.swift // OBD2Swift // // Created by Max Vitruk on 27/04/2017. // Copyright © 2017 Lemberg. All rights reserved. // import Foundation /** Supported OBD2 sensors list For detailed information read https://en.wikipedia.org/wiki/OBD-II_PIDs */ enum OBD2Sensor : UInt8 { case Supported01_20 = 0x00 case MonitorStatusSinceDTCsCleared = 0x01 case FreezeFrameStatus = 0x02 case FuelSystemStatus = 0x03 case CalculatedEngineLoadValue = 0x04 case EngineCoolantTemperature = 0x05 case ShorttermfueltrimBank1 = 0x06 case LongtermfueltrimBank1 = 0x07 case ShorttermfueltrimBank2 = 0x08 case LongtermfueltrimBank2 = 0x09 case FuelPressure = 0x0A case IntakeManifoldPressure = 0x0B case EngineRPM = 0x0C case VehicleSpeed = 0x0D case TimingAdvance = 0x0E case IntakeAirTemperature = 0x0F case MassAirFlow = 0x10 case ThrottlePosition = 0x11 case SecondaryAirStatus = 0x12 case OxygenSensorsPresent = 0x13 case OxygenVoltageBank1Sensor1 = 0x14 case OxygenVoltageBank1Sensor2 = 0x15 case OxygenVoltageBank1Sensor3 = 0x16 case OxygenVoltageBank1Sensor4 = 0x17 case OxygenVoltageBank2Sensor1 = 0x18 case OxygenVoltageBank2Sensor2 = 0x19 case OxygenVoltageBank2Sensor3 = 0x1A case OxygenVoltageBank2Sensor4 = 0x1B case OBDStandardsThisVehicleConforms = 0x1C case OxygenSensorsPresent2 = 0x1D case AuxiliaryInputStatus = 0x1E case RunTimeSinceEngineStart = 0x1F case PIDsSupported21_40 = 0x20 case DistanceTraveledWithMalfunctionIndicatorLampOn = 0x21 case FuelRailPressureManifoldVacuum = 0x22 case FuelRailPressureDiesel = 0x23 case EquivalenceRatioVoltageO2S1 = 0x24 case EquivalenceRatioVoltageO2S2 = 0x25 case EquivalenceRatioVoltageO2S3 = 0x26 case EquivalenceRatioVoltageO2S4 = 0x27 case EquivalenceRatioVoltageO2S5 = 0x28 case EquivalenceRatioVoltageO2S6 = 0x29 case EquivalenceRatioVoltageO2S7 = 0x2A case EquivalenceRatioVoltageO2S8 = 0x2B case CommandedEGR = 0x2C case EGRError = 0x2D case CommandedEvaporativePurge = 0x2E case FuelLevelInput = 0x2F case NumberofWarmUpsSinceCodesCleared = 0x30 case DistanceTraveledSinceCodesCleared = 0x31 case EvaporativeSystemVaporPressure = 0x32 case BarometricPressure = 0x33 case EquivalenceRatioCurrentO2S1 = 0x34 case EquivalenceRatioCurrentO2S2 = 0x35 case EquivalenceRatioCurrentO2S3 = 0x36 case EquivalenceRatioCurrentO2S4 = 0x37 case EquivalenceRatioCurrentO2S5 = 0x38 case EquivalenceRatioCurrentO2S6 = 0x39 case EquivalenceRatioCurrentO2S7 = 0x3A case EquivalenceRatioCurrentO2S8 = 0x3B case CatalystTemperatureBank1Sensor1 = 0x3C case CatalystTemperatureBank2Sensor1 = 0x3D case CatalystTemperatureBank1Sensor2 = 0x3E case CatalystTemperatureBank2Sensor2 = 0x3F case PIDsSupported41_60 = 0x40 case MonitorStatusThisDriveCycle = 0x41 case ControlModuleVoltage = 0x42 case AbsoluteLoadValue = 0x43 case CommandEquivalenceRatio = 0x44 case RelativeThrottlePosition = 0x45 case AmbientAirTemperature = 0x46 case AbsoluteThrottlePositionB = 0x47 case AbsoluteThrottlePositionC = 0x48 case AcceleratorPedalPositionD = 0x49 case AcceleratorPedalPositionE = 0x4A case AcceleratorPedalPositionF = 0x4B case CommandedThrottleActuator = 0x4C case TimeRunWithMILOn = 0x4D case TimeSinceTroubleCodesCleared = 0x4E // From this point sensors don't have full support yet case MaxValueForER_OSV_OSC_IMAP = 0x4F /* Maximum value for equivalence ratio, oxygen sensor voltage, oxygen sensor current and intake manifold absolute pressure */ case MaxValueForAirFlowRateFromMAFSensor = 0x50 case FuelType = 0x51 case EthanolFuelRatio = 0x52 case AbsoluteEvapSystemVaporPressure = 0x53 case EvapSystemVaporPressure = 0x54 case ShortTermSecondaryOxygenSensorTrimBank_1_3 = 0x55 case LongTermSecondaryOxygenSensorTrimBank_1_3 = 0x56 case ShortTermSecondaryOxygenSensorTrimBank_2_4 = 0x57 case LongTermSecondaryOxygenSensorTrimBank_2_4 = 0x58 case FuelRailPressure_Absolute = 0x59 case RelativeAcceleratorPedalPosition = 0x5A case HybridBatteryPackRemainingLife = 0x5B case EngineOilTemperature = 0x5C //OBD2SensorsVIN = 0x123, // OBD2Sensor = 0x, // Sensors should be added at this point for supporting count and last. }
1eb596c058d5a14cc4f963826dd1d786
34.92437
106
0.80117
false
false
false
false
jacobjiggler/FoodMate
refs/heads/master
src/iOS/FoodMate/FoodMate/ScanItemViewController.swift
mit
1
// // ScanItemViewController.swift // FoodMate // // Created by Jordan Horwich on 9/13/14. // Copyright (c) 2014 FoodMate. All rights reserved. // import UIKit import AVFoundation class ScanItemViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var _session:AVCaptureSession! var _device:AVCaptureDevice! var _input:AVCaptureDeviceInput! var _output:AVCaptureMetadataOutput! var _prevLayer:AVCaptureVideoPreviewLayer! @IBOutlet weak var scanView: UIView! override func viewDidLoad() { super.viewDidLoad() _session = AVCaptureSession() _device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) var error: NSError? = nil _input = AVCaptureDeviceInput.deviceInputWithDevice(_device, error: &error) as AVCaptureDeviceInput if ((_input) != nil) { _session.addInput(_input) } else { print("Error: \(error)") } _output = AVCaptureMetadataOutput() _output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) _session.addOutput(_output) _output.metadataObjectTypes = _output.availableMetadataObjectTypes _prevLayer = AVCaptureVideoPreviewLayer.layerWithSession(_session) as AVCaptureVideoPreviewLayer _prevLayer.frame = scanView.bounds _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill scanView.layer.addSublayer(_prevLayer) } override func viewDidAppear(animated: Bool) { _session.startRunning() } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { var highlightViewRect:CGRect = CGRectZero var barCodeObject:AVMetadataMachineReadableCodeObject var detectionString = "" var barCodeTypes = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode] for metadata in metadataObjects { for type in barCodeTypes { if metadata.type == type { barCodeObject = _prevLayer.transformedMetadataObjectForMetadataObject(metadata as AVMetadataObject) as AVMetadataMachineReadableCodeObject highlightViewRect = barCodeObject.bounds detectionString = metadata.stringValue break } } if detectionString != "" { let storyboard = UIStoryboard(name: "Main", bundle: nil); let vc = storyboard.instantiateViewControllerWithIdentifier("manualItem") as ManualItemViewController vc.initwithBarcode(detectionString) self.presentViewController(vc, animated: true, completion: nil) _session.stopRunning() break } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ ///////////////////// // Button Bar Actions ///////////////////// @IBAction func doneButtonClicked(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
1ef168a2849d357c4c48f1a431a502f6
37.307692
162
0.664408
false
false
false
false
petrone/PetroneAPI_swift
refs/heads/master
PetroneAPI/PetroneStructs.swift
mit
1
// // PetroneStructs.swift // Petrone // // Created by Byrobot on 2017. 7. 31.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation public struct PetroneScanData { public var name: String? public var uuid: String? public var rssi: NSNumber = 0 public var fpv: Bool = false public init( name: String, uuid: String, rssi: NSNumber ) { self.name = name self.uuid = uuid self.rssi = rssi } } public struct PetroneStatus { public var mode: PetroneMode = PetroneMode.None public var modeSystem: PetroneModeSystem = PetroneModeSystem.None public var modeFlight: PetroneModeFlight = PetroneModeFlight.None public var modeDrive: PetroneModeDrive = PetroneModeDrive.None public var sensorOrientation: PetroneSensorOrientation = PetroneSensorOrientation.None public var coordinate: PetroneCoordinate = PetroneCoordinate.None public var battery: UInt8 = 0 public mutating func parse(_ data:Data) { self.mode = PetroneMode(rawValue: data[1])! self.modeSystem = PetroneModeSystem(rawValue: data[2])! self.modeFlight = PetroneModeFlight(rawValue: data[3])! self.modeDrive = PetroneModeDrive(rawValue: data[4])! self.sensorOrientation = PetroneSensorOrientation(rawValue: data[5])! self.coordinate = PetroneCoordinate(rawValue: data[6])! self.battery = data[7] } } public struct PetroneTrimFlight { public var throttle: Int16 = 0 public var yaw: Int16 = 0 public var roll: Int16 = 0 public var pitch: Int16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.throttle = Petrone.getInt16(data, start:&index) self.yaw = Petrone.getInt16(data, start:&index) self.roll = Petrone.getInt16(data, start:&index) self.pitch = Petrone.getInt16(data, start:&index) } } public struct PetroneTrimDrive { public var wheel: Int16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.wheel = Petrone.getInt16(data, start:&index) } } public struct PetroneTrim { public var flight: PetroneTrimFlight = PetroneTrimFlight() public var drive: PetroneTrimDrive = PetroneTrimDrive() public mutating func parse(_ data:Data) { var index:Int = 1 self.flight.throttle = Petrone.getInt16(data, start:&index) self.flight.yaw = Petrone.getInt16(data, start:&index) self.flight.roll = Petrone.getInt16(data, start:&index) self.flight.pitch = Petrone.getInt16(data, start:&index) self.drive.wheel = Petrone.getInt16(data, start:&index) } } public struct PetroneAttitude { public var roll:Int16 = 0 public var pitch:Int16 = 0 public var yaw:Int16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.roll = Petrone.getInt16(data, start: &index) self.pitch = Petrone.getInt16(data, start: &index) self.yaw = Petrone.getInt16(data, start: &index) } } public struct PetroneGyroBias { public var roll:Int16 = 0 public var pitch:Int16 = 0 public var yaw:Int16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.roll = Petrone.getInt16(data, start: &index) self.pitch = Petrone.getInt16(data, start: &index) self.yaw = Petrone.getInt16(data, start: &index) } } public struct PetroneCountFlight { public var time:UInt64 = 0 public var takeOff:UInt16 = 0 public var landing:UInt16 = 0 public var accident:UInt16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.time = Petrone.getUInt64(data, start: &index) self.takeOff = Petrone.getUInt16(data, start: &index) self.landing = Petrone.getUInt16(data, start: &index) self.accident = Petrone.getUInt16(data, start: &index) } } public struct PetroneCountDrive { public var time:UInt64 = 0 public var accident:UInt16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.time = Petrone.getUInt64(data, start: &index) self.accident = Petrone.getUInt16(data, start: &index) } } public struct PetroneImuRawAndAngle { public var accX:Int16 = 0 public var accY:Int16 = 0 public var accZ:Int16 = 0 public var gyroRoll:Int16 = 0 public var gyroPitch:Int16 = 0 public var gyroYaw:Int16 = 0 public var angleRoll:Int16 = 0 public var anglePitch:Int16 = 0 public var angleYaw:Int16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.accX = Petrone.getInt16(data, start: &index) self.accY = Petrone.getInt16(data, start: &index) self.accZ = Petrone.getInt16(data, start: &index) self.gyroRoll = Petrone.getInt16(data, start: &index) self.gyroPitch = Petrone.getInt16(data, start: &index) self.gyroYaw = Petrone.getInt16(data, start: &index) self.angleRoll = Petrone.getInt16(data, start: &index) self.anglePitch = Petrone.getInt16(data, start: &index) self.angleYaw = Petrone.getInt16(data, start: &index) } } public struct PetronePressure { public var d1:Int32 = 0 public var d2:Int32 = 0 public var temperature:Int32 = 0 public var pressure:Int32 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.d1 = Petrone.getInt32(data, start: &index) self.d2 = Petrone.getInt32(data, start: &index) self.temperature = Petrone.getInt32(data, start: &index) self.pressure = Petrone.getInt32(data, start: &index) } } public struct PetroneImageFlow { public var fVelocitySumX:Int32 = 0 public var fVelocitySumY:Int32 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.fVelocitySumX = Petrone.getInt32(data, start: &index) self.fVelocitySumY = Petrone.getInt32(data, start: &index) } } public struct PetroneBattery { public var percent:UInt8 = 0 public mutating func parse(_ data:Data) { self.percent = data[1] } } public struct PetroneMotorBase { public var forward:Int16 = 0 public var reverse:Int16 = 0 public mutating func parse(_ data:Data, start:inout Int) { self.forward = Petrone.getInt16(data, start: &start) self.reverse = Petrone.getInt16(data, start: &start) } } public struct PetroneMotor { public var motor:[PetroneMotorBase] = [PetroneMotorBase(), PetroneMotorBase(), PetroneMotorBase(), PetroneMotorBase()] public mutating func parse(_ data:Data) { var index:Int = 1 motor[0].parse(data, start: &index) motor[1].parse(data, start: &index) motor[2].parse(data, start: &index) motor[3].parse(data, start: &index) } } public struct PetroneTemperature { public var temperature:Int32 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.temperature = Petrone.getInt32(data, start: &index) } } public struct PetroneRange { public var left:UInt16 = 0 public var front:UInt16 = 0 public var right:UInt16 = 0 public var rear:UInt16 = 0 public var top:UInt16 = 0 public var bottom:UInt16 = 0 public mutating func parse(_ data:Data) { var index:Int = 1 self.left = Petrone.getUInt16(data, start: &index) self.front = Petrone.getUInt16(data, start: &index) self.right = Petrone.getUInt16(data, start: &index) self.rear = Petrone.getUInt16(data, start: &index) self.top = Petrone.getUInt16(data, start: &index) self.bottom = Petrone.getUInt16(data, start: &index) } } public struct PetroneLedModeBase { public var mode:UInt8 = PetroneLigthMode.None.rawValue public var color:UInt8 = 0 public var interval:UInt8 = 0 } public struct PetroneLedBase { public var mode:UInt8 = PetroneLigthMode.None.rawValue public var red:UInt8 = 0 public var green:UInt8 = 0 public var blue:UInt8 = 0 public var interval:UInt8 = 0 }
750cfe63e3c8194cbe50d280b1804b82
31.64
122
0.655515
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/Editor/Sources/ProtoUIComponents/ScrollViewController1.swift
mit
1
// // ScrollViewController1.swift // RFC Formaliser // // Created by Hoon H. on 10/27/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation import Cocoa /// `translatesAutoresizingMaskIntoConstraints` set to `false` implicitly. @availability(*,deprecated=0) class ScrollViewController1: NSViewController { override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { super.init(coder: coder) } final var documentViewController:NSViewController? = nil { willSet { if let dc1 = documentViewController { scrollView.documentView = nil self.removeChildViewController(dc1) } } didSet { if let dc1 = documentViewController { scrollView.documentView = dc1.view self.addChildViewController(dc1) } } } final var scrollView:NSScrollView { get { return super.view as! NSScrollView } set(v) { super.view = v } } override var view:NSView { willSet { fatalError("You cannot replace view of this object.") } } override func loadView() { // super.loadView() super.view = NSScrollView() scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = true scrollView.translatesAutoresizingMaskIntoConstraints = false /// This shall benefit everyone in the universe... } }
14671548dc835622841f70dc675582ed
19.852941
114
0.708039
false
false
false
false
ddaguro/clintonconcord
refs/heads/master
OIMApp/Controls/ADVAnimatedButton/ADVAnimatedButton.swift
mit
1
// // ADVAnimatedButton.swift // Mega // // Created by Tope Abayomi on 10/12/2014. // Copyright (c) 2014 App Design Vault. All rights reserved. // import Foundation import UIKit @IBDesignable class ADVAnimatedButton: UIButton { var refreshImageView = UIImageView(frame: CGRectZero) var animating : Bool = false override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } @IBInspectable var imageToShow : UIImage = UIImage(named: "sync")! { didSet { refreshImageView.image = imageToShow.imageWithRenderingMode(.AlwaysTemplate) } } func setupView(){ refreshImageView.image = UIImage(named: "sync")?.imageWithRenderingMode(.AlwaysTemplate) refreshImageView.tintColor = UIColor(white: 1.0, alpha: 0.5) refreshImageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(refreshImageView) } override func layoutSubviews() { super.layoutSubviews() let heightConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Height, relatedBy: .Equal, toItem: titleLabel, attribute: .Height, multiplier: 1.0, constant: 0.0) let aspectRatioConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Height, relatedBy: .Equal, toItem: refreshImageView, attribute: .Width, multiplier: 1.0, constant: 0.0) let horizontalSpacingConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Right, relatedBy: .Equal, toItem: titleLabel, attribute: .Left, multiplier: 1.0, constant: -10.0) let topConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute: .Top, multiplier: 1.0, constant: 0.0) refreshImageView.addConstraint(aspectRatioConstraint) addConstraints([heightConstraint, horizontalSpacingConstraint, topConstraint]) let horizontalCenterConstraint = NSLayoutConstraint(item: titleLabel!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0) let verticalCenterConstraint = NSLayoutConstraint(item: titleLabel!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0) addConstraints([horizontalCenterConstraint, verticalCenterConstraint]) } func startAnimating(){ if !animating { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.toValue = M_PI * 2.0 animation.cumulative = true animation.duration = 1.0 animation.repeatCount = 10000 refreshImageView.layer.addAnimation(animation, forKey: "rotationAnimation") animating = true } } func stopAnimating(){ CATransaction.begin() refreshImageView.layer.removeAllAnimations() CATransaction.commit() animating = false } }
b889e028b98ab6858f2daa15bd9941f5
34.11828
194
0.647275
false
false
false
false
groue/GRDB.swift
refs/heads/master
Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift
mit
1
import XCTest import GRDB // Ordered hasManyThrough private struct Team: Codable, FetchableRecord, PersistableRecord, Equatable { static let playerRoles = hasMany(PlayerRole.self).order(Column("position")) static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player) var id: Int64 var name: String } private struct PlayerRole: Codable, FetchableRecord, PersistableRecord { static let player = belongsTo(Player.self) var teamId: Int64 var playerId: Int64 var position: Int } private struct Player: Codable, FetchableRecord, PersistableRecord, Equatable { var id: Int64 var name: String } private struct TeamInfo: Decodable, FetchableRecord, Equatable { var team: Team var players: [Player] } /// A usage test for ordered hasManyThrough association class AssociationHasManyThroughOrderingTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() t.column("name", .text).notNull() } try db.create(table: "player") { t in t.column("id", .integer).primaryKey() t.column("name", .text).notNull() } try db.create(table: "playerRole") { t in t.column("teamId", .integer).notNull().references("team") t.column("playerId", .integer).notNull().references("player") t.column("position", .integer).notNull() t.primaryKey(["teamId", "playerId"]) } try Team(id: 1, name: "Red").insert(db) try Team(id: 2, name: "Blue").insert(db) try Player(id: 1, name: "Arthur").insert(db) try Player(id: 2, name: "Barbara").insert(db) try Player(id: 3, name: "Craig").insert(db) try Player(id: 4, name: "Diane").insert(db) try PlayerRole(teamId: 1, playerId: 1, position: 1).insert(db) try PlayerRole(teamId: 1, playerId: 2, position: 2).insert(db) try PlayerRole(teamId: 1, playerId: 3, position: 3).insert(db) try PlayerRole(teamId: 2, playerId: 2, position: 3).insert(db) try PlayerRole(teamId: 2, playerId: 3, position: 2).insert(db) try PlayerRole(teamId: 2, playerId: 4, position: 1).insert(db) } } func testRequestFor() throws { try makeDatabaseQueue().read { db in let team = try Team.fetchOne(db, key: 2)! let players = try team.request(for: Team.players).fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT "player".* \ FROM "player" \ JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" = 2) \ ORDER BY "playerRole"."position" """) XCTAssertEqual(players, [ Player(id: 4, name: "Diane"), Player(id: 3, name: "Craig"), Player(id: 2, name: "Barbara"), ]) } } func testReorderedRequestFor() throws { try makeDatabaseQueue().read { db in let team = try Team.fetchOne(db, key: 2)! let players = try team.request(for: Team.players).order(Column("name")).fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT "player".* \ FROM "player" \ JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" = 2) \ ORDER BY "player"."name", "playerRole"."position" """) XCTAssertEqual(players, [ Player(id: 2, name: "Barbara"), Player(id: 3, name: "Craig"), Player(id: 4, name: "Diane"), ]) } } func testIncludingAll() throws { try makeDatabaseQueue().read { db in let teamInfos = try Team .orderByPrimaryKey() .including(all: Team.players) .asRequest(of: TeamInfo.self) .fetchAll(db) XCTAssertTrue(sqlQueries.contains(""" SELECT * FROM "team" ORDER BY "id" """)) XCTAssertTrue(sqlQueries.contains(""" SELECT "player".*, "playerRole"."teamId" AS "grdb_teamId" \ FROM "player" \ JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" IN (1, 2)) \ ORDER BY "playerRole"."position" """)) XCTAssertEqual(teamInfos, [ TeamInfo( team: Team(id: 1, name: "Red"), players: [ Player(id: 1, name: "Arthur"), Player(id: 2, name: "Barbara"), Player(id: 3, name: "Craig"), ]), TeamInfo( team: Team(id: 2, name: "Blue"), players: [ Player(id: 4, name: "Diane"), Player(id: 3, name: "Craig"), Player(id: 2, name: "Barbara"), ])]) } } func testReorderedIncludingAll() throws { try makeDatabaseQueue().read { db in let teamInfos = try Team .orderByPrimaryKey() .including(all: Team.players.order(Column("name"))) .asRequest(of: TeamInfo.self) .fetchAll(db) XCTAssertTrue(sqlQueries.contains(""" SELECT * FROM "team" ORDER BY "id" """)) XCTAssertTrue(sqlQueries.contains(""" SELECT "player".*, "playerRole"."teamId" AS "grdb_teamId" \ FROM "player" \ JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" IN (1, 2)) \ ORDER BY "player"."name", "playerRole"."position" """)) XCTAssertEqual(teamInfos, [ TeamInfo( team: Team(id: 1, name: "Red"), players: [ Player(id: 1, name: "Arthur"), Player(id: 2, name: "Barbara"), Player(id: 3, name: "Craig"), ]), TeamInfo( team: Team(id: 2, name: "Blue"), players: [ Player(id: 2, name: "Barbara"), Player(id: 3, name: "Craig"), Player(id: 4, name: "Diane"), ])]) } } }
44f9c4974a2564b58819d0481039c4b7
39.676647
118
0.500221
false
false
false
false
clayellis/StringScanner
refs/heads/master
Sources/StringScanner/CharacterSet.swift
mit
1
// // CharactersSet.swift // StringScanner // // Created by Omar Abdelhafith on 26/10/2016. // // /// Range Set public enum CharactersSet: Containable { /// All english letters set case allLetters /// Small english letters set case smallLetters /// Capital english letters set case capitalLetters /// Numbers set case numbers /// Spaces set case space /// Alpha Numeric set case alphaNumeric /// Characters in the string case string(String) /// Containable Array case containables([Containable]) /// Range (and closed range) case range(Containable) /// Join with another containable public func join(characterSet: CharactersSet) -> CharactersSet { let array = [characterSet.containable, self.containable] return .containables(array) } public func contains(character element: Character) -> Bool { return self.containable.contains(character: element) } var containable: Containable { switch self { case .smallLetters: return RangeContainable(ranges: "a"..."z") case .capitalLetters: return RangeContainable(ranges: "A"..."Z") case .allLetters: return RangeContainable( ranges: CharactersSet.smallLetters.containable, CharactersSet.capitalLetters.containable) case .numbers: return RangeContainable(ranges: "0"..."9") case .space: return RangeContainable(ranges: " "..." ") case .alphaNumeric: return RangeContainable(ranges: CharactersSet.allLetters.containable, CharactersSet.numbers.containable) case .string(let string): return ContainableString(stringOfCharacters: string) case .containables(let array): return RangeContainable(array: array) case .range(let range): return RangeContainable(ranges: range) } } } private struct ContainableString: Containable { let stringOfCharacters: String func contains(character element: Character) -> Bool { return stringOfCharacters.find(string: String(element)) != nil } } private struct RangeContainable: Containable { let ranges: [Containable] init(ranges: Containable...) { self.ranges = ranges } init(array: [Containable]) { self.ranges = array } func contains(character element: Character) -> Bool { let filtered = ranges.filter { $0.contains(character: element) } return filtered.count > 0 } }
ee5961e70fb6cb1b38bfced3e31770fd
22.930693
97
0.683906
false
false
false
false
zskyfly/yelp
refs/heads/master
Yelp/FiltersViewController.swift
apache-2.0
1
// // FiltersViewController.swift // Yelp // // Created by Zachary Matthews on 2/18/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit protocol FiltersViewControllerDelegate { func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [SearchFilter]) } class FiltersViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var searchFilters: [SearchFilter]! var delegate: FiltersViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.allowsSelection = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onCancelButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onSearchButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) delegate?.filtersViewController(self, didUpdateFilters: self.searchFilters) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension FiltersViewController: UITableViewDataSource { func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let searchFilter = self.searchFilters[section] return searchFilter.sectionName } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let searchFilter = self.searchFilters[section] switch searchFilter.cellIdentifier { case "SwitchCell": return searchFilter.values.count case "SegmentedCell": return 1 default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell let section = indexPath.section let index = indexPath.row let searchFilter = self.searchFilters[section] let searchFilterValues = searchFilter.values let selectedIndex = searchFilter.selectedIndex let searchFilterValue = searchFilterValues[index] let searchFilterState = searchFilter.states[index] switch searchFilter.cellIdentifier { case "SwitchCell": let switchCell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchCell switchCell.delegate = self switchCell.filterState = searchFilterState switchCell.filterValue = searchFilterValue cell = switchCell break case "SegmentedCell": let segmentedCell = tableView.dequeueReusableCellWithIdentifier("SegmentedCell", forIndexPath: indexPath) as! SegmentedCell segmentedCell.delegate = self segmentedCell.selectedIndex = selectedIndex segmentedCell.segmentNames = searchFilterValues cell = segmentedCell break default: cell = UITableViewCell() } return cell } } extension FiltersViewController: UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.searchFilters.count } } extension FiltersViewController: SwitchCellDelegate { func switchCell(switchCell: SwitchCell, didChangeValue value: Bool) { let indexPath = tableView.indexPathForCell(switchCell)! let section = indexPath.section let row = indexPath.row self.searchFilters[section].states[row] = value } } extension FiltersViewController: SegmentedCellDelegate { func segmentedCell(segmentedCell: SegmentedCell, didChangeValue value: Int) { let indexPath = tableView.indexPathForCell(segmentedCell)! let section = indexPath.section self.searchFilters[section].selectedIndex = value } }
06968f06afc1ee998390c81cc2efc3da
29.809859
135
0.693257
false
false
false
false
brightdigit/speculid
refs/heads/master
frameworks/speculid/Controllers/VersionMenuItem.swift
mit
1
import Cocoa import SwiftVer extension Version { public var buildHexidecimal: String { String(format: "%05x", build) } } public class VersionMenuItem: NSMenuItem { public static func buildNumbers(fromResource resource: String?, withExtension extension: String?) -> Set<Int>? { if let url = Application.bundle.url(forResource: resource, withExtension: `extension`) { if let text = try? String(contentsOf: url) { return Set(text.components(separatedBy: CharacterSet.newlines).compactMap { Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) }) } } return nil } public init() { let title: String if let version = Application.current.version, Application.vcs != nil { title = version.developmentDescription } else { title = "\(String(describing: Application.bundle.infoDictionary?["CFBundleShortVersionString"])) (\(String(describing: Application.bundle.infoDictionary?["CFBundleVersion"])))" } super.init(title: title, action: nil, keyEquivalent: "") } public required init(coder decoder: NSCoder) { super.init(coder: decoder) } }
46250b4d0e313d63d57f50fc50f27536
32.088235
182
0.702222
false
false
false
false
isaced/fir-mac
refs/heads/master
fir-mac/Tools/Util.swift
gpl-3.0
1
// // Util.swift // fir-mac // // Created by isaced on 2017/5/8. // // import Foundation import Cocoa enum UploadAppIOSReleaseType: String { case adhoc = "Adhoc" case inHouse = "Inhouse" } struct ParsedAppInfo: CustomStringConvertible { var appName: String? var bundleID: String? var version: String? var build: String? var type: UploadAppType? var iosReleaseType: UploadAppIOSReleaseType? var iconImage: NSImage? var sourceFileURL: URL? var description: String { return "--- App Info --- \nApp Name: \((appName ?? "")) \nBundle ID: \((bundleID ?? "")) \nVersion: \((version ?? "")) \nBuild: \((build ?? ""))\nType: \(type?.rawValue ?? "")\nIcon: \(iconImage != nil ? "YES":"NO") \n--- App Info ---" } } class Util { //MARK: Constants fileprivate static let mktempPath = "/usr/bin/mktemp" fileprivate static let unzipPath = "/usr/bin/unzip" fileprivate static let defaultsPath = "/usr/bin/defaults" static func parseAppInfo(sourceFile: URL, callback:((_ : ParsedAppInfo?)->Void)) { if sourceFile.pathExtension.lowercased() == "ipa" { // Create temp folder if let tempFolder = makeTempFolder() { print("--- makeTempFolder : \(tempFolder)") // unzip unzip(sourceFile.path, outputPath: tempFolder.path) print("--- unzip...") // Payload Path let payloadPath = tempFolder.appendingPathComponent("Payload") if payloadPath.isExists() { // Loop payload directory do { let files = try FileManager.default.contentsOfDirectory(atPath: payloadPath.path) for file in files { let filePath = payloadPath.appendingPathComponent(file) if !filePath.isExists(dir: true) { continue } if filePath.pathExtension.lowercased() != "app" { continue} // Got info.plist let infoPlistPath = filePath.appendingPathComponent("Info.plist") if let data = try? Data(contentsOf: infoPlistPath) { if let plist = (try? PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)) as? [String: Any] { var info = ParsedAppInfo() info.bundleID = plist["CFBundleIdentifier"] as? String info.version = plist["CFBundleShortVersionString"] as? String info.build = plist["CFBundleVersion"] as? String info.appName = plist["CFBundleDisplayName"] as? String info.type = .ios info.sourceFileURL = sourceFile // icon let iconNames = ["AppIcon60x60@3x.png", "AppIcon60x60@2x.png", "AppIcon57x57@3x.png", "AppIcon57x57@2x.png", "AppIcon40x40@3x.png", "AppIcon40x40@2x.png"] for iconName in iconNames { let iconFile = filePath.appendingPathComponent(iconName, isDirectory: false) if iconFile.isExists() { info.iconImage = NSImage(contentsOfFile: iconFile.path) break } } callback(info) } } // clean cleanTempDir(path: tempFolder) return } } catch { print("loop file error...") } }else{ print("can't find payload...") } // clean cleanTempDir(path: tempFolder) }else{ print("make temp dir error...") } }else{ print("pathExtension error...") } callback(nil) } static func cleanTempDir(path: URL) { try! FileManager.default.removeItem(atPath: path.path) print("--- clean temp dir...") } static func makeTempFolder() -> URL? { let tempTask = Process().execute(mktempPath, workingDirectory: nil, arguments: ["-d"]) let url = URL(fileURLWithPath: tempTask.output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), isDirectory: true) return url } static func unzip(_ inputFile: String, outputPath: String) { _ = Process().execute(unzipPath, workingDirectory: nil, arguments: ["-q", "-o", inputFile,"-d",outputPath]) } static func defaultsRead(item: String, plistFilePath: String) -> String { let output = Process().execute(defaultsPath, workingDirectory: nil, arguments: ["read", plistFilePath, item]).output return output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } static func generateQRCode(from string: String) -> NSImage? { let data = string.data(using: String.Encoding.ascii) if let filter = CIFilter(name: "CIQRCodeGenerator") { filter.setValue(data, forKey: "inputMessage") let transform = CGAffineTransform(scaleX: 3, y: 3) if let output = filter.outputImage?.applying(transform) { let rep = NSCIImageRep(ciImage: output) let nsImage = NSImage(size: rep.size) nsImage.addRepresentation(rep) return nsImage } } return nil } } extension URL { func isExists(dir: Bool = false) -> Bool { if dir { var isDirectory: ObjCBool = true return FileManager.default.fileExists(atPath: self.path, isDirectory: &isDirectory) }else{ return FileManager.default.fileExists(atPath: self.path) } } }
80ac9dc2594ffe1ace03a7bb6f1d89ae
39.952096
243
0.474777
false
false
false
false
thewells1024/TipICal
refs/heads/master
TipICal/TipCalculatorBrain.swift
mit
1
// // TipCalculatorBrain.swift // TipICal // // Created by Kent Kawahara on 5/9/17. // Copyright © 2017 Kent Kawahara. All rights reserved. // import Foundation class TipCalculatorBrain { public enum TipPercentage: Double { case Fifteen = 0.15 case Twenty = 0.20 case TwentyFive = 0.25 } init() { self.tipPercentage = nil } init(tipPercentage: TipPercentage) { self.tipPercentage = tipPercentage } private var tipPercentageValue: Double? public var tipPercentage: TipPercentage? { get { if let rawValue = tipPercentageValue { return TipPercentage.init(rawValue: rawValue) } return nil } set { tipPercentageValue = newValue?.rawValue } } public func calculateTip(dollarAmount: Double) -> Double { let percentage = tipPercentageValue ?? 0 return percentage * dollarAmount } }
1ee9afeaf06fef801c80837305e60cea
20.522727
61
0.621964
false
false
false
false
LearningSwift2/LearningApps
refs/heads/master
SimpleRealm/SimpleRealm/ViewController.swift
apache-2.0
1
// // ViewController.swift // SimpleRealm // // Created by Phil Wright on 3/5/16. // Copyright © 2016 The Iron Yard. All rights reserved. // import UIKit import RealmSwift class ViewController: UIViewController { let realm = try! Realm() override func viewDidLoad() { super.viewDidLoad() let luke = Person() luke.name = "Luke Skywalker" luke.createdAt = NSDate() let starship = Starship() starship.name = "X-wing" starship.createdAt = NSDate() let starship2 = Starship() starship2.name = "Millennium Falcon" starship2.createdAt = NSDate() luke.starships.append(starship) luke.starships.append(starship2) do { try realm.write() { () -> Void in realm.add(luke) } } catch { print("An error occurred writing luke") } let persons = realm.objects(Person) for p in persons { print(p.name) print(p.createdAt) for s in p.starships { print(s.name) print(s.createdAt) } } } }
1ead325cd67c6ea77b8104bedd273b34
19.171875
56
0.487219
false
false
false
false
luinily/hOme
refs/heads/master
hOme/Model/FlicManager.swift
mit
1
// // FlicManager.swift // hOme // // Created by Coldefy Yoann on 2016/03/06. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import CloudKit class FlicManager: NSObject, SCLFlicManagerDelegate { private let _appKey = "6f90a672-3a48-4d43-9070-d7f06ecd1704" private let _appSecret = "cfd3a24d-091f-414f-8f0e-978ee49e1712" private var _manager: SCLFlicManager? private var _onButtonGrabbed: ((_ button: Button) -> Void)? override init() { super.init() _manager = SCLFlicManager.configure(with: self, defaultButtonDelegate: nil, appID: _appKey, appSecret: _appSecret, backgroundExecution: false) print("known buttons: " + String(describing: _manager?.knownButtons().count)) } func deleteButton(_ button: FlicButton) { if let flic = button.button { _manager?.forget(flic) } } func setOnButtonGrabbed(_ onButtonGrabbed: @escaping (_ button: Button) -> Void) { _onButtonGrabbed = onButtonGrabbed } func getButton(identifier: UUID) -> SCLFlicButton? { return _manager?.knownButtons()[identifier] } func grabButton() { _manager?.grabFlicFromFlicApp(withCallbackUrlScheme: "hOme://button") } func flicManagerDidRestoreState(_ manager: SCLFlicManager) { print("known buttons after restoration: " + String(describing: _manager?.knownButtons().count)) } func flicManager(_ manager: SCLFlicManager, didChange state: SCLFlicManagerBluetoothState) { NSLog("FlicManager did change state..") } func flicManager(_ manager: SCLFlicManager, didGrab button: SCLFlicButton?, withError error: Error?) { let button = FlicButton(button: button) _onButtonGrabbed?(button) } }
9f9ce508ad2cad70df935027da2579e7
29.5
144
0.73224
false
false
false
false
iOSreverse/DWWB
refs/heads/master
DWWB/DWWB/Classes/Tools(工具)/Categoy/NSDate-Extension.swift
apache-2.0
1
// // NSDate-Extension.swift // DWWB // // Created by xmg on 16/4/9. // Copyright © 2016年 NewDee. All rights reserved. // import Foundation extension NSDate { class func createDateString(createAtStr : String) -> String { // 1.创建时间格式化对象 let fmt = NSDateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" // 星期 月份 日 小时:分钟:秒 时区 年份 // 2.将字符串时间,转成NSDate类型 guard let createDate = fmt.dateFromString(createAtStr) else { return "" } // 3.创建当前时间 let nowDate = NSDate() // 4.计算创建时间和当前时间的时间差 let interval = Int(nowDate.timeIntervalSinceDate(createDate)) // 5.对时间间隔处理 // 5.1 显示刚刚 if interval < 60 { return "刚刚" } // 5.2 59分钟前 if interval < 60 * 60 { return "\(interval / 60)分钟前" } // 5.3 11小时前 if interval < 60 * 60 * 24 { return "\(interval / (60 * 60))小时前" } // 5.4 创建日历对象 let calendar = NSCalendar.currentCalendar() // 5.5 处理昨天数据: 昨天 12:23 if calendar.isDateInYesterday(createDate) { fmt.dateFormat = "昨天 HH:mm" let timerStr = fmt.stringFromDate(createDate) return timerStr } // 5.6 处理一年之内 02-22 12:22 let cmps = calendar.components(.Year, fromDate: createDate, toDate: nowDate, options: []) if cmps.year < 1 { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.stringFromDate(createDate) return timeStr } // 5.7 超过一年 2014-02-12 13:22 fmt.dateFormat = "yyyy-MM-dd HH:mm" let timeStr = fmt.stringFromDate(createDate) return timeStr } }
5e3a052652503ec804c338defe6734e4
24.955224
97
0.540852
false
false
false
false
cotkjaer/Silverback
refs/heads/master
Silverback/ArcView.swift
mit
1
// // ArcView.swift // Silverback // // Created by Christian Otkjær on 09/12/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit @IBDesignable public class ArcView: UIView { @IBInspectable public var width : CGFloat { set { arcLayer.arcWidth = newValue } get { return arcLayer.arcWidth } } @IBInspectable public var startDegrees: CGFloat { set { startAngle = degrees2radians(newValue) } get { return radians2degrees(startAngle) } } public var startAngle: CGFloat { set { if clockwise { arcLayer.arcStartAngle = newValue } else { arcLayer.arcEndAngle = newValue } } get { return clockwise ? arcLayer.arcStartAngle : arcLayer.arcEndAngle } } @IBInspectable public var endDegrees: CGFloat { set { endAngle = degrees2radians(newValue) } get { return radians2degrees(endAngle) } } public var endAngle: CGFloat { set { if !clockwise { arcLayer.arcStartAngle = newValue } else { arcLayer.arcEndAngle = newValue } } get { return !clockwise ? arcLayer.arcStartAngle : arcLayer.arcEndAngle } } @IBInspectable public var clockwise: Bool = true { didSet { if clockwise != oldValue { swap(&arcLayer.arcStartAngle, &arcLayer.arcEndAngle) } } } @IBInspectable public var color: UIColor = UIColor.blackColor() { didSet { arcLayer.arcColor = color.CGColor } } // MARK: - Layout public override func layoutSubviews() { super.layoutSubviews() updateArc() } public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) if layer == self.layer { updateArc() } } // MARK: - Init override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { layer.addSublayer(arcLayer) arcLayer.arcColor = color.CGColor updateArc() } override public var bounds : CGRect { didSet { updateArc() } } override public var frame : CGRect { didSet { updateArc() } } // MARK: - Arc private let arcLayer = ArcLayer() func updateArc() { arcLayer.frame = bounds } } // MARK: - CustomDebugStringConvertible extension ArcView : CustomDebugStringConvertible { override public var debugDescription : String { return super.debugDescription + "<startDegrees = \(startDegrees), endDegrees = \(endDegrees), clockwise = \(clockwise), width = \(width)>" } }
144a3ed1ba4fd84f174d05f36dd66f45
22.306452
192
0.586851
false
false
false
false
rwbutler/TypographyKit
refs/heads/master
TypographyKit/Classes/ParsingService.swift
mit
1
// // ParsingService.swift // TypographyKit // // Created by Ross Butler on 7/15/17. // // import Foundation import UIKit typealias ConfigurationParsingResult = Result<ConfigurationModel, ConfigurationParsingError> protocol ConfigurationParsingService { func parse(_ data: Data) -> ConfigurationParsingResult } private enum CodingKeys { static let buttons = "buttons" static let colorsEntry = "typography-colors" static let labels = "labels" static let minimumPointSize = "minimum-point-size" static let maximumPointSize = "maximum-point-size" static let pointStepMultiplier = "point-step-multiplier" static let pointStepSize = "point-step-size" static let scalingMode = "scaling-mode" static let stylesEntry = "ui-font-text-styles" static let umbrellaEntry = "typography-kit" } typealias FontTextStyleEntries = [String: [String: Any]] typealias ColorEntries = [String: Any] extension ConfigurationParsingService { // MARK: - Type definitions fileprivate typealias ExtendedTypographyStyleEntry = (existingStyleName: String, newStyle: Typography) func parse(_ configEntries: [String: Any]) -> ConfigurationParsingResult { let configuration: ConfigurationSettings if let typographyKitConfig = configEntries[CodingKeys.umbrellaEntry] as? [String: Any], let stepSize = typographyKitConfig[CodingKeys.pointStepSize] as? Float, let stepMultiplier = typographyKitConfig[CodingKeys.pointStepMultiplier] as? Float { let buttonsConfig = typographyKitConfig[CodingKeys.buttons] as? [String: String] let labelsConfig = typographyKitConfig[CodingKeys.labels] as? [String: String] let buttonSettings = self.buttonSettings(buttonsConfig) let labelSettings = self.labelSettings(labelsConfig) let minimumPointSize = typographyKitConfig[CodingKeys.minimumPointSize] as? Float let maximumPointSize = typographyKitConfig[CodingKeys.maximumPointSize] as? Float let scalingMode = typographyKitConfig[CodingKeys.scalingMode] as? String configuration = ConfigurationSettings( buttons: buttonSettings, labels: labelSettings, minPointSize: minimumPointSize, maxPointSize: maximumPointSize, pointStepSize: stepSize, pointStepMultiplier: stepMultiplier, scalingMode: scalingMode ) } else { configuration = ConfigurationSettings(buttons: ButtonSettings(), labels: LabelSettings()) } // Colors let colorEntries = configEntries[CodingKeys.colorsEntry] as? ColorEntries ?? [:] var colorParser = ColorParser(colors: colorEntries) let typographyColors = colorParser.parseColors() let uiColors = typographyColors.mapValues { $0.uiColor } // Fonts let fontTextStyles = configEntries[CodingKeys.stylesEntry] as? FontTextStyleEntries ?? [:] var fontParser = FontTextStyleParser(textStyles: fontTextStyles, colorEntries: typographyColors) let typographyStyles = fontParser.parseFonts() return .success(ConfigurationModel(settings: configuration, colors: uiColors, styles: typographyStyles)) } /// Translates a dictionary of configuration settings into a `ButtonSettings` model object. private func buttonSettings(_ config: [String: String]?) -> ButtonSettings { guard let config = config, let lineBreakConfig = config["title-color-apply"], let applyMode = UIButton.TitleColorApplyMode(string: lineBreakConfig) else { return ButtonSettings() } return ButtonSettings(titleColorApplyMode: applyMode) } /// Translates a dictionary of configuration settings into a `LabelSettings` model object. private func labelSettings(_ config: [String: String]?) -> LabelSettings { guard let config = config, let lineBreakConfig = config["line-break"], let lineBreak = NSLineBreakMode(string: lineBreakConfig) else { return LabelSettings() } return LabelSettings(lineBreak: lineBreak) } }
8fc9c5b7f0f6b0773360a28f12560fa6
43.635417
106
0.685414
false
true
false
false
devpunk/cartesian
refs/heads/master
cartesian/View/DrawProject/Menu/VDrawProjectMenu.swift
mit
1
import UIKit class VDrawProjectMenu:UIView { weak var layoutBottom:NSLayoutConstraint! private weak var controller:CDrawProject! private(set) weak var viewBar:VDrawProjectMenuBar! private(set) weak var viewSettings:VDrawProjectMenuSettings! private(set) weak var viewNodes:VDrawProjectMenuNodes! private(set) weak var viewLabels:VDrawProjectMenuLabels! private(set) weak var viewEdit:VDrawProjectMenuEdit! private(set) weak var viewText:VDrawProjectMenuText! private let kBarHeight:CGFloat = 51 private let kKeyboardAnimationDuration:TimeInterval = 0.3 init(controller:CDrawProject) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let viewBar:VDrawProjectMenuBar = VDrawProjectMenuBar(controller:controller) self.viewBar = viewBar let viewSettings:VDrawProjectMenuSettings = VDrawProjectMenuSettings( controller:controller) viewSettings.isHidden = true self.viewSettings = viewSettings let viewNodes:VDrawProjectMenuNodes = VDrawProjectMenuNodes( controller:controller) viewNodes.isHidden = true self.viewNodes = viewNodes let viewEdit:VDrawProjectMenuEdit = VDrawProjectMenuEdit( controller:controller) viewEdit.isHidden = true self.viewEdit = viewEdit let viewLabels:VDrawProjectMenuLabels = VDrawProjectMenuLabels( controller:controller) viewLabels.isHidden = true self.viewLabels = viewLabels let viewText:VDrawProjectMenuText = VDrawProjectMenuText( controller:controller) viewText.isHidden = true self.viewText = viewText let background:UIView = UIView() background.isUserInteractionEnabled = false background.backgroundColor = UIColor.white background.translatesAutoresizingMaskIntoConstraints = false addSubview(background) addSubview(viewBar) addSubview(viewSettings) addSubview(viewNodes) addSubview(viewLabels) addSubview(viewEdit) addSubview(viewText) NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) layoutView(view:background) layoutView(view:viewSettings) layoutView(view:viewNodes) layoutView(view:viewLabels) layoutView(view:viewEdit) layoutView(view:viewText) NotificationCenter.default.addObserver( self, selector:#selector(notifiedKeyboardChanged(sender:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object:nil) } required init?(coder:NSCoder) { return nil } deinit { NotificationCenter.default.removeObserver(self) } //MARK: notifications func notifiedKeyboardChanged(sender notification:Notification) { guard let userInfo:[AnyHashable:Any] = notification.userInfo, let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let menuBottom:CGFloat = controller.modelMenuState.current?.bottom else { return } let keyRect:CGRect = keyboardFrameValue.cgRectValue let yOrigin = keyRect.origin.y let height:CGFloat = UIScreen.main.bounds.maxY let keyboardHeight:CGFloat if yOrigin < height { keyboardHeight = -height + yOrigin + menuBottom } else { keyboardHeight = menuBottom } layoutBottom.constant = keyboardHeight UIView.animate(withDuration:kKeyboardAnimationDuration) { [weak self] in self?.layoutIfNeeded() } } //MARK: private private func layoutView(view:UIView) { NSLayoutConstraint.topToBottom( view:view, toView:viewBar) NSLayoutConstraint.bottomToBottom( view:view, toView:self) NSLayoutConstraint.equalsHorizontal( view:view, toView:self) } //MARK: public func displayNothing() { viewSettings.isHidden = true viewNodes.isHidden = true viewLabels.isHidden = true viewEdit.isHidden = true viewText.isHidden = true viewBar.selectNothing() } func displayNode(model:DNode) { viewSettings.isHidden = true viewNodes.isHidden = true viewLabels.isHidden = true viewEdit.isHidden = false viewText.isHidden = true viewEdit.loadNode(model:model) viewBar.modeEdit() } func displaySettings() { viewSettings.isHidden = false viewNodes.isHidden = true viewLabels.isHidden = true viewEdit.isHidden = true viewText.isHidden = true } func displayNodes() { viewSettings.isHidden = true viewNodes.isHidden = false viewLabels.isHidden = true viewEdit.isHidden = true viewText.isHidden = true } func displayLabels() { viewSettings.isHidden = true viewNodes.isHidden = true viewLabels.isHidden = false viewEdit.isHidden = true viewText.isHidden = true } func displayText(model:DLabel) { viewSettings.isHidden = true viewNodes.isHidden = true viewLabels.isHidden = true viewEdit.isHidden = true viewText.isHidden = false viewText.loadLabel(model:model) } }
8f2e9a620c44717e60b22a165a72aa0a
27.686916
97
0.61541
false
false
false
false
alvinvarghese/GNTickerButton
refs/heads/master
Pod/Classes/GNTickerButton.swift
mit
2
// // GNTickerButton.swift // Letters // // Created by Gonzalo Nunez on 5/11/15. // Copyright (c) 2015 Gonzalo Nunez. All rights reserved. // import UIKit @objc public protocol GNTickerButtonRotationDelegate { func tickerButtonTickerRotated(tickerButton button:GNTickerButton) } @IBDesignable public class GNTickerButton : UIButton { static private let kInnerRingLineWidth:CGFloat = 1 static private let kOuterRingLineWidth:CGFloat = 4 static private let kOutterInnerRingSpacing:CGFloat = 6 static private let kTearDropRadius:CGFloat = 5 static private let kTickerRotationAnimationKey = "transform.rotation" static private let kRingProgressAnimationKey = "strokeEnd" static private let kRingProgressAnimationDuration = 0.15 @IBInspectable public var fillColor = UIColor(red: 251/255, green: 77/255, blue: 31/255, alpha: 1) { didSet { setNeedsDisplay() } } @IBInspectable public var ringColor = UIColor.whiteColor() { didSet { setNeedsDisplay() } } @IBInspectable public var tickerColor = UIColor.whiteColor() { didSet { setNeedsDisplay() } } public var shouldShowRingProgress = true { didSet { ringLayer.hidden = !shouldShowRingProgress } } private var isPressed : Bool = false { didSet { setNeedsDisplay() } } private(set) var tickerIsSpinning = false private var tickerLayer = CAShapeLayer() private var ringLayer = CAShapeLayer() private var desiredRotations:Int? weak var delegate : GNTickerButtonRotationDelegate? //MARK: - Initiliazation required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addTargets() } override public init(frame: CGRect) { super.init(frame: frame) addTargets() } //MARK: - Set Up private func setUpTicker() { tickerLayer.removeFromSuperlayer() let centerX = CGRectGetMidX(bounds) let centerY = CGRectGetMidY(bounds) let outerRadius = outerRadiusInRect(bounds) let innerRadius = outerRadius - GNTickerButton.kOutterInnerRingSpacing let path = CGPathCreateMutable() let padding = 8 as CGFloat CGPathAddArc(path, nil, centerX, centerY, GNTickerButton.kTearDropRadius, CGFloat(2*M_PI), CGFloat(M_PI), false) CGPathAddLineToPoint(path, nil, centerX, centerY - innerRadius + padding) CGPathAddLineToPoint(path, nil, centerX + GNTickerButton.kTearDropRadius, centerY) let tearDropHeight = innerRadius - padding let boundingBox = CGPathGetBoundingBox(path) let height = CGRectGetHeight(boundingBox) let anchorY = 1 - (height - tearDropHeight)/height tickerLayer.anchorPoint = CGPoint(x: 0.5, y: anchorY) tickerLayer.position = CGPoint(x: CGRectGetMidX(layer.bounds), y: CGRectGetMidY(layer.bounds)) tickerLayer.bounds = boundingBox tickerLayer.path = path tickerLayer.fillColor = tickerColor.CGColor tickerLayer.strokeColor = tickerColor.CGColor layer.addSublayer(tickerLayer) } private func setUpRing() { ringLayer.removeFromSuperlayer() let rect = layer.bounds let outerRadius = outerRadiusInRect(rect) let centerX = CGRectGetMidX(rect) let centerY = CGRectGetMidY(rect) let ringPath = CGPathCreateMutable() CGPathAddArc(ringPath, nil, centerX, centerY, outerRadius, CGFloat(-M_PI_2), CGFloat(M_PI_2*3), false) ringLayer.path = ringPath ringLayer.position = CGPoint(x: CGRectGetMidX(layer.bounds), y: CGRectGetMidY(layer.bounds)) ringLayer.bounds = CGPathGetBoundingBox(ringPath) ringLayer.fillColor = UIColor.clearColor().CGColor ringLayer.strokeColor = ringColor.CGColor ringLayer.lineWidth = GNTickerButton.kOuterRingLineWidth ringLayer.strokeEnd = 0 layer.addSublayer(ringLayer) } private func addTargets() { addTarget(self, action: "touchDown", forControlEvents: .TouchDown) addTarget(self, action: "touchUpInside", forControlEvents: .TouchUpInside) addTarget(self, action: "touchUpOutside", forControlEvents: .TouchUpOutside) } @objc private func touchDown() { isPressed = true } @objc private func touchUpInside() { isPressed = false } @objc private func touchUpOutside() { isPressed = false } //MARK: Public public func rotateTickerWithDuration(duration:CFTimeInterval, rotations repeatCount:Int = 1, rotationBlock: (Void -> Void)?) { _rotateTickerWithDuration(duration, rotations: repeatCount, shouldSetDesiredRotationCount: desiredRotations == nil, rotationBlock: rotationBlock) } public func stopRotatingTicker() { tickerLayer.removeAnimationForKey(GNTickerButton.kTickerRotationAnimationKey) } public func clearRingProgress() { CATransaction.begin() CATransaction.setCompletionBlock() { CATransaction.begin() self.ringLayer.strokeStart = 0 self.ringLayer.strokeEnd = 0 CATransaction.commit() } ringLayer.strokeStart = 1 CATransaction.commit() } //MARK: Private private func _rotateTickerWithDuration(duration:CFTimeInterval, rotations repeatCount:Int = 1, shouldSetDesiredRotationCount:Bool = true, rotationBlock: (Void -> Void)?) { tickerIsSpinning = true if (shouldSetDesiredRotationCount) { desiredRotations = repeatCount } let rotationAnimation = CABasicAnimation(keyPath: GNTickerButton.kTickerRotationAnimationKey) rotationAnimation.duration = duration rotationAnimation.fromValue = 0 rotationAnimation.toValue = 2*M_PI rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) var repeats = repeatCount CATransaction.begin() CATransaction.setCompletionBlock() { dispatch_async(dispatch_get_main_queue()) { self.updateRingProgress(repeatCount, animated: true) if (rotationBlock != nil) { rotationBlock!() } else { self.delegate?.tickerButtonTickerRotated(tickerButton: self) } if (repeats > 0) { self.rotateTickerWithDuration(duration, rotations: --repeats, rotationBlock: rotationBlock) } else { self.desiredRotations = nil self.tickerIsSpinning = false } } } tickerLayer.addAnimation(rotationAnimation, forKey: GNTickerButton.kTickerRotationAnimationKey) CATransaction.commit() } private func updateRingProgress(rotationsLeft:Int, animated:Bool) { var strokeEnd = 0 as CGFloat if (desiredRotations != nil) { strokeEnd = CGFloat((desiredRotations! - rotationsLeft)) / CGFloat(desiredRotations!) } let fillAnimation = CABasicAnimation(keyPath: GNTickerButton.kRingProgressAnimationKey) fillAnimation.duration = animated ? GNTickerButton.kRingProgressAnimationDuration : 0 fillAnimation.fromValue = ringLayer.strokeEnd fillAnimation.toValue = strokeEnd fillAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) ringLayer.strokeEnd = strokeEnd CATransaction.begin() ringLayer.addAnimation(fillAnimation, forKey: GNTickerButton.kRingProgressAnimationKey) CATransaction.commit() } //MARK: - Drawing override public func drawRect(rect: CGRect) { super.drawRect(rect) func addCircleInContext(context:CGContextRef, centerX:CGFloat, centerY:CGFloat, radius:CGFloat) { CGContextAddArc(context, centerX, centerY, radius, CGFloat(0), CGFloat(2*M_PI), 0) } let context = UIGraphicsGetCurrentContext() let color = isPressed ? fillColor.colorWithAlphaComponent(0.5) : fillColor CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetStrokeColorWithColor(context, ringColor.CGColor) let outerRadius = outerRadiusInRect(rect) let innerRadius = outerRadius - GNTickerButton.kOutterInnerRingSpacing let centerX = CGRectGetMidX(rect) let centerY = CGRectGetMidY(rect) // Inner Circle addCircleInContext(context, centerX, centerY, innerRadius) CGContextFillPath(context) // Inner Ring CGContextSetLineWidth(context, GNTickerButton.kInnerRingLineWidth) addCircleInContext(context, centerX, centerY, innerRadius) CGContextStrokePath(context) } override public func drawLayer(layer: CALayer!, inContext ctx: CGContext!) { super.drawLayer(layer, inContext: ctx) setUpTicker() setUpRing() } //MARK - Helpers private func outerRadiusInRect(rect:CGRect) -> CGFloat { return rect.width/2 - 2 } }
dcfb60025e4c91cf216b80f20f1e9db2
33.588448
175
0.643528
false
false
false
false
vapor/vapor
refs/heads/main
Sources/Vapor/Concurrency/Request+Concurrency.swift
mit
1
#if compiler(>=5.7) && canImport(_Concurrency) import NIOCore import NIOConcurrencyHelpers // MARK: - Request.Body.AsyncSequenceDelegate @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) extension Request.Body { /// `Request.Body.AsyncSequenceDelegate` bridges between EventLoop /// and AsyncSequence. Crucially, this type handles backpressure /// by synchronizing bytes on the `EventLoop` /// /// `AsyncSequenceDelegate` can be created and **must be retained** /// in `Request.Body/makeAsyncIterator()` method. fileprivate final class AsyncSequenceDelegate: @unchecked Sendable, NIOAsyncSequenceProducerDelegate { private enum State { case noSignalReceived case waitingForSignalFromConsumer(EventLoopPromise<Void>) } private var _state: State = .noSignalReceived private let eventLoop: any EventLoop init(eventLoop: any EventLoop) { self.eventLoop = eventLoop } private func produceMore0() { self.eventLoop.preconditionInEventLoop() switch self._state { case .noSignalReceived: preconditionFailure() case .waitingForSignalFromConsumer(let promise): self._state = .noSignalReceived promise.succeed(()) } } private func didTerminate0() { self.eventLoop.preconditionInEventLoop() switch self._state { case .noSignalReceived: // we will inform the producer, since the next write will fail. break case .waitingForSignalFromConsumer(let promise): self._state = .noSignalReceived promise.fail(CancellationError()) } } func registerBackpressurePromise(_ promise: EventLoopPromise<Void>) { self.eventLoop.preconditionInEventLoop() switch self._state { case .noSignalReceived: self._state = .waitingForSignalFromConsumer(promise) case .waitingForSignalFromConsumer: preconditionFailure() } } func didTerminate() { self.eventLoop.execute { self.didTerminate0() } } func produceMore() { self.eventLoop.execute { self.produceMore0() } } } } // MARK: - Request.Body.AsyncSequence @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) extension Request.Body: AsyncSequence { public typealias Element = ByteBuffer /// This wrapper generalizes our implementation. /// `RequestBody.AsyncIterator` is the override point for /// using another implementation public struct AsyncIterator: AsyncIteratorProtocol { public typealias Element = ByteBuffer fileprivate typealias Underlying = NIOThrowingAsyncSequenceProducer<ByteBuffer, any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Request.Body.AsyncSequenceDelegate>.AsyncIterator private var underlying: Underlying fileprivate init(underlying: Underlying) { self.underlying = underlying } public mutating func next() async throws -> ByteBuffer? { return try await self.underlying.next() } } /// Checks that the request has a body suitable for an AsyncSequence /// /// AsyncSequence streaming should use a body of type .stream(). /// Using `.collected(_)` will load the entire request into memory /// which should be avoided for large file uploads. /// /// Example: app.on(.POST, "/upload", body: .stream) { ... } private func checkBodyStorage() { switch request.bodyStorage { case .stream(_): break case .collected(_): break default: preconditionFailure(""" AsyncSequence streaming should use a body of type .stream() Example: app.on(.POST, "/upload", body: .stream) { ... } """) } } /// Generates an `AsyncIterator` to stream the body’s content as /// `ByteBuffer` sequences. This implementation supports backpressure using /// `NIOAsyncSequenceProducerBackPressureStrategies` /// - Returns: `AsyncIterator` containing the `Requeset.Body` as a /// `ByteBuffer` sequence public func makeAsyncIterator() -> AsyncIterator { let delegate = AsyncSequenceDelegate(eventLoop: request.eventLoop) let producer = NIOThrowingAsyncSequenceProducer.makeSequence( elementType: ByteBuffer.self, failureType: Error.self, backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies .HighLowWatermark(lowWatermark: 5, highWatermark: 20), delegate: delegate ) let source = producer.source self.drain { streamResult in switch streamResult { case .buffer(let buffer): // Send the buffer to the async sequence let result = source.yield(buffer) // Inspect the source view and handle outcomes switch result { case .dropped: // The consumer dropped the sequence. // Inform the producer that we don't want more data // by returning an error in the future. return request.eventLoop.makeFailedFuture(CancellationError()) case .stopProducing: // The consumer is too slow. // We need to create a promise that we succeed later. let promise = request.eventLoop.makePromise(of: Void.self) // We pass the promise to the delegate so that we can succeed it, // once we get a call to `delegate.produceMore()`. delegate.registerBackpressurePromise(promise) // return the future that we will fulfill eventually. return promise.futureResult case .produceMore: // We can produce more immidately. Return a succeeded future. return request.eventLoop.makeSucceededVoidFuture() } case .error(let error): source.finish(error) return request.eventLoop.makeSucceededVoidFuture() case .end: source.finish() return request.eventLoop.makeSucceededVoidFuture() } } return AsyncIterator(underlying: producer.sequence.makeAsyncIterator()) } } #endif
2337d2dd6f6a5ec1fc0fb22f7c882974
38.216374
213
0.605279
false
false
false
false
WaterReporter/WaterReporter-iOS
refs/heads/master
WaterReporter/WaterReporter/NewReportTableViewController.swift
agpl-3.0
1
// // NewReportTableViewController.swift // WaterReporter // // Created by Viable Industries on 7/24/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import CoreLocation import Mapbox import OpenGraph import SwiftyJSON import UIKit class NewReportTableViewController: UITableViewController, UIImagePickerControllerDelegate, UITextViewDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, MGLMapViewDelegate, NewReportLocationSelectorDelegate { // // MARK: @IBOutlets // @IBOutlet weak var navigationBarButtonSave: UIBarButtonItem! @IBOutlet var indicatorLoadingView: UIView! // // MARK: @IBActions // @IBAction func launchNewReportLocationSelector(sender: UIButton) { self.performSegueWithIdentifier("setLocationForNewReport", sender: sender) } @IBAction func attemptOpenPhotoTypeSelector(sender: AnyObject) { let thisActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .Default, handler:self.cameraActionHandler) thisActionSheet.addAction(cameraAction) let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .Default, handler:self.photoLibraryActionHandler) thisActionSheet.addAction(photoLibraryAction) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) thisActionSheet.addAction(cancelAction) presentViewController(thisActionSheet, animated: true, completion: nil) } @IBAction func buttonSaveNewReportTableViewController(sender: UIBarButtonItem) { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] self.attemptNewReportSave(headers) } @IBAction func selectGroup(sender: UISwitch) { if sender.on { let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])" self.tempGroups.append(_organization_id_number) print("addGroup::finished::tempGroups \(self.tempGroups)") } else { let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])" self.tempGroups = self.tempGroups.filter() {$0 != _organization_id_number} print("removeGroup::finished::tempGroups \(self.tempGroups)") } } // // MARK: Variables // var loadingView: UIView! var userSelectedCoorindates: CLLocationCoordinate2D! var imageReportImagePreviewIsSet:Bool = false var thisLocationManager: CLLocationManager = CLLocationManager() var tempGroups: [String] = [String]() var groups: JSON? var reportImage: UIImage! var reportDescription: String = "Write a few words about the photo or paste a link..." var hashtagAutocomplete: [String] = [String]() var hashtagSearchEnabled: Bool = false var dataSource: HashtagTableView = HashtagTableView() var hashtagSearchTimer: NSTimer = NSTimer() var og_paste: String! var og_active: Bool = false var og_title: String! var og_description: String! var og_sitename: String! var og_type: String! var og_image: String! var og_url: String! // // MARK: Overrides // override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) // // Load default list of groups into the form // self.attemptLoadUserGroups() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(true) if self.tabBarController?.selectedIndex != 2 { // // When navigating away from this tab the Commons team wants this // form to clear out. // // Reset all fields self.imageReportImagePreviewIsSet = false self.reportDescription = "Write a few words about the photo or paste a link..." self.reportImage = nil self.og_paste = "" self.og_active = false self.og_title = "" self.og_description = "" self.og_sitename = "" self.og_type = "" self.og_image = "" self.og_url = "" self.tempGroups = [String]() self.tableView.reloadData() self.userSelectedCoorindates = nil } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) } override func viewDidLoad() { super.viewDidLoad() // // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up // self.view.setNeedsLayout() self.view.layoutIfNeeded() self.navigationItem.title = "New Report" self.tableView.backgroundColor = UIColor.colorBackground(1.00) self.dataSource.parent = self // // Setup Navigation Bar // navigationBarButtonSave.target = self navigationBarButtonSave.action = #selector(buttonSaveNewReportTableViewController(_:)) } // // MARK: Advanced TextView Interactions // func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { // [text isEqualToString:[UIPasteboard generalPasteboard].string] let _pasteboard = UIPasteboard.generalPasteboard().string if (text == _pasteboard) { // // Step 1: Get the information being pasted // print("Pasting text", _pasteboard) // _pasteboard = _pasteboard!.stringByRemovingPercentEncoding!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! if let checkedUrl = NSURL(string: _pasteboard!) { // // Step 2: Check to see if the text being pasted is a link // OpenGraph.fetch(checkedUrl) { og, error in print("Open Graph \(og)") self.og_paste = "\(checkedUrl)" if og?[.title] != nil { let _og_title = og?[.title]!.stringByDecodingHTMLEntities self.og_title = "\(_og_title!)" } else { self.og_title = "" } if og?[.description] != nil { let _og_description_encoded = og?[.description]! let _og_description = _og_description_encoded?.stringByDecodingHTMLEntities self.og_description = "\(_og_description!)" self.reportDescription = "\(_og_description!)" } else { self.og_description = "" } if og?[.type] != nil { let _og_type = og?[.type]! self.og_type = "\(_og_type!)" } else { self.og_type = "" } if og?[.image] != nil { let _ogImage = og?[.image]! print("_ogImage \(_ogImage!)") if let imageURL = NSURL(string: _ogImage!) { self.og_image = "\(imageURL)" } else { let _tmpImage = "\(_ogImage!)" let _image = _tmpImage.characters.split{$0 == " "}.map(String.init) if _image.count >= 1 { var _imageUrl = _image[0] if let imageURLRange = _imageUrl.rangeOfString("?") { _imageUrl.removeRange(imageURLRange.startIndex..<_imageUrl.endIndex) self.og_image = "\(_imageUrl)" } } } } else { self.og_image = "" } if og?[.url] != nil { let _og_url = og?[.url]! self.og_url = "\(_og_url!)" } else { self.og_url = "" } if self.og_url != "" && self.og_image != "" { self.og_active = true } // We need to wait for all other tasks to finish before // executing the table reload // NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.reloadData() } } } return true } return false } func textViewDidBeginEditing(textView: UITextView) { if textView.text == "Write a few words about the photo or paste a link..." { textView.text = "" } } func textViewDidChange(textView: UITextView) { let _text: String = "\(textView.text)" // let _index = NSIndexPath.init(forRow: 0, inSection: 0) // Always make sure we are constantly copying what is entered into the // remote text field into this controller so that we can pass it along // to the report save methods. // self.reportDescription = _text // if _text != "" && _text.characters.last! == "#" { // self.hashtagSearchEnabled = true // // print("Hashtag Search: Found start of hashtag") // } // else if _text != "" && self.hashtagSearchEnabled == true && _text.characters.last! == " " { // self.hashtagSearchEnabled = false // self.dataSource.results = [String]() // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // print("Hashtag Search: Disabling search because space was entered") // print("Hashtag Search: Timer reset to zero due to search termination (space entered)") // self.hashtagSearchTimer.invalidate() // // } // else if _text != "" && self.hashtagSearchEnabled == true { // // self.dataSource.results = [String]() // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // // Identify hashtag search // // // let _hashtag_identifier = _text.rangeOfString("#", options:NSStringCompareOptions.BackwardsSearch) // if ((_hashtag_identifier) != nil) { // let _hashtag_search: String! = _text.substringFromIndex((_hashtag_identifier?.endIndex)!) // // // Add what the user is typing to the top of the list // // // print("Hashtag Search: Performing search for \(_hashtag_search)") // // dataSource.results = ["\(_hashtag_search)"] // dataSource.search = "\(_hashtag_search)" // // dataSource.numberOfRowsInSection(dataSource.results.count) // //// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) // // // Execute the serverside search BUT wait a few milliseconds between // // each character so we aren't returning inconsistent results to // // the user // // // print("Hashtag Search: Timer reset to zero") // self.hashtagSearchTimer.invalidate() // // print("Hashtag Search: Send this to search methods \(_hashtag_search) after delay expires") //// self.hashtagSearchTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.searchHashtags(_:)), userInfo: _hashtag_search, repeats: false) // // } // // } } // // MARK: Custom TextView Functionality // func focusTextView() { } // // MARK: Table Overrides // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRows: Int = 2 if section == 0 { numberOfRows = 2 // if self.dataSource.results != nil { // let numberOfHashtags: Int = (self.dataSource.results.count) // numberOfRows = numberOfHashtags // } } else if section == 1 { if self.groups != nil { let numberOfGroups: Int = (self.groups?["features"].count)! numberOfRows = (numberOfGroups) } } return numberOfRows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportContentTableViewCell", forIndexPath: indexPath) as! NewReportContentTableViewCell // Report Image // cell.buttonReportAddImage.addTarget(self, action: #selector(NewReportTableViewController.attemptOpenPhotoTypeSelector(_:)), forControlEvents: .TouchUpInside) if (self.reportImage != nil) { cell.imageReportImage.image = self.reportImage } else { cell.imageReportImage.image = UIImage(named: "icon--camera") } // Report Description // if self.reportDescription != "" { cell.textviewReportDescription.text = self.reportDescription } cell.textviewReportDescription.delegate = self cell.textviewReportDescription.targetForAction(#selector(self.textViewDidChange(_:)), withSender: self) // Report Description > Hashtag Type Ahead // cell.tableViewHashtag.delegate = self.dataSource cell.tableViewHashtag.dataSource = self.dataSource if self.hashtagSearchEnabled == true { cell.tableViewHashtag.hidden = false cell.typeAheadHeight.constant = 128.0 } else { cell.tableViewHashtag.hidden = true cell.typeAheadHeight.constant = 0.0 } // Report Description > Open Graph // if self.og_active { cell.ogView.hidden = false cell.ogViewHeightConstraint.constant = 256.0 // Open Graph > Title // cell.ogTitle.text = self.og_title // Open Graph > Description // cell.ogDescription.text = self.og_description // Open Graph > Image // if self.og_image != "" { let ogImageURL:NSURL = NSURL(string: "\(self.og_image)")! cell.ogImage.kf_indicatorType = .Activity cell.ogImage.kf_showIndicatorWhenLoading = true cell.ogImage.kf_setImageWithURL(ogImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.ogImage.image = image if (self.imageReportImagePreviewIsSet == false) { self.reportImage = image self.imageReportImagePreviewIsSet = true self.tableView.reloadData() } }) } } else { cell.ogView.hidden = true cell.ogViewHeightConstraint.constant = 0.0 } return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportLocationTableViewCell", forIndexPath: indexPath) as! NewReportLocationTableViewCell print("Location Row") // Display location selection map when Confirm Location button is // tapped/touched // cell.buttonChangeLocation.addTarget(self, action: #selector(self.launchNewReportLocationSelector(_:)), forControlEvents: .TouchUpInside) // Update the text display for the user selected coordinates when // the self.userSelectedCoorindates variable is not empty // print("self.userSelectedCoorindates \(self.userSelectedCoorindates)") if self.userSelectedCoorindates != nil { cell.labelLocation.text = String(self.userSelectedCoorindates.longitude) + " " + String(self.userSelectedCoorindates.latitude) } else { cell.labelLocation.text = "Confirm location" } return cell } } else if indexPath.section == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("newReportGroupTableViewCell", forIndexPath: indexPath) as! NewReportGroupTableViewCell guard (self.groups != nil) else { return cell } let _index = indexPath.row let group = self.groups?["features"][_index] if group != nil { // Organization Logo // cell.imageGroupLogo.tag = _index cell.imageGroupLogo.tag = indexPath.row let organizationImageUrl:NSURL = NSURL(string: "\(group!["properties"]["organization"]["properties"]["picture"])")! cell.imageGroupLogo.kf_indicatorType = .Activity cell.imageGroupLogo.kf_showIndicatorWhenLoading = true cell.imageGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.imageGroupLogo.image = image cell.imageGroupLogo.layer.cornerRadius = cell.imageGroupLogo.frame.size.width / 2 cell.imageGroupLogo.clipsToBounds = true }) // Organization Name // cell.labelGroupName.text = "\(group!["properties"]["organization"]["properties"]["name"])" // Organization Switch/Selection // cell.switchGroupSelect.tag = _index if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] { if self.tempGroups.contains("\(_organization_id_number)") { cell.switchGroupSelect.on = true } else { cell.switchGroupSelect.on = false } } } return cell } return UITableViewCell() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var rowHeight: CGFloat = 44.0 if indexPath.section == 0 { // if (indexPath.row == 1 && self.hashtagTypeAhead.hidden == false) { if (indexPath.row == 0) { if (self.og_active == false) { if (self.hashtagSearchEnabled == true) { rowHeight = 288.0 } else if (self.hashtagSearchEnabled == false) { rowHeight = 128.0 } } else if (self.og_active == true) { if (self.hashtagSearchEnabled == true) { rowHeight = 527.0 } else if (self.hashtagSearchEnabled == false) { rowHeight = 384.0 } } else { rowHeight = 128.0 } } } else if indexPath.section == 1 { rowHeight = 72.0 } return rowHeight } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let segueId = segue.identifier else { return } switch segueId { case "setLocationForNewReport": let destinationNavigationViewController = segue.destinationViewController as! UINavigationController let destinationNewReportLocationSelectorViewController = destinationNavigationViewController.topViewController as! NewReportLocationSelector destinationNewReportLocationSelectorViewController.delegate = self destinationNewReportLocationSelectorViewController.userSelectedCoordinates = self.userSelectedCoorindates break default: break } } func onSetCoordinatesComplete(isFinished: Bool) { return } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // // MARK: Custom Statuses // func saving() { // // Create a view that covers the entire screen // self.loadingView = self.indicatorLoadingView self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) self.view.addSubview(self.loadingView) self.view.bringSubviewToFront(self.loadingView) // // Make sure that the Done/Save button is disabled // self.navigationItem.rightBarButtonItem?.enabled = false // // Make sure our view is scrolled to the top // self.tableView.setContentOffset(CGPointZero, animated: false) } func finishedSaving() { // // Create a view that covers the entire screen // self.loadingView.removeFromSuperview() // // Make sure that the Done/Save button is disabled // self.navigationItem.rightBarButtonItem?.enabled = true // // Make sure our view is scrolled to the top // self.tableView.setContentOffset(CGPointZero, animated: false) // Reset all fields self.imageReportImagePreviewIsSet = false self.reportDescription = "Write a few words about the photo or paste a link..." self.reportImage = nil self.og_paste = "" self.og_active = false self.og_title = "" self.og_description = "" self.og_sitename = "" self.og_type = "" self.og_image = "" self.og_url = "" self.tempGroups = [String]() self.tableView.reloadData() self.userSelectedCoorindates = nil } func finishedSavingWithError() { self.navigationItem.rightBarButtonItem?.enabled = true } // // MARK: Camera Functionality // func cameraActionHandler(action:UIAlertAction) -> Void { if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } func photoLibraryActionHandler(action:UIAlertAction) -> Void { if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { // Change the default camera icon to a preview of the image the user // has selected to be their report image. // self.reportImage = image self.imageReportImagePreviewIsSet = true // Refresh the table view to display the updated image data // self.dismissViewControllerAnimated(true, completion: { self.tableView.reloadData() }) } // // MARK: Location Child Delegate // func sendCoordinates(coordinates: CLLocationCoordinate2D) { print("PARENT:sendCoordinates see \(coordinates)") // Pass off coorindates to the self.userSelectedCoordinates // self.userSelectedCoorindates = coordinates // Update the display of the returned coordinates in the "Confirm // Location" table view cell label // self.tableView.reloadData() } // // MARK: Server Request/Response functionality // func displayErrorMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func buildRequestHeaders() -> [String: String] { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") return [ "Authorization": "Bearer " + (accessToken! as! String) ] } func attemptNewReportSave(headers: [String: String]) { // // Error Check for Geometry // var geometryCollection: [String: AnyObject] = [ "type": "GeometryCollection" ] if (self.userSelectedCoorindates != nil) { var geometry: [String: AnyObject] = [ "type": "Point" ] let coordinates: Array = [ self.userSelectedCoorindates.longitude, self.userSelectedCoorindates.latitude ] geometry["coordinates"] = coordinates let geometries: [AnyObject] = [geometry] geometryCollection["geometries"] = geometries } else { self.displayErrorMessage("Location Field Empty", message: "Please add a location to your report before saving") self.finishedSavingWithError() return } // // Check image value // if (!imageReportImagePreviewIsSet) { self.displayErrorMessage("Image Field Empty", message: "Please add an image to your report before saving") self.finishedSavingWithError() return } // Before starting the saving process, hide the form // and show the user the saving indicator self.saving() // // REPORT DATE // let dateFormatter = NSDateFormatter() let date = NSDate() dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle let report_date: String = dateFormatter.stringFromDate(date) print("report_date \(report_date)") // // PARAMETERS // if self.reportDescription == "Write a few words about the photo or paste a link..." { self.reportDescription = "" } var parameters: [String: AnyObject] = [ "report_description": self.reportDescription, "report_date": report_date, "is_public": "true", "geometry": geometryCollection, "state": "open" ] // // GROUPS // var _temporary_groups: [AnyObject] = [AnyObject]() for _organization_id in tempGroups { print("group id \(_organization_id)") let _group = [ "id": "\(_organization_id)", ] _temporary_groups.append(_group) } parameters["groups"] = _temporary_groups // // OPEN GRAPH // var open_graph: [AnyObject] = [AnyObject]() if self.og_active { let _social = [ "og_title": self.og_title, "og_type": self.og_type, "og_url": self.og_url, "og_image_url": self.og_image, "og_description": self.og_description ] open_graph.append(_social) } parameters["social"] = open_graph // // Make request // if (self.reportImage != nil) { Alamofire.upload(.POST, Endpoints.POST_IMAGE, headers: headers, multipartFormData: { multipartFormData in // import image to request if let imageData = UIImageJPEGRepresentation(self.reportImage!, 1) { multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "ReportImageFromiPhone.jpg", mimeType: "image/jpeg") } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in print("Image uploaded \(response)") if let value = response.result.value { let imageResponse = JSON(value) let image = [ "id": String(imageResponse["id"].rawValue) ] let images: [AnyObject] = [image] parameters["images"] = images print("parameters \(parameters)") Alamofire.request(.POST, Endpoints.POST_REPORT, parameters: parameters, headers: headers, encoding: .JSON) .responseJSON { response in print("Response \(response)") switch response.result { case .Success(let value): print("Response Sucess \(value)") // Hide the loading indicator self.finishedSaving() // Send user to the Activty Feed self.tabBarController?.selectedIndex = 0 case .Failure(let error): print("Response Failure \(error)") break } } } } case .Failure(let encodingError): print(encodingError) } }) } } func attemptLoadUserGroups() { // Set headers let _headers = self.buildRequestHeaders() if let userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber { let GET_GROUPS_ENDPOINT = Endpoints.GET_USER_PROFILE + "\(userId)" + "/groups" Alamofire.request(.GET, GET_GROUPS_ENDPOINT, headers: _headers, encoding: .JSON).responseJSON { response in print("response.result \(response.result)") switch response.result { case .Success(let value): // print("Request Success for Groups: \(value)") // Assign response to groups variable self.groups = JSON(value) // Refresh the data in the table so the newest items appear self.tableView.reloadData() break case .Failure(let error): print("Request Failure: \(error)") break } } } else { self.attemptRetrieveUserID() } } func attemptRetrieveUserID() { // Set headers let _headers = self.buildRequestHeaders() Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): let json = JSON(value) if let data: AnyObject = json.rawValue { NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID") self.attemptLoadUserGroups() } case .Failure(let error): print(error) } } } // // MARK: Hashtag // func searchHashtags(timer: NSTimer) { let queryText: String! = "\(timer.userInfo!)" print("searchHashtags fired with \(queryText)") // // Send a request to the defined endpoint with the given parameters // let parameters = [ "q": "{\"filters\": [{\"name\":\"tag\",\"op\":\"like\",\"val\":\"\(queryText)%\"}]}" ] Alamofire.request(.GET, Endpoints.GET_MANY_HASHTAGS, parameters: parameters) .responseJSON { response in switch response.result { case .Success(let value): let _results = JSON(value) // print("self.dataSource >>>> _results \(_results)") for _result in _results["features"] { print("_result \(_result.1["properties"]["tag"])") let _tag = "\(_result.1["properties"]["tag"])" self.dataSource.results.append(_tag) } self.dataSource.numberOfRowsInSection(_results["features"].count) let _index = NSIndexPath.init(forRow: 0, inSection: 0) self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) case .Failure(let error): print(error) break } } } func selectedValue(value: String, searchText: String) { let _index = NSIndexPath.init(forRow: 0, inSection: 0) let _selection = "\(value)" print("Hashtag Selected, now we need to update the textview with selected \(value) and search text \(searchText) so that it makes sense with \(self.reportDescription)") let _temporaryCopy = self.reportDescription let _updatedDescription = _temporaryCopy.stringByReplacingOccurrencesOfString(searchText, withString: _selection, options: NSStringCompareOptions.LiteralSearch, range: nil) print("Updated Text \(_updatedDescription)") // Add the hashtag to the text // self.reportDescription = "\(_updatedDescription)" // Reset the search // self.hashtagSearchEnabled = false self.dataSource.results = [String]() self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None) print("Hashtag Search: Timer reset to zero due to user selection") self.hashtagSearchTimer.invalidate() } }
11d8b44a159ac2c635ad67c42fd70080
34.907609
226
0.50116
false
false
false
false
xdliu002/TongjiAppleClubDeviceManagement
refs/heads/master
TAC-DM/SettingEntryViewController.swift
mit
1
// // SettingEntryViewController.swift // TAC-DM // // Created by Harold Liu on 8/21/15. // Copyright (c) 2015 TAC. All rights reserved. // import UIKit // MARK:- NO NEED TO CHAGNE THIS CONTROLLER class SettingEntryViewController: UIViewController, DMDelegate { @IBOutlet var typeButtons: [UIButton]! var dmModel:DatabaseModel! var umbrellaInfo:BorrowItem? override func viewDidLoad() { super.viewDidLoad() configureUI() dmModel = DatabaseModel.getInstance() dmModel.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateUI() SVProgressHUD.show() } //更新雨伞的借出情况 func updateUI() { if let id = umbrellaId { dmModel.getDevice(id) } else { print("unget umbrella id") SVProgressHUD.showErrorWithStatus("无法获得雨伞信息,请后退刷新界面") } } func configureUI() { UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "setting background")?.drawInRect(self.view.bounds) let image :UIImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) for button:UIButton in typeButtons { button.layer.cornerRadius = button.frame.height/2 } } @IBAction func backAction(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toSettingChangeVC" { if let nextVC = segue.destinationViewController as? SettingChangeViewController { if let umbrella = umbrellaInfo { nextVC.title = "Setting Umbrella" nextVC.itemId = umbrella.id nextVC.itemCount = umbrella.count nextVC.itemLeftCount = umbrella.leftCount } else { nextVC.title = "无法获得雨伞信息,请后退刷新界面" } } } if segue.identifier == "bookSettingTableVC" { if let nextVC = segue.destinationViewController as? SettingTableView { nextVC.title = "Setting Book" nextVC.isBook = true } } if segue.identifier == "deviceSettingTableVC" { if let nextVC = segue.destinationViewController as? SettingTableView { nextVC.title = "Setting Device" nextVC.isBook = false } } } func getRequiredInfo(Info: String) { print("umbrella:\(Info)") let itemInfo = Info.componentsSeparatedByString(",") umbrellaInfo = BorrowItem(id: itemInfo[0], name: itemInfo[1], descri: itemInfo[2], type: itemInfo[3], count: itemInfo[4], leftCount: itemInfo[5]) SVProgressHUD.dismiss() } }
76f8749e62113fc700ed00cc19e2b6ae
28.622642
153
0.576115
false
false
false
false
ls1intum/sReto
refs/heads/master
Source/sReto/Core/Routing/MulticastConnection.swift
mit
1
// // MulticastConnection.swift // sReto // // Created by Julian Asamer on 18/09/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness // for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, // whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. // import Foundation /** * A MulticastConnection acts like a normal underlying connection, but sends all data written to it using a set of subconnections. * Data received from any subconnection is reported to the delegate. */ class MulticastConnection: UnderlyingConnection, UnderlyingConnectionDelegate { /** The subconnections used with this connection */ var subconnections: [UnderlyingConnection] = [] /** Stores the number of dataSent calls yet to be received. Once all are received, the delegate's didSendData can be called. */ var dataSentCallbacksToBeReceived: Int = 0 /** The number of data packets that have been sent in total. */ var dataPacketsSent: Int = 0 init() {} /** Adds a subconnection. */ func addSubconnection(_ connection: UnderlyingConnection) { self.subconnections.append(connection) connection.delegate = self } // MARK: UnderlyingConnection protocol var delegate: UnderlyingConnectionDelegate? var isConnected: Bool { get { return subconnections.map({ $0.isConnected }).reduce(false, { $0 && $1 }) } } var recommendedPacketSize: Int { get { return subconnections.map { $0.recommendedPacketSize }.min()! } } func connect() { for connection in self.subconnections { connection.connect() } } func close() { for connection in self.subconnections { connection.close() } } func writeData(_ data: Data) { if self.dataSentCallbacksToBeReceived != 0 { self.dataPacketsSent += 1 } else { self.dataSentCallbacksToBeReceived = self.subconnections.count } for connection in self.subconnections { connection.writeData(data) } } // MARK: UnderlyingConnectionDelegate protocol func didConnect(_ connection: UnderlyingConnection) { if self.isConnected { self.delegate?.didConnect(self) } } func didClose(_ closedConnection: UnderlyingConnection, error: AnyObject?) { for connection in self.subconnections { if connection !== closedConnection { connection.close() } } self.delegate?.didClose(self, error: error ) } func didReceiveData(_ connection: UnderlyingConnection, data: Data) { self.delegate?.didReceiveData(self, data: data) } func didSendData(_ connection: UnderlyingConnection) { if self.dataSentCallbacksToBeReceived == 0 { log(.medium, info: "Received unexpected didSendData call.") return } self.dataSentCallbacksToBeReceived -= 1 if self.dataSentCallbacksToBeReceived == 0 { if self.dataPacketsSent != 0 { self.dataPacketsSent -= 1 self.dataSentCallbacksToBeReceived = self.subconnections.count } self.delegate?.didSendData(self) } } }
0aa9b8f96cacefab318295512f2469cd
38.794393
159
0.672851
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
refs/heads/develop
DuckDuckGo/AutocompleteParser.swift
apache-2.0
1
// // AutocompleteParser.swift // DuckDuckGo // // Created by Mia Alexiou on 09/03/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import Foundation import Core class AutocompleteParser { enum ParsingError: Error { case noData case invalidJson } func parse(data: Data?) throws -> [Suggestion] { guard let data = data else { throw ParsingError.noData } guard let json = try JSONSerialization.jsonObject(with: data) as? [[String: String]] else { throw ParsingError.invalidJson } var suggestions = [Suggestion]() for element in json { if let type = element.keys.first, let suggestion = element[type] { suggestions.append(Suggestion(type: type, suggestion: suggestion)) } } return suggestions } }
aeaec6e40a3ac2900508f6e5cc110c7d
25.363636
132
0.609195
false
false
false
false
son11592/STKeyboard
refs/heads/master
Example/Pods/STKeyboard/STKeyboard/Classes/STKeyboardNumber.swift
mit
2
// // STKeyboardMoney.swift // Bubu // // Created by Sơn Thái on 9/27/16. // Copyright © 2016 LOZI. All rights reserved. // import UIKit open class STKeyboardNumber: STKeyboard { static let sharedNumber = STKeyboardNumber() fileprivate var buttons: [STButton] = [] override open func commonInit() { super.commonInit() self.backgroundColor = UIColor.commonWhiteSand let padding: CGFloat = 1.0 let width: CGFloat = (UIScreen.main.bounds.width - padding * 3) * 1/3 let height: CGFloat = (STKeyboard.STKeyboardDefaultHeight - padding * 5) * 0.25 var numberX: CGFloat = 0 var numberY: CGFloat = padding for i in 0..<9 { let frame = CGRect(x: numberX, y: numberY, width: width, height: height) let button = self.createButton(title: "\(i + 1)", tag: i + 1, frame: frame) self.addSubview(button) self.buttons.append(button) numberX += (width + padding) if (i + 1) % 3 == 0 { numberX = 0.0 numberY += (height + padding) } } let zeroFrame = CGRect(x: 0, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height) let zero = self.createButton(title: "0", tag: 0, frame: zeroFrame) self.addSubview(zero) self.buttons.append(zero) let trippleFrame = CGRect(x: width + padding, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height) let tripplezero = self.createButton(title: "000", tag: 11, frame: trippleFrame, titleSize: 20) self.addSubview(tripplezero) self.buttons.append(tripplezero) let backFrame = CGRect(x: UIScreen.main.bounds.width - width, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height) let backSpace = self.createButton(title: "\u{232B}", tag: -1, frame: backFrame) self.addSubview(backSpace) } open func numberTD(_ button: UIButton) { UIDevice.current.playInputClick() switch button.tag { case -1: self.backSpaceTD() break case 11: self.inputText(text: "000") break default: self.inputText(text: "\(button.tag)") break } } fileprivate func createButton(title: String, tag: Int, frame: CGRect, titleSize: CGFloat = 25) -> STButton { let button = STButton() button._normalBackgroundColor = UIColor.white button._selectedBackgroundColor = UIColor(hex: 0x535353) button.frame = frame button.setTitleColor(UIColor.black, for: .normal) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitle(title, for: .normal) button.titleLabel?.font = UIFont(name: "HelveticaNeue", size: titleSize) button.tag = tag button.addTarget(self, action: #selector(STKeyboardNumber.numberTD(_:)), for: .touchDown) button.layer.cornerRadius = 5 return button } }
6dd12ca1fcc3613ab582532097161db5
32.714286
153
0.670551
false
false
false
false
ozgur/AutoLayoutAnimation
refs/heads/master
autolayoutanimation/AlamofireViewController.swift
mit
1
// // AlamofireViewController.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 10/19/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit import Alamofire class AlamofireViewController: UIViewController { convenience init() { self.init(nibName: "AlamofireViewController", bundle: nil) } @IBOutlet fileprivate weak var responseLabel: UILabel! @IBOutlet fileprivate weak var activityIndicatorView: UIActivityIndicatorView! fileprivate func url(_ url: String) -> String { return "http://httpbin.org" + url } override func loadView() { super.loadView() view.backgroundColor = UIColor.white } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge() title = "Alamofire GET" } @IBAction func IPButtonTapped(_ sender: UIButton) { responseLabel.text = nil activityIndicatorView.startAnimating() Alamofire.request(.GET, url("/ip"), parameters: ["foo": "bar"]) .response { (request, response, data, error) -> Void in debugPrint(request) debugPrint(response) debugPrint("Data: \(data)") debugPrint(error) } .responseData { response -> Void in debugPrint("ResponseData: \(response.result.value)") } .responseJSON(options: []) { response -> Void in self.activityIndicatorView.stopAnimating() switch response.result { case .success(let value): print(value) case .failure(let error): print(error.localizedDescription) } let result = response.result.value as! [String: String] self.responseLabel.text = result["origin"]! } } @IBAction func userAgentButtonTapped(_ sender: UIButton) { responseLabel.text = nil activityIndicatorView.startAnimating() Alamofire.Manager.sharedInstance.request(.GET, url("/user-agent")).responseJSON { response in self.activityIndicatorView.stopAnimating() if response.result.isSuccess { let result = response.result.value as! [String: String] self.responseLabel.text = result["user-agent"] } else { self.responseLabel.text = response.result.error!.description } } } @IBAction func cookiesButtonTapped(_ sender: UIButton) { responseLabel.text = nil activityIndicatorView.startAnimating() Alamofire.request(.GET, url("/cookies/set"), parameters: ["foo": "bar", "sessionid": "test"]) .responseJSON { response in self.activityIndicatorView.stopAnimating() let result = response.result.value as! [String: [String: String]] let cookies = result["cookies"]!.map({ (k, v) -> String in return "\(k) -> \(v)" }) self.responseLabel.text = cookies.joined(separator: "\n") } } }
48b09da7b2182dfee081f9e81cb03394
28.111111
97
0.644691
false
false
false
false
sdaheng/Biceps
refs/heads/master
BicepsService.swift
mit
1
// // BicepsService.swift // HomeNAS // // Created by SDH on 03/04/2017. // Copyright © 2017 sdaheng. All rights reserved. // import Foundation // MARK: Service Layer public protocol BicepsProvidable { func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps } public extension BicepsProvidable { func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps { throw BicepsError.UnimplementedMethodError.fetch } func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps { throw BicepsError.UnimplementedMethodError.send } } open class BicepsService { open class func fetch<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws { do { let biceps = try provider.fetch(paramater: paramater, resultBlock: resultBlock) try add(biceps, to: BicepsOperationQueue.shared.operationQueue) } catch { throw BicepsError.UnimplementedMethodError.fetch } } open class func send<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws { do { let biceps = try provider.send(paramater: paramater, resultBlock: resultBlock) try add(biceps, to: BicepsOperationQueue.shared.operationQueue) } catch { throw BicepsError.UnimplementedMethodError.send } } class func add(_ biceps: Biceps, to queue: OperationQueue) throws { let operationQueue = queue if let combinedRequests = biceps.combinedRequest { operationQueue.addOperations(combinedRequests.map { (biceps) in return BicepsOperation(biceps) }, waitUntilFinished: false) } else if biceps.hasDependency() { guard let dependency = biceps.dependency, dependency != biceps else { throw BicepsError.DependencyError.cycle } operationQueue.addOperations(resolveDependencyChain(from: biceps), waitUntilFinished: false) } else { operationQueue.addOperation(BicepsOperation(biceps)) } } class func resolveDependencyChain(from head: Biceps) -> [BicepsOperation] { var dependencyChain = head var dependencyOperation = BicepsOperation(head) var dependencyOperations = Set<BicepsOperation>() while dependencyChain.hasDependency() { if let depsDependency = dependencyChain.dependency { let depsDependencyOperation = BicepsOperation(depsDependency) dependencyOperation.addDependency(depsDependencyOperation) dependencyOperations.insert(dependencyOperation) if !depsDependency.hasDependency() { dependencyOperations.insert(depsDependencyOperation) } dependencyOperation = depsDependencyOperation dependencyChain = depsDependency } } return dependencyOperations.map { return $0 } } }
925a44a78c444d64d47174a5d62e8465
39.117647
146
0.633138
false
false
false
false
LeeShiYoung/LSYWeibo
refs/heads/master
Pods/ALCameraViewController/ALCameraViewController/ViewController/ConfirmViewController.swift
artistic-2.0
1
// // ALConfirmViewController.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/30. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import Photos public enum PhotosMode: Int { case preview = 0 // 默认预览 case graph // 拍照预览 } public class ConfirmViewController: UIViewController, UIScrollViewDelegate { lazy var imageView: UIImageView = { let img = UIImageView() return img }() @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var cropOverlay: CropOverlay! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var confirmButton: UIButton! @IBOutlet weak var centeringView: UIView! var graphImage: UIImage? var allowsCropping: Bool = false var verticalPadding: CGFloat = 30 var horizontalPadding: CGFloat = 30 var modeType: PhotosMode? public var onComplete: CameraViewCompletion? var asset: PHAsset! public init(asset: PHAsset, allowsCropping: Bool, mode: PhotosMode) { self.allowsCropping = allowsCropping self.asset = asset self.modeType = mode super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle) } //MARK: - 增加初始化方法 public init(image: UIImage?, allowsCropping: Bool, mode: PhotosMode) { self.allowsCropping = allowsCropping self.graphImage = image self.modeType = mode super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func prefersStatusBarHidden() -> Bool { switch modeType! { case .graph: return false case .preview: return true } return true } public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.Slide } public override func viewDidLoad() { super.viewDidLoad() switch modeType! { case .graph: print("拍照初始化") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一步", style: UIBarButtonItemStyle.Plain, target: self, action: .next) view.backgroundColor = UIColor.whiteColor() configureWithImage(graphImage!) case .preview: view.backgroundColor = UIColor.blackColor() imageView.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(ConfirmViewController.cancel)) imageView.addGestureRecognizer(tap) } cancelButton.hidden = true cancelButton.enabled = false confirmButton.hidden = true confirmButton.enabled = false scrollView.addSubview(imageView) scrollView.delegate = self scrollView.maximumZoomScale = 1 cropOverlay.hidden = true guard let asset = asset else { return } switch modeType! { case .graph: return case .preview: let spinner = showSpinner() disable() SingleImageFetcher() .setAsset(asset) .setTargetSize(largestPhotoSize()) .onSuccess { image in self.configureWithImage(image) self.hideSpinner(spinner) self.enable() } .onFailure { error in self.hideSpinner(spinner) } .fetch() } } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let scale = calculateMinimumScale(view.frame.size) let frame = allowsCropping ? cropOverlay.frame : view.bounds scrollView.contentInset = calculateScrollViewInsets(frame) scrollView.minimumZoomScale = scale scrollView.zoomScale = scale centerScrollViewContents() centerImageViewOnRotate() } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let scale = calculateMinimumScale(size) var frame = view.bounds if allowsCropping { frame = cropOverlay.frame let centeringFrame = centeringView.frame var origin: CGPoint if size.width > size.height { // landscape let offset = (size.width - centeringFrame.height) let expectedX = (centeringFrame.height/2 - frame.height/2) + offset origin = CGPoint(x: expectedX, y: frame.origin.x) } else { let expectedY = (centeringFrame.width/2 - frame.width/2) origin = CGPoint(x: frame.origin.y, y: expectedY) } frame.origin = origin } else { frame.size = size } coordinator.animateAlongsideTransition({ context in self.scrollView.contentInset = self.calculateScrollViewInsets(frame) self.scrollView.minimumZoomScale = scale self.scrollView.zoomScale = scale self.centerScrollViewContents() self.centerImageViewOnRotate() }, completion: nil) } private func configureWithImage(image: UIImage) { if allowsCropping { cropOverlay.hidden = false } else { cropOverlay.hidden = true } buttonActions() imageView.image = image imageView.sizeToFit() view.setNeedsLayout() } private func calculateMinimumScale(size: CGSize) -> CGFloat { var _size = size if allowsCropping { _size = cropOverlay.frame.size } guard let image = imageView.image else { return 1 } let scaleWidth = _size.width / image.size.width let scaleHeight = _size.height / image.size.height var scale: CGFloat if allowsCropping { scale = max(scaleWidth, scaleHeight) } else { scale = min(scaleWidth, scaleHeight) } return scale } private func calculateScrollViewInsets(frame: CGRect) -> UIEdgeInsets { let bottom = view.frame.height - (frame.origin.y + frame.height) let right = view.frame.width - (frame.origin.x + frame.width) let insets = UIEdgeInsets(top: frame.origin.y, left: frame.origin.x, bottom: bottom, right: right) return insets } private func centerImageViewOnRotate() { if allowsCropping { let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size let scrollInsets = scrollView.contentInset let imageSize = imageView.frame.size var contentOffset = CGPoint(x: -scrollInsets.left, y: -scrollInsets.top) contentOffset.x -= (size.width - imageSize.width) / 2 contentOffset.y -= (size.height - imageSize.height) / 2 scrollView.contentOffset = contentOffset } } private func centerScrollViewContents() { let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size let imageSize = imageView.frame.size var imageOrigin = CGPoint.zero if imageSize.width < size.width { imageOrigin.x = (size.width - imageSize.width) / 2 } if imageSize.height < size.height { imageOrigin.y = (size.height - imageSize.height) / 2 } imageView.frame.origin = imageOrigin } private func buttonActions() { confirmButton.action = { [weak self] in self?.confirmPhoto() } cancelButton.action = { [weak self] in self?.cancel() } } internal func cancel() { onComplete?(nil, nil) } internal func confirmPhoto() { disable() imageView.hidden = true if graphImage != nil { self.onComplete?(graphImage, nil) return } let spinner = showSpinner() let fetcher = SingleImageFetcher() .onSuccess { image in switch self.modeType! { case .preview: print("默认") case .graph: print("拍照") self.onComplete?(self.graphImage, self.asset) } self.hideSpinner(spinner) self.enable() } .onFailure { error in self.hideSpinner(spinner) self.showNoImageScreen(error) } .setAsset(asset) if allowsCropping { var cropRect = cropOverlay.frame cropRect.origin.x += scrollView.contentOffset.x cropRect.origin.y += scrollView.contentOffset.y let normalizedX = cropRect.origin.x / imageView.frame.width let normalizedY = cropRect.origin.y / imageView.frame.height let normalizedWidth = cropRect.width / imageView.frame.width let normalizedHeight = cropRect.height / imageView.frame.height let rect = normalizedRect(CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight), orientation: imageView.image!.imageOrientation) fetcher.setCropRect(rect) } fetcher.fetch() } public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewDidZoom(scrollView: UIScrollView) { centerScrollViewContents() } func showSpinner() -> UIActivityIndicatorView { let spinner = UIActivityIndicatorView() spinner.activityIndicatorViewStyle = .White spinner.center = view.center spinner.startAnimating() view.addSubview(spinner) view.bringSubviewToFront(spinner) return spinner } func hideSpinner(spinner: UIActivityIndicatorView) { spinner.stopAnimating() spinner.removeFromSuperview() } func disable() { confirmButton.enabled = false } func enable() { confirmButton.enabled = true } func showNoImageScreen(error: NSError) { let permissionsView = PermissionsView(frame: view.bounds) let desc = localizedString("error.cant-fetch-photo.description") permissionsView.configureInView(view, title: error.localizedDescription, descriptiom: desc, completion: cancel) } deinit { print("ConfirmViewController 死") } } private extension Selector { static let next = #selector(ConfirmViewController.confirmPhoto) }
e2c1bc61a99a1aa8931985f6c5a4729d
30.189041
175
0.58192
false
false
false
false
zisko/swift
refs/heads/master
test/SILGen/nested_generics.swift
apache-2.0
1
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen -parse-as-library %s | %FileCheck %s // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null // TODO: // - test generated SIL -- mostly we're just testing mangling here // - class_method calls // - witness_method calls // - inner generic parameters on protocol requirements // - generic parameter list on method in nested type // - types nested inside unconstrained extensions of generic types protocol Pizza : class { associatedtype Topping } protocol HotDog { associatedtype Condiment } protocol CuredMeat {} // Generic nested inside generic struct Lunch<T : Pizza> where T.Topping : CuredMeat { struct Dinner<U : HotDog> where U.Condiment == Deli<Pepper>.Mustard { let firstCourse: T let secondCourse: U? var leftovers: T var transformation: (T) -> U func coolCombination(t: T.Topping, u: U.Condiment) { func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) { return (x, y) } _ = nestedGeneric(x: t, y: u) } } } // CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> () // CHECK-LABEL: // nestedGeneric #1 <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(x: A2, y: B2) -> (A2, B2) in nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil private @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF0A7GenericL_1x1yqd0___qd0_0_tqd0___qd0_0_tAA5PizzaRzAA6HotDogRd__AA9CuredMeatAJRQAQ9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y) // CHECK-LABEL: // nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: Swift.Optional<A1>, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1> // CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV11firstCourse06secondF09leftovers14transformationAEyx_qd__Gx_qd__Sgxqd__xctcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_guaranteed (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U> // Non-generic nested inside generic class Deli<Spices> : CuredMeat { class Pepperoni : CuredMeat {} struct Sausage : CuredMeat {} enum Mustard { case Yellow case Dijon case DeliStyle(Spices) } } // CHECK-LABEL: // nested_generics.Deli.Pepperoni.init() -> nested_generics.Deli<A>.Pepperoni // CHECK-LABEL: sil hidden @$S15nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni // Typealiases referencing outer generic parameters struct Pizzas<Spices> { class NewYork : Pizza { typealias Topping = Deli<Spices>.Pepperoni } class DeepDish : Pizza { typealias Topping = Deli<Spices>.Sausage } } class HotDogs { struct Bratwurst : HotDog { typealias Condiment = Deli<Pepper>.Mustard } struct American : HotDog { typealias Condiment = Deli<Pepper>.Mustard } } // Local type in extension of type in another module extension String { func foo() { // CHECK-LABEL: // init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> () // CHECK-LABEL: sil private @$SSS15nested_genericsE3fooyyF6CheeseL_V8materialADyxGx_tcfC struct Cheese<Milk> { let material: Milk } let _ = Cheese(material: "cow") } } // Local type in extension of type in same module extension HotDogs { func applyRelish() { // CHECK-LABEL: // init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> ()<A> in Relish #1 in nested_generics.HotDogs.applyRelish() -> () // CHECK-LABEL: sil private @$S15nested_generics7HotDogsC11applyRelishyyF0F0L_V8materialAFyxGx_tcfC struct Relish<Material> { let material: Material } let _ = Relish(material: "pickles") } } struct Pepper {} struct ChiliFlakes {} // CHECK-LABEL: // nested_generics.eatDinnerGeneric<A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(d: inout nested_generics.Lunch<A>.Dinner<B>, t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @$S15nested_generics16eatDinnerGeneric1d1t1uyAA5LunchV0D0Vyx_q_Gz_7ToppingQzAA4DeliC7MustardOyAA6PepperV_GtAA5PizzaRzAA6HotDogR_AA9CuredMeatALRQAS9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> () func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // Overloading concrete function with different bound generic arguments in parent type // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAA6PepperV_GtF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, t: Deli<ChiliFlakes>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIegxr_AhLIegxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAO_GtF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, t: Deli<Pepper>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIegxr_AhLIegxd_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // closure #1 (nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> nested_generics.HotDogs.American in nested_generics.calls() -> () // CHECK-LABEL: sil private @$S15nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American func calls() { let firstCourse = Pizzas<Pepper>.NewYork() let secondCourse = HotDogs.American() var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>( firstCourse: firstCourse, secondCourse: secondCourse, leftovers: firstCourse, transformation: { _ in HotDogs.American() }) let topping = Deli<Pepper>.Pepperoni() let condiment1 = Deli<Pepper>.Mustard.Dijon let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper()) eatDinnerGeneric(d: &dinner, t: topping, u: condiment1) eatDinnerConcrete(d: &dinner, t: topping, u: condiment2) } protocol ProtocolWithGenericRequirement { associatedtype T associatedtype U func method<V>(t: T, u: U, v: V) -> (T, U, V) } class OuterRing<T> { class InnerRing<U> : ProtocolWithGenericRequirement { func method<V>(t: T, u: U, v: V) -> (T, U, V) { return (t, u, v) } } } class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> { override func method<V>(t: T, u: U, v: V) -> (T, U, V) { return super.method(t: t, u: u, v: v) } } // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIegxd_AhLIegxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American // CHECK-LABEL: sil private [transparent] [thunk] @$S15nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1t1u1v1TQz_1UQzqd__tAN_APqd__tlFTW : $@convention(witness_method: ProtocolWithGenericRequirement) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) { // CHECK: bb0([[T:%[0-9]+]] : @trivial $*τ_0_0, [[U:%[0-9]+]] : @trivial $*τ_1_0, [[V:%[0-9]+]] : @trivial $*τ_2_0, [[TOut:%[0-9]+]] : @trivial $*τ_0_0, [[UOut:%[0-9]+]] : @trivial $*τ_1_0, [[VOut:%[0-9]+]] : @trivial $*τ_2_0, [[SELF:%[0-9]+]] : @trivial $*OuterRing<τ_0_0>.InnerRing<τ_1_0>): // CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load_borrow [[SELF]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: [[METHOD:%[0-9]+]] = class_method [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: end_borrow [[SELF_COPY_VAL]] from [[SELF]] // CHECK: return [[RESULT]] : $() // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Pepperoni // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Sausage // CHECK: } // CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: } // CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: }
0234956d950cf60a3115ab52eb4a4f7c
54.211538
407
0.711181
false
false
false
false
MrSuperJJ/JJMediatorDemo
refs/heads/master
JJMediatorDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // JJMediatorDemo // // Created by Mr.JJ on 2017/5/11. // Copyright © 2017年 Mr.JJ. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = .white let mainViewController = MainTableViewController() let navigationController = UINavigationController(rootViewController: mainViewController) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
01e19d99fd8e78db95c152d974cb4284
45.981481
285
0.74931
false
false
false
false
txstate-etc/mobile-tracs-ios
refs/heads/master
mobile-tracs-ios/AppDelegate.swift
mit
1
// // AppDelegate.swift // mobile-tracs-ios // // Created by Nick Wing on 3/17/17. // Copyright © 2017 Texas State University. All rights reserved. // import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Clear out cache data between versions in case we change the structure of the object being saved if let savedversion = Utils.grab("version") as? String { if let currentversion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { if currentversion != savedversion { TRACSClient.sitecache.clean() Utils.save(currentversion, withKey: "version") } } } // register for push notifications if #available(iOS 10, *) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in } center.delegate = self } else { let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() //Set a custom user agent so that UIWebView and URLSession dataTasks will match UserDefaults.standard.register(defaults: ["UserAgent": Utils.userAgent]) return true } func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { if self.window?.rootViewController?.presentedViewController is LoginViewController { return UIInterfaceOrientationMask.portrait } else { return UIInterfaceOrientationMask.all } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { IntegrationClient.deviceToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() Utils.save(IntegrationClient.deviceToken, withKey: "deviceToken") NSLog("deviceToken: %@", IntegrationClient.deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { IntegrationClient.deviceToken = Utils.randomHexString(length:32) Utils.save(IntegrationClient.deviceToken, withKey: "deviceToken") } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { Analytics.event(category: "External Launch", action: url.absoluteString, label: sourceApplication ?? "null", value: nil) return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: ObservableEvent.PUSH_NOTIFICATION), object: self) var badge:Int? if let aps = userInfo["aps"] as? [String:Any] { badge = aps["badge"] as? Int } UIApplication.shared.applicationIconBadgeNumber = badge ?? 0 } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let tabController = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController tabController?.selectedIndex = 1 let navController = tabController?.selectedViewController as? UINavigationController navController?.popToRootViewController(animated: true) } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: ObservableEvent.PUSH_NOTIFICATION), object: self) UIApplication.shared.applicationIconBadgeNumber = notification.request.content.badge?.intValue ?? 0 completionHandler([.alert, .badge]) } }
477ac07cded5773d167eda999a24909e
53.105263
285
0.716926
false
false
false
false
BasThomas/TimeTable
refs/heads/master
TimeTable/TimeTable/ScheduleTableViewController.swift
mit
1
// // ScheduleTableViewController.swift // TimeTable // // Created by Bas Broek on 21/11/2014. // Copyright (c) 2014 Bas Broek. All rights reserved. // import UIKit class ScheduleTableViewController: UITableViewController { var daysAhead: Int var url: String required init(coder aDecoder: NSCoder) { // Do stuff. self.daysAhead = 14 // Gets two weeks ahead + startOfWeek. self.url = "https://apps.fhict.nl/api/v1/Schedule/me?expandTeacher=false&daysAhead=\(daysAhead)&IncludeStartOfWeek=true" super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 5 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "HEADER" } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("default", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } // MARK: - Actions @IBAction func logout(sender: AnyObject) { println("logging out") } }
81d8b9b98a220a8ffa2f4bcb4f50ef61
27.378049
128
0.647615
false
false
false
false
waltflanagan/AdventOfCode
refs/heads/master
2015/AOC6.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit enum Instruction { case On(CGPoint,CGPoint) case Off(CGPoint, CGPoint) case Toggle(CGPoint,CGPoint) init(string:String) { let components = string.componentsSeparatedByString(" ") switch components[0] { case "toggle": let points = Instruction.parseArguments(Array(components[1..<components.count])) self = .Toggle(points.0, points.1) default: let points = Instruction.parseArguments(Array(components[2..<components.count])) switch components[0] + components [1] { case "turnon": self = .On(points.0, points.1) case "turnoff": self = .Off(points.0, points.1) default: self = .Toggle(CGPointMake(0, 0), CGPointMake(0, 0)) } } } static func pointFromString(string: String) -> CGPoint { let numbers = string.componentsSeparatedByString(",") return CGPointMake(CGFloat(Int(numbers[0])!), CGFloat(Int(numbers[1])!)) } static func parseArguments(args: [String]) -> (CGPoint, CGPoint) { let first = pointFromString(args[0]) let second = pointFromString(args[2]) return (first,second) } } var lights = [[Bool]]() for _ in 0..<10 { var row = [Bool]() for _ in 0..<10 { row.append(false) } lights.append(row) } func set(value: Bool, first: CGPoint, second: CGPoint) { for x in Int(first.x)..<Int(second.x) { for y in Int(first.y)..<Int(second.y) { lights[x][y] = value } } } func toggle(first: CGPoint, second: CGPoint) { for x in Int(first.x)..<Int(second.x) { for y in Int(first.y)..<Int(second.y) { lights[x][y] = !lights[x][y] } } } let input = ["turn on 3,2 through 8,7"] let instructions = input.map { Instruction(string: $0) } for instruction in instructions { switch instruction { case .Toggle(let first, let second): toggle(first,second:second) case .On(let first, let second): set(true, first:first, second:second) case .Off(let first, let second): set(false, first:first, second:second) } } var count = 0 for row in lights { for light in row { if light { count += 1 } } } count
c806152c920e2f5665ee09f46cb75dc0
21.584906
92
0.571429
false
false
false
false
nalexn/ViewInspector
refs/heads/master
.watchOS/watchOS-Ext/watchOSApp+Testable.swift
mit
1
import SwiftUI import WatchKit import Combine #if !(os(watchOS) && DEBUG) typealias RootView<T> = T typealias TestViewSubject = Set<Int> extension View { @inline(__always) func testable(_ injector: TestViewSubject) -> Self { self } } #else typealias RootView<T> = ModifiedContent<T, TestViewHost> typealias TestViewSubject = CurrentValueSubject<[(String, AnyView)], Never> extension View { func testable(_ injector: TestViewSubject) -> ModifiedContent<Self, TestViewHost> { modifier(TestViewHost(injector: injector)) } } struct TestViewHost: ViewModifier { @State private var hostedViews: [(String, AnyView)] = [] let injector: TestViewSubject func body(content: Content) -> some View { ZStack { content ForEach(hostedViews, id: \.0) { $0.1 } } .onReceive(injector) { hostedViews = $0 } } } #endif
4322018b60ec1adbd3bd60676ca5183a
20.809524
87
0.648472
false
true
false
false
aschwaighofer/swift
refs/heads/master
test/AutoDiff/Sema/DerivedConformances/derived_differentiable.swift
apache-2.0
1
// RUN: %target-swift-frontend -print-ast %s | %FileCheck %s --check-prefix=CHECK-AST import _Differentiation struct GenericTangentVectorMember<T: Differentiable>: Differentiable, AdditiveArithmetic { var x: T.TangentVector } // CHECK-AST-LABEL: internal struct GenericTangentVectorMember<T> : Differentiable, AdditiveArithmetic where T : Differentiable // CHECK-AST: internal var x: T.TangentVector // CHECK-AST: internal init(x: T.TangentVector) // CHECK-AST: internal typealias TangentVector = GenericTangentVectorMember<T> // CHECK-AST: internal static var zero: GenericTangentVectorMember<T> { get } // CHECK-AST: internal static func + (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T> // CHECK-AST: internal static func - (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T> // CHECK-AST: @_implements(Equatable, ==(_:_:)) internal static func __derived_struct_equals(_ a: GenericTangentVectorMember<T>, _ b: GenericTangentVectorMember<T>) -> Bool public struct ConditionallyDifferentiable<T> { public var x: T } extension ConditionallyDifferentiable: Differentiable where T: Differentiable {} // CHECK-AST-LABEL: public struct ConditionallyDifferentiable<T> { // CHECK-AST: @differentiable(wrt: self where T : Differentiable) // CHECK-AST: public var x: T // CHECK-AST: internal init(x: T) // CHECK-AST: } // Verify that `TangentVector` is not synthesized to be `Self` for // `AdditiveArithmetic`-conforming classes. final class AdditiveArithmeticClass<T: AdditiveArithmetic & Differentiable>: AdditiveArithmetic, Differentiable { var x, y: T init(x: T, y: T) { self.x = x self.y = y } // Dummy `AdditiveArithmetic` requirements. static func == (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Bool { fatalError() } static var zero: AdditiveArithmeticClass { fatalError() } static func + (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Self { fatalError() } static func - (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Self { fatalError() } } // CHECK-AST-LABEL: final internal class AdditiveArithmeticClass<T> : AdditiveArithmetic, Differentiable where T : AdditiveArithmetic, T : Differentiable { // CHECK-AST: final internal var x: T, y: T // CHECK-AST: internal struct TangentVector : Differentiable, AdditiveArithmetic // CHECK-AST: } @frozen public struct FrozenStruct: Differentiable {} // CHECK-AST-LABEL: @frozen public struct FrozenStruct : Differentiable { // CHECK-AST: internal init() // CHECK-AST: @frozen public struct TangentVector : Differentiable, AdditiveArithmetic { @usableFromInline struct UsableFromInlineStruct: Differentiable {} // CHECK-AST-LABEL: @usableFromInline // CHECK-AST: struct UsableFromInlineStruct : Differentiable { // CHECK-AST: internal init() // CHECK-AST: @usableFromInline // CHECK-AST: struct TangentVector : Differentiable, AdditiveArithmetic {
e33696118fc0b796d907f9c8c46dcbeb
37.02439
174
0.730597
false
false
false
false
OwenLaRosa/MemeMe
refs/heads/master
Meme Me/Meme Me/TextFieldDelegate.swift
gpl-3.0
1
// // TextFieldDelegate.swift // Meme Me // // Created by Owen LaRosa on 3/23/15. // Copyright (c) 2015 Owen LaRosa. All rights reserved. // import Foundation import UIKit class TextFieldDelegate: NSObject, UITextFieldDelegate { var defaultText: String! init(defaultText: String) { self.defaultText = defaultText } func textFieldDidBeginEditing(textField: UITextField) { // clears the text field when the user begins editing if textField.text == defaultText { textField.text = "" } textField.becomeFirstResponder() } func textFieldDidEndEditing(textField: UITextField) { // reverts to default text if text field is empty if textField.text == "" { textField.text = defaultText } } func textFieldShouldReturn(textField: UITextField) -> Bool { // dismiss the keyboard textField.resignFirstResponder() return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var newText = textField.text! as NSString newText = newText.stringByReplacingCharactersInRange(range, withString: string) // ensure all inserted text is capitalized textField.text = newText.uppercaseString return false } }
2a063c64c9e9d1b5c0ba942a00ddea30
27.591837
132
0.652391
false
false
false
false
atuooo/notGIF
refs/heads/master
notGIF/Controllers/Compose/AccountTableViewController.swift
mit
1
// // AccountTableViewController.swift // notGIF // // Created by Atuooo on 13/10/2016. // Copyright © 2016 xyz. All rights reserved. // import UIKit import Accounts private let cellID = "AccountTableViewCell" class AccountTableViewController: UITableViewController { public var composeVC: ComposeViewController! deinit { printLog(" deinited") } override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = .clear tableView.tableFooterView = UIView() tableView.tintColor = .black tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return composeVC.accounts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) let account = composeVC.accounts[indexPath.item] cell.backgroundColor = .clear cell.textLabel?.text = account.accountDescription cell.accessoryType = account == composeVC.selectedAccount ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { composeVC.selectedAccount = composeVC.accounts[indexPath.item] composeVC.reloadConfigurationItems() composeVC.popConfigurationViewController() } }
e7b4bacfba63aaadd7f4235460ca7546
29.769231
109
0.693125
false
false
false
false
wanliming11/MurlocAlgorithms
refs/heads/master
Last/编程之法/1.2_字符串的包含/1.2 字符串的包含/main.swift
mit
1
// // main.swift // 1.2 字符串的包含 // // Created by FlyingPuPu on 20/02/2017. // Copyright (c) 2017 FPP. All rights reserved. // import Foundation /* 1. "abcd" contains "cba" "acd" contains "acd" "ad" not contains "ac" Thinking: 暴力解法,就是一个一个的遍历 时间复杂度: O(nm) 空间复杂度: O(1) Thinking: 排序后轮询,先每个字符串排序,A,B 注意排序后的两个元素判断是否包含的步骤,首先因为是判断 A 是否包含 B, 所以拿B 中的字母去A中查询,另外,先要找到B中每一个字符在A中第一次不小于的位置,如果是大于则直接返回,如果是等于 继续往下遍历, 因为这个像梭子一样的比较,每次比较的结果都会导致其中一个元素往前一位,所以最坏是O(n+m) 时间复杂度:按一般的快排算法 O(nlogn) + O(mlogm) + O(n+m) 空间复杂度:O(1) Thinking: 素数排序法,这个采用的素数的原理:素数指在一个大于1的自然数中,除了1和此整数自身外, 没法被其他自然数整除的数。 也就是说如果一个 String 里面把所有的转换为素数,然后相乘,判断另一个 String 里面的对应素数会不会被整除,如果不能,则会失败。 很显然这个很容易导致平台类型的越界。 时间复杂度: O(n+m) 空间复杂度:产生了一个26个数子的数组, O(26) -> O(1) Thinking: 位排序,原理就是用一个26位的数来表示,然后利用位运算, | 融合进数字, & 来判断是否被包含 时间复杂度:O(n+m) 空间复杂度: O(1) 2. 如果 "abc" ==> "bca", "acb" 都属于它的兄弟字符串 那么判断一个字典中,某一个字符串的兄弟子串。 如果用通用判断方法,那显然相当复杂,这里用到了"标识",把一个字符串排序,然后转换成例如 a1b1c1 这种模式,然后产生一个 a1b1c1 => ["bca", "acb"] 的映射,对应 key 的值 就是兄弟数组。 时间复杂度: 用一个26的数组来辅助生成 a1b1c1, O(n*m) (m 字符的平均长度) 然后整个数组按key 排序,排序复杂度 O(nlogn), 然后再找出对应的 key 的value */ //1.暴力解法 func containsStr1(_ a: String, _ b: String) -> Bool { let aArray = [Character](a.characters) let bArray = [Character](b.characters) for v in bArray { var match = false for c in aArray { if c == v { match = true break } } if !match { return false } } return true } //print(containsStr1("abc", "ad")) //排序后轮询 func containsStr2(_ a: String, _ b: String) -> Bool { var aArray = [Character](a.characters) var bArray = [Character](b.characters) aArray.sort(by: <) bArray.sort(by: <) //从 b 中去遍历 var index = 0 for v in bArray { //找到第一个不比v小的数 while index < aArray.count, aArray[index] < v { index += 1 } //如果大于,直接返回 if index >= aArray.count || aArray[index] > v { return false } } return true } //print(containsStr2("abc", "ac")) //素数排序 func containsStr3(_ a: String, _ b: String) -> Bool { let nArray = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 91, 97, 101] let aArray = [Character](a.characters) let bArray = [Character](b.characters) var calcInt: Int = 1 for v in aArray { let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value) calcInt = calcInt * nArray[space] } for v in bArray { let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value) if calcInt % nArray[space] != 0 { return false } } return true } //print(containsStr3("abc", "ad")) //位排序 func containsStr4(_ a: String, _ b: String) -> Bool { var hashInt = 0 let aArray = [Character](a.characters) let bArray = [Character](b.characters) for v in aArray { let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value) hashInt |= 1 << space } for v in bArray { let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value) if hashInt & 1 << space == 0 { return false } } return true } //print(containsStr4("abc", "ad")) //2. func brotherStrings(_ a: String, _ b: [String]) -> [String] { //convert "abc" to "a1b1c1" func convert(_ s: String) -> String { let cArray = [Character](s.characters) var sArray = [("a", 0), ("b", 0), ("c", 0), ("d", 0), ("e", 0), ("f", 0), ("g", 0), ("h", 0), ("i", 0), ("j", 0), ("k", 0), ("l", 0), ("m", 0), ("n", 0), ("o", 0), ("p", 0), ("q", 0), ("r", 0), ("s", 0), ("t", 0), ("u", 0), ("v", 0), ("w", 0), ("x", 0), ("y", 0), ("z", 0)] for v in cArray { let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value) sArray[space].1 += 1 } var retStr = "" for s in sArray { if s.1 != 0 { retStr += (s.0 + String(s.1)) } } return retStr } var bDic: [String: [String]] = [String: [String]]() for s in b { let key = convert(s) if let _ = bDic[key] { } else { bDic[key] = [String]() } bDic[key]?.append(s) } let aKey = convert(a) if let array = bDic[aKey] { return array } return [String]() } print(brotherStrings("abc", ["ab", "cba", "cab"]))
7bc612cb00b6f068bfd976d437261e73
23.93617
111
0.526024
false
false
false
false
sendyhalim/Yomu
refs/heads/master
Yomu/Screens/ChapterPageList/ChapterPageCollectionViewModel.swift
mit
1
// // ChapterPagesViewModel.swift // Yomu // // Created by Sendy Halim on 6/26/16. // Copyright © 2016 Sendy Halim. All rights reserved. // import RxCocoa import RxMoya import RxSwift import Swiftz /// A data structure that represents zoom scale struct ZoomScale: CustomStringConvertible { /// Scale in 1 based, 1 -> 100% let scale: Double /// String representation of zoom scale, /// will automatically multiply the scale by 100 var description: String { return String(Int(scale * 100)) } /// Normalize the given scale . /// /// - parameter scale: Zoom scale, if the scale is greater than 10 then /// it's considered as 100 based scale (I believe no one wants to zoom in by 1000%) /// /// - returns: zoom scale with base 1 (1 -> 100%) static private func normalize(scale: Double) -> Double { return scale > 10 ? (scale / 100) : scale } init(scale: Double) { self.scale = ZoomScale.normalize(scale: scale) } init(scale: String) { self.init(scale: Double(scale)!) } } struct PageSizeMargin { let previousSize: CGSize let currentSize: CGSize var margin: CGSize { return CGSize( width: currentSize.width - previousSize.width, height: currentSize.height - previousSize.height ) } } struct ScrollOffset { let marginHeight: CGFloat let previousItemsCount: Int var deltaY: CGFloat { return marginHeight * CGFloat(previousItemsCount) } } struct ChapterPageCollectionViewModel { // MARK: Public /// Chapter image var chapterImage: ImageUrl? { return _chapterPages.value.isEmpty ? .none : _chapterPages.value.first!.image } /// Number of pages in one chapter var count: Int { return _chapterPages.value.count } /// Chapter page size based on config var pageSize: CGSize { return _pageSize.value } // MARK: Input let zoomIn = PublishSubject<Void>() let zoomOut = PublishSubject<Void>() // MARK: Output let reload: Driver<Void> let chapterPages: Driver<List<ChapterPage>> let invalidateLayout: Driver<Void> let zoomScale: Driver<String> let headerTitle: Driver<String> let chapterTitle: Driver<String> let readingProgress: Driver<String> let pageCount: Driver<String> let zoomScroll: Driver<ScrollOffset> let disposeBag = DisposeBag() // MARK: Private fileprivate let _chapterPages = Variable(List<ChapterPage>()) fileprivate let _currentPageIndex = Variable(0) fileprivate let _pageSize = Variable(CGSize( width: Config.chapterPageSize.width, height: Config.chapterPageSize.height )) fileprivate let _zoomScale = Variable(ZoomScale(scale: 1.0)) fileprivate let chapterVM: ChapterViewModel init(chapterViewModel: ChapterViewModel) { let _chapterPages = self._chapterPages let _zoomScale = self._zoomScale let _pageSize = self._pageSize let _currentPageIndex = self._currentPageIndex chapterVM = chapterViewModel chapterPages = _chapterPages.asDriver() reload = chapterPages .asDriver() .map(void) readingProgress = _currentPageIndex .asDriver() .map { String($0 + 1) } pageCount = _chapterPages .asDriver() .map { "/ \($0.count) pages" } zoomIn .map { ZoomScale(scale: _zoomScale.value.scale + Config.chapterPageSize.zoomScaleStep) } .bind(to: _zoomScale) ==> disposeBag zoomOut .filter { (_zoomScale.value.scale - Config.chapterPageSize.zoomScaleStep) > Config.chapterPageSize.minimumZoomScale } .map { ZoomScale(scale: _zoomScale.value.scale - Config.chapterPageSize.zoomScaleStep) } .bind(to: _zoomScale) ==> disposeBag _zoomScale .asObservable() .map { zoom in CGSize( width: Int(Double(Config.chapterPageSize.width) * zoom.scale), height: Int(Double(Config.chapterPageSize.height) * zoom.scale) ) } .bind(to: _pageSize) ==> disposeBag zoomScale = _zoomScale .asDriver() .map { $0.description } invalidateLayout = _zoomScale .asDriver() .map(void) let initialMargin = PageSizeMargin(previousSize: CGSize.zero, currentSize: _pageSize.value) zoomScroll = _pageSize .asDriver() .scan(initialMargin) { previousSizeMargin, nextSize in PageSizeMargin(previousSize: previousSizeMargin.currentSize, currentSize: nextSize) } .map { ScrollOffset( marginHeight: CGFloat($0.margin.height), previousItemsCount: _currentPageIndex.value ) } headerTitle = chapterVM.number chapterTitle = chapterVM.title } subscript(index: Int) -> ChapterPageViewModel { let page = _chapterPages.value[UInt(index)] return ChapterPageViewModel(page: page) } func fetch() -> Disposable { return MangaEden .request(MangaEdenAPI.chapterPages(chapterVM.chapter.id)) .mapArray(ChapterPage.self, withRootKey: "images") .subscribe(onSuccess: { let sortedPages = $0.sorted { x, y in return x.number < y.number } self._chapterPages.value = List<ChapterPage>(fromArray: sortedPages) }) } func setCurrentPageIndex(_ index: Int) { _currentPageIndex.value = index } func setZoomScale(_ scale: String) { _zoomScale.value = ZoomScale(scale: scale) } func chapterIndexIsValid(index: Int) -> Bool { return 0 ... (count - 1) ~= index } }
54820a85882af8be8dc6f66ffdba7020
25.038278
113
0.666483
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/API/Clients/SpotlightClient.swift
mit
1
// // SpotlightClient.swift // Rocket.Chat // // Created by Matheus Cardoso on 3/28/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import RealmSwift struct SpotlightClient: APIClient { let api: AnyAPIFetcher init(api: AnyAPIFetcher) { self.api = api } func search(query: String, realm: Realm? = Realm.current, completion: @escaping RequestCompletion) { api.fetch(SpotlightRequest(query: query)) { response in switch response { case .resource(let resource): guard resource.success else { completion(nil, true) return } realm?.execute({ (realm) in var subscriptions: [Subscription] = [] resource.rooms.forEach { object in // Important note: On this API "_id" means "rid" if let roomIdentifier = object["_id"].string { if let subscription = Subscription.find(rid: roomIdentifier, realm: realm) { subscription.map(object, realm: realm) subscription.mapRoom(object, realm: realm) subscriptions.append(subscription) } else { let subscription = Subscription() subscription.identifier = roomIdentifier subscription.rid = roomIdentifier subscription.name = object["name"].string ?? "" if let typeRaw = object["t"].string, let type = SubscriptionType(rawValue: typeRaw) { subscription.type = type } subscriptions.append(subscription) } } } resource.users.forEach { object in let user = User.getOrCreate(realm: realm, values: object, updates: nil) guard let username = user.username else { return } let subscription = Subscription.find(name: username, subscriptionType: [.directMessage]) ?? Subscription() if subscription.realm == nil { subscription.identifier = subscription.identifier ?? user.identifier ?? "" subscription.otherUserId = user.identifier subscription.type = .directMessage subscription.name = user.username ?? "" subscription.fname = user.name ?? "" subscriptions.append(subscription) } } realm.add(subscriptions, update: true) }, completion: { completion(resource.raw, false) }) case .error: completion(nil, true) } } } }
da62209f7d0176624df8051b850fc726
39.74359
130
0.461611
false
false
false
false
presence-insights/pi-sample-ios-DeviceRegistration
refs/heads/master
pi-sample-ios-DeviceRegistration/ViewController.swift
apache-2.0
1
// © Copyright 2015 IBM Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import PresenceInsightsSDK class ViewController: UIViewController, UITextFieldDelegate { //hard coding the tenantID, orgID, username, password, baseURL //This information can be found in your Presence Insights UI/Dashboard let tenantID = "" let orgID = "" let username = "" let passwd = "" let baseURL = "" override func viewDidLoad() { super.viewDidLoad() self.deviceName.delegate = self self.deviceType.delegate = self self.unencryptedDataValue.delegate = self self.unencryptedDataKey.delegate = self self.datakey.delegate = self self.datavalue.delegate = self //creating a PIAdapter object with bm information piAdapter = PIAdapter(tenant: tenantID, org: orgID, baseURL: baseURL, username: username, password: passwd) //piAdapter.enableLogging() deviceType.userInteractionEnabled = false //initializing device to see if it's registered when the app is loaded. //if regsitered switch the registered switch to on. // note: i do not pull the encrypted data and unecnrypted data in the fields when the device is populated. device = PIDevice(name: " ") piAdapter.getDeviceByDescriptor(device.descriptor) { (rdevice, NSError) -> () in if((rdevice.name?.isEmpty) == nil){ } else{ //using UI thread to make teh necessary changes. dispatch_async(dispatch_get_main_queue(), { () -> Void in self.RegisterSwitch.setOn(true, animated: true) self.deviceName.text = rdevice.name self.deviceType.text = rdevice.type self.alert("Status", messageInput: "The Device is currently registered. Device Name and Type will popular based on PI information") }) print("Device is already registered") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //initializing piAdapter object and PIdevice var piAdapter : PIAdapter! var device : PIDevice! @IBOutlet weak var deviceName: UITextField! @IBOutlet weak var datakey: UITextField! @IBOutlet weak var datavalue: UITextField! @IBOutlet weak var unencryptedDataKey: UITextField! @IBOutlet weak var unencryptedDataValue: UITextField! @IBOutlet weak var deviceType: UITextField! //pop up alert and display BM information @IBAction func bmAction(sender: UIButton) { alert("BM Information", messageInput: "Username: \(username) \n Password: \(passwd) \n Tenant ID: \(tenantID) \n Org ID: \(orgID)") } //UI selection for which device Type exist in the user's PI @IBAction func DeviceTypeAction() { //gets org information piAdapter.getOrg { (org, NSError) -> () in print(org.registrationTypes); //grab the different device types let Types = org.registrationTypes print("TEST") print(Types.count) //need this dispatch to change from backend thread to UI thread dispatch_async(dispatch_get_main_queue(), { () -> Void in let alert = UIAlertController(title: "Select Device Type", message: "", preferredStyle: UIAlertControllerStyle.Alert) for Type in Types{ alert.addAction(UIAlertAction(title: "\(Type)", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction) in self.deviceType.text = Type print(Type) })) } alert.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) } } //Update action @IBAction func Action(sender: UIButton) { //adding device name to the device object device = PIDevice(name: deviceName.text!) device.type = deviceType.text //adding device type to the device object. //NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External" //method to add encrypted data // ("VALUE", key: "KEY_NAME") //checks to see if key or value is empty and throw error as necessary if( MissingText(datavalue, key: datakey) == false){ device.addToDataObject(datavalue.text!, key: datakey.text!) } //checks to see if key or value is empty and throw error as necessary for unencrypted data if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){ device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!) } //when the user flicks the switch to green //checking to see if the device is registered before updating the device. if RegisterSwitch.on { //set device register to true if the light is on device.registered=true //device is registered and will update. piAdapter.updateDevice(device, callback: { (newDevice, NSError) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Updated the Device Information") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } else { //if the device is not registered, will alert saying must register device alert("Error", messageInput: "Must Register Device Before Updating") } } //function to make keyboard disappear when pressing return. func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } @IBOutlet weak var RegisterSwitch: UISwitch! //Register Switch Action @IBAction func switchAction(sender: AnyObject) { //adding device name to the device object device = PIDevice(name: deviceName.text!) device.type = deviceType.text //adding device type to the device object. //NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External" //checks to see if key or value is empty if( MissingText(datavalue, key: datakey) == false){ device.addToDataObject(datavalue.text!, key: datakey.text!) } // checks to see if key or value is empty if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){ device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!) } if RegisterSwitch.on { //PI Device Register SDK call piAdapter.registerDevice(device, callback: { (newDevice, NSError) -> () in // newDevice is of type PIDevice. dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Registered the Device") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } else { //PI Device unregister SDK call piAdapter.unregisterDevice(device, callback: { (newDevice, NSError) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Unregistered the Device") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } } //function to easily create alert messages func alert(titleInput : String , messageInput : String){ let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } //function to check if both or none of the data value and key exist. func MissingText (value: UITextField, key : UITextField) -> Bool{ if ( (key.text! == "" && value.text! == "")){ print("here") return true } else{ print("test") return false } } }
3f4358adca5e44abec0de4078ac55a13
36.310861
151
0.576691
false
false
false
false
ivygulch/SwiftPromises
refs/heads/master
SwiftPromises/source/Synchronizer.swift
mit
1
// // Synchronizer.swift // SwiftPromises // // Created by Douglas Sjoquist on 2/25/15. // Copyright (c) 2015 Ivy Gulch LLC. All rights reserved. // import Foundation /** A simple helper class that uses dispatch_sync to emulate Objective-C's @synchronize behavior in swift classes. Example usage: ```swift let synchronizer = Synchronizer() func functionAToBeSynchronized() { synchronizer.synchronize { // this is the code to be synchronized } } func functionBToBeSynchronized() { synchronizer.synchronize { // this is the code to be synchronized } } ``` */ open class Synchronizer : NSObject { private let queue:DispatchQueue /** Creates a new synchronizer that uses a newly created, custom queue with a random name */ public override init() { let uuid = UUID().uuidString self.queue = DispatchQueue(label: "Sync.\(uuid)",attributes: []) } /** Creates a new synchronizer that uses a newly created, custom queue with a given name */ public init(queueName:String) { self.queue = DispatchQueue(label: queueName,attributes: []) } /** Creates a new synchronizer that uses an existing dispatch queue */ public init(queue:DispatchQueue) { self.queue = queue } /** - Parameter closure: the closure to be synchronized */ public func synchronize(_ closure:()->Void) { queue.sync(execute: { closure() }) } }
3e3d4f8da64c747b844e95ac1cd3f2bb
21.402985
92
0.639574
false
false
false
false
svenbacia/TraktKit
refs/heads/master
TraktKit/Sources/Resource/Generic/Resource+Request.swift
mit
1
// // Resource+Request.swift // TraktKit // // Created by Sven Bacia on 29.10.17. // Copyright © 2017 Sven Bacia. All rights reserved. // import Foundation func buildRequest(base: String, path: String, params: [String: Any]?, method: Method) -> URLRequest { func body(from params: [String: Any]?, method: Method) -> Data? { guard let params = params, method.allowsHttpBody else { return nil } return try? JSONSerialization.data(withJSONObject: params, options: []) } return buildRequest(base: base, path: path, params: params, body: body(from: params, method: method), method: method) } func buildRequest(base: String, path: String, params: [String: Any]?, body: Data?, method: Method) -> URLRequest { guard var components = URLComponents(string: base) else { fatalError("unexpected url components") } components.path = path if let params = params as? [String: String], method == .get { components.queryItems = params.map(toQueryItem) } guard let url = components.url else { fatalError("could not build url with path: \(path)") } var request = URLRequest(url: url) request.httpMethod = method.rawValue if let body = body, method.allowsHttpBody { request.httpBody = body } return request }
4f4de777f8d388e9834376c95cd3b8d6
33.72973
121
0.675486
false
false
false
false
vitortexc/MyAlertController
refs/heads/master
MyAlertController/MyAlertOverlayView.swift
mit
1
// // MyAlertOverlayView.swift // Pods // // Created by Vitor Carrasco on 28/04/17. // Copyright © 2017 Empresinha. All rights reserved. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit final class MyAlertOverlayView: UIView { // MARK: - Appearance /// The blur radius of the overlay view @objc public dynamic var blurRadius: Float { get { return Float(blurView.blurRadius) } set { blurView.blurRadius = CGFloat(newValue) } } /// Turns the blur of the overlay view on or off @objc public dynamic var blurEnabled: Bool { get { return blurView.isBlurEnabled } set { blurView.isBlurEnabled = newValue blurView.alpha = newValue ? 1 : 0 } } /// Whether the blur view should allow for /// dynamic rendering of the background @objc public dynamic var liveBlur: Bool { get { return blurView.isDynamic } set { return blurView.isDynamic = newValue } } /// The background color of the overlay view @objc public dynamic var color: UIColor? { get { return overlay.backgroundColor } set { overlay.backgroundColor = newValue } } /// The opacity of the overay view @objc public dynamic var opacity: Float { get { return Float(overlay.alpha) } set { overlay.alpha = CGFloat(newValue) } } // MARK: - Views internal lazy var blurView: FXBlurView = { let blurView = FXBlurView(frame: .zero) blurView.blurRadius = 8 blurView.isDynamic = false blurView.tintColor = UIColor.clear blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] return blurView }() internal lazy var overlay: UIView = { let overlay = UIView(frame: .zero) overlay.backgroundColor = UIColor.black overlay.autoresizingMask = [.flexibleHeight, .flexibleWidth] overlay.alpha = 0.7 return overlay }() // MARK: - Inititalizers override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View setup internal override func setupView() { // Self appearance self.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.backgroundColor = UIColor.clear self.alpha = 0 // Add subviews addSubview(blurView) addSubview(overlay) } }
e84be9ceb22f25a6fbbd7ee52cb9a950
27.020833
81
0.713755
false
false
false
false
jdbateman/OnTheMap
refs/heads/master
OnTheMap/LoginViewController.swift
mit
1
// // LoginViewController.swift // OnTheMap // // Created by john bateman on 7/23/15. // Copyright (c) 2015 John Bateman. All rights reserved. // // This file implements the LoginViewController which allows the user to create an account on Udacity, Login to a session on Udacity, or Login to Facebook on the device. import UIKit class LoginViewController: UIViewController, FBSDKLoginButtonDelegate { @IBOutlet weak var loginButton: FBSDKLoginButton! var appDelegate: AppDelegate! var activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) as UIActivityIndicatorView /* a reference to the studentLocations singleton */ let studentLocations = StudentLocations.sharedInstance() @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // get a reference to the app delegate appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // Setup facebook login... // Facebook Login loginButton.delegate = self // request access to user's facebook profile, email, and friends self.loginButton.readPermissions = ["public_profile", "email", "user_friends"] if (FBSDKAccessToken.currentAccessToken() != nil) { // The user is already logged in to Facebook on this device. appDelegate.loggedIn == true // Acquire the user's facebook user id. getFacebookUserID() } // If already logged in to Udacity or Facebook present the Tab Bar conttoller. if appDelegate.loggedIn == true { presentMapController() } // inset text in edit text fields var insetView = UIView(frame:CGRect(x:0, y:0, width:10, height:10)) emailTextField.leftViewMode = UITextFieldViewMode.Always emailTextField.leftView = insetView var insetViewPwd = UIView(frame:CGRect(x:0, y:0, width:10, height:10)) passwordTextField.leftViewMode = UITextFieldViewMode.Always passwordTextField.leftView = insetViewPwd // set placeholder text color to white in edit text fields emailTextField.attributedPlaceholder = NSAttributedString(string:"Email", attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()]) passwordTextField.attributedPlaceholder = NSAttributedString(string:"Password", attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()]) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.view.setNeedsDisplay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* User selected Login button. Attempt to login to Parse. */ @IBAction func onLoginButtonTap(sender: AnyObject) { startActivityIndicator() if let username = emailTextField.text, password = passwordTextField.text { RESTClient.sharedInstance().loginUdacity(username: username, password: password) {result, accountKey, error in if error == nil { self.appDelegate.loggedIn = true // Get the logged in user's data from the Udacity service and store the relevant elements in a studentLocation variable for retrieval later when we post the user's data to Parse. self.getLoggedInUserData(userAccountKey: accountKey) { success, studentLocation, error in if error == nil { // got valid user data back, so save it self.appDelegate.loggedInUser = studentLocation } else { // didn't get valid data back so set to default values self.appDelegate.loggedInUser = StudentLocation() } } // get student locations from Parse self.studentLocations.reset() self.studentLocations.getStudentLocations(0) { success, errorString in dispatch_async(dispatch_get_main_queue()) { self.stopActivityIndicator() } if success == false { if let errorString = errorString { OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: errorString) } else { OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: "Unknown error") } } else { // successfully logged in - save the user's account key self.appDelegate.loggedInUser?.uniqueKey = accountKey self.presentMapController() } } self.presentMapController() } else { self.appDelegate.loggedIn = false dispatch_async(dispatch_get_main_queue()) { self.stopActivityIndicator() self.parseLoginError(error!) OTMError(viewController:self).displayErrorAlertView("Login Error", message: error!.localizedDescription) } } } } } /* @brief Get user data for logged in user @param (in) userAccountKey: The Udacity account key for the user account. */ func getLoggedInUserData(#userAccountKey: String, completion: (success: Bool, studentLocation: StudentLocation?, error: NSError?) -> Void) { RESTClient.sharedInstance().getUdacityUser(userID: userAccountKey) { result, studentLocation, error in if error == nil { completion(success: true, studentLocation: studentLocation, error: nil) } else { println("error getUdacityUser()") completion(success: false, studentLocation: nil, error: error) } } } /* SignUp button selected. Open Udacity signup page in the Safari web browser. */ @IBAction func onSignUpButtonTap(sender: AnyObject) { let signupUrl = RESTClient.Constants.udacityBaseURL + RESTClient.Constants.udacitySignupMethod if let requestUrl = NSURL(string: signupUrl) { UIApplication.sharedApplication().openURL(requestUrl) } } /* Modally present the MapViewController on the main thread. */ func presentMapController() { dispatch_async(dispatch_get_main_queue()) { //self.displayMapViewController() self.performSegueWithIdentifier("LoginToTabBarSegueID", sender: self) } } /* show activity indicator */ func startActivityIndicator() { activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge view.addSubview(activityIndicator) activityIndicator.startAnimating() } /* hide acitivity indicator */ func stopActivityIndicator() { activityIndicator.stopAnimating() } // Facebook Delegate Methods /* The Facebook login button was selected. Get the user's Facebook Id and transition to the Map view controller. */ func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { appDelegate.loggedIn = true if ((error) != nil) { // Process the error } else if result.isCancelled { // Handle the cancellation } else { // Acquire the user's facebook user id getFacebookUserID() // Verify permissions were granted. if result.grantedPermissions.contains("email") { println("facebook email permission granted") } if result.grantedPermissions.contains("public_profile") { println("facebook public_profile permission granted") } if result.grantedPermissions.contains("user_friends") { println("facebook user_friends permission granted") } // present the MapViewController presentMapController() } } /* The user selected the logout facebook button. */ func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { appDelegate.loggedIn = false } /* Acquire the user's Facebook user id */ func getFacebookUserID() { //let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let fbToken = FBSDKAccessToken.currentAccessToken() self.appDelegate.loggedInUser?.uniqueKey = fbToken.userID } /* Identify the UITextView responsible for the error, and shake the appropriate UITextView. */ func parseLoginError(error: NSError) { let message = error.localizedDescription // Handle case where the username or password was not supplied if error.code == 400 { //if message.lowercaseString.rangeOfString("Error 400") != nil && message.lowercaseString.rangeOfString("Missing parameter") != nil { if message.lowercaseString.rangeOfString("username") != nil { self.shake(self.emailTextField) } else if message.lowercaseString.rangeOfString("password") != nil { self.shake(self.passwordTextField) } } // Handle case where username or password was incorrect else if error.code == 403 && message.lowercaseString.rangeOfString("Account not found") != nil || message.lowercaseString.rangeOfString("invalid credentials") != nil { self.shake(self.emailTextField) self.shake(self.passwordTextField) } } /* Create a shake animation for the specified textField. */ func shake(textField: UITextField) { let shakeAnimation = CABasicAnimation(keyPath: "position") shakeAnimation.duration = 0.1 shakeAnimation.repeatCount = 3 shakeAnimation.autoreverses = true shakeAnimation.fromValue = NSValue(CGPoint: CGPointMake(textField.center.x - 7, textField.center.y - 2)) shakeAnimation.toValue = NSValue(CGPoint: CGPointMake(textField.center.x + 7, textField.center.y + 2)) textField.layer.addAnimation(shakeAnimation, forKey: "position") } }
86dd0ee50f63a6badedeb6075d37bd60
42.042308
198
0.606023
false
false
false
false
twtstudio/WePeiYang-iOS
refs/heads/master
WePeiYang/PartyService/Controller/TwentyCourseScoreViewController.swift
mit
1
// // TwentyCourseScoreViewController.swift // WePeiYang // // Created by JinHongxu on 16/8/14. // Copyright © 2016年 Qin Yubo. All rights reserved. // import Foundation class TwentyCourseScoreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var scoreList = [] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self Applicant.sharedInstance.get20score({ self.scoreList = Applicant.sharedInstance.scoreOf20Course self.tableView.reloadData() }) } //iOS 8 fucking bug init(){ super.init(nibName: "TwentyCourseScoreViewController", bundle: nil) //print("haha") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print(Applicant.sharedInstance.scoreOf20Course.count) return scoreList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let dict = scoreList[indexPath.row] let cell = ScoreTableViewCell(title: dict.objectForKey("course_name") as! String, score: dict.objectForKey("score") as! String, completeTime: dict.objectForKey("complete_time") as! String) cell.selectionStyle = .None //cell?.textLabel?.text = Applicant.sharedInstance.scoreOf20Course[indexPath.row].objectForKey("course_name") return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section == 0 else { return nil } let view = UIView(frame: CGRect(x: 0, y: 0, width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!, height: 40)) let titleLabel = UILabel(text: "课程名称") let scoreLabel = UILabel(text: "成绩") let timeLabel = UILabel(text: "完成时间") titleLabel.font = UIFont.boldSystemFontOfSize(13.0) scoreLabel.font = UIFont.boldSystemFontOfSize(13.0) timeLabel.font = UIFont.boldSystemFontOfSize(13.0) view.addSubview(titleLabel) view.addSubview(scoreLabel) view.addSubview(timeLabel) timeLabel.snp_makeConstraints { make in make.right.equalTo(view).offset(-8) make.centerY.equalTo(view) } scoreLabel.snp_makeConstraints { make in make.right.equalTo(timeLabel.snp_left).offset(-56) make.centerY.equalTo(view) } titleLabel.snp_makeConstraints { make in make.left.equalTo(view).offset(8) make.centerY.equalTo(view) } return view } }
a93f5b16c95d286c7c4f082113d0297c
30.101852
196
0.616438
false
false
false
false
zhubinchen/MarkLite
refs/heads/master
MarkLite/Utils/ActivityIndicator.swift
gpl-3.0
2
// // UIView+Loading.swift // Markdown // // Created by 朱炳程 on 2020/5/13. // Copyright © 2020 zhubch. All rights reserved. // import UIKit class ActivityIndicator { var inticators = [UIView]() var toast: UIView? static let shared = ActivityIndicator() class func showError(withStatus: String?) { showMessage(message: withStatus) } class func showSuccess(withStatus: String?) { showMessage(message: withStatus) } class func showMessage(message: String?) { guard let v = UIApplication.shared.keyWindow else { return } ActivityIndicator.shared.toast?.removeFromSuperview() let bg = UIView() ActivityIndicator.shared.toast = bg bg.setBackgroundColor(.primary) bg.cornerRadius = 8 v.addSubview(bg) bg.snp.makeConstraints { maker in maker.center.equalToSuperview() maker.width.lessThanOrEqualToSuperview().multipliedBy(0.8) maker.height.greaterThanOrEqualTo(30) } let label = UILabel() label.text = message label.setTextColor(.background) label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 16) bg.addSubview(label) label.snp.makeConstraints { maker in maker.top.equalToSuperview().offset(10) maker.left.equalToSuperview().offset(10) maker.right.equalToSuperview().offset(-10) maker.bottom.equalToSuperview().offset(-10) } UIView.animate(withDuration: 0.5, delay: 1.0, options: .curveLinear, animations: { bg.alpha = 0 }) DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { ActivityIndicator.shared.toast?.removeFromSuperview() } } class func show(on parent: UIView? = UIApplication.shared.keyWindow) { guard let v = parent else { return } let container = UIView() container.backgroundColor = .clear container.frame = v.bounds v.addSubview(container) container.snp.makeConstraints { maker in maker.edges.equalToSuperview() } let loadingView = UIView() loadingView.isHidden = true let size = CGSize(width: 30, height: 30) container.addSubview(loadingView) loadingView.snp.makeConstraints { maker in maker.center.equalToSuperview() maker.size.equalTo(size) } if v == UIApplication.shared.keyWindow { setUpAnimation(in: loadingView.layer, size: size, color: ColorCenter.shared.secondary.value) } else { setUpAnimation(in: loadingView.layer, size: size, color: ColorCenter.shared.secondary.value) } ActivityIndicator.shared.inticators.append(container) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { loadingView.isHidden = false if v == UIApplication.shared.keyWindow { container.backgroundColor = UIColor(white: 0, alpha: 0.2) } } print("ActivityIndicator add\(ActivityIndicator.shared.inticators.count)") } class func dismiss() { guard let v = UIApplication.shared.keyWindow else { return } dismissOnView(v) } class func dismissOnView(_ view: UIView) { guard let v = ActivityIndicator.shared.inticators.first(where: { $0.superview == view }) else { return } v.removeFromSuperview() ActivityIndicator.shared.inticators = ActivityIndicator.shared.inticators.filter{ $0.window != nil } print("ActivityIndicator remove\(ActivityIndicator.shared.inticators.count)") } class func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = 1 animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw lines for i in 0 ..< 5 { let line: CAShapeLayer = CAShapeLayer() var path: UIBezierPath = UIBezierPath() let size = CGSize(width: lineSize, height: size.height) path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height), cornerRadius: size.width / 2) line.fillColor = color.cgColor line.backgroundColor = nil line.path = path.cgPath line.frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: size.width, height: size.height) animation.beginTime = Double(integerLiteral: Int64(i)) * 0.1 + CACurrentMediaTime() line.add(animation, forKey: "animation") layer.addSublayer(line) } } }
000fcfa7b75ec5fbab8de6f539a4c0d6
36.119718
112
0.611079
false
false
false
false
zhoudengfeng8/EmptyDataSetInfo
refs/heads/master
EmptyDataSetInfo/EmptyInfoTableViewCell.swift
mit
1
// // EmptyInfoTableViewCell.swift // Kirin-iOS // // Created by zhou dengfeng derek on 1/12/16. // // import UIKit @objc protocol EmptyInfoTableViewCellDelegate: class { @objc optional func emptyInfoTableViewCellDidTapInfoButton(cell: EmptyInfoTableViewCell) } class EmptyInfoTableViewCell: UITableViewCell { weak var delegate: EmptyInfoTableViewCellDelegate? @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var infoImageView: UIImageView! @IBOutlet weak var infoButton: UIButton! override func awakeFromNib() { super.awakeFromNib() setupInfoButton() } private func setupInfoButton() { layoutIfNeeded() infoButton.layer.cornerRadius = 4.0 infoButton.layer.borderColor = UIColor(red: 0, green: 122/255.0, blue: 1, alpha: 1).cgColor infoButton.layer.borderWidth = 1.0 infoButton.contentEdgeInsets = UIEdgeInsetsMake(5, 15, 5, 15) infoButton.addTarget(self, action: #selector(tapInfoButton(_:)), for: .touchUpInside) } func tapInfoButton(_ sender: UIButton) { _ = self.delegate?.emptyInfoTableViewCellDidTapInfoButton?(cell: self) } }
e1e7937d4032eeeaf1046108e14bde65
27.47619
99
0.685619
false
false
false
false
HeartRateLearning/HRLApp
refs/heads/master
HRLApp/Common/HealthStore/HealthStoreFactory.swift
mit
1
// // HealthStoreFactory.swift // HRLApp // // Created by Enrique de la Torre (dev) on 01/02/2017. // Copyright © 2017 Enrique de la Torre. All rights reserved. // import Foundation import HealthKit // MARK: - Main body final class HealthStoreFactory { // MARK: - Private properties fileprivate var state = State.rejected } // MARK: - HealthStoreFactoryProtocol methods extension HealthStoreFactory: HealthStoreFactoryProtocol { func setup() { guard !isRequestingAuthorization() else { print("Already requesting authorization") return } requestAuthorization() } func makeHeartRateReader() -> HeartRateReaderProtocol? { guard let currentStore = currentHealthStore() else { return nil } return HeartRateReader(store: currentStore) } func makeWorkoutWriter() -> WorkoutWriterProtocol? { guard let currentStore = currentHealthStore() else { return nil } return WorkoutWriter(store: currentStore) } } // MARK: - Private body private extension HealthStoreFactory { // MARK: - Type definitions enum State { case requesting case rejected case authorized(HKHealthStore) init(isAuthorized: Bool, store: HKHealthStore) { self = isAuthorized ? .authorized(store) : .rejected } } // MARK: - Constants enum Constants { static let typesToShare = Set(arrayLiteral: WorkoutWriter.workoutType) static let typesToRead = Set(arrayLiteral: HeartRateReader.heartRateType) } // MARK: - Private methods func isRequestingAuthorization() -> Bool { var isRequesting = false switch state { case .requesting: isRequesting = true default: isRequesting = false } return isRequesting } func requestAuthorization() { guard HKHealthStore.isHealthDataAvailable() else { print("Health data is NOT available") state = .rejected return } state = .requesting let store = HKHealthStore() let completion = { [weak self] (success: Bool, error: Error?) in if !success { print("Request authorization failed: \(error)") } DispatchQueue.main.async { self?.state = State(isAuthorized: success, store: store) } } store.requestAuthorization(toShare: Constants.typesToShare, read: Constants.typesToRead, completion: completion) } func currentHealthStore() -> HKHealthStore? { var currentStore: HKHealthStore? switch state { case .authorized(let store): currentStore = store default: currentStore = nil } return currentStore } }
307177004f715646c1b9fb9b9f761ad9
22.062016
81
0.591597
false
false
false
false
adamahrens/noisily
refs/heads/master
Noisily/Noisily/NoisePlayManager.swift
mit
1
// // NoisePlayManager.swift // Noisily // // Created by Adam Ahrens on 3/19/15. // Copyright (c) 2015 Appsbyahrens. All rights reserved. // import AVFoundation class NoisePlayerManager: NSObject, AVAudioPlayerDelegate { private var players = [Noise : AVAudioPlayer]() /** Toggles playing the noise. If currently playing turns it off, otherwise on - parameter noise: The Noise to toggle on/off */ func toggleNoise(noise: Noise) { let noiseResource = noise.soundFilePath() var error: NSError? // Already have a player going for the noise if let player = players[noise] { player.stop() players[noise] = nil } else { // Need to start a new player let player: AVAudioPlayer! do { player = try AVAudioPlayer(contentsOfURL: noiseResource) } catch let error1 as NSError { error = error1 player = nil } player.volume = 0.5 player.numberOfLoops = -1 player.delegate = self player.prepareToPlay() player.play() players[noise] = player } if (error != nil) { print("Error constructing player \(error)") } } /** Determines if a noise is currently playing */ func noiseIsPlaying(noise: Noise) -> Bool { return players[noise] != nil } /** Adjusts the volume level of a noise if it's currently playing - parameter noise: The Noise to adjust - parameter volume: Volume level between 0.0 and 1.0 (inclusive) */ func adjustVolumeLevel(noise: Noise, volume: Double) { if let player = players[noise] { assert(volume >= 0.0 && volume <= 1.0, "Volume has to been in 0.0 - 1.0 range") player.volume = Float(volume) } } }
36084e5868f3bf603a8756c740348a1d
27.661765
91
0.560062
false
false
false
false
box/box-ios-sdk
refs/heads/main
Sources/Core/Errors/BoxSDKError.swift
apache-2.0
1
// // BoxSDKError.swift // BoxSDK-iOS // // Created by Sujay Garlanka on 10/14/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Box SDK Error public enum BoxSDKErrorEnum: BoxEnum { // swiftlint:disable cyclomatic_complexity /// Box client was destroyed case clientDestroyed /// URL is invalid case invalidURL(urlString: String) /// The requested resource was not found case notFound(String) /// Object needed in closure was deallocated case instanceDeallocated(String) /// Could not decode or encode keychain data case keychainDataConversionError /// Value not found in Keychain case keychainNoValue /// Unhandled keychain error case keychainUnhandledError(String) /// Request has hit the maximum number of retries case rateLimitMaxRetries /// Value for key is of an unexpected type case typeMismatch(key: String) /// Value for key is not one of the accepted values case valueMismatch(key: String, value: String, acceptedValues: [String]) /// Value for key is of a valid type, but was not able to convert value to expected type case invalidValueFormat(key: String) /// Key was not present case notPresent(key: String) /// The file representation couldn't be made case representationCreationFailed /// Error with TokenStore operation (write, read or clear) case tokenStoreFailure /// Unsuccessful token retrieval. Token not found case tokenRetrieval /// OAuth web session authorization failed due to invalid redirect configuration case invalidOAuthRedirectConfiguration /// Couldn't obtain authorization code from OAuth web session result case invalidOAuthState /// Unauthorized request to API case unauthorizedAccess /// Unsuccessful refresh token retrieval. Token not found in the retrieved TokenInfo object case refreshTokenNotFound /// Access token has expired case expiredToken /// Authorization with JWT token failed case jwtAuthError /// Authorization with CCG token failed case ccgAuthError /// Couldn't create paging iterable for non-paged response case nonIterableResponse /// The end of the list was reached case endOfList /// Custom error message case customValue(String) public init(_ value: String) { switch value { case "clientDestroyed": self = .clientDestroyed case "keychainDataConversionError": self = .keychainDataConversionError case "keychainNoValue": self = .keychainNoValue case "rateLimitMaxRetries": self = .rateLimitMaxRetries case "representationCreationFailed": self = .representationCreationFailed case "tokenStoreFailure": self = .tokenStoreFailure case "tokenRetrieval": self = .tokenRetrieval case "invalidOAuthRedirectConfiguration": self = .invalidOAuthRedirectConfiguration case "invalidOAuthState": self = .invalidOAuthState case "unauthorizedAccess": self = .unauthorizedAccess case "refreshTokenNotFound": self = .refreshTokenNotFound case "expiredToken": self = .expiredToken case "jwtAuthError": self = .jwtAuthError case "nonIterableResponse": self = .nonIterableResponse case "endOfList": self = .endOfList default: self = .customValue(value) } } public var description: String { switch self { case .clientDestroyed: return "Tried to use a BoxClient instance that was already destroyed" case let .invalidURL(urlString): return "Invalid URL: \(urlString)" case let .notFound(message): return "Not found: \(message)" case let .instanceDeallocated(message): return "Object needed in closure was deallocated: \(message)" case .keychainDataConversionError: return "Could not decode or encode data for or from keychain" case .keychainNoValue: return "Value not found in Keychain" case let .keychainUnhandledError(message): return "Unhandled keychain error: \(message)" case .rateLimitMaxRetries: return "Request has hit the maximum number of retries" case let .typeMismatch(key): return "Value for key \(key) was of an unexpected type" case let .valueMismatch(key, value, acceptedValues): return "Value for key \(key) is \(value), which is not one of the accepted values [\(acceptedValues.map { "\(String(describing: $0))" }.joined(separator: ", "))]" case let .invalidValueFormat(key): return "Value for key \(key) is of a valid type, but was not able to convert value to expected type" case let .notPresent(key): return "Key \(key) was not present" case .representationCreationFailed: return "The file representation could not be made" case .tokenStoreFailure: return "Could not finish the operation (write, read or clear) on TokenStore object" case .tokenRetrieval: return "Unsuccessful token retrieval. Token was not found" case .invalidOAuthRedirectConfiguration: return "Failed OAuth web session authorization" case .invalidOAuthState: return "Couldn't obtain authorization code from OAuth web session success result" case .unauthorizedAccess: return "Unauthorized request to API" case .refreshTokenNotFound: return "Unsuccessful refresh token retrieval. Token was not found in the retrieved TokenInfo object" case .expiredToken: return "Access token has expired" case .jwtAuthError: return "Authorization with JWT token failed" case .ccgAuthError: return "Client Credentials Grant authorization failed" case .nonIterableResponse: return "Could not create paging iterable for non-paged response" case .endOfList: return "The end of the list has been reached" case let .customValue(userValue): return userValue } } // swiftlint:enable cyclomatic_complexity } extension BoxSDKErrorEnum: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self = BoxSDKErrorEnum(value) } } /// Describes general SDK errors public class BoxSDKError: Error { /// Type of error public var errorType: String /// Error message public var message: BoxSDKErrorEnum /// Stack trace public var stackTrace: [String] /// Error public var error: Error? init(message: BoxSDKErrorEnum = "Internal SDK Error", error: Error? = nil) { errorType = "BoxSDKError" self.message = message stackTrace = Thread.callStackSymbols self.error = error } /// Get a dictionary representing BoxSDKError public func getDictionary() -> [String: Any] { var dict = [String: Any]() dict["errorType"] = errorType dict["message"] = message.description dict["stackTrace"] = stackTrace dict["error"] = error?.localizedDescription return dict } } extension BoxSDKError: CustomStringConvertible { /// Provides error JSON string if found. public var description: String { guard let encodedData = try? JSONSerialization.data(withJSONObject: getDictionary(), options: [.prettyPrinted, .sortedKeys]), let JSONString = String(data: encodedData, encoding: .utf8) else { return "<Unparsed Box Error>" } return JSONString.replacingOccurrences(of: "\\", with: "") } } extension BoxSDKError: LocalizedError { public var errorDescription: String? { return message.description } }
555e390811d17b99d52722c3f6a17f93
36.877358
174
0.656663
false
false
false
false
mownier/Umalahokan
refs/heads/master
Umalahokan/Source/Transition/ContactListTransitionAnimator.swift
mit
1
// // ContactListTransitionAnimator.swift // Umalahokan // // Created by Mounir Ybanez on 04/03/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class ContactListTransitionAnimator: DrawerMenuTransitionDelegate { weak var view: ContactListView? private(set) var toX: CGFloat! private(set) var toBackgroundColor: UIColor! func dismissalPreAnimation(transition: DrawerMenuTransition) { guard let view = view else { return } toX = -max(view.tableView.frame.width, view.searchTextField.frame.width) toBackgroundColor = toBackgroundColor.withAlphaComponent(0.0) } func dismissalAnimation(transition: DrawerMenuTransition) { animate() } func presentationPreAnimation(transition: DrawerMenuTransition) { guard let view = view else { return } let theme = UITheme() view.setNeedsLayout() view.layoutIfNeeded() toX = 0 toBackgroundColor = theme.color.violet.withAlphaComponent(0.5) let fromX = -max(view.tableView.frame.width, view.searchTextField.frame.width) view.backgroundColor = toBackgroundColor.withAlphaComponent(0.0) view.tableView.frame.origin.x = fromX view.searchTextField.frame.origin.x = fromX } func presentationAnimation(transition: DrawerMenuTransition) { animate() } private func animate() { guard let view = view else { return } view.backgroundColor = toBackgroundColor view.tableView.frame.origin.x = toX view.searchTextField.frame.origin.x = toX } }
579f27c6739144e5d5008eb6908228ad
28.45614
86
0.655152
false
false
false
false
realgreys/RGPageMenu
refs/heads/master
RGPageMenu/Classes/RGPageMenuController.swift
mit
1
// // PageMenuController.swift // paging // // Created by realgreys on 2016. 5. 10.. // Copyright © 2016 realgreys. All rights reserved. // import UIKit @objc public protocol RGPageMenuControllerDelegate: class { optional func willMoveToPageMenuController(viewController: UIViewController, nextViewController: UIViewController) optional func didMoveToPageMenuController(viewController: UIViewController) } public class RGPageMenuController: UIViewController { weak public var delegate: RGPageMenuControllerDelegate? private var menuView: MenuView! private var options: RGPageMenuOptions! private var menuTitles: [String] { return viewControllers.map { return $0.title ?? "Menu" } } private var pageViewController: UIPageViewController! private(set) var currentPage = 0 private var viewControllers: [UIViewController]! // MARK: - Lifecycle public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(viewControllers: [UIViewController], options: RGPageMenuOptions) { super.init(nibName: nil, bundle: nil) configure(viewControllers, options: options) } public convenience init(viewControllers: [UIViewController]) { self.init(viewControllers: viewControllers, options: RGPageMenuOptions()) } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) menuView.moveToMenu(currentPage, animated: false) } // MARK: - Layout private func setupMenuView() { menuView = MenuView(menuTitles: menuTitles, options: options) menuView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(menuView) addTapGestureHandlers() } private func layoutMenuView() { // cleanup // NSLayoutConstraint.deactivateConstraints(menuView.constraints) let viewsDictionary = ["menuView": menuView] let metrics = ["height": options.menuHeight] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuView]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints: [NSLayoutConstraint] switch options.menuPosition { case .Top: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView(height)]", options: [], metrics: metrics, views: viewsDictionary) case .Bottom: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView(height)]|", options: [], metrics: metrics, views: viewsDictionary) } NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) menuView.setNeedsLayout() menuView.layoutIfNeeded() } private func setupPageView() { pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) pageViewController.delegate = self pageViewController.dataSource = self let childViewControllers = [ viewControllers[currentPage] ] pageViewController.setViewControllers(childViewControllers, direction: .Forward, animated: false, completion: nil) addChildViewController(pageViewController) pageViewController.view.frame = .zero pageViewController.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(pageViewController.view) pageViewController.didMoveToParentViewController(self) } private func layoutPageView() { let viewsDictionary = ["pageView": pageViewController.view, "menuView": menuView] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageView]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints: [NSLayoutConstraint] switch options.menuPosition { case .Top: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView][pageView]|", options: [], metrics: nil, views: viewsDictionary) case .Bottom: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pageView][menuView]", options: [], metrics: nil, views: viewsDictionary) } NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) view.setNeedsLayout() view.layoutIfNeeded() } private func validateDefaultPage() { guard options.defaultPage >= 0 && options.defaultPage < options.menuItemCount else { NSException(name: "PageMenuException", reason: "default page is not valid!", userInfo: nil).raise() return } } private func indexOfViewController(viewController: UIViewController) -> Int { return viewControllers.indexOf(viewController) ?? NSNotFound } // MARK: - Gesture handler private func addTapGestureHandlers() { menuView.menuItemViews.forEach { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture)) gestureRecognizer.numberOfTapsRequired = 1 $0.addGestureRecognizer(gestureRecognizer) } } func handleTapGesture(recognizer: UITapGestureRecognizer) { guard let menuItemView = recognizer.view as? MenuItemView else { return } guard let page = menuView.menuItemViews.indexOf(menuItemView) where page != menuView.currentPage else { return } moveToPage(page) } // MARK: - public public func configure(viewControllers: [UIViewController], options: RGPageMenuOptions) { let menuItemCount = viewControllers.count guard menuItemCount > 0 else { NSException(name: "PageMenuException", reason: "child view controller is empty!", userInfo: nil).raise() return } self.viewControllers = viewControllers self.options = options self.options.menuItemCount = menuItemCount validateDefaultPage() currentPage = options.defaultPage setupMenuView() layoutMenuView() setupPageView() layoutPageView() } public func moveToPage(page: Int, animated: Bool = true) { guard page < options.menuItemCount && page != currentPage else { return } let direction: UIPageViewControllerNavigationDirection = page < currentPage ? .Reverse : .Forward // page 이동 currentPage = page % viewControllers.count // for infinite loop // menu 이동 menuView.moveToMenu(currentPage, animated: animated) let childViewControllers = [ viewControllers[currentPage] ] pageViewController.setViewControllers(childViewControllers, direction: direction, animated: animated, completion: nil) } } extension RGPageMenuController: UIPageViewControllerDelegate { // MARK: - UIPageViewControllerDelegate public func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { if let nextViewController = pendingViewControllers.first { let index = indexOfViewController(nextViewController) guard index != NSNotFound else { return } currentPage = index menuView.moveToMenu(currentPage, animated: true) if let viewController = pageViewController.viewControllers?.first { // delegate가 있으면 notify delegate?.willMoveToPageMenuController?(viewController, nextViewController: nextViewController) } } } public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if !completed { if let previousViewController = previousViewControllers.first { let index = indexOfViewController(previousViewController) guard index != NSNotFound else { return } currentPage = index menuView.moveToMenu(currentPage, animated: true) } } else { if let nextViewController = pageViewController.viewControllers?.first { // delegate가 있으면 notify delegate?.didMoveToPageMenuController?(nextViewController) } } } } extension RGPageMenuController: UIPageViewControllerDataSource { // MARK: - UIPageViewControllerDataSource public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let index = indexOfViewController(viewController) guard index != 0 && index != NSNotFound else { return nil } return viewControllers[index - 1] } public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let index = indexOfViewController(viewController) guard index < viewControllers.count - 1 && index != NSNotFound else { return nil } return viewControllers[index + 1] } }
3ab5b5b44d3e6f46d47c5aacef718cff
40.017857
195
0.564475
false
false
false
false
KlubJagiellonski/pola-ios
refs/heads/master
BuyPolish/Pola/UI/ProductSearch/Keyboard/KeyboardViewController.swift
gpl-2.0
1
import AudioToolbox import UIKit protocol KeyboardViewControllerDelegate: AnyObject { func keyboardViewController(_ keyboardViewController: KeyboardViewController, didConfirmWithCode code: String) } final class KeyboardViewController: UIViewController { let barcodeValidator: BarcodeValidator fileprivate let barcode = KeyboardBarcode(code: "") weak var delegate: KeyboardViewControllerDelegate? init(barcodeValidator: BarcodeValidator) { self.barcodeValidator = barcodeValidator super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private var castedView: KeyboardView! { view as? KeyboardView } override func loadView() { view = KeyboardView() } override func viewDidLoad() { super.viewDidLoad() castedView.numberButtons.forEach { $0.addTarget(self, action: #selector(enterNumber(sender:)), for: .touchUpInside) } castedView.okButton.addTarget(self, action: #selector(confirm), for: .touchUpInside) castedView.textView.removeButton.addTarget(self, action: #selector(removeLastNumber), for: .touchUpInside) castedView.textView.codeLabel.delegate = self castedView.textView.codeLabel.accessibilityIdentifier = NSStringFromClass(KeyboardLabel.self) } @objc private func enterNumber(sender: UIButton) { playSound() let number = sender.tag barcode.append(number: number) castedView.textView.codeLabel.text = barcode.code updateCodeLabel() playSound() } @objc private func removeLastNumber() { playSound() barcode.removeLast() updateCodeLabel() } @objc private func confirm() { playSound() if let code = castedView.textView.code, barcodeValidator.isValid(barcode: code) { delegate?.keyboardViewController(self, didConfirmWithCode: code) } else { castedView.textView.showErrorMessage() } } private func playSound() { AudioServicesPlaySystemSound(1104) } fileprivate func updateCodeLabel() { castedView.textView.codeLabel.text = barcode.code castedView.textView.hideErrorMessage() } } extension KeyboardViewController: KeyboardLabelDelegate { func keyboardLabelIsPasteAvailable(_: KeyboardLabel, pasteboardContent: String?) -> Bool { let isPasteboardNotEmpty = pasteboardContent?.isNotEmpty ?? false return isPasteboardNotEmpty && barcode.isAppendable } func keyboardLabelUserDidTapPaste(_: KeyboardLabel, pasteboardContent: String?) { guard let pasteboardContent = pasteboardContent else { return } barcode.append(string: pasteboardContent) updateCodeLabel() } func keyboardLabelUserDidTapPasteAndActivate(_ label: KeyboardLabel, pasteboardContent: String?) { keyboardLabelUserDidTapPaste(label, pasteboardContent: pasteboardContent) confirm() } func keyboardLabelUserDidRemoveContent(_: KeyboardLabel) { barcode.removeAll() updateCodeLabel() } }
290b1ab3471a7555162dd248ea90502b
30.365385
125
0.685162
false
false
false
false
che1404/RGViperChat
refs/heads/master
RGViperChat/ChatList/DataManager/API/ChatListAPIDataManager.swift
mit
1
// // Created by Roberto Garrido // Copyright (c) 2017 Roberto Garrido. All rights reserved. // import Foundation import FirebaseDatabase import FirebaseAuth class ChatListAPIDataManager: ChatListAPIDataManagerInputProtocol { let rootRef = Database.database().reference() weak var newChatListener: NewChatListenerProtocol? var newChatsObserverHandler: UInt = 0 func fetchChats(completion: @escaping (Result<[Chat]>) -> Void) { guard let firebaseUser = Auth.auth().currentUser else { completion(.failure(NSError(domain: "fetchChats", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"]))) return } rootRef.child("User/\(firebaseUser.uid)").observeSingleEvent(of: .value, with: { snapshot in if let userValues = snapshot.value as? [String: Any], let senderDisplayName = userValues["name"] as? String, let userChats = userValues["chats"] as? [String: Any] { var chats: [Chat] = [] let dispatchGroup = DispatchGroup() for chatDict in userChats { let chatKey = chatDict.key // Get the chat info dispatchGroup.enter() self.rootRef.child("Chat/\(chatKey)").observeSingleEvent(of: .value, with: { snapshot in let chat = Chat(chatID: chatKey, displayName: "", senderID: firebaseUser.uid, senderDisplayName: senderDisplayName, receiverID: "", lastMessage: "") chat.senderID = firebaseUser.uid if let chatDictionary = snapshot.value as? [String: Any], let users = chatDictionary["users"] as? [String: Any] { var lastMessage = "" if let message = chatDictionary["lastMessage"] as? String { lastMessage = message } for user in users where user.key != firebaseUser.uid { if let userDisplayName = user.value as? String { chat.displayName = userDisplayName chat.receiverID = user.key chat.lastMessage = lastMessage chats.append(chat) break } } } dispatchGroup.leave() }) } dispatchGroup.notify(queue: .main, execute: { completion(.success(chats)) }) } else { completion(.success([])) } }) } func logout() -> Bool { do { try Auth.auth().signOut() return true } catch (let error) { print(error.localizedDescription) return false } } func startListeningForNewChats(listener: NewChatListenerProtocol) { newChatListener = listener guard let firebaseUser = Auth.auth().currentUser else { return } newChatsObserverHandler = rootRef.child("User/\(firebaseUser.uid)/chats").observe(.childAdded, with: { [weak self] chatSnapshot in let chatID = chatSnapshot.key let senderID = firebaseUser.uid var receiverID = "" self?.rootRef.child("Chat/\(chatID)/users").observeSingleEvent(of: .value, with: { snapshot in guard let chatUsersDict = snapshot.value as? [String: Any] else { return } for chatUser in chatUsersDict where chatUser.key != firebaseUser.uid { receiverID = chatUser.key break } self?.rootRef.child("User/\(receiverID)/name").observeSingleEvent(of: .value, with: { snapshot in guard let receiverName = snapshot.value as? String else { return } self?.rootRef.child("User/\(firebaseUser.uid)/name").observeSingleEvent(of: .value, with: { snapshot in guard let senderName = snapshot.value as? String else { return } self?.rootRef.child("Chat/\(chatID)/lastMessge").observeSingleEvent(of: .value, with: { snapshot in var lastMessage = "" if let message = snapshot.value as? String { lastMessage = message } let chat = Chat(chatID: chatID, displayName: receiverName, senderID: senderID, senderDisplayName: senderName, receiverID: receiverID, lastMessage: lastMessage) self?.newChatListener?.chatAdded(chat: chat) }) }) }) }) }) } }
22d014fde49b3dfc02e84e22a9130b87
41.366667
187
0.508655
false
false
false
false
apple/swift-llbuild
refs/heads/main
products/llbuildSwift/BuildDBBindings.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for Swift project authors // This file contains Swift bindings for the llbuild C API. #if canImport(Darwin) import Darwin.C #elseif os(Windows) import ucrt import WinSDK #elseif canImport(Glibc) import Glibc #else #error("Missing libc or equivalent") #endif import Foundation // We don't need this import if we're building // this file as part of the llbuild framework. #if !LLBUILD_FRAMEWORK import llbuild #endif public typealias KeyID = UInt64 public typealias KeyType = [UInt8] public typealias ValueType = [UInt8] /// Defines the result of a call to fetch all keys from the database /// Wraps calls to the llbuild database, but all results are fetched and available with this result public final class BuildDBKeysResult { /// Opaque pointer to the actual result object private let result: OpaquePointer fileprivate init(result: OpaquePointer) { self.result = result } private lazy var _count: Int = Int(llb_database_fetch_result_get_count(result)) deinit { llb_database_destroy_fetch_result(result) } } public final class BuildDBKeysWithResult { /// Opaque pointer to the actual result object private let result: OpaquePointer fileprivate init(result: OpaquePointer) { self.result = result assert(llb_database_fetch_result_contains_rule_results(result)) } private lazy var _count: Int = Int(llb_database_fetch_result_get_count(result)) deinit { llb_database_destroy_fetch_result(result) } } extension BuildDBKeysResult: Collection { public typealias Index = Int public typealias Element = BuildKey public var startIndex: Index { return 0 } public var endIndex: Index { return self._count + startIndex } public subscript(index: Index) -> Iterator.Element { guard (startIndex..<endIndex).contains(index) else { fatalError("Index \(index) is out of bounds (\(startIndex)..<\(endIndex))") } return BuildKey.construct(key: llb_database_fetch_result_get_key_at_index(self.result, Int32(index))) } public func index(after i: Index) -> Index { return i + 1 } } extension BuildDBKeysWithResult: Collection { public struct Element: Hashable { public let key: BuildKey public let result: RuleResult public func hash(into hasher: inout Hasher) { hasher.combine(key) } } public typealias Index = Int public var startIndex: Index { return 0 } public var endIndex: Index { return self._count + startIndex } public subscript(index: Index) -> Iterator.Element { guard (startIndex..<endIndex).contains(index) else { fatalError("Index \(index) is out of bounds (\(startIndex)..<\(endIndex))") } guard let result = llb_database_fetch_result_get_result_at_index(self.result, Int32(index)) else { fatalError("Build database fetch result doesn't contain result at index \(index) although the count is given at \(count)") } let key = BuildKey.construct(key: llb_database_fetch_result_get_key_at_index(self.result, Int32(index))) let ruleResult = RuleResult(result: result.pointee)! return Element(key: key, result: ruleResult) } public func index(after i: Index) -> Index { return i + 1 } } extension BuildDBKeysResult: CustomReflectable { public var customMirror: Mirror { let keys = (startIndex..<endIndex).map { self[$0] } return Mirror(BuildDBKeysResult.self, unlabeledChildren: keys, displayStyle: .collection) } } extension BuildDBKeysResult: CustomStringConvertible { public var description: String { let keyDescriptions = (startIndex..<endIndex).map { "\(self[$0]))" } return "[\(keyDescriptions.joined(separator: ", "))]" } } /// Defines the result of a built task public struct RuleResult { /// The value of the result public let value: BuildValue /// Signature of the node that generated the result public let signature: UInt64 /// The build iteration this result was computed at public let computedAt: UInt64 /// The build iteration this result was built at public let builtAt: UInt64 /// The start of the command as a duration since a reference time public let start: Double /// The duration since a reference time of when the command finished computing public let end: Double /// The duration in seconds the result needed to finish public var duration: Double { return end - start } /// A list of the dependencies of the computed task, use the database's allKeys to check for their key public let dependencies: [BuildKey] public init(value: BuildValue, signature: UInt64, computedAt: UInt64, builtAt: UInt64, start: Double, end: Double, dependencies: [BuildKey]) { self.value = value self.signature = signature self.computedAt = computedAt self.builtAt = builtAt self.start = start self.end = end self.dependencies = dependencies } fileprivate init?(result: BuildDBResult) { guard let value = BuildValue.construct(from: Value(ValueType(UnsafeBufferPointer(start: result.value.data, count: Int(result.value.length))))) else { return nil } let dependencies = UnsafeBufferPointer(start: result.dependencies, count: Int(result.dependencies_count)) .map(BuildKey.construct(key:)) self.init(value: value, signature: result.signature, computedAt: result.computed_at, builtAt: result.built_at, start: result.start, end: result.end, dependencies: dependencies) } } extension RuleResult: Equatable { public static func == (lhs: RuleResult, rhs: RuleResult) -> Bool { return lhs.value == rhs.value && lhs.signature == rhs.signature && lhs.computedAt == rhs.computedAt && lhs.builtAt == rhs.builtAt && lhs.start == rhs.start && lhs.end == rhs.end && lhs.dependencies == rhs.dependencies } } extension RuleResult: CustomStringConvertible { public var description: String { return "<RuleResult value=\(value) signature=\(String(format: "0x%X", signature)) computedAt=\(computedAt) builtAt=\(builtAt) duration=\(duration)sec dependenciesCount=\(dependencies.count)>" } } /// Private class for easier handling of out-parameters private class MutableStringPointer { var ptr = llb_data_t() init() { } deinit { ptr.data?.deallocate() } var msg: String? { guard ptr.data != nil else { return nil } return stringFromData(ptr) } } /// Database object that defines a connection to a llbuild database public final class BuildDB { /// Errors that can happen when opening the database or performing operations on it public enum Error: Swift.Error { /// If the system can't open the database, this error is thrown at init case couldNotOpenDB(error: String) /// If an operation on the database fails, this error is thrown case operationDidFail(error: String) /// If the database didn't provide an error but the operation still failed, the unknownError is thrown case unknownError } /// The opaque pointer to the database object private var _database: OpaquePointer /// Initializes the build database at a given path /// If the database at this path doesn't exist, it will created /// If the clientSchemaVersion is different to the one in the database at this path, its content will be automatically erased! public init(path: String, clientSchemaVersion: UInt32) throws { // Safety check that we have linked against a compatibile llbuild framework version if llb_get_api_version() != LLBUILD_C_API_VERSION { throw Error.couldNotOpenDB(error: "llbuild C API version mismatch, found \(llb_get_api_version()), expect \(LLBUILD_C_API_VERSION)") } // check if the database file exists var directory: ObjCBool = false guard FileManager.default.fileExists(atPath: path, isDirectory: &directory) else { throw Error.couldNotOpenDB(error: "Database at path '\(path)' does not exist.") } if directory.boolValue { throw Error.couldNotOpenDB(error: "Path '\(path)' exists, but is a directory.") } let errorPtr = MutableStringPointer() guard let database = llb_database_open(strdup(path), clientSchemaVersion, &errorPtr.ptr) else { throw Error.couldNotOpenDB(error: errorPtr.msg ?? "Unknown error.") } _database = database } deinit { llb_database_destroy(_database) } /// Fetches all keys from the database public func getKeys() throws -> BuildDBKeysResult { let errorPtr = MutableStringPointer() let keys = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) let success = llb_database_get_keys(_database, keys, &errorPtr.ptr) if let error = errorPtr.msg { throw Error.operationDidFail(error: error) } if !success { throw Error.unknownError } guard let resultKeys = keys.pointee else { throw Error.unknownError } return BuildDBKeysResult(result: resultKeys) } public func getKeysWithResult() throws -> BuildDBKeysWithResult { let errorPtr = MutableStringPointer() let keys = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) let success = llb_database_get_keys_and_results(_database, keys, &errorPtr.ptr) if let error = errorPtr.msg { throw Error.operationDidFail(error: error) } if !success { throw Error.unknownError } guard let resultKeys = keys.pointee else { throw Error.unknownError } return BuildDBKeysWithResult(result: resultKeys) } /// Get the result for a given keyID public func lookupRuleResult(buildKey: BuildKey) throws -> RuleResult? { let errorPtr = MutableStringPointer() var result = BuildDBResult() let stored = llb_database_lookup_rule_result(_database, buildKey.internalBuildKey, &result, &errorPtr.ptr) if let error = errorPtr.msg { throw Error.operationDidFail(error: error) } if !stored { return nil } let mappedResult = RuleResult(result: result) llb_database_destroy_result(&result) return mappedResult } public func currentBuildEpoch() throws -> UInt64 { let errorPtr = MutableStringPointer() let epoch = llb_database_get_epoch(_database, &errorPtr.ptr) if let error = errorPtr.msg { throw Error.operationDidFail(error: error) } return epoch } }
7868a36852e051a33ff63d1d003a8b17
34.374613
225
0.653685
false
false
false
false
seanwoodward/IBAnimatable
refs/heads/master
IBAnimatable/ActivityIndicatorAnimationBallZigZag.swift
mit
1
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallZigZag: ActivityIndicatorAnimating { // MARK: Properties private let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = .infinity animation.removedOnCompletion = false circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0))] circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallZigZag { func circleAt(frame frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) { let circle = ActivityIndicatorShape.Circle.createLayerWith(size: size, color: color) circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } }
91c5f4b9181a4553d334f41e701cdbd8
42.928571
156
0.702033
false
false
false
false
TEDxBerkeley/iOSapp
refs/heads/master
iOSApp/MainTabBarController.swift
apache-2.0
1
// // MainTabBarController.swift // TEDxBerkeley // // Created by alvinwan on 1/4/16. // Copyright (c) 2016 TExBerkeley. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { self.tabBar.tintColor = UIColor.whiteColor() // change default text color UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)], forState: .Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected) // change default image tint for item in self.tabBar.items! { if let image = item.image { item.image = image.imageWithColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)).imageWithRenderingMode(.AlwaysOriginal) } } } } extension UIImage { // written by "gotnull" on StackOverflow // http://stackoverflow.com/questions/19274789/how-can-i-change-image-tintcolor-in-ios-and-watchkit/24545102#24545102 func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, CGBlendMode.Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } }
c9a220e2ef784181aa496e1523eb5129
36
157
0.672853
false
false
false
false
alessandroorru/SimpleSwiftLogger
refs/heads/master
Log.swift
mit
1
public enum Log : Int { case Trace, Debug, Info, Warning, Error, None public typealias PrintFunction = (items: Any..., separator: String, terminator: String) -> Void public typealias SimpleFormatter = (object: Any) -> String public typealias ExtendedFormatter = (object: Any, file: String, line: Int, function: String) -> String public typealias ColorForLevel = (level: Log) -> UIColor public static var Level : Log = Log.Error public static var printFunction : PrintFunction = Swift.print public static var simpleFormatter : SimpleFormatter = Log.format public static var extendedFormatter : ExtendedFormatter = Log.format public static var colorForLevel : ColorForLevel = Log.colorForLevel public static var dateFormatter : NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .MediumStyle dateFormatter.locale = NSLocale.systemLocale() return dateFormatter }() public func print(object:Any, extended: Bool = true, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { guard rawValue >= Log.Level.rawValue else { return } let color = colorString() var formattedString : String switch extended { case false: formattedString = Log.simpleFormatter(object: object) case true: formattedString = Log.extendedFormatter(object: object, file: file, line: line, function: function) } if Log.colorsEnabled { formattedString = "\(Log.ESCAPE)\(color)\(formattedString)\(Log.RESET)" } Log.printFunction(items: formattedString, separator: ",", terminator: "\n") } // MARK: - Private private func colorString() -> String { let color = Log.colorForLevel(self) var r : CGFloat = 0 var g : CGFloat = 0 var b : CGFloat = 0 var a : CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) return String(format: "fg%.0f,%.0f,%.0f;", arguments: [round(r*255), round(g*255), round(b*255)]) } private static func colorForLevel(level: Log) -> UIColor { switch level { case .Trace: return UIColor.whiteColor() case .Debug: return UIColor.darkGrayColor() case .Info: return UIColor.yellowColor() case .Warning: return UIColor.orangeColor() case .Error: return UIColor.redColor() default: return UIColor.whiteColor() } } private static func format(object: Any) -> String { return "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" } private static func format(object: Any, file: String, line: Int, function: String) -> String { let file = file.componentsSeparatedByString("/").last! var logString = "\n\n[\(file):\(line)] \(function) | \n" logString += "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" logString += "\n" return logString } private static var colorsEnabled: Bool = { let xcodeColors = NSProcessInfo().environment["XcodeColors"] let xcodeColorsAvailable = xcodeColors != nil && xcodeColors == "YES" return xcodeColorsAvailable }() private static let ESCAPE = "\u{001b}[" private static let RESET_FG = "\(ESCAPE) fg;" // Clear any foreground color private static let RESET_BG = "\(ESCAPE) bg;" // Clear any background color private static let RESET = "\(ESCAPE);" // Clear any foreground or background color } infix operator => {} public func =>(lhs: Any, rhs: Log) { rhs.print(lhs, extended: false) }
e147d44da64adabe5110c6d763fdb8e1
36.201923
138
0.609359
false
false
false
false
satoshin21/Anima
refs/heads/master
Sources/Anima.swift
mit
1
// // Anima.swift // Pods // // Created by Satoshi Nagasaka on 2017/03/09. // // import UIKit public typealias AnimaCompletion = () -> Void public class Anima: NSObject { public enum Status: Equatable { case notFired case active case willPaused case paused(AnimaCompletion?) case completed public static func ==(left: Status, right: Status) -> Bool { switch (left, right) { case (.notFired, .notFired): fallthrough case (.active, .active): fallthrough case (.willPaused, .willPaused): fallthrough case (.paused, .paused): fallthrough case (.completed, .completed): return true default: return false } } } // MARK: - Properties public private(set) var status: Status = .notFired /** If you don't add any duration option 'AnimaOption.duration()', `defaultDuration` is applied. Default value is one. */ public static var defaultDuration: TimeInterval = 1 /** If you don't add any TimingFunction option 'AnimaOption.timingFunction()', `defaultTimingFunction` is applied. Default value is 'easeInCubic'. */ public static var defaultTimingFunction = TimingFunction.easeInCubic /// animation stack. internal var stack = [AnimaNode]() /// Animation target Layer. weak private var layer: CALayer? public var isActive: Bool { return status == .active } // MARK: - Initializer /// Anima needs target layer of animation in initializer. init(_ layer: CALayer) { self.layer = layer super.init() } // MARK: - Set Animations /// call this method to define next (or first) animation. /// /// - Parameters: /// - animationType: Animation that you want to perform (moveX, size, rotation, ... etc) /// - options: Animation option that you want to apply (duration, timingFunction, completion, ... etc) /// - Returns: itself (Anima object) public func then(_ animationType: AnimaType, options: [AnimaOption] = []) -> Self { return next(animaNode: AnimaNode(nodeType: .single(animationType), options: options)) } /// call this method to define next (or first) grouped animation. /// each animations will run concurrently in the same time. /// /// - Parameters: /// - animationType: Animation that you want to perform (moveX, size, rotation, ... etc) /// - options: Animation option that you want to apply (duration, timingFunction, completion, ... etc) /// - Returns: itself (Anima object) public func then(group animations: [AnimaType], options: [AnimaOption] = []) -> Self { return next(animaNode: AnimaNode(nodeType: .group(animations), options: options)) } /// call this method to delay next animation. /// /// - Parameter t: TimeInterval. time of waiting next action /// - Returns: itself public func then(waitFor t: TimeInterval) -> Self { return next(animaNode: AnimaNode(nodeType: .wait(t))) } /// Set the CALayer.anchorPoint value with enum of "AnchorPoint". /// Usualy, updating CALayer.anchorPoint directly, it will change layer's frame. /// but this method do not affect layer's frame, it update layer's anchorPoint only. /// - Parameter anchorPoint: AnchorPoint /// - Returns: itself public func then(setAnchor anchorPoint: AnimaAnchorPoint) -> Self { return next(animaNode: AnimaNode(nodeType: .anchor(anchorPoint))) } /// perform series of animation you defined. /// /// - Parameter completion: all of animation is finished, it will be called. public func fire(completion: AnimaCompletion? = nil) { status = .active guard stack.count > 0 else { onCompletion(completion) return } fireNext(completion) } public func pause() { switch status { case .willPaused, .active: status = .willPaused default: break; } } public func resume() { switch status { case .willPaused: status = .active case .paused(let completion): status = .active fireNext(completion) default: break; } } /// perform animation at top of stack. private func fireNext(_ completion: AnimaCompletion?) { guard case .active = status else { status = .paused(completion) return } guard let layer = layer, !stack.isEmpty else { onCompletion(completion) return } stack.removeFirst().addAnimation(to: layer) {[weak self] (finished) in self?.fireNext(completion) } } private func next(animaNode: AnimaNode) -> Self { stack.append(animaNode) return self } private func onCompletion(_ completion: AnimaCompletion?) { status = .completed completion?() } }
5e4df121d2fe5647d058ca71bf16a82d
27.818182
108
0.571535
false
false
false
false
WaterReporter/WaterReporter-iOS
refs/heads/master
WaterReporter/WaterReporter/GroupsTableView.swift
agpl-3.0
1
// // GroupsTableView.swift // Water-Reporter // // Created by Joshua Powell on 9/13/17. // Copyright © 2017 Viable Industries, L.L.C. All rights reserved. // import Foundation import SwiftyJSON import UIKit class GroupsTableView: UITableView, UITableViewDelegate, UITableViewDataSource { var groups: JSON? func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { print("GroupsTableView::tableView::cellForRowAtIndexPath \(groups!)"); let cell = tableView.dequeueReusableCellWithIdentifier("reportGroupTableViewCell", forIndexPath: indexPath) as! ReportGroupTableViewCell // // Assign the organization logo to the UIImageView // cell.imageViewGroupLogo.tag = indexPath.row var organizationImageUrl:NSURL! if let thisOrganizationImageUrl: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["picture"].string { organizationImageUrl = NSURL(string: thisOrganizationImageUrl) } cell.imageViewGroupLogo.kf_indicatorType = .Activity cell.imageViewGroupLogo.kf_showIndicatorWhenLoading = true cell.imageViewGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.imageViewGroupLogo.image = image cell.imageViewGroupLogo.layer.cornerRadius = cell.imageViewGroupLogo.frame.size.width / 2 cell.imageViewGroupLogo.clipsToBounds = true }) // // Assign the organization name to the UILabel // if let thisOrganizationName: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["name"].string { cell.labelGroupName.text = thisOrganizationName } // Assign existing groups to the group field cell.switchSelectGroup.tag = indexPath.row // if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] { // //// if self.tempGroups.contains("\(_organization_id_number)") { //// cell.switchSelectGroup.on = true //// } //// else { //// cell.switchSelectGroup.on = false //// } // // } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 72.0 } // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // print("GroupsTableView::tableView::numberOfSectionsInTableView") // // return 1 // } func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int { if self.groups == nil { print("Showing 0 group cells") return 0 } print("Showing \((self.groups?.count)!) group cells") return (self.groups?.count)! } }
68cf2996cac1b83ede2bd5ec509064f2
33.472527
154
0.635958
false
false
false
false
sjtu-meow/iOS
refs/heads/master
Meow/RichTextEditor.swift
apache-2.0
1
// // RichTextEditor.swift // Meow // // Created by 林武威 on 2017/7/6. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit import RxSwift protocol RichTextEditorDelegate { func didTapAddImage() } class RichTextEditor: UIView { @IBOutlet weak var webview: UIWebView! var delegate: RichTextEditorDelegate? override func awakeFromNib() { loadEditor() } @IBAction func addImage(_ sender: Any) { delegate?.didTapAddImage() } var htmlString: String { get { return webview.stringByEvaluatingJavaScript(from: "document.getElementById('content').innerHTML")! } } func insertImage(id: String, url: String) { let script = "window.insertImage('\(id)', '\(url)')" let _ = webview.stringByEvaluatingJavaScript(from: script) } func loadEditor() { let editorURL = Bundle.main.url(forResource: "editor", withExtension: "html")! webview.loadRequest(URLRequest(url: editorURL)) } func updateImagePath(id: String, url: String ) { let scripts = "window.setImagePath('\(id )', '\(url)')" let _ = webview.stringByEvaluatingJavaScript(from: scripts) } }
7f06c32b435adee366eca0c0540e05a0
23.352941
110
0.622383
false
false
false
false
IntrepidPursuits/swift-wisdom
refs/heads/master
SwiftWisdomTests/StandardLibrary/Date/TimeOfDayTests.swift
mit
1
// // TimeOfDayTests.swift // SwiftWisdom // // Created by Patrick Butkiewicz on 3/1/17. // Copyright © 2017 Intrepid. All rights reserved. // import Foundation import XCTest import SwiftWisdom final class TimeOfDayTests: XCTestCase { // Corresponds to Jan 1st, 2017, 3:16 AM GMT private var testSingleHourDigitEpochTime: TimeInterval = 1483240560 // Corresponds to Jan 1st, 2017, 11:00 AM GMT private var testDoubleHourDigitEpochTime: TimeInterval = 1483268400 override func setUp() { let offset = TimeZone.autoupdatingCurrent.secondsFromGMT(for: Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) // Was breaking on Daylight savings time. testSingleHourDigitEpochTime -= TimeInterval(offset) testDoubleHourDigitEpochTime -= TimeInterval(offset) } func testTimeFromDate() { let td1 = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) XCTAssert(td1?.displayString.compare("3:16 AM") == .orderedSame) XCTAssert(td1?.stringRepresentation.compare("03:16") == .orderedSame) let td2 = TimeOfDay(Date(timeIntervalSince1970: testDoubleHourDigitEpochTime)) XCTAssert(td2?.displayString.compare("11:00 AM") == .orderedSame) XCTAssert(td2?.stringRepresentation.compare("11:00") == .orderedSame) } func testTimeFromString() { let td = TimeOfDay("3:16") XCTAssert(td?.displayString.compare("3:16 AM") == .orderedSame) XCTAssert(td?.stringRepresentation.compare("03:16") == .orderedSame) let td2 = TimeOfDay("11:00") XCTAssert(td2?.displayString.compare("11:00 AM") == .orderedSame) XCTAssert(td2?.stringRepresentation.compare("11:00") == .orderedSame) let td3 = TimeOfDay("16:21") XCTAssert(td3?.displayString.compare("4:21 PM") == .orderedSame) XCTAssert(td3?.stringRepresentation.compare("16:21") == .orderedSame) } func testNilTimeFromInvalidString() { XCTAssertNil(TimeOfDay("")) } func testApplyingTimeToDate() { let timeToApply = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) let receivingDate = Date(timeIntervalSince1970: testDoubleHourDigitEpochTime) let newDate = timeToApply?.timeOnDate(receivingDate) let newTime = TimeOfDay(newDate!) XCTAssert(timeToApply?.minutes == newTime?.minutes) XCTAssert(timeToApply?.hours == newTime?.hours) } func testApplyingTimeToToday() { let timeToApply = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) let newDate = timeToApply?.timeToday() let newTime = TimeOfDay(newDate!) XCTAssert(timeToApply?.minutes == newTime?.minutes) XCTAssert(timeToApply?.hours == newTime?.hours) } }
71ee0d6fc9377ecb7f9299ef0f631d36
39.8
170
0.686625
false
true
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKitDemo/SwiftMKitDemo/UI/Data/Audio/AudioViewController.swift
mit
1
// // AudioViewController.swift // SwiftMKitDemo // // Created by wei.mao on 2018/7/13. // Copyright © 2018年 cdts. All rights reserved. // import UIKit import AudioKit import AudioKitUI import SwiftMKit class AudioViewController: UIViewController, AKKeyboardDelegate { let bank = AKOscillatorBank() var keyboardView: AKKeyboardView? override func viewDidLoad() { super.viewDidLoad() AudioKit.output = bank try? AudioKit.start() keyboardView = AKKeyboardView(width: 440, height: 100) keyboardView?.delegate = self // keyboard.polyphonicMode = true self.view.addSubview(keyboardView!) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { keyboardView?.frame = CGRect(x: 0, y: 100, w: 440, h: 100) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func noteOn(note: MIDINoteNumber) { bank.play(noteNumber: note, velocity: 80) } func noteOff(note: MIDINoteNumber) { bank.stop(noteNumber: note) } }
19369d1ebd8c96fbd47605660943b476
24.125
66
0.646766
false
false
false
false
arsonik/AKTrakt
refs/heads/master
Source/shared/Requests/Search.swift
mit
1
// // Search.swift // Pods // // Created by Florian Morello on 27/05/16. // // import Foundation import Alamofire /// Represents trakt search object type private enum TraktSearchType: String { /// Movie case Movie = "movie" /// Show case Show = "show" /// Season case Season = "season" /// Episode case Episode = "episode" /// Person case Person = "person" /// Associated TraktObject type public var classType: TraktObject.Type? { switch self { case .Movie: return TraktMovie.self case .Show: return TraktShow.self case .Season: return TraktSeason.self case .Person: return TraktPerson.self case .Episode: return TraktEpisode.self } } } /// Serarch request public class TraktRequestSearch<T: TraktObject where T: protocol<Searchable>>: TraktRequest { /** Init - parameter query: search query string - parameter type: optional trakt type - parameter year: optional year - parameter pagination: optional pagination */ public init(query: String, type: T.Type? = nil, year: UInt? = nil, pagination: TraktPagination? = nil) { var params: JSONHash = [ "query": query ] if year != nil { params["year"] = year! } if type != nil { params["type"] = type!.objectName } if pagination != nil { params += pagination!.value() } super.init(path: "/search", params: params) } /** Execute request - parameter trakt: trakt client - parameter completion: closure [TraktObject]?, NSError? - returns: Alamofire.Request */ public func request(trakt: Trakt, completion: ([TraktObject]?, NSError?) -> Void) -> Request? { return trakt.request(self) { response in guard let entries = response.result.value as? [JSONHash] else { return completion(nil, response.result.error) } completion(entries.flatMap { guard let type = TraktSearchType(rawValue: $0["type"] as? String ?? "") else { return nil } return type.classType?.init(data: $0[type.rawValue] as? JSONHash) }, nil) } } }
5800956822e394689bbd5608335b30f1
25.655556
108
0.554815
false
false
false
false
mikelikespie/swiftled
refs/heads/master
src/main/swift/SwiftledMobile/RootSplitViewController.swift
mit
1
// // ViewController.swift // SwiftledMobile // // Created by Michael Lewis on 12/29/15. // Copyright © 2015 Lolrus Industries. All rights reserved. // import UIKit import RxSwift import OPC //import RxCocoa import Foundation import Visualizations import Cleanse import yoga_YogaKit import Views private let segmentLength = 18 private let segmentCount = 30 private let ledCount = segmentLength * segmentCount class ViewController: UIViewController, UISplitViewControllerDelegate { let disposeBag = DisposeBag() private var typedView: ContentView { return scrollView.container } private lazy var scrollView: YogaScrollView = YogaScrollView() override func loadView() { self.view = scrollView } override func viewDidLoad() { super.viewDidLoad() typedView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) scrollView.addSubview(typedView) self.splitViewController?.delegate = self let root = try! ComponentFactory .of(SwiftLedComponent.self) .build(LedConfiguration( segmentLength: segmentLength, segmentCount: segmentCount )) root .entryPoint .start() .addDisposableTo(disposeBag) root.rootVisualization .controls .map { Array($0.map { $0.cells }.joined()) } .subscribe(onNext: { [unowned self] cells in self.scrollView.cells = cells }) .addDisposableTo(disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } }
786015823d0b4c56365b1c62a7ddbef0
23.757143
71
0.613387
false
false
false
false
carabina/DDMathParser
refs/heads/master
MathParser/RewriteRule.swift
mit
2
// // RewriteRule.swift // DDMathParser // // Created by Dave DeLong on 8/25/15. // // import Foundation public struct RuleTemplate { public static let AnyExpression = "__exp" public static let AnyNumber = "__num" public static let AnyVariable = "__var" public static let AnyFunction = "__func" private init() { } } public struct RewriteRule { public let predicate: Expression public let condition: Expression? public let template: Expression public init(predicate: Expression, condition: Expression? = nil, template: Expression) { self.predicate = predicate self.condition = condition self.template = template } public init(predicate: String, condition: String? = nil, template: String) throws { self.predicate = try Expression(string: predicate) self.template = try Expression(string: template) if let condition = condition { self.condition = try Expression(string: condition) } else { self.condition = nil } } public func rewrite(expression: Expression, substitutions: Substitutions, evaluator: Evaluator) -> Expression { guard let replacements = matchWithCondition(expression, substitutions: substitutions, evaluator: evaluator) else { return expression } return applyReplacements(replacements, toExpression: template) } private func matchWithCondition(expression: Expression, substitutions: Substitutions = [:], evaluator: Evaluator, replacementsSoFar: Dictionary<String, Expression> = [:]) -> Dictionary<String, Expression>? { guard let replacements = match(expression, toExpression: predicate, replacementsSoFar: replacementsSoFar) else { return nil } // we replaced, and we don't have a condition => we match guard let condition = condition else { return replacements } // see if the expression matches the condition let matchingCondition = applyReplacements(replacements, toExpression: condition) // if there's an error evaluating the condition, then we don't match guard let result = try? evaluator.evaluate(matchingCondition, substitutions: substitutions) else { return nil } // non-zero => we match return (result != 0) ? replacements : nil } private func match(expression: Expression, toExpression target: Expression, replacementsSoFar: Dictionary<String, Expression>) -> Dictionary<String, Expression>? { var replacements = replacementsSoFar switch target.kind { // we're looking for a specific number; return the replacements if we match that number case .Number(_): return expression == target ? replacements : nil // we're looking for a specific variable; return the replacements if we match case .Variable(_): return expression == target ? replacements : nil // we're looking for something else case .Function(let f, let args): // we're looking for anything if f.hasPrefix(RuleTemplate.AnyExpression) { // is this a matcher ("__exp42") we've seen before? // if it is, only return replacements if it's the same expression // as what has already been matched if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } // otherwise remember this one and return the new replacements replacements[f] = expression return replacements } // we're looking for any number if f.hasPrefix(RuleTemplate.AnyNumber) && expression.kind.isNumber { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // we're looking for any variable if f.hasPrefix(RuleTemplate.AnyVariable) && expression.kind.isVariable { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // we're looking for any function if f.hasPrefix(RuleTemplate.AnyFunction) && expression.kind.isFunction { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // if we make it this far, we're looking for a specific function // make sure the expression we're matching against is also a function guard case let .Function(expressionF, expressionArgs) = expression.kind else { return nil } // make sure the functions have the same name guard expressionF == f else { return nil } // make sure the functions have the same number of arguments guard expressionArgs.count == args.count else { return nil } // make sure each argument matches for (expressionArg, targetArg) in zip(expressionArgs, args) { // if this argument doesn't match, return nil guard let argReplacements = match(expressionArg, toExpression: targetArg, replacementsSoFar: replacements) else { return nil } replacements = argReplacements } return replacements } } private func applyReplacements(replacements: Dictionary<String, Expression>, toExpression expression: Expression) -> Expression { switch expression.kind { case .Function(let f, let args): if let replacement = replacements[f] { return Expression(kind: replacement.kind, range: replacement.range) } let newArgs = args.map { applyReplacements(replacements, toExpression: $0) } return Expression(kind: .Function(f, newArgs), range: expression.range) default: return Expression(kind: expression.kind, range: expression.range) } } }
48271ebb175238357144a1ac21a3e6ec
43.135484
211
0.578424
false
false
false
false
pirishd/InstantMock
refs/heads/dev
Sources/InstantMock/Verifications/Verifier.swift
mit
1
// // Verifier.swift // InstantMock // // Created by Patrick on 08/05/2017. // Copyright © 2017 pirishd. All rights reserved. // /** Protoocl dedicated to verify equality between values */ public protocol Verifier { func equal(_ arg: Any?, to value: Any?) -> Bool } /** Main verifier implementation */ final class VerifierImpl: Verifier { /// Singleton static let instance = VerifierImpl() /** Make sure two optional values are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equal(_ arg: Any?, to value: Any?) -> Bool { // compare nil values if arg == nil && value == nil { return true } if arg != nil && value == nil { return false } if arg == nil && value != nil { return false } // otherwise, perform advanced verifications return self.equal(arg!, to: value!) } /** Make sure two non-nil values are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equal(_ arg: Any, to value: Any) -> Bool { // MockUsable values if let mockArg = arg as? MockUsable, let mockValue = value as? MockUsable { return mockArg.equal(to: mockValue) } // try to compare by reference if (arg as AnyObject) === (value as AnyObject) { return true } // compare Void types if arg is Void && value is Void { return true } // arguments can be types if let argType = arg as? Any.Type, let valueType = value as? Any.Type { return argType == valueType } // arguments can be tuples if self.equalTuples(arg, to: value) { return true } // default case return false } /** Make sure two values that are tuples are equal (up to five arguments in the tuple) - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ private func equalTuples(_ arg: Any?, to value: Any?) -> Bool { return self.equalTuple2(arg, to: value) || self.equalTuple3(arg, to: value) || self.equalTuple4(arg, to: value) || self.equalTuple5(arg, to: value) } private func equalTuple2(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2) = arg as? (Any?, Any?), let (val1, val2) = value as? (Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) } return false } private func equalTuple3(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3) = arg as? (Any?, Any?, Any?), let (val1, val2, val3) = value as? (Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) } return false } private func equalTuple4(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3, arg4) = arg as? (Any?, Any?, Any?, Any?), let (val1, val2, val3, val4) = value as? (Any?, Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) && self.equal(arg4, to: val4) } return false } private func equalTuple5(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3, arg4, arg5) = arg as? (Any?, Any?, Any?, Any?, Any?), let (val1, val2, val3, val4, val5) = value as? (Any?, Any?, Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) && self.equal(arg4, to: val4) && self.equal(arg5, to: val5) } return false } /** Make sure two arrays are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equalArray(_ arg: [Any?], to value: [Any?]) -> Bool { // make sure the two arrays have the same number of elements if arg.count != value.count { return false } // verify equality between array elements if arg.count > 0 { for i in 0...arg.count-1 { if !self.equal(arg[i], to: value[i]) { return false } } } return true } }
415c07433c475349c0e060999988438d
28.738562
119
0.55011
false
false
false
false
ppraveentr/MobileCore
refs/heads/master
Sources/CoreComponents/Contollers/ViewControllerProtocol.swift
mit
1
// // ViewControllerProtocol.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 15/06/17. // Copyright © 2017 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import UIKit public protocol ViewControllerProtocol where Self: UIViewController { var modelStack: AnyObject? { get set } // Setup View func setupCoreView() // MARK: Navigation Bar // Bydefalut leftButton action is set to 'leftButtonAction' func setupNavigationbar(title: String, leftButton: UIBarButtonItem?, rightButton: UIBarButtonItem?) // invokes's 'popViewController' if not rootViewController or-else invokes 'dismiss' func dismissSelf(_ animated: Bool) // Navigation bar defalut Actions func leftButtonAction() func rightButtonAction() // MARK: Keyboard notification. func registerKeyboardNotifications() // Notifications will be unregistered in 'deinit' func unregisterKeyboardNotifications() // MARK: Alert ViewController func showAlert(title: String?, message: String?, action: UIAlertAction?, actions: [UIAlertAction]?) // MARK: Activity indicator func showActivityIndicator() func hideActivityIndicator(_ completionBlock: LoadingIndicator.CompletionBlock?) // MARK: Layout Guide func topSafeAreaLayoutGuide() -> Bool func horizontalSafeAreaLayoutGuide() -> Bool func shouldDissmissKeyboardOnTap() -> Bool } private extension AssociatedKey { static var baseView = "baseView" static var screenIdentifier = "screenIdentifier" static var modelStack = "modelStack" static var completionBlock = "completionBlock" } extension UIViewController: ViewControllerProtocol { @IBOutlet public var baseView: FTView? { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.baseView) { FTView() } } set { AssociatedObject<FTView>.setAssociated(self, value: newValue, key: &AssociatedKey.baseView) } } @IBOutlet public var topPinnedView: UIView? { get { self.baseView?.topPinnedView } set { self.baseView?.topPinnedView = newValue } } @IBOutlet public var bottomPinnedView: UIView? { get { self.baseView?.bottomPinnedView } set { self.baseView?.bottomPinnedView = newValue } } // Unquie Identifier for eachScreen public var screenIdentifier: String? { get { AssociatedObject<String>.getAssociated(self, key: &AssociatedKey.screenIdentifier) } set { AssociatedObject<String>.setAssociated(self, value: newValue, key: &AssociatedKey.screenIdentifier) } } // modelData that can be passed from previous controller public var modelStack: AnyObject? { get { AssociatedObject<AnyObject>.getAssociated(self, key: &AssociatedKey.modelStack) } set { AssociatedObject<AnyObject>.setAssociated(self, value: newValue, key: &AssociatedKey.modelStack) } } // Setup baseView's topLayoutGuide by sending true in subControllers if needed @objc open func topSafeAreaLayoutGuide() -> Bool { true } @objc open func horizontalSafeAreaLayoutGuide() -> Bool { true } // Will dismiss Keyboard by tapping on any non-interative part of the view. @objc open func shouldDissmissKeyboardOnTap() -> Bool { true } public func setupCoreView() { if self.view == self.baseView { return } guard let rootView = self.view else { return } var isValidBaseView = false // Make it as Views RooView, if forget to map it in IB. if self.baseView != rootView, (rootView as? FTView) != nil { self.baseView = rootView as? FTView isValidBaseView = true } self.view = self.baseView // Setup baseView's topLayoutGuide & bottomLayoutGuide setupLayoutGuide() // To Dismiss keyboard on tap in view setupKeyboardTapRecognizer() // Reset rootView if !isValidBaseView { rootView.removeFromSuperview() self.mainView?.pin(view: rootView, edgeOffsets: .zero) } } } extension UIViewController { // MARK: Navigation Bar public func setupNavigationbar(title: String, leftButton: UIBarButtonItem? = nil, rightButton: UIBarButtonItem? = nil) { self.title = title configureBarButton(button: leftButton, defaultAction: kleftButtonAction) configureBarButton(button: rightButton, defaultAction: kRightButtonAction) self.navigationItem.leftBarButtonItem = leftButton self.navigationItem.rightBarButtonItem = rightButton } // MARK: Dissmiss Self model public func dismissSelf(_ animated: Bool = true) { self_dismissSelf(animated) } // MARK: default Nav-bar button actions @IBAction open func leftButtonAction() { dismissSelf() } @IBAction open func rightButtonAction() { // Optional Protocol implementation: intentionally empty } } // MARK: Layout Guide for rootView private extension UIViewController { func setupLayoutGuide() { // Update: topPinnedButtonView if let topView = self.topPinnedView { self.baseView?.topPinnedView = topView } // Update: bottomPinnedButtonView if let bottomView = self.bottomPinnedView { self.baseView?.bottomPinnedView = bottomView } // Pin: rootView let local = self.baseView?.rootView /* Pin view bellow status bar */ // Pin - rootView's topAnchor if topSafeAreaLayoutGuide(), let local = local { setupTopSafeAreaLayoutGuide(local) } // Pin - rootView's topAnchor if #available(iOS 11.0, *), horizontalSafeAreaLayoutGuide() { local?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0.0).isActive = true local?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0.0).isActive = true } // Pin - rootView's bottomAnchor if #available(iOS 11.0, *) { local?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0.0).isActive = true } else { local?.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor, constant: 0.0).isActive = true } } func setupTopSafeAreaLayoutGuide(_ local: UIView) { if #available(iOS 11.0, *) { local.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true } else { local.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 0.0).isActive = true } } }
7b9bd304a94c9bbbec44fea096eef5f3
32.466667
124
0.650683
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/ChatModule/CWInput/More/CWMoreInputView.swift
mit
2
// // CWMoreKeyBoard.swift // CWWeChat // // Created by wei chen on 2017/4/11. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import YYText public protocol CWMoreInputViewDelegate: NSObjectProtocol { func moreInputView(_ inputView: CWMoreInputView, didSelect item: MoreItem) } private let kOneLines: Int = 2 private let kOneLineItem: Int = 4 private let kOneItemHeight: CGFloat = 280/3 public class CWMoreInputView: UIView { fileprivate var items = [MoreItem]() // 总共页数 var totalPageCount: Int = 0 var pageItemCount: Int = 0 private convenience init() { let size = CGSize(width: kScreenWidth, height: kMoreInputViewHeight) let origin = CGPoint(x: 0, y: kScreenHeight-size.height) let frame = CGRect(origin: origin, size: size) self.init(frame: frame) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(hex: "#E7EFF5") self.addSubview(collectionView) self.addSubview(pageControl) pageControl.top = collectionView.bottom } weak var deleagte: CWMoreInputViewDelegate? // 加载items func loadMoreItems(_ items: [MoreItem]) { self.items = items pageItemCount = kOneLines * kOneLineItem totalPageCount = Int(ceil(CGFloat(items.count)/CGFloat(pageItemCount))) pageControl.numberOfPages = totalPageCount collectionView.reloadData() } lazy var collectionView: UICollectionView = { // 间距 var itemWidth = (kScreenWidth - 10*2)/CGFloat(kOneLineItem) itemWidth = YYTextCGFloatPixelRound(itemWidth) let padding = (kScreenWidth - CGFloat(kOneLineItem) * itemWidth) / 2.0 let paddingLeft = YYTextCGFloatPixelRound(padding) let paddingRight = kScreenWidth - paddingLeft - itemWidth * CGFloat(kOneLineItem) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: itemWidth, height: kOneItemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsetsMake(0, paddingLeft, 0, paddingRight) let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kOneItemHeight*CGFloat(kOneLines)) var collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) collectionView.dataSource = self collectionView.backgroundColor = UIColor.clear collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.register(MoreItemCell.self, forCellWithReuseIdentifier: MoreItemCell.identifier) collectionView.top = 10 return collectionView }() var pageControl: UIPageControl! public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CWMoreInputView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageItemCount } public func numberOfSections(in collectionView: UICollectionView) -> Int { return totalPageCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MoreItemCell.identifier, for: indexPath) as! MoreItemCell cell.item = moreItemForIndexPath(indexPath) return cell } func moreItemForIndexPath(_ indexPath: IndexPath) -> MoreItem? { var index = indexPath.section * self.pageItemCount + indexPath.row // let page = index / self.pageItemCount index = index % self.pageItemCount let x = index / kOneLines let y = index % kOneLines let resultIndex = self.pageItemCount / kOneLines * y + x + page * self.pageItemCount if resultIndex > items.count - 1 { return nil } return items[resultIndex] } }
b04bbe9250ff90761da62a18ba0d6052
33.826446
132
0.67608
false
false
false
false
BugMomon/weibo
refs/heads/master
NiceWB/NiceWB/Classes/Main(主要)/AccessToken/UserAccountViewModel.swift
apache-2.0
1
// // UserAccountViewModel.swift // NiceWB // // Created by HongWei on 2017/4/5. // Copyright © 2017年 HongWei. All rights reserved. // import Foundation class UserAccountViewModel { static let shareInstance : UserAccountViewModel = UserAccountViewModel() var account : UserAccount? var isLogin : Bool { guard let account = account else { return false } if let expires_date = account.expires_date{ //判断时间升序降序 if expires_date.compare(Date()) == ComparisonResult.orderedDescending{ return true } } return true } var accountPath : String{ let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return (accountPath as NSString).appendingPathComponent("account.plist") } init() { account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as! UserAccount? // print("viewModel : \(account)") // print(accountPath) } }
f1962dac0f8aeff68f6e56ed32992890
25.5
111
0.601078
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionUI/Send/Analytics/NewAnalyticsEvents+Send.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import FeatureTransactionDomain import Foundation import PlatformKit extension AnalyticsEvents.New { public enum Send: AnalyticsEvent { public var type: AnalyticsEventType { .nabu } case sendReceiveClicked( origin: Origin = .navigation, type: Type ) case sendReceiveViewed(type: Type) case sendAmountMaxClicked( currency: String, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendFeeRateSelected( currency: String, feeRate: FeeRate, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendFromSelected( currency: String, fromAccountType: FromAccountType ) case sendSubmitted( currency: String, feeRate: FeeRate, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendDomainResolved public enum Origin: String, StringRawRepresentable { case navigation = "NAVIGATION" } public enum `Type`: String, StringRawRepresentable { case receive = "RECEIVE" case send = "SEND" } public enum FromAccountType: String, StringRawRepresentable { case savings = "SAVINGS" case trading = "TRADING" case userKey = "USERKEY" public init(_ account: BlockchainAccount?) { switch account { case is CryptoInterestAccount: self = .savings case is CryptoTradingAccount: self = .trading default: self = .userKey } } } public enum ToAccountType: String, StringRawRepresentable { case external = "EXTERNAL" case savings = "SAVINGS" case trading = "TRADING" case userKey = "USERKEY" case exchange = "EXCHANGE" public init(_ account: CryptoAccount) { switch account { case is CryptoNonCustodialAccount: self = .userKey case is CryptoInterestAccount: self = .savings case is CryptoTradingAccount: self = .trading case is CryptoExchangeAccount: self = .exchange default: self = .external } } public init(_ target: TransactionTarget?) { switch target?.accountType { case .trading: self = .trading case .external: self = .external case .exchange: self = .exchange default: self = .userKey } } } public enum FeeRate: String, StringRawRepresentable { case custom = "CUSTOM" case normal = "NORMAL" case priority = "PRIORITY" init(_ feeLevel: FeeLevel) { switch feeLevel { case .priority: self = .priority case .custom: self = .custom default: self = .normal } } } } }
75ac6d52d54e00fe10bf405dabdf4458
29.159664
69
0.494288
false
false
false
false
barisarsan/ScreenSceneController
refs/heads/master
ScreenSceneController/ScreenSceneController/ScreenSceneSettings.swift
mit
2
// // ScreenSceneSettings.swift // ScreenSceneController // // Copyright (c) 2014 Ruslan Shevchuk // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @objc (ScreenSceneSettings) public class ScreenSceneSettings { private struct Static { static let instance = ScreenSceneSettings() } public class var defaultSettings : ScreenSceneSettings { return Static.instance } public var classesThatDisableScrolling = [AnyClass]() public func addClassThatDisableScrolling(classThatDisableScrolling: AnyClass) { classesThatDisableScrolling.append(classThatDisableScrolling) } public var navigationBarTitleTextAttributes: [String: AnyObject] = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.whiteColor() ] public var bringFocusAnimationDuration: NSTimeInterval = 0.15 public var attachAnimationDamping: CGFloat = 0.8 public var attachAnimationDuration: NSTimeInterval = 0.4 public var detachAnimationDuration: NSTimeInterval = 0.3 public var detachCap: CGFloat = 0.1 public var attachmentAllowInterpolatingEffect: Bool = true public var attachmentInterpolatingEffectRelativeValue:Int = 20 public var attachmentCornerRadius: CGFloat = 10 public var attachmentPortraitWidth: CGFloat = 0.5 public var attachmentLandscapeWidth: CGFloat = 0.5 public var attachmentRelative: Bool = true public var attachmentExclusiveFocus: Bool = false public var attachmentTopInset: CGFloat = 65 public var attachmentBottomInset: CGFloat = 20 public var attachmentMinLeftInset: CGFloat = 10 public var attachmentMinRightInset: CGFloat = 10 public var attachmentNavigationBarHeight:CGFloat = 65 public var attachmentShadowIntensity:CGFloat = 4 }
808ae9dc47f0eb6820a9655f11f4c0e1
39.805195
83
0.692871
false
false
false
false