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
frajaona/LiFXSwiftKit
refs/heads/master
Sources/LiFXCASSocket.swift
apache-2.0
1
/* * Copyright (C) 2016 Fred Rajaona * * 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 Foundation import CocoaAsyncSocket class LiFXCASSocket: NSObject, LiFXSocket { var messageHandler: ((LiFXMessage, String) -> ())? var udpSocket: Socket? { return rawSocket } fileprivate var rawSocket: UdpCASSocket<LiFXMessage>? func openConnection() { let socket = UdpCASSocket<LiFXMessage>(destPort: LiFXCASSocket.UdpPort, shouldBroadcast: true, socketDelegate: self) rawSocket = socket if !socket.openConnection() { closeConnection() } else { } } func closeConnection() { rawSocket?.closeConnection() rawSocket = nil } func isConnected() -> Bool { return udpSocket != nil } } extension LiFXCASSocket: GCDAsyncUdpSocketDelegate { func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { Log.debug("socked did send data with tag \(tag)") } func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { Log.debug("socked did not send data with tag \(tag)") } func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { Log.debug("Socket closed: \(error?.localizedDescription)") } func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { Log.debug("\nReceive data from isIPv4=\(GCDAsyncUdpSocket.isIPv4Address(address)) address: \(GCDAsyncUdpSocket.host(fromAddress: address))") //Log.debug(data.description) let message = LiFXMessage(fromData: data) messageHandler?(message, GCDAsyncUdpSocket.host(fromAddress: address)!) } }
0c46df7019de932ee82573d70fe9075d
31.643836
148
0.668065
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Foundation/Extensions/UIDeviceExtension.swift
mpl-2.0
2
// // UIDeviceExtension.swift // Client // // Created by Mahmoud Adam on 11/16/15. // Copyright © 2015 Cliqz. All rights reserved. // import Foundation public extension UIDevice { var modelName: String { let identifierKey = "UIDevice.identifier" let storedIdentified = LocalDataStore.objectForKey(identifierKey) as? String guard storedIdentified == nil else { return storedIdentified! } var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } var deviceIdentifier: String switch identifier { case "iPod5,1": deviceIdentifier = "iPod Touch 5" case "iPod7,1": deviceIdentifier = "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": deviceIdentifier = "iPhone 4" case "iPhone4,1": deviceIdentifier = "iPhone 4s" case "iPhone5,1", "iPhone5,2": deviceIdentifier = "iPhone 5" case "iPhone5,3", "iPhone5,4": deviceIdentifier = "iPhone 5c" case "iPhone6,1", "iPhone6,2": deviceIdentifier = "iPhone 5s" case "iPhone7,2": deviceIdentifier = "iPhone 6" case "iPhone7,1": deviceIdentifier = "iPhone 6 Plus" case "iPhone8,1": deviceIdentifier = "iPhone 6s" case "iPhone8,2": deviceIdentifier = "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": deviceIdentifier = "iPhone 7" case "iPhone9,2", "iPhone9,4": deviceIdentifier = "iPhone 7 Plus" case "iPhone8,4": deviceIdentifier = "iPhone SE" case "iPhone10,1", "iPhone10,4": deviceIdentifier = "iPhone 8" case "iPhone10,2", "iPhone10,5": deviceIdentifier = "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": deviceIdentifier = "iPhone X" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":deviceIdentifier = "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": deviceIdentifier = "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": deviceIdentifier = "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": deviceIdentifier = "iPad Air" case "iPad5,3", "iPad5,4": deviceIdentifier = "iPad Air 2" case "iPad6,11", "iPad6,12": deviceIdentifier = "iPad 5" case "iPad2,5", "iPad2,6", "iPad2,7": deviceIdentifier = "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": deviceIdentifier = "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": deviceIdentifier = "iPad Mini 3" case "iPad5,1", "iPad5,2": deviceIdentifier = "iPad Mini 4" case "iPad6,3", "iPad6,4": deviceIdentifier = "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": deviceIdentifier = "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": deviceIdentifier = "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": deviceIdentifier = "iPad Pro 10.5 Inch" case "AppleTV5,3": deviceIdentifier = "Apple TV" case "i386", "x86_64": deviceIdentifier = "Simulator" default: deviceIdentifier = identifier } LocalDataStore.setObject(deviceIdentifier, forKey: identifierKey) return deviceIdentifier } // Find better name func isiPhoneXDevice() -> Bool { return modelName.startsWith("iPhone X") } // Find better name func isiPad() -> Bool { return modelName.startsWith("iPad") } func isSmallIphoneDevice() -> Bool { return modelName.startsWith("iPhone 4") || modelName.startsWith("iPhone 5") || modelName.startsWith("iPhone SE") } }
f0dda31de95d564c12595ed81f4aba53
51.130952
120
0.536195
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/ViewModels/TxDetailViewModel.swift
mit
1
// // TxDetailViewModel.swift // breadwallet // // Created by Adrian Corscadden on 2017-12-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit /// View model of a transaction in detail view struct TxDetailViewModel: TxViewModel { // MARK: - let amount: String let fiatAmount: String let originalFiatAmount: String? let exchangeRate: String? let tx: Transaction // Ethereum-specific fields var gasPrice: String? var gasLimit: String? var fee: String? var total: String? var title: String { guard status != .invalid else { return S.TransactionDetails.titleFailed } switch direction { case .recovered: return S.TransactionDetails.titleInternal case .received: return status == .complete ? S.TransactionDetails.titleReceived : S.TransactionDetails.titleReceiving case .sent: return status == .complete ? S.TransactionDetails.titleSent : S.TransactionDetails.titleSending } } var timestampHeader: NSAttributedString { if status == .complete { let text = " " + S.TransactionDetails.completeTimestampHeader let attributedString = NSMutableAttributedString(string: text) let icon = NSTextAttachment() icon.image = #imageLiteral(resourceName: "CircleCheckSolid").withRenderingMode(.alwaysTemplate) icon.bounds = CGRect(x: 0, y: -2.0, width: 14.0, height: 14.0) let iconString = NSMutableAttributedString(string: S.Symbols.narrowSpace) // space required before an attachment to apply template color (UIKit bug) iconString.append(NSAttributedString(attachment: icon)) attributedString.insert(iconString, at: 0) attributedString.addAttributes([.foregroundColor: UIColor.receivedGreen, .font: UIFont.customBody(size: 0.0)], range: NSRange(location: 0, length: iconString.length)) return attributedString } else { return NSAttributedString(string: S.TransactionDetails.initializedTimestampHeader) } } var addressHeader: String { if direction == .sent { return S.TransactionDetails.addressToHeader } else { if tx.currency.isBitcoinCompatible { return S.TransactionDetails.addressViaHeader } else { return S.TransactionDetails.addressFromHeader } } } var extraAttribute: String? { return tx.extraAttribute } var extraAttributeHeader: String { if tx.currency.isXRP { return S.TransactionDetails.destinationTagHeader } if tx.currency.isHBAR { return S.TransactionDetails.memoTagHeader } return "" } var transactionHash: String { return currency.isEthereumCompatible ? tx.hash : tx.hash.removing(prefix: "0x") } } extension TxDetailViewModel { init(tx: Transaction) { let rate = tx.currency.state?.currentRate ?? Rate.empty amount = TxDetailViewModel.tokenAmount(tx: tx) ?? "" let fiatAmounts = TxDetailViewModel.fiatAmounts(tx: tx, currentRate: rate) fiatAmount = fiatAmounts.0 originalFiatAmount = fiatAmounts.1 exchangeRate = TxDetailViewModel.exchangeRateText(tx: tx) self.tx = tx if tx.direction == .sent { var feeAmount = tx.fee feeAmount.maximumFractionDigits = Amount.highPrecisionDigits fee = Store.state.showFiatAmounts ? feeAmount.fiatDescription : feeAmount.tokenDescription } //TODO:CRYPTO incoming token transfers have a feeBasis with 0 values if let feeBasis = tx.feeBasis, (currency.isEthereum || (currency.isEthereumCompatible && tx.direction == .sent)) { let gasFormatter = NumberFormatter() gasFormatter.numberStyle = .decimal gasFormatter.maximumFractionDigits = 0 self.gasLimit = gasFormatter.string(from: feeBasis.costFactor as NSNumber) let gasUnit = feeBasis.pricePerCostFactor.currency.unit(named: "gwei") ?? currency.defaultUnit gasPrice = feeBasis.pricePerCostFactor.tokenDescription(in: gasUnit) } // for outgoing txns for native tokens show the total amount sent including fee if tx.direction == .sent, tx.confirmations > 0, tx.amount.currency == tx.fee.currency { var totalWithFee = tx.amount + tx.fee totalWithFee.maximumFractionDigits = Amount.highPrecisionDigits total = Store.state.showFiatAmounts ? totalWithFee.fiatDescription : totalWithFee.tokenDescription } } /// The fiat exchange rate at the time of transaction /// Returns nil if no rate found or rate currency mismatches the current fiat currency private static func exchangeRateText(tx: Transaction) -> String? { guard let metaData = tx.metaData, let currentRate = tx.currency.state?.currentRate, !metaData.exchangeRate.isZero, (metaData.exchangeRateCurrency == currentRate.code || metaData.exchangeRateCurrency.isEmpty) else { return nil } let nf = NumberFormatter() nf.currencySymbol = currentRate.currencySymbol nf.numberStyle = .currency return nf.string(from: metaData.exchangeRate as NSNumber) ?? nil } private static func tokenAmount(tx: Transaction) -> String? { let amount = Amount(amount: tx.amount, rate: nil, maximumFractionDigits: Amount.highPrecisionDigits, negative: (tx.direction == .sent && !tx.amount.isZero)) return amount.description } /// Fiat amount at current exchange rate and at original rate at time of transaction (if available) /// Returns the token transfer description for token transfer originating transactions, as first return value. /// Returns (currentFiatAmount, originalFiatAmount) private static func fiatAmounts(tx: Transaction, currentRate: Rate) -> (String, String?) { let currentAmount = Amount(amount: tx.amount, rate: currentRate).description guard let metaData = tx.metaData else { return (currentAmount, nil) } guard metaData.tokenTransfer.isEmpty else { let tokenTransfer = String(format: S.Transaction.tokenTransfer, metaData.tokenTransfer.uppercased()) return (tokenTransfer, nil) } // no tx-time rate guard !metaData.exchangeRate.isZero, (metaData.exchangeRateCurrency == currentRate.code || metaData.exchangeRateCurrency.isEmpty) else { return (currentAmount, nil) } let originalRate = Rate(code: currentRate.code, name: currentRate.name, rate: metaData.exchangeRate, reciprocalCode: currentRate.reciprocalCode) let originalAmount = Amount(amount: tx.amount, rate: originalRate).description return (currentAmount, originalAmount) } }
bdc6ed76f61566110c51889d22a0cfa9
41.113636
160
0.630464
false
false
false
false
renrawnalon/AutoHeightTextView
refs/heads/master
AutoHeightTextView/ViewController.swift
mit
1
// // ViewController.swift // AutoHeightTextView // // Created by ノーランワーナー on 2015/10/21. // Copyright © 2015年 test. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate { let verticalInset = 20.0 let horizontalInset = 10.0 let backgroundColor = UIColor(white: 0.97, alpha: 1.0) let animationDuration = 0.2 @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var scrollViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() textView.textAlignment = .Left textView.showsVerticalScrollIndicator = false textView.backgroundColor = backgroundColor imageViewWidthConstraint.constant = self.view.frame.size.width - 16 NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let oldString: NSString = textView.text let newString: NSString = oldString.stringByReplacingCharactersInRange(range, withString: text) let size = CGSizeMake(textView.frame.size.width - CGFloat(horizontalInset), CGFloat(MAXFLOAT)) let rect = newString.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font!], context: nil) textViewHeightConstraint.constant = rect.height + CGFloat(verticalInset) self.view.animateLayout(animationDuration) return true } func keyboardWillChangeFrame(notification: NSNotification) { guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() else { return; } guard let animationDuration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return; } print("\(animationDuration) and \(keyboardRect)") scrollViewBottomConstraint.constant = view.frame.size.height - keyboardRect.origin.y self.view.animateLayout(animationDuration) } } extension UIView { func animateLayout(duration: NSTimeInterval) { UIView.animateWithDuration(duration, animations: { [weak self] in self?.layoutIfNeeded() }) } }
87230bd126a415e26ce63e3f52a89aed
37.356164
176
0.705357
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Avatars/AvatarManager.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import Teapot import Haneke final class AvatarManager: NSObject { @objc static let shared = AvatarManager() private let cache = Shared.imageCache func refreshAvatar(at path: String) { cache.remove(key: path) } @objc func cleanCache() { cache.removeAll() } @objc func startDownloadContactsAvatars() { if let currentUserAvatarPath = Profile.current?.avatar { downloadAvatar(for: currentUserAvatarPath) } for path in SessionManager.shared.profilesManager.profilesAvatarPaths { downloadAvatar(for: path) } } private func baseURL(from url: URL) -> String? { if url.baseURL == nil { guard let scheme = url.scheme, let host = url.host else { return nil } return "\(scheme)://\(host)" } return url.baseURL?.absoluteString } func downloadAvatar(for key: String, completion: ((UIImage?, String?) -> Void)? = nil) { if key.hasAddressPrefix { cache.fetch(key: key).onSuccess { image in completion?(image, key) }.onFailure({ _ in IDAPIClient.shared.findContact(name: key) { [weak self] profile, _ in guard let avatarPath = profile?.avatar else { completion?(nil, key) return } UserDefaults.standard.set(avatarPath, forKey: key) self?.downloadAvatar(path: avatarPath, completion: completion) } }) } else { cache.fetch(key: key).onSuccess { image in completion?(image, key) return }.onFailure { [weak self] _ in guard let strongSelf = self else { return } strongSelf.downloadAvatar(path: key) } } } private func downloadAvatar(path: String, completion: ((UIImage?, String?) -> Void)? = nil) { cache.fetch(key: path).onSuccess { image in completion?(image, path) }.onFailure({ _ in guard let url = URL(string: path) else { DispatchQueue.main.async { completion?(nil, path) } return } URLSession.shared.dataTask(with: url, completionHandler: { [weak self] data, _, _ in guard let strongSelf = self else { return } guard let retrievedData = data else { return } guard let image = UIImage(data: retrievedData) else { return } strongSelf.cache.set(value: image, key: path) DispatchQueue.main.async { completion?(image, path) } }).resume() }) } /// Downloads or finds avatar for given key. /// /// - Parameters: /// - key: token_id/address or resource url path. /// - completion: The completion closure to fire when the request completes or image is found in cache. /// - image: Found in cache or fetched image. /// - path: Path for found in cache or fetched image. func avatar(for key: String, completion: @escaping ((UIImage?, String?) -> Void)) { if key.hasAddressPrefix { if let avatarPath = UserDefaults.standard.object(forKey: key) as? String { _avatar(for: avatarPath, completion: completion) } else { downloadAvatar(for: key, completion: completion) } } _avatar(for: key, completion: completion) } /// Downloads or finds avatar for the resource url path. /// /// - Parameters: /// - path: An resource url path. /// - completion: The completion closure to fire when the request completes or image is found in cache. /// - image: Found in cache or fetched image. /// - path: Path for found in cache or fetched image. private func _avatar(for path: String, completion: @escaping ((UIImage?, String?) -> Void)) { cache.fetch(key: path).onSuccess { image in completion(image, path) }.onFailure { [weak self] _ in guard let strongSelf = self else { return } strongSelf.downloadAvatar(path: path, completion: completion) } } /// Finds avatar for the given key. /// /// - Parameters: /// - key: token_id/address or resource url path. /// - Returns: /// - found image or nil if not present @objc func cachedAvatar(for key: String) -> UIImage? { guard !key.hasAddressPrefix else { guard let avatarPath = UserDefaults.standard.object(forKey: key) as? String else { return nil } return cachedAvatar(for: avatarPath) } var image: UIImage? cache.fetch(key: key).onSuccess { cachedImage in image = cachedImage } return image } }
0f85ff76b7bbf45ba53d7624c9f6acf6
33.529412
109
0.561499
false
false
false
false
gewill/Feeyue
refs/heads/develop
Feeyue/Main/Weibo/Views/GWStatusOnePhotoCell.swift
mit
1
// // GWStatusOnePhotoCell.swift // Feeyue // // Created by Will on 11/05/2017. // Copyright © 2017 Will. All rights reserved. // import UIKit import SnapKit protocol GWStatusOnePhotoCellDelegate: class { func statusOnePhotoCelDidClickPhoto(_ cell: GWStatusOnePhotoCell) } class GWStatusOnePhotoCell: UICollectionViewCell { var oneImageView: UIImageView! weak var delegate: GWStatusOnePhotoCellDelegate? var status: Status? { didSet { if self.status?.hasRetweetedPics == true { self.backgroundColor = GWColor.f2 } else { self.backgroundColor = UIColor.white } if let status = status { setupImageWith(urlArray: status.largePics) } } } // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } private func setupViews() { oneImageView = UIImageView() oneImageView.clipsToBounds = true oneImageView.contentMode = .scaleAspectFill oneImageView.gw_addTapGestureRecognizer(target: self, action: #selector(self.oneImageViewClick(_:))) self.addSubview(oneImageView) oneImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 16, right: 16)) } } // MARK: - config methods static func cellSize() -> CGSize { return CGSize(width: ScreenWidth, height: ScreenWidth - 16 * 2 + 16) } // MARK: - response methods @objc func oneImageViewClick(_ sender: UITapGestureRecognizer) { delegate?.statusOnePhotoCelDidClickPhoto(self) } // MARK: - private methods private func setupImageWith(urlArray array: [String]) { if array.count == 1 { var string = array[0] if array[0].hasSuffix(".gif") == true { let playImageView = UIImageView() playImageView.image = UIImage(named: "MMVideoPreviewPlayHL") self.oneImageView.addSubview(playImageView) playImageView.snp.makeConstraints({ (make) in make.center.equalToSuperview() make.width.height.equalTo(60) }) string = string.replacingOccurrences(of: "/bmiddle/", with: "/or480/") } if let url = URL(string: string) { self.oneImageView.kf.setImage(with: url, placeholder: PlaceholderView.randomColor()) } } } }
08573ac93c06e3738b4283589c60bd40
28.163043
108
0.600447
false
false
false
false
biohazardlover/ByTrain
refs/heads/master
ByTrain/Entities/Train.swift
mit
1
import SwiftyJSON public struct Train { public var train_no: String? /// 车次 public var station_train_code: String? public var start_station_telecode: String? /// 出发站 public var start_station_name: String? public var end_station_telecode: String? /// 到达站 public var end_station_name: String? public var from_station_telecode: String? public var from_station_name: String? public var to_station_telecode: String? public var to_station_name: String? /// 出发时间 public var start_time: String? /// 到达时间 public var arrive_time: String? public var day_difference: String? public var train_class_name: String? /// 历时 public var lishi: String? public var canWebBuy: String? public var lishiValue: String? /// 余票信息 public var yp_info: String? public var control_train_day: String? public var start_train_date: String? public var seat_feature: String? public var yp_ex: String? public var train_seat_feature: String? public var seat_types: String? public var location_code: String? public var from_station_no: String? public var to_station_no: String? public var control_day: String? public var sale_time: String? public var is_support_card: String? public var gg_num: String? /// 高级软卧 public var gr_num: String? /// 其他 public var qt_num: String? /// 软卧 public var rw_num: String? /// 软座 public var rz_num: String? /// 特等座 public var tz_num: String? /// 无座 public var wz_num: String? public var yb_num: String? /// 硬卧 public var yw_num: String? /// 硬座 public var yz_num: String? /// 二等座 public var ze_num: String? /// 一等座 public var zy_num: String? /// 商务座 public var swz_num: String? public var secretStr: String? public var buttonTextInfo: String? public var distance: String? public var fromStation: Station? public var toStation: Station? public var departureDate: Date? public var businessClassSeatType: SeatType public var specialClassSeatType: SeatType public var firstClassSeatType: SeatType public var secondClassSeatType: SeatType public var premiumSoftRoometteType: SeatType public var softRoometteType: SeatType public var hardRoometteType: SeatType public var softSeatType: SeatType public var hardSeatType: SeatType public var noSeatType: SeatType public var otherType: SeatType public var allSeatTypes: [SeatType] public var duration: String? { if let durationInMinutes = Int(lishiValue ?? "") { let days = durationInMinutes / (60 * 24) let hours = (durationInMinutes % (60 * 24)) / 60 let minutes = (durationInMinutes % (60 * 24)) % 60 var duration = "" if days > 0 { duration += "\(days)天" } if hours > 0 { duration += "\(hours)小时" } duration += "\(minutes)分" return duration } return nil } /// yyyy-MM-dd public var departureDateString: String? { if let start_train_date = start_train_date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd" if let departureDate = dateFormatter.date(from: start_train_date) { dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: departureDate) } } return nil } public var availableSeatTypes: [SeatType] { let availableSeatTypes = allSeatTypes.filter { (seatType) -> Bool in return seatType.leftSeats != "--" } return availableSeatTypes } public var highlightedSeatType: SeatType? { for seatType in availableSeatTypes.reversed() { if seatType.leftSeats != "无" { return seatType } } return availableSeatTypes.last } public init() { businessClassSeatType = SeatType(identifier: SeatTypeIdentifierBusinessClassSeat) specialClassSeatType = SeatType(identifier: SeatTypeIdentifierSpecialClassSeat) firstClassSeatType = SeatType(identifier: SeatTypeIdentifierFirstClassSeat) secondClassSeatType = SeatType(identifier: SeatTypeIdentifierSecondClassSeat) premiumSoftRoometteType = SeatType(identifier: SeatTypeIdentifierPremiumSoftRoomette) softRoometteType = SeatType(identifier: SeatTypeIdentifierSoftRoomette) hardRoometteType = SeatType(identifier: SeatTypeIdentifierHardRoomette) softSeatType = SeatType(identifier: SeatTypeIdentifierSoftSeat) hardSeatType = SeatType(identifier: SeatTypeIdentifierHardSeat) noSeatType = SeatType(identifier: SeatTypeIdentifierNoSeat) otherType = SeatType(identifier: SeatTypeIdentifierOther) allSeatTypes = [businessClassSeatType, specialClassSeatType, firstClassSeatType, secondClassSeatType, premiumSoftRoometteType, softRoometteType, hardRoometteType, softSeatType, hardSeatType, noSeatType, otherType] } } extension Train: Equatable { public static func ==(lhs: Train, rhs: Train) -> Bool { return lhs.train_no == rhs.train_no } } extension Train: ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? JSON else { return nil } self.init() let queryLeftNewDTO = representation["queryLeftNewDTO"] train_no = queryLeftNewDTO["train_no"].string station_train_code = queryLeftNewDTO["station_train_code"].string start_station_telecode = queryLeftNewDTO["start_station_telecode"].string start_station_name = queryLeftNewDTO["start_station_name"].string end_station_telecode = queryLeftNewDTO["end_station_telecode"].string end_station_name = queryLeftNewDTO["end_station_name"].string from_station_telecode = queryLeftNewDTO["from_station_telecode"].string from_station_name = queryLeftNewDTO["from_station_name"].string to_station_telecode = queryLeftNewDTO["to_station_telecode"].string to_station_name = queryLeftNewDTO["to_station_name"].string start_time = queryLeftNewDTO["start_time"].string arrive_time = queryLeftNewDTO["arrive_time"].string day_difference = queryLeftNewDTO["day_difference"].string train_class_name = queryLeftNewDTO["train_class_name"].string lishi = queryLeftNewDTO["lishi"].string canWebBuy = queryLeftNewDTO["canWebBuy"].string lishiValue = queryLeftNewDTO["lishiValue"].string yp_info = queryLeftNewDTO["yp_info"].string control_train_day = queryLeftNewDTO["control_train_day"].string start_train_date = queryLeftNewDTO["start_train_date"].string seat_feature = queryLeftNewDTO["seat_feature"].string yp_ex = queryLeftNewDTO["yp_ex"].string train_seat_feature = queryLeftNewDTO["train_seat_feature"].string seat_types = queryLeftNewDTO["seat_types"].string location_code = queryLeftNewDTO["location_code"].string from_station_no = queryLeftNewDTO["from_station_no"].string to_station_no = queryLeftNewDTO["to_station_no"].string control_day = queryLeftNewDTO["control_day"].string sale_time = queryLeftNewDTO["sale_time"].string is_support_card = queryLeftNewDTO["is_support_card"].string gg_num = queryLeftNewDTO["gg_num"].string gr_num = queryLeftNewDTO["gr_num"].string qt_num = queryLeftNewDTO["qt_num"].string rw_num = queryLeftNewDTO["rw_num"].string rz_num = queryLeftNewDTO["rz_num"].string tz_num = queryLeftNewDTO["tz_num"].string wz_num = queryLeftNewDTO["wz_num"].string yb_num = queryLeftNewDTO["yb_num"].string yw_num = queryLeftNewDTO["yw_num"].string yz_num = queryLeftNewDTO["yz_num"].string ze_num = queryLeftNewDTO["ze_num"].string zy_num = queryLeftNewDTO["zy_num"].string swz_num = queryLeftNewDTO["swz_num"].string secretStr = representation["secretStr"].string buttonTextInfo = representation["buttonTextInfo"].string businessClassSeatType.leftSeats = swz_num specialClassSeatType.leftSeats = tz_num firstClassSeatType.leftSeats = zy_num secondClassSeatType.leftSeats = ze_num premiumSoftRoometteType.leftSeats = gr_num softRoometteType.leftSeats = rw_num hardRoometteType.leftSeats = yw_num softSeatType.leftSeats = rz_num hardSeatType.leftSeats = yz_num noSeatType.leftSeats = wz_num otherType.leftSeats = qt_num } }
9c10dd202038f8f7664c52341aad5237
32.606618
221
0.640958
false
false
false
false
richy486/EndlessPageView
refs/heads/master
EndlessPageView/EndlessPageView.swift
mit
1
// // EndlessPageView.swift // EndlessPageView // // Created by Richard Adem on 6/21/16. // Copyright © 2016 Richard Adem. All rights reserved. // import UIKit import Interpolate public struct IndexLocation : Hashable { public var column:Int public var row:Int public var hashValue: Int { if MemoryLayout<Int>.size == MemoryLayout<Int64>.size { return column.hashValue | (row.hashValue << 32) } else { return column.hashValue | (row.hashValue << 16) } } public init(column: Int, row: Int) { self.column = column self.row = row } } public func == (lhs: IndexLocation, rhs: IndexLocation) -> Bool { return lhs.column == rhs.column && lhs.row == rhs.row } public protocol EndlessPageViewDataSource : class { func endlessPageView(_ endlessPageView:EndlessPageView, cellForIndexLocation indexLocation: IndexLocation) -> EndlessPageCell? } public protocol EndlessPageViewDelegate : class { func endlessPageViewDidSelectItemAtIndex(_ indexLocation: IndexLocation) func endlessPageViewWillScroll(_ endlessPageView: EndlessPageView) func endlessPageViewDidScroll(_ endlessPageView: EndlessPageView) func endlessPageViewShouldScroll(_ endlessPageView: EndlessPageView, scrollingDirection: EndlessPageScrollDirectionRules) -> EndlessPageScrollDirectionRules func endlessPageView(_ endlessPageView: EndlessPageView, willDisplayCell cell: EndlessPageCell, forItemAtIndexLocation indexLocation: IndexLocation) func endlessPageView(_ endlessPageView: EndlessPageView, didEndDisplayingCell cell: EndlessPageCell, forItemAtIndexLocation indexLocation: IndexLocation) func endlessPageViewDidEndDecelerating(_ endlessPageView: EndlessPageView) } public struct EndlessPageScrollDirectionRules : OptionSet { public var rawValue : UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } public static let Horizontal = EndlessPageScrollDirectionRules(rawValue: 1 << 0) public static let Vertical = EndlessPageScrollDirectionRules(rawValue: 1 << 2) public static var Both : EndlessPageScrollDirectionRules = [ .Horizontal, .Vertical ] } @IBDesignable open class EndlessPageView : UIView, UIGestureRecognizerDelegate, _EndlessPageCellDelegate { // - Public - // Protocols open weak var dataSource:EndlessPageViewDataSource? open weak var delegate:EndlessPageViewDelegate? // Public settings open var printDebugInfo = false open var scrollDirection:EndlessPageScrollDirectionRules = .Both open var pagingEnabled = true open var directionalLockEnabled = true fileprivate(set) open var directionLockedTo:EndlessPageScrollDirectionRules = .Both // - Private - // Offset position open var contentOffset = CGPoint.zero { didSet { if contentOffset.x.isNaN || contentOffset.y.isNaN { contentOffset = oldValue } updateBounds() updateCells() } } fileprivate var panStartContentOffset = CGPoint.zero open var scrollingInDirection: CGFloat { get { if directionLockedTo == .Horizontal { return self.bounds.origin.x - panStartContentOffset.x } else if directionLockedTo == .Vertical { return self.bounds.origin.y - panStartContentOffset.y } return CGFloat(0) } } // Cell pool fileprivate var cellPool = [String: [EndlessPageCell]]() fileprivate var registeredCellClasses = [String: EndlessPageCell.Type]() fileprivate var visibleCellsFromLocation = [IndexLocation: EndlessPageCell]() // Animation fileprivate var offsetChangeAnimation:Interpolate? fileprivate var hasDoneFirstReload = false // MARK: View lifecycle override public init(frame: CGRect) { super.init(frame: frame) setup() } convenience public init () { self.init(frame:CGRect.zero) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture_scroll(_:))) panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) clipsToBounds = true } override open func layoutSubviews() { super.layoutSubviews() if !hasDoneFirstReload { hasDoneFirstReload = true reloadData() } } override open func prepareForInterfaceBuilder() { print("prepareForInterfaceBuilder") } // MARK: Actions func panGesture_scroll(_ panGesture: UIPanGestureRecognizer) { if let gestureView = panGesture.view, let holder = gestureView.superview { let translatePoint = panGesture.translation(in: holder) var runCompletion = false if panGesture.state == UIGestureRecognizerState.began { panStartContentOffset = contentOffset if let offsetChangeAnimation = offsetChangeAnimation { runCompletion = false offsetChangeAnimation.stopAnimation() } delegate?.endlessPageViewWillScroll(self) } if panGesture.state == UIGestureRecognizerState.changed { contentOffset = { var point = contentOffset guard scrollDirection != [] else { return panStartContentOffset } if scrollDirection.contains(.Horizontal) { point.x = (panStartContentOffset - translatePoint).x } if scrollDirection.contains(.Vertical) { point.y = (panStartContentOffset - translatePoint).y } if directionalLockEnabled { if directionLockedTo == .Both { let deltaX = abs(panStartContentOffset.x - point.x) let deltaY = abs(panStartContentOffset.y - point.y) if deltaX != 0 && deltaY != 0 { if deltaX >= deltaY { directionLockedTo = [.Horizontal] } else { directionLockedTo = [.Vertical] } } } } guard directionLockedTo != [] else { return panStartContentOffset } if let allowedScrollDirection = delegate?.endlessPageViewShouldScroll(self, scrollingDirection: directionLockedTo) { guard allowedScrollDirection != [] else { return panStartContentOffset } if !allowedScrollDirection.contains(.Horizontal) { point.x = panStartContentOffset.x } if !allowedScrollDirection.contains(.Vertical) { point.y = panStartContentOffset.y } } return point }() } if panGesture.state == UIGestureRecognizerState.ended { if let offsetChangeAnimation = offsetChangeAnimation { runCompletion = false offsetChangeAnimation.stopAnimation() } if pagingEnabled { let offsetPage = floor((panStartContentOffset / self.bounds.size) + 0.5) var targetColumn = Int(offsetPage.x) var targetRow = Int(offsetPage.y) let localizedOffset = contentOffset - (CGPoint(x: targetColumn, y: targetRow) * self.bounds.size) let triggerPercent = CGFloat(0.1) if abs(localizedOffset.x) > self.bounds.size.width * triggerPercent { if contentOffset.x > panStartContentOffset.x { targetColumn += 1 } else if contentOffset.x < panStartContentOffset.x { targetColumn -= 1 } } else if abs(localizedOffset.y) > self.bounds.size.height * triggerPercent { if contentOffset.y > panStartContentOffset.y { targetRow += 1 } else if contentOffset.y < panStartContentOffset.y { targetRow -= 1 } } var pagePoint = CGPoint(x: CGFloat(targetColumn), y: CGFloat(targetRow)) * self.bounds.size // Check if cell exists, we already have loaded the visible cells if visibleCellsFromLocation[IndexLocation(column: targetColumn, row: targetRow)] == nil { let targetColumn = Int(offsetPage.x) let targetRow = Int(offsetPage.y) pagePoint = CGPoint(x: CGFloat(targetColumn), y: CGFloat(targetRow)) * self.bounds.size } if printDebugInfo { print("targetColumn: \(targetColumn), targetRow: \(targetRow)") } let animationTime:TimeInterval = 0.2 runCompletion = true offsetChangeAnimation = Interpolate(from: contentOffset , to: pagePoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos self?.updateBounds() self?.updateCells() }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if runCompletion { if let strongSelf = self { strongSelf.directionLockedTo = .Both strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } } }) } else { let velocity = panGesture.velocity(in: holder) * -1 let magnitude = sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)) let slideMult = magnitude / 200 let slideFactor = 0.1 * slideMult let animationTime = TimeInterval(slideFactor * 2) let slideToPoint:CGPoint = { var point = contentOffset if scrollDirection.contains(.Horizontal) { point.x = contentOffset.x + (velocity.x * slideFactor) } if scrollDirection.contains(.Vertical) { point.y = contentOffset.y + (velocity.y * slideFactor) } return point }() offsetChangeAnimation = Interpolate(from: contentOffset , to: slideToPoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if let strongSelf = self { strongSelf.directionLockedTo = .Both strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } }) } } } } // MARK: Public getters open func visibleCells() -> [EndlessPageCell] { return Array(visibleCellsFromLocation.values) } open func indexLocationsForVisibleItems() -> [IndexLocation] { return Array(visibleCellsFromLocation.keys) } open func indexLocationForCell(_ cell: EndlessPageCell) -> IndexLocation? { let pagePoint = round(cell.frame.origin / self.bounds.size, tollerence: 0.0001) if !pagePoint.x.isNaN && !pagePoint.y.isNaN { let indexLocation = IndexLocation(column: Int(pagePoint.x), row: Int(pagePoint.y)) return indexLocation } return nil } open func setContentOffset(_ offset: CGPoint, animated: Bool) { if let indexLocation = indexLocationForItemAtPoint(offset) { scrollToItemAtIndexLocation(indexLocation, animated: animated) } } open func indexLocationForItemAtPoint(_ point: CGPoint) -> IndexLocation? { let pagePoint = round(point / self.bounds.size, tollerence: 0.0001) if !pagePoint.x.isNaN && !pagePoint.y.isNaN { let indexLocation = IndexLocation(column: Int(pagePoint.x), row: Int(pagePoint.y)) return indexLocation } return nil } open func indexLocationFromContentOffset() -> IndexLocation? { return indexLocationForItemAtPoint(contentOffset) } open func cellForItemAtIndexLocation(_ indexLocation: IndexLocation) -> EndlessPageCell? { if let cell = visibleCellsFromLocation[indexLocation] { return cell } else if let cell = dataSource?.endlessPageView(self, cellForIndexLocation: indexLocation) { visibleCellsFromLocation[indexLocation] = cell addSubview(cell) delegate?.endlessPageView(self, willDisplayCell: cell, forItemAtIndexLocation: indexLocation) return cell } return nil } open func scrollToItemAtIndexLocation(_ indexLocation: IndexLocation, animated:Bool) { let animationTime = TimeInterval(animated ? 0.25 : 0.0) let pagePoint = CGPoint(x: indexLocation.column, y: indexLocation.row) * self.bounds.size if let offsetChangeAnimation = offsetChangeAnimation { offsetChangeAnimation.stopAnimation() offsetChangeAnimation.invalidate() } if animated { if contentOffset.x != pagePoint.x && contentOffset.y == pagePoint.y { directionLockedTo = [.Horizontal] } else if contentOffset.x == pagePoint.x && contentOffset.y != pagePoint.y { directionLockedTo = [.Vertical] } else { directionLockedTo = .Both } } offsetChangeAnimation = Interpolate(from: contentOffset , to: pagePoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if let strongSelf = self { strongSelf.contentOffset = pagePoint strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } }) } // MARK: Data cache open func reloadData() { let keys = visibleCellsFromLocation.keys keys.forEach({ (indexLocation) in if let cell = visibleCellsFromLocation[indexLocation] { delegate?.endlessPageView(self, didEndDisplayingCell: cell, forItemAtIndexLocation: indexLocation) cell.removeFromSuperview() } visibleCellsFromLocation[indexLocation] = nil }) contentOffset = CGPoint.zero updateBounds() updateCells() } open func setIndexLocation(_ indexLocation: IndexLocation) { let position = CGPoint(x: CGFloat(indexLocation.column) * self.frame.width , y: CGFloat(indexLocation.row) * self.frame.height) contentOffset = position updateBounds() } open func registerClass(_ cellClass: EndlessPageCell.Type?, forViewWithReuseIdentifier identifier: String) { registeredCellClasses[identifier] = cellClass } open func registerNib(_ nib: UINib?, forViewWithReuseIdentifier identifier: String) { fatalError("registerNib(nib:forViewWithReuseIdentifier:) has not been implemented") } open func dequeueReusableCellWithReuseIdentifier(_ identifier: String) -> EndlessPageCell { if cellPool[identifier] == nil { cellPool[identifier] = [EndlessPageCell]() } // This could probably be faster with two arrays for is use and not in use if let cells = cellPool[identifier] { for cell in cells { if cell.superview == nil { cell.prepareForReuse() return cell } } } if let cellClass = registeredCellClasses[identifier] { let cell = cellClass.init(frame: bounds) cell.privateDelegate = self cellPool[identifier]?.append(cell) if printDebugInfo { print("generated cell for identifer: \(identifier), pool size: ", cellPool[identifier]?.count) } return cell } fatalError(String(format: "Did not register class %@ for EndlessPageView ", identifier)) } // MARK: Update cells fileprivate func updateBounds() { bounds = CGRect(origin: contentOffset, size: bounds.size) delegate?.endlessPageViewDidScroll(self) } fileprivate func updateCells() { let pageOffset = round(contentOffset / CGPoint(x: self.frame.width, y: self.frame.height) , tollerence: 0.0001) if !pageOffset.x.isNaN && !pageOffset.y.isNaN { let rows:[Int] = { if pageOffset.y >= 0 { return floor(pageOffset.y) == pageOffset.y ? [Int(pageOffset.y)] : [Int(pageOffset.y), Int(pageOffset.y + 1)] } return floor(pageOffset.y) == pageOffset.y ? [Int(pageOffset.y)] : [Int(pageOffset.y), Int(pageOffset.y - 1)] }() let columns:[Int] = { if pageOffset.x >= 0 { return floor(pageOffset.x) == pageOffset.x ? [Int(pageOffset.x)] : [Int(pageOffset.x), Int(pageOffset.x + 1)] } return floor(pageOffset.x) == pageOffset.x ? [Int(pageOffset.x)] : [Int(pageOffset.x), Int(pageOffset.x - 1)] }() var updatedVisibleCellIndexLocations = [IndexLocation]() for row in rows { for column in columns { let indexLocation = IndexLocation(column: column, row: row) if let cell = cellForItemAtIndexLocation(indexLocation) { cell.frame = CGRect(x: self.frame.width * CGFloat(column) , y: self.frame.height * CGFloat(row) , width: self.frame.width , height: self.frame.height) updatedVisibleCellIndexLocations.append(indexLocation) } } } let oldCount = visibleCellsFromLocation.count let previousKeys = visibleCellsFromLocation.keys let removedKeys = previousKeys.filter( { !updatedVisibleCellIndexLocations.contains($0) } ) removedKeys.forEach({ (indexLocation) in if let cell = visibleCellsFromLocation[indexLocation] { delegate?.endlessPageView(self, didEndDisplayingCell: cell, forItemAtIndexLocation: indexLocation) cell.removeFromSuperview() } visibleCellsFromLocation[indexLocation] = nil }) if printDebugInfo { if oldCount != visibleCellsFromLocation.count { print("removed \(oldCount - visibleCellsFromLocation.count) cells") } } } else { print("Error in page offset: \(pageOffset)") } } // MARK: Gesture delegate open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // MARK: Endless page cell delegate internal func didSelectCell(_ cell: EndlessPageCell) { if let indexLocation = self.indexLocationForCell(cell) { delegate?.endlessPageViewDidSelectItemAtIndex(indexLocation) } } }
d480d4597cb93c5e2156f559cccd6565
37.798276
162
0.532018
false
false
false
false
kharrison/CodeExamples
refs/heads/master
Playgrounds/ContentMode.playground/Sources/CircleView.swift
bsd-3-clause
1
import UIKit public class CircleView: UIView { var lineWidth: CGFloat = 5 { didSet { setNeedsDisplay() } } var color: UIColor = .red { didSet { setNeedsDisplay() } } public override func draw(_ rect: CGRect) { let circleCenter = convert(center, from: superview) let circleRadius = min(bounds.size.width,bounds.size.height)/2 * 0.80 let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) circlePath.lineWidth = lineWidth color.set() circlePath.stroke() } }
275f8f11c3a4a220b1d342674a6b2f32
28.590909
148
0.626728
false
false
false
false
Baglan/MCViewport
refs/heads/master
Classes/MCViewportItem.swift
mit
1
// // MCViewportItem.swift // MCViewport // // Created by Baglan on 2/11/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation import UIKit extension MCViewport { /// The general inmlementation of a viewport item class Item: Hashable { /// Reference to the viewport weak var viewport: MCViewport? /// The original frame of the item /// /// Position calculations will be based on it var originalFrame = CGRect.zero /// The parallax ratio of the item in the XY coordinate space var parallax = CGPoint(x: 1, y: 1) /// Item z-index for stacking var zIndex: CGFloat = 0 /// The current calculated frame var frame: CGRect { guard let viewport = viewport else { return originalFrame } var transformedFrame = originalFrame.applying(transformForContentOffset(viewport.contentOffset)) for movementConstraint in movementConstraints { transformedFrame = movementConstraint.applyToFrame(transformedFrame, viewport: viewport) } return transformedFrame } /// Calculate the affine transform for a given content offset of the viewport /// - Parameter contentOffset: The content offset of the viewport to calculate for /// - Returns: The affine transform func transformForContentOffset(_ contentOffset: CGPoint) -> CGAffineTransform { return CGAffineTransform(translationX: -contentOffset.x * (parallax.x - 1), y: -contentOffset.y * (parallax.y - 1)) } /// Position the item in the viewport /// - Parameter frame: The frame rect of the item /// - Parameter viewportOffset: Offset of the viewport for which the frame is set /// - Parameter parallax: The parallax ratio of the item func place(frame: CGRect, viewportOffset: CGPoint = CGPoint.zero, parallax: CGPoint = CGPoint(x: 1, y: 1)) { self.parallax = parallax let referenceOffset = CGPoint.zero.applying(transformForContentOffset(viewportOffset)) originalFrame = frame.applying(CGAffineTransform(translationX: viewportOffset.x - referenceOffset.x, y: viewportOffset.y - referenceOffset.y)) } /// The associated view, if any var view: UIView? { return nil } // MARK: - Distances /// Distances to viewport lazy var distances: Distances = { return Distances(item: self) }() // MARK: - Movement constraints /// The current movement constraints fileprivate var movementConstraints = [MovementConstraint]() /// Add a movement constraint func addMovementConstraint(_ movementConstraint: MovementConstraint) { movementConstraints.append(movementConstraint) movementConstraints.sort { (a, b) -> Bool in a.priority < b.priority } viewport?.setNeedsLayout() } // MARK: - Visibility /// Whether the item is currently visible on the screen var isVisible: Bool { if let viewport = viewport { return viewport.isItemVisible(self) } return false } /// Hook just before the item appears on the screen func willBecomeVisible() { } /// Hook right after the item leaves the screen func didBecomeInvisible() { } // MARK: - Updates /// Update the item position func update() { guard let view = view else { return } view.center = CGPoint(x: frame.midX, y: frame.midY) } // MARK: - Hashable compliance func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(Item.self).hashValue) } } /// An item based on a UIView class ViewItem: Item { /// The associated view fileprivate var _view: UIView? override var view: UIView? { return _view } /// Create a new view /// /// To be implemented by descendants; the default implmenetation returns a simlpe UIView. /// /// - Returns: a new view func newView() -> UIView { return UIView() } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view _view = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIView ?? newView() guard let view = view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: view) } } /// An item based on a UIViewController class ViewControllerItem: Item { /// The associated view controller, if any var viewController: UIViewController? override var view: UIView? { return viewController?.view } /// Create a new view controller /// /// To beimplemented by descendants; the default implementation returns nil /// /// - Returns: A new view controller or nil func newViewController() -> UIViewController? { return nil } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view controller viewController = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIViewController ?? newViewController() guard let viewController = viewController, let view = viewController.view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewController = viewController, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: viewController) } } } /// Check if items are the same func ==(lhs: MCViewport.Item, rhs: MCViewport.Item) -> Bool { return lhs === rhs }
5d99b8d0a14d67aa07f01f66c96935c7
32.873303
154
0.561715
false
false
false
false
mauryat/firefox-ios
refs/heads/master
Account/FxAPushMessageHandler.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import SwiftyJSON import Sync import XCGLogger private let log = Logger.syncLogger let PendingAccountDisconnectedKey = "PendingAccountDisconnect" /// This class provides handles push messages from FxA. /// For reference, the [message schema][0] and [Android implementation][1] are both useful resources. /// [0]: https://github.com/mozilla/fxa-auth-server/blob/master/docs/pushpayloads.schema.json#L26 /// [1]: https://dxr.mozilla.org/mozilla-central/source/mobile/android/services/src/main/java/org/mozilla/gecko/fxa/FxAccountPushHandler.java /// The main entry points are `handle` methods, to accept the raw APNS `userInfo` and then to process the resulting JSON. class FxAPushMessageHandler { let profile: Profile init(with profile: Profile) { self.profile = profile } } extension FxAPushMessageHandler { /// Accepts the raw Push message from Autopush. /// This method then decrypts it according to the content-encoding (aes128gcm or aesgcm) /// and then effects changes on the logged in account. @discardableResult func handle(userInfo: [AnyHashable: Any]) -> PushMessageResult { guard let subscription = profile.getAccount()?.pushRegistration?.defaultSubscription else { return deferMaybe(PushMessageError.notDecrypted) } guard let encoding = userInfo["con"] as? String, // content-encoding let payload = userInfo["body"] as? String else { return deferMaybe(PushMessageError.messageIncomplete) } // ver == endpointURL path, chid == channel id, aps == alert text and content_available. let plaintext: String? if let cryptoKeyHeader = userInfo["cryptokey"] as? String, // crypto-key let encryptionHeader = userInfo["enc"] as? String, // encryption encoding == "aesgcm" { plaintext = subscription.aesgcm(payload: payload, encryptionHeader: encryptionHeader, cryptoHeader: cryptoKeyHeader) } else if encoding == "aes128gcm" { plaintext = subscription.aes128gcm(payload: payload) } else { plaintext = nil } guard let string = plaintext else { return deferMaybe(PushMessageError.notDecrypted) } return handle(plaintext: string) } func handle(plaintext: String) -> PushMessageResult { return handle(message: JSON(parseJSON: plaintext)) } /// The main entry point to the handler for decrypted messages. func handle(message json: JSON) -> PushMessageResult { if !json.isDictionary() || json.isEmpty { return handleVerification() } let rawValue = json["command"].stringValue guard let command = PushMessageType(rawValue: rawValue) else { log.warning("Command \(rawValue) received but not recognized") return deferMaybe(PushMessageError.messageIncomplete) } let result: PushMessageResult switch command { case .deviceConnected: result = handleDeviceConnected(json["data"]) case .deviceDisconnected: result = handleDeviceDisconnected(json["data"]) case .profileUpdated: result = handleProfileUpdated() case .passwordChanged: result = handlePasswordChanged() case .passwordReset: result = handlePasswordReset() case .collectionChanged: result = handleCollectionChanged(json["data"]) case .accountVerified: result = handleVerification() } return result } } extension FxAPushMessageHandler { func handleVerification() -> PushMessageResult { guard let account = profile.getAccount(), account.actionNeeded == .needsVerification else { log.info("Account verified by server either doesn't exist or doesn't need verifying") return deferMaybe(.accountVerified) } // Progress through the FxAStateMachine, then explicitly sync. // We need a better solution than calling out to FxALoginHelper, because that class isn't // available in NotificationService, where this class is also used. // Since verification via Push has never been seen to work, we can be comfortable // leaving this as unimplemented. return unimplemented(.accountVerified) } } /// An extension to handle each of the messages. extension FxAPushMessageHandler { func handleDeviceConnected(_ data: JSON?) -> PushMessageResult { guard let deviceName = data?["deviceName"].string else { return messageIncomplete(.deviceConnected) } let message = PushMessage.deviceConnected(deviceName) return deferMaybe(message) } } extension FxAPushMessageHandler { func handleDeviceDisconnected(_ data: JSON?) -> PushMessageResult { guard let deviceId = data?["id"].string else { return messageIncomplete(.deviceDisconnected) } if let ourDeviceId = self.getOurDeviceId(), deviceId == ourDeviceId { // We can't disconnect the device from the account until we have // access to the application, so we'll handle this properly in the AppDelegate, // by calling the FxALoginHelper.applicationDidDisonnect(application). profile.prefs.setBool(true, forKey: PendingAccountDisconnectedKey) return deferMaybe(PushMessage.thisDeviceDisconnected) } guard let profile = self.profile as? BrowserProfile else { // We can't look up a name in testing, so this is the same as // not knowing about it. return deferMaybe(PushMessage.deviceDisconnected(nil)) } let clients = profile.remoteClientsAndTabs let getClient = clients.getClient(fxaDeviceId: deviceId) return getClient >>== { device in let message = PushMessage.deviceDisconnected(device?.name) if let id = device?.guid { return clients.deleteClient(guid: id) >>== { _ in deferMaybe(message) } } return deferMaybe(message) } } fileprivate func getOurDeviceId() -> String? { return profile.getAccount()?.deviceRegistration?.id } } extension FxAPushMessageHandler { func handleProfileUpdated() -> PushMessageResult { return unimplemented(.profileUpdated) } } extension FxAPushMessageHandler { func handlePasswordChanged() -> PushMessageResult { return unimplemented(.passwordChanged) } } extension FxAPushMessageHandler { func handlePasswordReset() -> PushMessageResult { return unimplemented(.passwordReset) } } extension FxAPushMessageHandler { func handleCollectionChanged(_ data: JSON?) -> PushMessageResult { guard let collections = data?["collections"].arrayObject as? [String] else { log.warning("collections_changed received but incomplete: \(data ?? "nil")") return deferMaybe(PushMessageError.messageIncomplete) } // Possible values: "addons", "bookmarks", "history", "forms", "prefs", "tabs", "passwords", "clients" // syncManager will only do a subset; others will be ignored. return profile.syncManager.syncNamedCollections(why: .push, names: collections) >>== { deferMaybe(.collectionChanged(collections: collections)) } } } /// Some utility methods fileprivate extension FxAPushMessageHandler { func unimplemented(_ messageType: PushMessageType, with param: String? = nil) -> PushMessageResult { if let param = param { log.warning("\(messageType) message received with parameter = \(param), but unimplemented") } else { log.warning("\(messageType) message received, but unimplemented") } return deferMaybe(PushMessageError.unimplemented(messageType)) } func messageIncomplete(_ messageType: PushMessageType) -> PushMessageResult { log.info("\(messageType) message received, but incomplete") return deferMaybe(PushMessageError.messageIncomplete) } } enum PushMessageType: String { case deviceConnected = "fxaccounts:device_connected" case deviceDisconnected = "fxaccounts:device_disconnected" case profileUpdated = "fxaccounts:profile_updated" case passwordChanged = "fxaccounts:password_changed" case passwordReset = "fxaccounts:password_reset" case collectionChanged = "sync:collection_changed" // This isn't a real message type, just the absence of one. case accountVerified = "account_verified" } enum PushMessage: Equatable { case deviceConnected(String) case deviceDisconnected(String?) case profileUpdated case passwordChanged case passwordReset case collectionChanged(collections: [String]) case accountVerified // This is returned when we detect that it is us that has been disconnected. case thisDeviceDisconnected var messageType: PushMessageType { switch self { case .deviceConnected(_): return .deviceConnected case .deviceDisconnected(_): return .deviceDisconnected case .thisDeviceDisconnected: return .deviceDisconnected case .profileUpdated: return .profileUpdated case .passwordChanged: return .passwordChanged case .passwordReset: return .passwordReset case .collectionChanged(collections: _): return .collectionChanged case .accountVerified: return .accountVerified } } public static func ==(lhs: PushMessage, rhs: PushMessage) -> Bool { guard lhs.messageType == rhs.messageType else { return false } switch (lhs, rhs) { case (.deviceConnected(let lName), .deviceConnected(let rName)): return lName == rName case (.collectionChanged(let lList), .collectionChanged(let rList)): return lList == rList default: return true } } } typealias PushMessageResult = Deferred<Maybe<PushMessage>> enum PushMessageError: MaybeErrorType { case notDecrypted case messageIncomplete case unimplemented(PushMessageType) case timeout case accountError public var description: String { switch self { case .notDecrypted: return "notDecrypted" case .messageIncomplete: return "messageIncomplete" case .unimplemented(let what): return "unimplemented=\(what)" case .timeout: return "timeout" case .accountError: return "accountError" } } }
f2e25771967026cc9c0ad7e32b7a66d3
36.696552
153
0.668039
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
refs/heads/master
PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/HybridTools/NativeViewController.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** * View Controller wrapper around the HybridViewController that smooths the transition to a hybrid view */ class NativeViewController: PerchViewController { weak var appDelegate: AppDelegate! var pollingTimer: NSTimer! /// Allows only one request at a time to be sent to worklight for the getCurrentAssetDetail procedure var requestInProcess = false /// Allows hybrid view to essentially be reset when leaving the asset detail / asset history flow var leavingAssetDetailFlow = false override func viewDidLoad() { super.viewDidLoad() appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate } // MARK: Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MQALogger.log("NativeViewController#viewWillAppear(Bool) invoked!") self.setUpContainer() if let sensorID = appDelegate.hybridViewController.deviceID { self.pollCurrentSensor() self.pollingTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "pollCurrentSensor", userInfo: nil, repeats: true) HistoricalDataManager.sharedInstance.getAllHistoricalData(sensorID, callback: nil) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.pollingTimer.invalidate() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if leavingAssetDetailFlow { let otherRoute = ["route":"loading"] WL.sharedInstance().sendActionToJS("changePage", withData: otherRoute) leavingAssetDetailFlow = false appDelegate.hybridViewController.deviceID = nil } } /** This method sets up the container to hold the hybridViewController within the nativeViewController. */ func setUpContainer(){ self.addChildViewController(appDelegate.hybridViewController) appDelegate.hybridViewController.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height) self.view.addSubview(appDelegate.hybridViewController.view) appDelegate.hybridViewController.didMoveToParentViewController(self) } // MARK: Perch specific methods /** Polling method called every 5 seconds to query server (on a background thread) for new sensor value */ func pollCurrentSensor() { if let sensorID = appDelegate.hybridViewController.deviceID { if !requestInProcess { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.requestInProcess = true CurrentSensorDataManager.sharedInstance.getCurrentAssetDetail(sensorID, callback: {[weak self] in self?.sensorPollingResult($0)}) } } } } /** CurrentSensorDataManager callback to inform native view controller if query worked, useful in detecting asset status change - parameter success: boolean representing if query succeeded */ func sensorPollingResult(success: Bool) { dispatch_async(dispatch_get_main_queue()) { self.requestInProcess = false if success { if CurrentSensorDataManager.sharedInstance.prevSensorStatus != CurrentSensorDataManager.sharedInstance.currentSensorStatus { // Update native separtor color and mark asset overview page to be updated on re-appearing if let parentVC = self.parentViewController as? NavHandlerViewController { parentVC.updateSepartorColor(CurrentSensorDataManager.sharedInstance.currentSensorStatus) } AssetOverviewDataManager.sharedInstance.shouldReload = true } // reset to detect future changesd CurrentSensorDataManager.sharedInstance.prevSensorStatus = CurrentSensorDataManager.sharedInstance.currentSensorStatus } else { MQALogger.log("Call to getCurrentAssetDetail has failed") } } } } extension NativeViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
7016cc930f67c7f95e61780294939115
37.658537
172
0.671924
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica API Client/Habitica API Client/Models/Content/APIQuestProgress.swift
gpl-3.0
1
// // File.swift // Habitica API Client // // Created by Phillip Thelen on 13.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class APIQuestProgress: QuestProgressProtocol, Decodable { var health: Float = 0 var rage: Float = 0 var up: Float = 0 var collect: [QuestProgressCollectProtocol] enum CodingKeys: String, CodingKey { case health = "hp" case rage case up case collect } public required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) health = (try? values.decode(Float.self, forKey: .health)) ?? 0 rage = (try? values.decode(Float.self, forKey: .rage)) ?? 0 up = (try? values.decode(Float.self, forKey: .up)) ?? 0 collect = (try? values.decode([String: Int].self, forKey: .collect).map({ (collect) in return APIQuestProgressCollect(key: collect.key, count: collect.value) })) ?? [] } }
8a57bbafc3927d9e896cf720e2353c79
29.647059
94
0.627639
false
false
false
false
CraigZheng/KomicaViewer
refs/heads/master
KomicaViewer/KomicaViewer/ViewController/AddForumTableViewController.swift
mit
1
// // AddForumTableViewController.swift // KomicaViewer // // Created by Craig Zheng on 21/08/2016. // Copyright © 2016 Craig. All rights reserved. // import UIKit import KomicaEngine import DTCoreText enum ForumField: String { case name = "Name" case indexURL = "Index URL" case listURL = "Page URL" case responseURL = "Response URL" case parserType = "Page Style" } enum AddForumViewControllerType { case readonly case edit } class AddForumTableViewController: UITableViewController, SVWebViewProtocol { // MARK: UI elements. @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var pageURLLabel: UILabel! @IBOutlet weak var responseURLLabel: UILabel! @IBOutlet weak var pageStyleLabel: UILabel! @IBOutlet weak var nameDetailLabel: UILabel! @IBOutlet weak var indexDetailLabel: UILabel! @IBOutlet weak var pageDetailLabel: UILabel! @IBOutlet weak var responseDetailLabel: UILabel! @IBOutlet weak var parserPickerView: UIPickerView! @IBOutlet weak var addForumHelpButtonItem: UIBarButtonItem! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var addButtonTableViewCell: UITableViewCell! @IBOutlet weak var qrButtonTableViewCell: UITableViewCell! var newForum: KomicaForum! var unmodifiedForum: KomicaForum? var displayType = AddForumViewControllerType.edit // MARK: Private. fileprivate let pausedForumKey = "pausedForumKey" fileprivate let parserTypes = KomicaForum.parserNames fileprivate struct SegueIdentifier { static let name = "name" static let index = "index" static let page = "page" static let response = "response" static let showQRCode = "showQRCode" } // MARK: SVWebViewProtocol var svWebViewURL: URL? { set {} get { return Configuration.singleton.addForumHelpURL as URL? } } var svWebViewGuardDog: WebViewGuardDog? = { let guardDog = WebViewGuardDog() guardDog.showWarningOnBlock = true guardDog.home = Configuration.singleton.addForumHelpURL?.host return guardDog }() override func viewDidLoad() { super.viewDidLoad() if newForum == nil { // Restore from cache. if let jsonString = UserDefaults.standard.object(forKey: pausedForumKey) as? String, !jsonString.isEmpty { if let jsonData = jsonString.data(using: String.Encoding.utf8), let rawDict = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? Dictionary<String, AnyObject>, let jsonDict = rawDict { newForum = KomicaForum(jsonDict: jsonDict) } } else { // Cannot read from cache, create a new KomicaForum object. newForum = KomicaForum() } } else { unmodifiedForum = newForum addButton.setTitle("Edit", for: .normal) } reload() } deinit { // Save the incompleted forum to NSUserDefaults. if displayType == .edit && newForum.isModified() { if newForum.parserType == nil { newForum.parserType = KomicaForum.parserTypes[parserPickerView.selectedRow(inComponent: 0)] } if let jsonString = newForum.jsonEncode(), !jsonString.isEmpty { UserDefaults.standard.set(jsonString, forKey: pausedForumKey) UserDefaults.standard.synchronize() } } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { var should = true if identifier == SegueIdentifier.showQRCode { should = newForum.isReady() } return should } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segueIdentifier = segue.identifier, let textInputViewController = segue.destination as? ForumTextInputViewController { textInputViewController.delegate = self textInputViewController.allowEditing = displayType == .edit switch segueIdentifier { case SegueIdentifier.name: textInputViewController.field = ForumField.name textInputViewController.prefilledString = newForum.name case SegueIdentifier.index: textInputViewController.field = ForumField.indexURL textInputViewController.prefilledString = newForum.indexURL case SegueIdentifier.page: textInputViewController.field = ForumField.listURL textInputViewController.prefilledString = newForum.listURL case SegueIdentifier.response: textInputViewController.field = ForumField.responseURL textInputViewController.prefilledString = newForum.responseURL default: break } } else if segue.identifier == SegueIdentifier.showQRCode, let destinationViewController = segue.destination as? ShowForumQRCodeViewController { destinationViewController.forum = newForum } } func reload() { addForumHelpButtonItem.isEnabled = Configuration.singleton.addForumHelpURL != nil let incompleted = "Incompleted..." title = newForum.name nameDetailLabel.text = !(newForum.name ?? "").isEmpty ? newForum.name : incompleted indexDetailLabel.text = !(newForum.indexURL ?? "").isEmpty ? newForum.indexURL : incompleted pageDetailLabel.text = !(newForum.listURL ?? "").isEmpty ? newForum.listURL : incompleted responseDetailLabel.text = !(newForum.responseURL ?? "").isEmpty ? newForum.responseURL : incompleted var selectRow = 0 if let parserType = newForum.parserType { selectRow = KomicaForum.parserTypes.index(where: { $0 == parserType }) ?? 0 } parserPickerView.selectRow(selectRow, inComponent: 0, animated: false) addButton.isEnabled = displayType == .edit resetButton.isEnabled = displayType == .edit } fileprivate func reportAdded(_ customForum: KomicaForum) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" let timeString = dateFormatter.string(from: Date()) let nameString = "KV_ADD_CUSTOM_FORUM" if let vendorIDString = UIDevice.current.identifierForVendor?.uuidString, let contentString = customForum.jsonEncode(), let targetURL = URL(string: "http://civ.atwebpages.com/KomicaViewer/kv_add_custom_forum.php"), var targetURLComponent = URLComponents(url: targetURL, resolvingAgainstBaseURL: false) { let vendorQueryItem = URLQueryItem(name: "vendorID", value: vendorIDString) let nameQueryItem = URLQueryItem(name: "name", value: nameString) let timeQueryItem = URLQueryItem(name: "time", value: timeString) let contentQueryItem = URLQueryItem(name: "content", value: contentString) targetURLComponent.queryItems = [vendorQueryItem, nameQueryItem, timeQueryItem, contentQueryItem] // Create a quick and dirty connection to upload the content to server. if let url = targetURLComponent.url { NSURLConnection.sendAsynchronousRequest(URLRequest(url: url), queue: OperationQueue.main) {(response, data, error) in } } } } } // MARK: UI actions. extension AddForumTableViewController { @IBAction func addForumHelpAction(_ sender: AnyObject) { presentSVWebView() } @IBAction func addForumAction(_ sender: UIButton) { DLog("") if !newForum.isReady() { let warning = "Supplied information not enough to construct a new board" DLog(warning) ProgressHUD.showMessage(warning) } else { newForum.parserType = KomicaForum.parserTypes[parserPickerView.selectedRow(inComponent: 0)] // Remove the original unmodified forum when it's presented. if let unmodifiedForum = unmodifiedForum { Forums.customForumGroup.forums?.removeObject(unmodifiedForum) Forums.saveCustomForums() } Forums.addCustomForum(newForum) // Report a custom forum has been added. reportAdded(newForum) _ = navigationController?.popToRootViewController(animated: true) // The forum has been added, reset the forum. newForum = KomicaForum() // Remove the paused forum from the user default. UserDefaults.standard.removeObject(forKey: self.pausedForumKey) UserDefaults.standard.synchronize() OperationQueue.main.addOperation({ ProgressHUD.showMessage("\(self.newForum.name ?? "A new board") has been added") }) } } @IBAction func resetForumAction(_ sender: AnyObject) { let alertController = UIAlertController(title: "Reset?", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (_) in self.newForum = KomicaForum() self.reload() // Remove the paused forum from the user default. UserDefaults.standard.removeObject(forKey: self.pausedForumKey) UserDefaults.standard.synchronize() })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertController.popoverPresentationController?.sourceView = view alertController.popoverPresentationController?.sourceRect = view.bounds if let topViewController = UIApplication.topViewController { topViewController.present(alertController, animated: true, completion: nil) } } } // MARK: ForumTextInputViewControllerProtocol extension AddForumTableViewController: ForumTextInputViewControllerProtocol { func forumDetailEntered(_ inputViewController: ForumTextInputViewController, enteredDetails: String, forField field: ForumField) { // Safe guard. if enteredDetails.isEmpty { return } DLog("\(enteredDetails) - \(field)") switch field { case .indexURL: newForum.indexURL = enteredDetails case .listURL: newForum.listURL = enteredDetails case .name: newForum.name = enteredDetails case .responseURL: newForum.responseURL = enteredDetails default: break } reload() } } // MARK: UIPickerViewDelegate, UIPickerViewDataSource extension AddForumTableViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return parserTypes.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return parserTypes[row] } } // MARK: UITableViewDelegate extension AddForumTableViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cell = super.tableView(tableView, cellForRowAt: indexPath) // When the display type is editing, hide QR button. // When the display type is readyonly, hide the add/reset buttons. if (displayType == .edit && cell == qrButtonTableViewCell) || (displayType == .readonly && cell == addButtonTableViewCell) { return 0 } return super.tableView(tableView, heightForRowAt: indexPath) } } extension KomicaForum { func isReady() -> Bool { var isReady = true if (name ?? "").isEmpty || (indexURL ?? "" ).isEmpty || (listURL ?? "").isEmpty || (responseURL ?? "").isEmpty { isReady = false } return isReady } func isModified() -> Bool { var isModified = false if !(name ?? "").isEmpty || !(indexURL ?? "" ).isEmpty || !(listURL ?? "").isEmpty || !(responseURL ?? "").isEmpty { isModified = true } return isModified } }
f086c3efd8c6ad3856eb584fae62dd78
38.646875
144
0.639789
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
Swift_A_Big_Nerd_Ranch_Guide/MonsterTown property/MonsterTown/Zombie.swift
mit
1
// // Zombie.swift // MonsterTown // // Created by Hanguang on 3/1/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation class Zombie: Monster { override class var spookyNoise: String { return "Brains..." } var walksWithLimp: Bool private(set) var isFallingApart: Bool init(limp: Bool, fallingApart: Bool, town: Town?, monsterName: String) { walksWithLimp = limp isFallingApart = fallingApart super.init(town: town, monsterName: monsterName) } convenience init(limp: Bool, fallingApart: Bool) { self.init(limp: limp, fallingApart: fallingApart, town: nil, monsterName: "Fred") if walksWithLimp { print("This zombie has a bad knee.") } } required init(town: Town?, monsterName: String) { walksWithLimp = false isFallingApart = false super.init(town: town, monsterName: monsterName) } final override func terrorizeTown() { if !isFallingApart { town?.changePopulation(-10) } super.terrorizeTown() } func changeName(name: String, walksWithLimp: Bool) { self.name = name self.walksWithLimp = walksWithLimp } deinit { print("Zombie named \(name) is no longer with us.") } }
6f3a596da613541db9de55ce79ae978a
24.037037
89
0.602517
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
refs/heads/master
chapter-22/GoldChallenge.playground/Contents.swift
mit
1
/* GOLD CHALLENGE The return type for this function is changed from [Int] to [C.Index], where C.Index is the type used to subscript the *CollectionType*. *CollectionType*s have an *Index* property because they conform to the *Indexable* protocol. The Index type for Array<Element> is defined to be Int, but this is not the case for all collection types. For example, the index for *Set<Element: Hashable>* is defined as a *SetIndex<Element>*. *Note: This function will not work with *Dictionary<Key: Hashable, Value>* types, because the *Element* for a Dictionary is defined as the tuple (Key, Value). Tuples do not conform to the *Equatable* protocol by default, so the constraint T: Equatable below precludes dictionary collection types from being used as the first argument to the function. */ import Cocoa func findAll<T: Equatable, C: CollectionType where C.Generator.Element == T>(collection: C, item: T) -> [C.Index] { var matchingIndices: Array<C.Index> = [] var currentIndex: C.Index = collection.startIndex for element in collection { if element == item { matchingIndices.append(currentIndex) } currentIndex = currentIndex.advancedBy(1) } return matchingIndices } print(findAll([5, 3, 7, 3, 9], item: 3)) var mySet = Set<Double>() for num in [1.1, 2.2, 3.3] { mySet.insert(num) } print(findAll(mySet, item: 2.2))
03aaca6e9f05ca60965734004e1cc9e8
29.5
115
0.678279
false
false
false
false
PureSwift/BlueZ
refs/heads/master
Sources/BluetoothLinux/DeviceCommand.swift
mit
2
// // DeviceCommand.swift // BluetoothLinux // // Created by Alsey Coleman Miller on 3/2/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(Linux) import Glibc #elseif os(OSX) || os(iOS) import Darwin.C #endif import Foundation import Bluetooth public extension HostController { func deviceCommand<T: HCICommand>(_ command: T) throws { try HCISendCommand(internalSocket, command: command) } func deviceCommand<T: HCICommandParameter>(_ commandParameter: T) throws { let command = T.command let parameterData = commandParameter.data try HCISendCommand(internalSocket, command: command, parameterData: parameterData) } } // MARK: - Internal HCI Function internal func HCISendCommand <T: HCICommand> (_ deviceDescriptor: CInt, command: T, parameterData: Data = Data()) throws { let packetType = HCIPacketType.Command.rawValue let header = HCICommandHeader(command: command, parameterLength: UInt8(parameterData.count)) /// data sent to host controller interface var data = [UInt8]([packetType]) + [UInt8](header.data) + [UInt8](parameterData) // write to device descriptor socket guard write(deviceDescriptor, &data, data.count) >= 0 // should we check if all data was written? else { throw POSIXError.errorno } }
45590a9475fdbc6afc59b96a6af57093
27.372549
101
0.648238
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/AssetManager+AssetCollection.swift
mit
1
// // AssetManager+AssetCollection.swift // HXPHPickerExample // // Created by Slience on 2020/12/29. // Copyright © 2020 Silence. All rights reserved. // import Photos import UIKit public extension AssetManager { /// 获取系统相册 /// - Parameter options: 选型 /// - Returns: 相册列表 static func fetchSmartAlbums( options: PHFetchOptions? ) -> PHFetchResult<PHAssetCollection> { return PHAssetCollection.fetchAssetCollections( with: .smartAlbum, subtype: .any, options: options ) } /// 获取用户创建的相册 /// - Parameter options: 选项 /// - Returns: 相册列表 static func fetchUserAlbums( options: PHFetchOptions? ) -> PHFetchResult<PHAssetCollection> { return PHAssetCollection.fetchAssetCollections( with: .album, subtype: .any, options: options ) } /// 获取所有相册 /// - Parameters: /// - filterInvalid: 过滤无效的相册 /// - options: 可选项 /// - usingBlock: 枚举每一个相册集合 static func enumerateAllAlbums( filterInvalid: Bool, options: PHFetchOptions?, usingBlock :@escaping (PHAssetCollection, Int, UnsafeMutablePointer<ObjCBool>) -> Void ) { let smartAlbums = fetchSmartAlbums(options: nil) let userAlbums = fetchUserAlbums(options: nil) let albums = [smartAlbums, userAlbums] var stopAblums: Bool = false for result in albums { result.enumerateObjects { (collection, index, stop) in if !collection.isKind(of: PHAssetCollection.self) { return } if filterInvalid { if collection.estimatedAssetCount <= 0 || collection.assetCollectionSubtype.rawValue == 205 || collection.assetCollectionSubtype.rawValue == 215 || collection.assetCollectionSubtype.rawValue == 212 || collection.assetCollectionSubtype.rawValue == 204 || collection.assetCollectionSubtype.rawValue == 1000000201 { return } } usingBlock(collection, index, stop) stopAblums = stop.pointee.boolValue } if stopAblums { break } } } /// 获取相机胶卷资源集合 /// - Parameter options: 可选项 /// - Returns: 相机胶卷集合 static func fetchCameraRollAlbum( options: PHFetchOptions? ) -> PHAssetCollection? { let smartAlbums = fetchSmartAlbums(options: options) var assetCollection: PHAssetCollection? smartAlbums.enumerateObjects { (collection, index, stop) in if !collection.isKind(of: PHAssetCollection.self) || collection.estimatedAssetCount <= 0 { return } if collection.isCameraRoll { assetCollection = collection stop.initialize(to: true) } } return assetCollection } /// 创建相册 /// - Parameter collectionName: 相册名 /// - Returns: 对应的 PHAssetCollection 数据 static func createAssetCollection( for collectionName: String ) -> PHAssetCollection? { let collections = PHAssetCollection.fetchAssetCollections( with: .album, subtype: .albumRegular, options: nil ) var assetCollection: PHAssetCollection? collections.enumerateObjects { (collection, index, stop) in if collection.localizedTitle == collectionName { assetCollection = collection stop.pointee = true } } if assetCollection == nil { do { var createCollectionID: String? try PHPhotoLibrary.shared().performChangesAndWait { createCollectionID = PHAssetCollectionChangeRequest.creationRequestForAssetCollection( withTitle: collectionName ).placeholderForCreatedAssetCollection.localIdentifier } if let createCollectionID = createCollectionID { assetCollection = PHAssetCollection.fetchAssetCollections( withLocalIdentifiers: [createCollectionID], options: nil ).firstObject } }catch {} } return assetCollection } }
86db7f736f19011e61ae15e28ad5dcf0
32.8
106
0.558843
false
false
false
false
warnerbros/cpe-manifest-ios-experience
refs/heads/master
Source/Utilities/BundleUtils.swift
apache-2.0
1
// // BundleUtils.swift // import Foundation extension Bundle { static var frameworkResources: Bundle { // CocoaPod using bundles if let resourcesBundleURL = Bundle(for: HomeViewController.self).url(forResource: "CPEExperience", withExtension: "bundle"), let resourcesBundle = Bundle(url: resourcesBundleURL) { return resourcesBundle } // Init resourcesBundle let resourcesBundle = Bundle(for: HomeViewController.self) // Carthage / Dynamic Framework if !resourcesBundle.bundlePath.isEmpty && resourcesBundle.bundleURL.pathExtension == "framework" { return resourcesBundle } // All Else return Bundle.main } }
b63ad1ba6307c1fd4b762689fe47e10e
25.964286
188
0.638411
false
false
false
false
J-Mendes/Weather
refs/heads/master
Weather/Weather/Views/WeatherTableViewController.swift
gpl-3.0
1
// // WeatherTableViewController.swift // Weather // // Created by Jorge Mendes on 05/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import UIKit class WeatherTableViewController: UITableViewController { internal var dataService: DataService? fileprivate enum Segues: String { case Settings = "showSettingsSegue" } fileprivate enum TableSections: Int { case Info = 0, Details, Forecast, Count } fileprivate enum DetailItems: Int { case Humidity = 0, Visibility, Wind, Sunrise, Sunset, Count } fileprivate var place: String! fileprivate var unitsType: Int! fileprivate var dataNeedsUpdate: Bool = false fileprivate var weatherInfo: WeatherData? { didSet { if self.weatherInfo != nil { DispatchQueue.main.async() { () -> Void in self.title = "\(self.weatherInfo!.city!), \(self.weatherInfo!.country!)" } } } } override func loadView() { super.loadView() // Init layout self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "settings"), style: .done, target: self, action: #selector(showSettings(_:))) self.refreshControl?.addTarget(self, action: #selector(WeatherTableViewController.getWeatherInfo), for: .valueChanged) self.refreshControl?.attributedTitle = NSAttributedString(string: NSLocalizedString("updating_wheather", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.white]) self.tableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "sky")) // Register custom table view cells self.tableView.register(WeatherInfoTableViewCell.nib, forCellReuseIdentifier: WeatherInfoTableViewCell.key) self.tableView.register(DetailTableViewCell.nib, forCellReuseIdentifier: DetailTableViewCell.key) self.tableView.register(ForecastTableViewCell.nib, forCellReuseIdentifier: ForecastTableViewCell.key) } override func viewDidLoad() { super.viewDidLoad() // Load place if let place: String = UserDefaults.standard.string(forKey: Constants.UserDefaultsKeys.location) { self.place = place } else { self.place = Constants.DefaultValues.defaultLocation UserDefaults.standard.set(self.place, forKey: Constants.UserDefaultsKeys.location) UserDefaults.standard.synchronize() } // Load units let units: Int = UserDefaults.standard.integer(forKey: Constants.UserDefaultsKeys.units) if units > 0 { self.unitsType = units } else { self.unitsType = Constants.DefaultValues.defaultUnit UserDefaults.standard.set(self.unitsType, forKey: Constants.UserDefaultsKeys.units) UserDefaults.standard.synchronize() } // Load weather data self.refreshControl?.beginRefreshing() self.getWeatherInfo() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.dataNeedsUpdate { self.refreshControl?.beginRefreshing() self.getWeatherInfo() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return self.weatherInfo != nil ? TableSections.Count.rawValue : 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case TableSections.Info.rawValue: return 1 case TableSections.Details.rawValue: return DetailItems.Count.rawValue case TableSections.Forecast.rawValue: return self.weatherInfo!.weather.forecastPrevisions.count default: return 0 } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var view: UIView? = nil switch section { case TableSections.Details.rawValue: let aView: HeaderView = HeaderView.create() aView.title = NSLocalizedString("details", comment: "") view = aView case TableSections.Forecast.rawValue: let aView: HeaderView = HeaderView.create() aView.title = NSLocalizedString("forecast", comment: "") view = aView default: break } return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return TableSections.Info.rawValue == section ? 0.0 : HeaderView.height } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = nil switch indexPath.section { case TableSections.Info.rawValue: let aCell: WeatherInfoTableViewCell = tableView.dequeueReusableCell(withIdentifier: WeatherInfoTableViewCell.key, for: indexPath) as! WeatherInfoTableViewCell aCell.configure(weatherData: self.weatherInfo!) cell = aCell case TableSections.Details.rawValue: let aCell: DetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: DetailTableViewCell.key, for: indexPath) as! DetailTableViewCell switch indexPath.row { case DetailItems.Humidity.rawValue: aCell.configure(title: NSLocalizedString("humidity", comment: ""), value: self.weatherInfo!.atmosphere.humidity, unit: "%") case DetailItems.Visibility.rawValue: aCell.configure(title: NSLocalizedString("visibility", comment: ""), value: self.weatherInfo!.atmosphere.visibility, unit: self.weatherInfo!.units.distance) case DetailItems.Wind.rawValue: aCell.configure(title: NSLocalizedString("wind", comment: ""), value: self.weatherInfo!.wind.speed, unit: self.weatherInfo!.units.speed) case DetailItems.Sunrise.rawValue: aCell.configure(title: NSLocalizedString("sunrise", comment: ""), value: self.weatherInfo!.astronomy.sunrise.hourFormat(), unit: "h") case DetailItems.Sunset.rawValue: aCell.configure(title: NSLocalizedString("sunset", comment: ""), value: self.weatherInfo!.astronomy.sunset.hourFormat(), unit: "h") default: break } cell = aCell case TableSections.Forecast.rawValue: let aCell: ForecastTableViewCell = tableView.dequeueReusableCell(withIdentifier: ForecastTableViewCell.key, for: indexPath) as! ForecastTableViewCell aCell.configure(forecast: self.weatherInfo!.weather.forecastPrevisions[indexPath.row]) cell = aCell default: break } return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case TableSections.Info.rawValue: return WeatherInfoTableViewCell.height case TableSections.Details.rawValue: return DetailTableViewCell.height case TableSections.Forecast.rawValue: return ForecastTableViewCell.height default: return 0.0 } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.Settings.rawValue { let settingsViewController: SettingsTableViewController = segue.destination as! SettingsTableViewController settingsViewController.delegate = self settingsViewController.currentLocation = self.place settingsViewController.currentUnit = self.unitsType } } @IBAction func showSettings(_ sender: Any?) { self.performSegue(withIdentifier: Segues.Settings.rawValue, sender: self) } // MARK: - Private methods @objc fileprivate func getWeatherInfo() { guard self.dataService != nil else { ErrorView.show(view: self.view) self.refreshControl?.endRefreshing() return } self.dataService?.getWeather(place: self.place, units: self.unitsType, completion: { (weatherData: WeatherData?, error: Error?) in if error == nil { if weatherData != nil { self.weatherInfo = weatherData; self.tableView.reloadData() } else { ErrorView.show(view: self.view, title: NSLocalizedString("error_place", comment: "")) } } else { DispatchQueue.main.async { ErrorView.show(view: self.view) } } ErrorView.dismiss(view: self.view) self.refreshControl?.endRefreshing() self.dataNeedsUpdate = false }) } } extension WeatherTableViewController: SettingsChangedDelegate { // MARK: - SettingsChangedDelegate func unitTypeChanged(unitType: Int) { self.unitsType = unitType self.dataNeedsUpdate = true } func locationChanged(place: String) { self.place = place DispatchQueue.main.async { self.title = self.place } self.dataNeedsUpdate = true } }
c91764300e053dfab70670026702525d
38.246964
187
0.639365
false
false
false
false
realDogbert/myScore
refs/heads/master
myScore/ScoreViewController.swift
mit
1
// // ViewController.swift // myScore // // Created by Frank on 20.07.14. // Copyright (c) 2014 Frank von Eitzen. All rights reserved. // import UIKit class ScoreViewController: UIViewController { @IBOutlet weak var lblHits: UILabel! @IBOutlet weak var lblPutts: UILabel! @IBOutlet weak var lblPenalty: UILabel! @IBOutlet weak var lblHole: UILabel! @IBOutlet weak var lblTotal: UILabel! @IBOutlet weak var lblLength: UILabel! @IBOutlet weak var lblPar: UILabel! @IBOutlet weak var stepperHits: UIStepper! @IBOutlet weak var stepperPutts: UIStepper! @IBOutlet weak var stepperPenalties: UIStepper! @IBOutlet weak var imgAverage: UIImageView! @IBOutlet weak var imgTotalAverage: UIImageView! var hole: Hole! var match: Match! var imgArrowUp = UIImage(named: "Arrow_Up") var imgArrowDown = UIImage(named: "Arrow_Down") var imgArrowSame = UIImage(named: "Arrow_Same") override func viewDidLoad() { super.viewDidLoad() lblHits.text = "\(hole.score.strokes)" lblPutts.text = "\(hole.score.putts)" lblPenalty.text = "\(hole.score.penalties)" stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHole.text = "Nr. \(hole.number)" lblPar.text = "Par: \(hole.par)" lblLength.text = "Len: \(hole.length)" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateScore() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTotalScore() { lblTotal.text = "Ges: \(match.getTotalScore())" } func updateHitsColor() { if hole.score.strokes <= hole.par { lblHits.textColor = UIColor.greenColor() } else { lblHits.textColor = UIColor.blackColor() } } func updateScore() { stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHits.text = hole.score.strokes.description lblPutts.text = hole.score.putts.description lblPenalty.text = hole.score.penalties.description //imgAverage.hidden = !(hole.score.strokes > hole.average) switch (hole.score.strokes - hole.average) { case -100...(-1): imgAverage.image = imgArrowUp case 1...100: imgAverage.image = imgArrowDown default: imgAverage.image = imgArrowSame } switch match.getCalculatedAverage() { case -1: imgTotalAverage.image = imgArrowUp case 1: imgTotalAverage.image = imgArrowDown default: imgTotalAverage.image = imgArrowSame } updateHitsColor() updateTotalScore() } @IBAction func updateHits(sender: AnyObject) { hole.score.strokes = Int(stepperHits.value) updateScore() } @IBAction func updatePutts(sender: AnyObject) { hole.score.putts = Int(stepperPutts.value) updateScore() } @IBAction func updatePenalties(sender: AnyObject) { hole.score.penalties = Int(stepperPenalties.value) updateScore() } }
cf5d7d163900c19838489474516b719a
26.529851
66
0.594199
false
false
false
false
seeaya/Simplex
refs/heads/master
Simplex/Drawing.swift
gpl-3.0
1
// // Drawing.swift // Simplex // // Created by Connor Barnes on 5/22/17. // Copyright © 2017 Connor Barnes. All rights reserved. // import Cocoa import CoreGraphics import CoreText /// The view that Simplex renders to on macOS. open class GameView: NSView { var mouse = Mouse() var keyboard = Keyboard() /// An array of drawable objects that are called upon in the draw loop to draw. var toDraw: [Drawable] = [] var context = Context() /// Where each draw function is called for nodes in the same hierarchy as the root node. /// /// - Parameter dirtyRect: A rectangle defining the portion of the view that requires redrawing open override func draw(_ dirtyRect: NSRect) { // Sorts the toDraw array by depth toDraw.sort { (lhs, rhs) -> Bool in return lhs.depth > rhs.depth } // Sets the context let context = NSGraphicsContext.current?.cgContext // Used to only update the new CGContext once var hasUpdatedContext = false for var drawable in toDraw { // Updates the CGContext with values of the current context contextUpdate: if !hasUpdatedContext { hasUpdatedContext = true guard let superContext = drawable.context else { break contextUpdate } // Set the stroke width context?.setLineWidth(CGFloat(superContext.strokeWidth)) // Set the stroke color and alpha context?.setStrokeColor(red: CGFloat(superContext.strokeColor.rgb.red), green: CGFloat(superContext.strokeColor.rgb.green), blue: CGFloat(superContext.strokeColor.rgb.blue), alpha: CGFloat(superContext.strokeAlpha)) // Set the fill color and alpha context?.setFillColor(red: CGFloat(superContext.fillColor.rgb.red), green: CGFloat(superContext.fillColor.rgb.green), blue: CGFloat(superContext.fillColor.rgb.blue), alpha: CGFloat(superContext.fillAlpha)) } // Sets each drawable object's context to the current cntext and runs its draw function drawable.context = self.context drawable.context?.cgContext = context drawable.draw() } // Reset the toDraw Array toDraw = [] } override public init(frame frameRect: NSRect) { super.init(frame: frameRect) let trackingArea: NSTrackingArea = NSTrackingArea(rect: bounds, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseMoved, NSTrackingArea.Options.enabledDuringMouseDrag], owner: self, userInfo: nil) addTrackingArea(trackingArea) } required public init?(coder: NSCoder) { let frame = NSRect(x: 0, y: 0, width: 0, height: 0) super.init(frame: frame) print("GameView.init(coder:) does not implement full mouse support!") } } /// Context for drawing including colors and alpha public class Context { // The Core Graphics Context for drawing on macOS and iOS var cgContext: CGContext? // Private variables that hold the actual values of drawing customizations var _strokeWidth = 1.0 var _strokeAlpha = 1.0 var _strokeColor = Color.black var _fillAlpha = 1.0 var _fillColor = Color.white var _font = Font(.system, ofSize: 12) var _fontColor = Color.black var _fontSize = 12.0 var _fontAlignStyle = FontAlignStyle(horizontalAlign: .left, verticalAlign: .top) /// The width of lines and outlines of shapes. public var strokeWidth: Double { get { return _strokeWidth } set { _strokeWidth = newValue cgContext?.setLineWidth(CGFloat(newValue)) } } /// The transparency of lines and outlines of shapes from 0 to 1, with 0 being fully transparent and 1 being fully opaque. public var strokeAlpha: Double { get { return _strokeAlpha } set { _strokeAlpha = newValue cgContext?.setStrokeColor(red: CGFloat(strokeColor.rgb.red), green: CGFloat(strokeColor.rgb.green), blue: CGFloat(strokeColor.rgb.blue), alpha: CGFloat(newValue)) } } /// The color of lines and outlines of shapes (The alpha value is ignored). public var strokeColor: Color { get { return _strokeColor } set { _strokeColor = newValue cgContext?.setStrokeColor(red: CGFloat(newValue.rgb.red), green: CGFloat(newValue.rgb.green), blue: CGFloat(newValue.rgb.blue), alpha: CGFloat(strokeAlpha)) } } /// The transparency the inside of shapes from 0 to 1, with 0 being fully transparent and 1 being fully opaque. public var fillAlpha: Double { get { return _fillAlpha } set { _fillAlpha = newValue cgContext?.setFillColor(red: CGFloat(fillColor.rgb.red), green: CGFloat(fillColor.rgb.green), blue: CGFloat(fillColor.rgb.blue), alpha: CGFloat(newValue)) } } /// The color of the inside of shapes. public var fillColor: Color { get { return _fillColor } set { _fillColor = newValue cgContext?.setFillColor(red: CGFloat(newValue.rgb.red), green: CGFloat(newValue.rgb.green), blue: CGFloat(newValue.rgb.blue), alpha: CGFloat(fillAlpha)) } } /// The font used for drawing text. public var font: Font { get { return _font } set { _font = newValue } } /// The color of text. public var fontColor: Color { get { return _fontColor } set { _fontColor = newValue } } /// The size of text. public var fontSize: Double { get { return _fontSize } set { _fontSize = newValue } } /// The alignment style of text. public var fontAlignStyle: FontAlignStyle { get { return _fontAlignStyle } set { _fontAlignStyle = newValue } } // Users should not create their own instances of Context, so no initializers are public init(with cgContext: CGContext) { self.cgContext = cgContext } init() { self.cgContext = nil } } /// The protocol that is adopted by nodes which are to draw to the screen. public protocol Drawable { /// The function called each render loop. Place all drawing functions and logic here. For non-drawing logic adopt the Updatable protocol and use its update(deltaTime:) method instead. func draw() /// The depth to draw at. Greater depths will be drawn first, and smaller depths will be drawn on top of greater depths. var depth: Double { get } /// The Current Context, used for drawing. var context: Context? { get set } } // Implements the draw loop that is called each render extension Node { // Executes the draw function for each drawable node in the hierarchy func superDraw(in view: GameView) { for child in children { child.superDraw(in: view) } if let drawableSelf = self as? Drawable { // Add self to the toDraw array in the GameView view.toDraw.append(drawableSelf) } } } // Implements geometric drawing functions which drawable objects can call extension Drawable { // MARK: Drawing functions /// Draws a line between two points. /// /// - Parameters: /// - start: The first point /// - end: The second point public func drawLine(from start: Vector2D, to end: Vector2D) { context?.cgContext?.move(to: CGPoint(start)) context?.cgContext?.addLine(to: CGPoint(end)) context?.cgContext?.strokePath() } /// Draws a rectangle with a given x and y position, and a given width and height. /// /// - Parameters: /// - x: The horizontal position of the top left of the rectangle /// - y: The vertival position of the bottom right of the rectangle /// - width: The width of the rectangle /// - height: The height of the rectangle public func drawRectangle(x: Double, y: Double, width: Double, height: Double) { context?.cgContext?.addRect(CGRect(x: x, y: y, width: width, height: height)) context?.cgContext?.fillPath() } /// Draws a rectangle at a given position, and with a given size. /// /// - Parameters: /// - origin: The position of the top left corner of the rectangle /// - size: The size of the rectangle public func drawRectangle(at position: Vector2D, withSize size: Size2D) { drawRectangle(x: position.x, y: position.y, width: size.width, height: size.height) context?.cgContext?.fillPath() } /// Draws a cricle with a given center position, and radius. /// /// - Parameters: /// - center: The position of the center of the circle /// - radius: The radius of the circle public func drawCircle(centeredAt center: Vector2D, withRadius radius: Double) { context?.cgContext?.addEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)) context?.cgContext?.fillPath() } /// Draws an ellipse with a given center and size. /// /// - Parameters: /// - center: The position of the center of teh circle /// - size: The size of the ellipse public func drawEllipse(centeredAt center: Vector2D, withSize size: Size2D) { context?.cgContext?.addEllipse(in: CGRect(x: center.x - size.width/2, y: center.y - size.height/2, width: size.width, height: size.height)) context?.cgContext?.fillPath() } /// Draws a path between a number of verticies. /// /// - Parameters: /// - verticies: The verticies to draw a path between /// - curved: Wheather to draw curved or straight lines between verticies public func drawPath(between verticies: [Vector2D], curved: Bool) { guard let origin = verticies.first else { return } if curved { // TODO: Implement curved paths print("Curved paths not yet supported") } else { context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } context?.cgContext?.strokePath() } } /// Draws a regular polygon with its bottommost side parallel to the horizontal axis. /// /// - Parameters: /// - center: The position of the center of the polygon /// - sides: The number of sides of the polygon /// - radius: The radius from the center of the polygon to any vertex public func drawRegularPolygon(centeredAt center: Vector2D, sides: Int, radius: Double) { var angle = pi/Double(sides) - pi/2 let origin = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) // Draw filled polygon context?.cgContext?.move(to: CGPoint(origin)) for _ in 0..<sides { angle += 2*pi/Double(sides) let point = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) context?.cgContext?.addLine(to: CGPoint(point)) } context?.cgContext?.fillPath() // Draw stoked polygon angle = pi/Double(sides) - pi/2 context?.cgContext?.move(to: CGPoint(origin)) for _ in 0..<sides { angle += 2*pi/Double(sides) let point = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) context?.cgContext?.addLine(to: CGPoint(point)) } context?.cgContext?.strokePath() } /// Draws a closed shape from a number of verticies. /// /// - Parameters: /// - verticies: the vertices the edge of the shape passes though /// - curved: Whether to draw a shape with straight or curved edges public func drawShape(between verticies: [Vector2D], curved: Bool) { guard let origin = verticies.first, let finalVertex = verticies.last else { return } if curved { // TODO: Implement curved shapes print("Curved shapes not yet supported") } else { // Draw filled shape context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } // Connect path back to origin if origin != finalVertex { context?.cgContext?.addLine(to: CGPoint(origin)) } context?.cgContext?.fillPath() // Draw stroked shape context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } // Connect path back to origin if origin != finalVertex { context?.cgContext?.addLine(to: CGPoint(origin)) } context?.cgContext?.strokePath() } } } // MARK: CoreGraphics Type Conversions // Converts Vector2D into CGPoint extension CGPoint { init(_ vector: Vector2D) { self.init(x: vector.x, y: vector.y) } } // Converts Color into cgColor extension Color { var cgColor: CGColor { get { return CGColor(red: CGFloat(rgb.red), green: CGFloat(rgb.green), blue: CGFloat(rgb.blue), alpha: CGFloat(alpha)) } } }
8e44d63f6fcf72ff7c834259efa19808
29.560914
223
0.694544
false
false
false
false
AfricanSwift/TUIKit
refs/heads/master
TUIKit/Source/UIElements/Foundation/TUIGeometry.swift
mit
1
// // File: TUIGeometry.swift // Created by: African Swift import Darwin // MARK: TUIVec2 - /// Vector in the two-dimensional Euclidean space – R×R /// /// - x: horizontal offset /// - y: vertical offset public struct TUIVec2 { public var x: Double public var y: Double /// Default TUIVec2 Initializer /// /// - parameters: /// - x: Int /// - y: Int public init(x: Int = 0, y: Int = 0) { self.x = Double(x) self.y = Double(y) } /// Default TUIVec2 Initializer /// /// - parameters: /// - x: Double /// - y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } // MARK: - // MARK: TUIVec2 CustomStringConvertible - extension TUIVec2: CustomStringConvertible { public var description: String { return "(x: \(self.x), y: \(self.y))" } } // MARK: - // MARK: TUIVec2 Equatable - extension TUIVec2: Equatable { } /// Equatable Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIVec2, rhs: TUIVec2) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } /// Plus Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Product of two TUIVec2 public func + (lhs: TUIVec2, rhs: TUIVec2) -> TUIVec2 { return TUIVec2(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// Minus Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Difference of two TUIVec2 public func - (lhs: TUIVec2, rhs: TUIVec2) -> TUIVec2 { return TUIVec2(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// Multiply Vector by Factor (Scale) /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: Double /// - returns: Factor increase of TUIVec2 public func * (lhs: TUIVec2, rhs: Double) -> TUIVec2 { return TUIVec2(x: lhs.x * rhs, y: lhs.y * rhs) } /// Dot Product of two TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: dot product of the two TUIVec2 vectors public func * (lhs: TUIVec2, rhs: TUIVec2) -> Double { return (lhs.x * rhs.x) + (lhs.y * rhs.y) } // MARK: - // MARK: TUIVec3 - /// Vector in the three-dimensional Euclidean space – R×R×R /// /// - x: X axis offset /// - y: Y axis offset /// - z: Z axis offset public struct TUIVec3 { public var x: Double public var y: Double public var z: Double /// Default TUIVec3 Initializer /// /// - parameters: /// - x: Double /// - y: Double /// - z: Double public init(x: Double = 0, y: Double = 0, z: Double = 0) { self.x = x self.y = y self.z = z } private func norm() -> Double { return sqrt(self.x * self.x + self.y * self.y + self.z * self.z) } public func normalize() -> TUIVec3 { return self * (1 / self.norm()) } } // MARK: - // MARK: TUIVec3 CustomStringConvertible - extension TUIVec3: CustomStringConvertible { public var description: String { return "(x: \(self.x), y: \(self.y), z: \(self.z))" } } // MARK: - // MARK: TUIVec3 Equatable - extension TUIVec3: Equatable { } /// Equatable Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIVec3, rhs: TUIVec3) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } /// Cross Product of two TUIVec3 infix operator ** { associativity left precedence 150 } /// Cross Product of two TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: cross product of the two TUIVec3 vectors public func ** (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.y * rhs.z - lhs.z * rhs.y, y: lhs.z * rhs.x - lhs.x * rhs.z, z: lhs.x * rhs.y - lhs.y * rhs.x) } /// Plus Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Product of two TUIVec3 vectors public func + (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z) } /// Minus Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Difference of two TUIVec3 vectors public func - (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z) } /// Multiply Vector by Factor (Scale) /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: Double (factor) /// - returns: Factor increase of TUIVec3 vector public func * (lhs: TUIVec3, rhs: Double) -> TUIVec3 { return TUIVec3(x: lhs.x * rhs, y: lhs.y * rhs, z: lhs.z * rhs) } /// Dot Product of two TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: dot product of the two vectors public func * (lhs: TUIVec3, rhs: TUIVec3) -> Double { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z } /// Radian Angle between two TUIVec3 vectors infix operator *> { associativity left precedence 150 } /// Radian Angle between two TUIVec3 vectors /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Radian Angle of two vectors public func *> (lhs: TUIVec3, rhs: TUIVec3) -> Double { return acos((lhs * rhs) / (lhs.norm() * rhs.norm())) } // MARK: - // MARK: TUISize - /// Terminal UI Size /// /// - width: horizontal size /// - size: vertical size public struct TUISize { public private(set) var width: Double public private(set) var height: Double /// Default Initializer /// /// - parameters: /// - width: Int /// - height: Int public init(width: Int = 0, height: Int = 0) { self.width = Double(width) self.height = Double(height) } /// Default Initializer /// /// - parameters: /// - width: Double /// - height: Double public init(width: Double, height: Double) { self.width = width self.height = height } } // MARK: - // MARK: TUISize Equatable - /// TUISize equatable extension TUISize: Equatable {} /// Equatable Operator for TUISize /// /// - parameters: /// = lhs: TUISize /// - rhs: TUISize /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUISize, rhs: TUISize) -> Bool { return lhs.height == rhs.height && lhs.width == rhs.width } // MARL: - // MARK: TUIViewSize - /// Terminal UI Viewsize with two size accessors: pixel vs. character /// /// - pixel is based on the braille symbols /// - 2 x 4 pixels per character (width x height) public struct TUIWindowSize { public var pixel: TUISize public var character: TUISize /// Default initializer /// /// - parameters: /// - width: Int (pixel width) /// - height: Int (pixel height) public init(width: Int, height: Int) { let w = Int(ceil(Double(width) / 2.0)) let h = Int(ceil(Double(height) / 4.0)) self.pixel = TUISize(width: w * 2, height: h * 4) self.character = TUISize(width: w, height: h) } /// Default initializer /// /// - parameters: /// - width: Double (pixel width) /// - height: Double (pixel height) public init(width: Double, height: Double) { self.init(width: Int(width), height: Int(height)) } /// Default initializer /// /// - parameters: /// - columns: Int (character width) /// - rows: Int (character height) public init(columns: Int, rows: Int) { self.init(width: columns * 2, height: rows * 4) } } // MARK: - // MARK: TUIRectangle - /// Terminal UI Rectangle // /// - origin (TUIVec2): left / top origin /// - size (TUISize): width / height public struct TUIRectangle { public private(set) var origin = TUIVec2() public private(set) var size = TUISize() /// Default Initializer /// /// - parameters: /// - x: Int /// - y: Int /// - width: Int /// - height: Int public init(x: Int = 0, y: Int = 0, width: Int = 0, height: Int = 0) { self.origin = TUIVec2(x: x, y: y) self.size = TUISize(width: width, height: height) } /// Default Initializer /// /// - parameters: /// - x: Double /// - y: Double /// - width: Double /// - height: Double public init(x: Double = 0.0, y: Double = 0.0, width: Double = 0.0, height: Double = 0.0) { self.origin = TUIVec2(x: x, y: y) self.size = TUISize(width: width, height: height) } /// Default Initializer /// /// - parameters: /// - origin: TUIVec2 /// - size: TUISize public init(origin: TUIVec2, size: TUISize) { self.origin = origin self.size = size } } // MARK: - // MARK: TUIRectangle Equatable - extension TUIRectangle: Equatable {} /// Equatable Operator for TUIRectangle /// /// - parameters: /// - lhs: TUIRectangle /// - rhs: TUIRectangle /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIRectangle, rhs: TUIRectangle) -> Bool { return lhs.origin == rhs.origin && lhs.size == rhs.size }
f60670fed1bf8aa13b34ff82f1566e89
21.037037
90
0.594398
false
false
false
false
blstream/StudyBox_iOS
refs/heads/master
StudyBox_iOS/DecksCollectionViewLayout.swift
apache-2.0
1
// // DecksCollectionViewLayout.swift // StudyBox_iOS // // Created by Damian Malarczyk on 26.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit protocol DecksCollectionLayoutDelegate: class { func shouldStrech() -> Bool } class DecksCollectionViewLayout: UICollectionViewFlowLayout { weak var delegate: DecksCollectionLayoutDelegate? override func collectionViewContentSize() -> CGSize { let expectedSize = super.collectionViewContentSize() if let collectionView = collectionView, delegate = delegate where delegate.shouldStrech() { var targetSize = collectionView.bounds.size let height = expectedSize.height if height < targetSize.height { let sharedApp = UIApplication.sharedApplication() if !sharedApp.statusBarHidden { targetSize.height -= UIApplication.sharedApplication().statusBarFrame.height } return targetSize } } return expectedSize } }
b0bff4f65cfe425e5efdfa0353a79873
27.45
99
0.618629
false
false
false
false
timothydang/SwiftLinksMenuBar
refs/heads/master
SwiftLinksMenuBar/AppDelegate.swift
mit
1
// // AppDelegate.swift // SwiftLinksMenuBar // // Created by Timothy Dang on 28/05/2015. // Copyright (c) 2015 Timothy Dang. All rights reserved. // import Cocoa import SwiftyJSON struct MenuBarItem:NilLiteralConvertible { let title:String? let url:String? let items:Array<MenuBarItem> init(nilLiteral: ()) { self.title = nil self.url = nil self.items = [] } init(title: String?, url: String?, items: Array<MenuBarItem>) { self.title = title self.url = url self.items = items } } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var statusBarItem: NSStatusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) var menu = NSMenu() var menuItems:Array<MenuBarItem> = [] func applicationDidFinishLaunching(aNotification: NSNotification) { let icon = NSImage(named: "statusIcon") icon?.setTemplate(true) self.statusBarItem.image = icon NSApp.setActivationPolicy(NSApplicationActivationPolicy.Accessory) parseJson() initMenu() } func parseJson() { let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("links", ofType: "json") var error:NSError? let data: NSData? = NSData(contentsOfFile: path!) let content = JSON(data: data!, options: NSJSONReadingOptions.allZeros, error: &error) var json = content.dictionary! as Dictionary<String, JSON> let values = json.values.first?.array! for i in 0...((values?.count)!-1) { var itemJSON = values?[i] as JSON? var itemName = itemJSON?.dictionary?.keys.first var itemLink = itemJSON?.dictionary?.values.array as Array? var menuItem:MenuBarItem = nil var childMenuItems:Array<MenuBarItem> = [] if itemName == nil { menuItems.append(nil) } if(itemLink?.first?.array != nil) { // Having child menu items var subItems = itemLink?.first?.array var subItem:MenuBarItem = nil for j in 0...(subItems?.count)!-1 { var subItemJSON = subItems?[j] as JSON? var subItemName = subItemJSON?.dictionary?.keys.first var subItemLink = subItemJSON?.dictionary?.values.first?.string subItem = MenuBarItem(title: subItemName, url: subItemLink, items: []) childMenuItems.append(subItem) } } menuItem = MenuBarItem(title: itemName, url: itemLink?.first?.string, items: childMenuItems) menuItems.append(menuItem) } } func initMenu() { for i in 0...self.menuItems.count-1 { var item = self.menuItems[i] as MenuBarItem if item.items.count > 0 { let subMenu = NSMenu() for j in 0...item.items.count-1 { var subMenuItem = NSMenuItem(title: item.items[j].title!, action: Selector("clickMenuItem:"), keyEquivalent: "") subMenuItem.representedObject = item.items[j].url subMenu.addItem(subMenuItem) } var menuItem = NSMenuItem(title: item.title!, action: nil, keyEquivalent: "") menuItem.submenu = subMenu menu.addItem(menuItem) } else if item.title == nil { menu.addItem(NSMenuItem.separatorItem()) } else { var menuItem = NSMenuItem(title: item.title!, action: Selector("clickMenuItem:"), keyEquivalent: "") menuItem.representedObject = item.url menu.addItem(menuItem) } } menu.addItem(NSMenuItem.separatorItem()) menu.addItemWithTitle("Quit", action: Selector("terminate:"), keyEquivalent: "") self.statusBarItem.menu = menu } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func clickMenuItem(sender: NSMenuItem) { var itemUrl = sender.representedObject as! String NSWorkspace.sharedWorkspace().openURL(NSURL(string: itemUrl)!) } }
dae1d240f5cf3beae7ca843839df5b06
33.066667
132
0.559904
false
false
false
false
BiteCoda/icebreaker-app
refs/heads/master
IceBreaker-iOS/IceBreaker/Utilities/RESTManager.swift
gpl-3.0
1
// // RESTManager.swift // IceBreaker // // Created by Jacob Chen on 2/21/15. // Copyright (c) 2015 floridapoly.IceMakers. All rights reserved. // import UIKit private let BASE_URL:String = "http://icebreaker.duckdns.org" private let _SingletonSharedRESTManager = RESTManager() private let USER_ID_KEY = "userId" private let DEVICE_TOKEN_KEY = "deviceToken" private let DEVICE_TYPE_KEY = "deviceType" private let PASSWORD_KEY = "password" private let TARGET_USER_ID_KEY = "targetUserId" class RESTManager { let manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager() var hasRegistered: Bool = false var deviceToken: String? class var sharedRESTManager : RESTManager { return _SingletonSharedRESTManager } init() { } func register(deviceToken: String, password: String, completionClosure:(success: Bool) ->()) { println("Subscribing") let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))", DEVICE_TOKEN_KEY:deviceToken, DEVICE_TYPE_KEY:"ios", PASSWORD_KEY: password ] manager.POST( BASE_URL + "/subscribe", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in var result: NSDictionary = responseObj as NSDictionary var success: Bool = result.objectForKey(API_SUCCESS) as Bool if (success) { if !self.hasRegistered { self.hasRegistered = true println("Registered with server") completionClosure(success: true) } } else { completionClosure(success: false) } }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } func request(targetMajorID: NSNumber, targetMinorID: NSNumber) { let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))", TARGET_USER_ID_KEY:"(major:\(targetMajorID), minor:\(targetMinorID))" ] println("Messaging: \(parameters)") manager.POST( BASE_URL + "/message", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in var response: NSDictionary = responseObj as NSDictionary var success: Bool = response.objectForKey(API_SUCCESS) as Bool if (success) { var object: NSDictionary = response.objectForKey(API_OBJECT) as NSDictionary var question: String = object.objectForKey(API_QUESTION) as String var author: String = object.objectForKey(API_AUTHOR) as String var category: String = object.objectForKey(API_CATEGORY) as String var content = "Quote: \(question)\nAuthor: \(author)\nCategory: \(category)" var info: [String: String] = [NOTIF_CONTENT_KEY: content] NSNotificationCenter.defaultCenter().postNotificationName( NOTIF_BEACON_PAIRED, object: nil, userInfo: info ) println(responseObj) } else { var errors: [String] = response.objectForKey(API_ERRORS) as [String] for error in errors { switch error { case ERROR_PAIR_EXISTS_SOURCE: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_PAIR_EXISTS_SOURCE, object: nil) break; case ERROR_PAIR_EXISTS_TARGET: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_PAIR_EXISTS_TARGET, object: nil) break; case ERROR_INVALID_REQUEST: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_INVALID_REQUEST, object: nil) break; case ERROR_TARGET_NOT_SUBSCRIBED: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_TARGET_NOT_SUBSCRIBED, object: nil) break; default: break; } } } }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } func unpair() { println("Unpairing") let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))" ] manager.POST( BASE_URL + "/unpair", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in println("Pairing Successful") }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } }
31ce2f1d429dbf23461ca24b3895483d
33.919355
133
0.488297
false
false
false
false
shitoudev/v2ex
refs/heads/master
v2ex/NodeModel.swift
mit
1
// // NodeModel.swift // v2ex // // Created by zhenwen on 5/8/15. // Copyright (c) 2015 zhenwen. All rights reserved. // import Foundation import Kanna class NodeModel: NSObject { var name: String, title: String var node_id: Int?, header: String?, url: String?, topics: Int?, avatar_large: String? init(fromDictionary dictionary: NSDictionary) { self.node_id = dictionary["id"] as? Int self.name = dictionary["name"] as! String self.title = dictionary["title"] as! String self.url = dictionary["url"] as? String self.topics = dictionary["topics"] as? Int self.avatar_large = dictionary["avatar_large"] as? String if let header = dictionary["header"] as? String { self.header = header } } static func getNodeList(completionHandler:(obj: [AnyObject]?, NSError?)->Void) { let url = APIManage.baseURLString var result = [AnyObject]() let mgr = APIManage.sharedManager mgr.request(.GET, url, parameters: nil).responseString(encoding: nil, completionHandler: { (response) -> Void in if response.result.isSuccess { guard let doc = HTML(html: response.result.value!, encoding: NSUTF8StringEncoding) else { completionHandler(obj: result, nil) return } let body = doc.body! // parsing navi var data = ["title":"导航", "node":[], "type":NSNumber(integer: 2)] var nodeArr = [NodeModel]() for aNode in body.css("a[class='tab']") { let title = aNode.text! let href = aNode["href"]!.componentsSeparatedByString("=") let name = href.last! let nodeInfo = ["name":name, "title":title] as NSDictionary let nodeModel = NodeModel(fromDictionary: nodeInfo) nodeArr.append(nodeModel) } data["node"] = nodeArr if nodeArr.count > 0 { result.append(data) } // parsing node var titleArr = [String]() for divNode in body.css("div[class='cell']") { if let table = divNode.at_css("table"), tdFirst = table.css("td").first, span = tdFirst.at_css("span[class='fade']") { let a = table.css("td").last!.css("a") if a.count > 0 { var canAdd = true for titleStr in titleArr { if titleStr == span.text { canAdd = false } } if canAdd { titleArr.append(span.text!) var data = ["title":span.text!, "node":[], "type":NSNumber(integer: 1)] var nodeArr = [NodeModel]() for aNode in a { let title = aNode.text! let href = aNode["href"]!.componentsSeparatedByString("/") let name = href.last! let nodeInfo = ["name":name, "title":title] as NSDictionary let nodeModel = NodeModel(fromDictionary: nodeInfo) nodeArr.append(nodeModel) } data["node"] = nodeArr result.append(data) } } } } } completionHandler(obj: result, nil) }) } }
1fba8ee029d7428c4af12a50d548c097
39.42
138
0.434933
false
false
false
false
imzyf/99-projects-of-swift
refs/heads/master
021-marslink/Marslink/ViewControllers/FeedViewController.swift
mit
1
// // FeedViewController.swift // Marslink // // Created by moma on 2017/11/23. // Copyright © 2017年 Ray Wenderlich. All rights reserved. // import UIKit import IGListKit class FeedViewController: UIViewController { let loader = JournalEntryLoader() // acts as messaging system let pathfinder = Pathfinder() let wxScanner = WxScanner() let collectionView: IGListCollectionView = { let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) view.backgroundColor = UIColor.black return view }() lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() override func viewDidLoad() { super.viewDidLoad() loader.loadLatest() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self pathfinder.delegate = self pathfinder.connect() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } } extension FeedViewController: IGListAdapterDataSource { // returns an array of data objects the should show up in the collection view. func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { var items: [IGListDiffable] = [wxScanner.currentWeather] items += loader.entries as [IGListDiffable] items += pathfinder.messages as [IGListDiffable] return items.sorted(by: { (left: Any, right: Any) -> Bool in if let left = left as? DateSortable, let right = right as? DateSortable { return left.date > right.date } return false }) } // for each data object, must return a new instance of a section controller. func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { if object is Message { return MessageSectionController() } else if object is Weather { return WeatherSectionController() } else { return JournalSectionController() } } // returns a view that should be displayed when the list is empty func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } } extension FeedViewController: PathfinderDelegate { func pathfinderDidUpdateMessages(pathfinder: Pathfinder) { adapter.performUpdates(animated: true) } }
ed0753ba3e7e2d6e08d9ba1efef31479
29.287356
113
0.653131
false
false
false
false
nineteen-apps/swift
refs/heads/master
lessons-01/lesson5/Sources/main.swift
mit
1
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-06-21 by Ronaldo Faria Lima // This file purpose: Demonstração do uso de coleções e tuplas import Foundation typealias MenuItem = (title: String, action: ()->()) var stop = false let menuItems: [MenuItem] = [ (title: "A - Mostrar Versão" , action: { print("Versão 1.0") }), (title: "B - Hora do Sistema", action: { print("\(Date())") }), (title: "X - Sair do Sistema", action: { stop = true }) ] let menuMap: [Character:Int] = ["A":0, "B":1, "X":2] func printMenu(menu: [MenuItem]) { for item in menu { print (item.title) } print ("Escolha sua opção: ", terminator: "") } while !stop { printMenu(menu: menuItems) if let input = readLine() { if let letter = input.uppercased().characters.first { if let index = menuMap[letter] { let menuItem = menuItems[index] menuItem.action() } else { print("Opção inválida!") } } } }
bbaf8280500e353b1a055b5caa62238b
36.421053
81
0.666667
false
false
false
false
18775134221/SwiftBase
refs/heads/master
SwiftTest/SwiftTest/Classes/Main/VC/BaseTabBarVC.swift
apache-2.0
2
// // BaseTabBarVC.swift // SwiftTest // // Created by MAC on 2016/12/10. // Copyright © 2016年 MAC. All rights reserved. // import UIKit class BaseTabBarVC: UITabBarController { fileprivate var homeVC: HomeVC? = nil fileprivate var typesVC: TypesVC? = nil fileprivate var shoppingCartVC: ShoppingCartVC? = nil fileprivate var mineVC: MineVC? = nil override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseTabBarVC { fileprivate func setupUI() { setupChildVCs() setupTabBar() } // 设置自定义的TabBar private func setupTabBar() { UITabBar.appearance().tintColor = UIColor.orange let baseTabBar: BaseTabBar = BaseTabBar() baseTabBar.type = .plusDefault // 隐藏系统顶部tabBar的黑线 baseTabBar.shadowImage = UIImage() baseTabBar.backgroundImage = UIImage() baseTabBar.backgroundColor = UIColor(r: 0.62, g: 0.03, b: 0.05) setValue(baseTabBar, forKey: "tabBar") } private func setupChildVCs() { homeVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeVC") as? HomeVC addChildVC(homeVC!,"首页","icon_home_normal","icon_home_selected") typesVC = UIStoryboard(name: "Types", bundle: nil).instantiateViewController(withIdentifier: "TypesVC") as? TypesVC addChildVC(typesVC!,"分类","iocn_classification_normal","iocn_classification_selected") shoppingCartVC = UIStoryboard(name: "ShoppingCart", bundle: nil).instantiateViewController(withIdentifier: "ShoppingCartVC") as? ShoppingCartVC addChildVC(shoppingCartVC!,"购物车","icon_shopping-cart_normal","icon_shopping-cart_selected") mineVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "MineVC") as? MineVC addChildVC(mineVC!,"我的","icon_personal-center_normal","icon_personal-center_selected") } private func addChildVC(_ vc: UIViewController, _ title: String = "", _ normalImage: String = "",_ selectedImage: String = "") { vc.title = title; vc.tabBarItem.selectedImage = UIImage(named: selectedImage) vc.tabBarItem.image = UIImage(named: normalImage) let baseNaviVC: BaseNavigationVC = BaseNavigationVC(rootViewController: vc) addChildViewController(baseNaviVC) } } extension BaseTabBarVC: UITabBarControllerDelegate { // 选中底部导航按钮回调 override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { } }
68f767070cf7527ebf6af0f2cc72e46e
30.317647
151
0.648009
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/UIComponents/UIComponentsKit/Views/EmptyStateView.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// A view which represents the lack of content public struct EmptyStateView: View { let title: String let subHeading: String let image: Image private let layout = Layout() public init(title: String, subHeading: String, image: Image) { self.title = title self.subHeading = subHeading self.image = image } public var body: some View { VStack { Text(title) .textStyle(.title) .foregroundColor(.textTitle) Spacer() .frame(height: layout.textSpacing) Text(subHeading) .textStyle(.subheading) .foregroundColor(.textSubheading) Spacer() .frame(height: layout.imageSpacing) image } } } extension EmptyStateView { struct Layout { let textSpacing: CGFloat = 8 let imageSpacing: CGFloat = 24 } } struct EmptyStateView_Previews: PreviewProvider { static var previews: some View { EmptyStateView( title: "You Have No Activity", subHeading: "All your transactions will show up here.", image: ImageAsset.emptyActivity.image ) } }
5b87d307e90125e16542e9df098d1c76
22.535714
67
0.580425
false
false
false
false
motylevm/skstylekit
refs/heads/master
Sources/SKStyleKitSource.swift
mit
1
// // SKStyleKitSource.swift // SKStyleKit // // Created by Мотылёв Михаил on 09/03/2017. // Copyright © 2017 mmotylev. All rights reserved. // import Foundation enum SKStyleKitSourceLocation { case bundle(Bundle) case file(String) } enum SKStylesSourceType: Int { case main = 1 case styleKit = -1 case other = 0 } public final class SKStyleKitSource { // MARK: - Properties - let location: SKStyleKitSourceLocation let type: SKStylesSourceType let zIndex: Int // MARK: - Init - private init(location: SKStyleKitSourceLocation, type: SKStylesSourceType, zIndex: Int) { self.location = location self.type = type self.zIndex = zIndex } // MARK: - Providers - func getProviders() -> [SKStylesSourceProvider] { let files: [String] switch location { case .bundle(let bundle): guard let bundleFiles = try? FileManager.default.contentsOfDirectory(atPath: bundle.bundlePath) else { return [] } files = bundleFiles.filter({ $0.hasPrefix("style") && $0.hasSuffix(".json") }).compactMap({ bundle.path(forResource: $0, ofType: nil) }) case .file(let path): files = [path] } return files.compactMap { SKStylesSourceProvider(filePath: $0, sourceType: type, zIndex: zIndex) } } // MARK: - Factory - public class func main() -> SKStyleKitSource { return SKStyleKitSource(location: .bundle(Bundle.main), type: .main, zIndex: 0) } public class func styleKit() -> SKStyleKitSource { return SKStyleKitSource(location: .bundle(Bundle(for: SKStyleKitSource.self)), type: .styleKit, zIndex: 0) } public class func file(_ path: String, zIndex: Int = 0) -> SKStyleKitSource { return SKStyleKitSource(location: .file(path), type: .other, zIndex: zIndex) } public class func bundle(_ bundle: Bundle, zIndex: Int = 0)-> SKStyleKitSource { return SKStyleKitSource(location: .bundle(bundle), type: .other, zIndex: zIndex) } }
9691c3a95abb5a211ef334fb712fc69e
28.643836
152
0.61414
false
false
false
false
marty-suzuki/FluxCapacitor
refs/heads/master
Examples/Flux+MVVM/FluxCapacitorSample/Sources/UI/Search/SearchViewController.swift
mit
1
// // SearchViewController.swift // FluxCapacitorSample // // Created by marty-suzuki on 2017/08/01. // Copyright © 2017年 marty-suzuki. All rights reserved. // import UIKit import RxSwift import RxCocoa import NoticeObserveKit final class SearchViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var counterLabel: UILabel! private let searchBar: UISearchBar = UISearchBar(frame: .zero) private let disposeBag = DisposeBag() private let selectUserRowAt = PublishSubject<IndexPath>() private let fetchMoreUsers = PublishSubject<Void>() private(set) lazy var dataSource: SearchViewDataSource = .init(viewModel: self.viewModel) private(set) lazy var viewModel: SearchViewModel = { let viewWillAppear = self.rx .methodInvoked(#selector(SearchViewController.viewWillAppear(_:))) .map { _ in } let viewWillDisappear = self.rx .methodInvoked(#selector(SearchViewController.viewWillDisappear(_:))) .map { _ in } return .init(viewWillAppear: viewWillAppear, viewWillDisappear: viewWillDisappear, searchText: self.searchBar.rx.text.orEmpty, selectUserRowAt: self.selectUserRowAt, fetchMoreUsers: self.fetchMoreUsers) }() override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = searchBar searchBar.placeholder = "Input user name" tableView.contentInset.top = 44 configureDataSource() observeUI() observeViewModel() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if searchBar.isFirstResponder { searchBar.resignFirstResponder() } } private func configureDataSource() { dataSource.selectUserRowAt .bind(to: selectUserRowAt) .disposed(by: disposeBag) dataSource.fetchMoreUsers .bind(to: fetchMoreUsers) .disposed(by: disposeBag) dataSource.configure(with: tableView) } private func observeViewModel() { viewModel.keyboardWillShow .bind(to: keyboardWillShow) .disposed(by: disposeBag) viewModel.keyboardWillHide .bind(to: keyboardWillHide) .disposed(by: disposeBag) viewModel.showUserRepository .bind(to: showUserRepository) .disposed(by: disposeBag) viewModel.counterText .bind(to: counterLabel.rx.text) .disposed(by: disposeBag) viewModel.reloadData .bind(to: reloadData) .disposed(by: disposeBag) } private func observeUI() { Observable.merge(searchBar.rx.cancelButtonClicked.asObservable(), searchBar.rx.searchButtonClicked.asObservable()) .bind(to: resignFirstResponder) .disposed(by: disposeBag) searchBar.rx.textDidBeginEditing .map { true } .bind(to: showsCancelButton) .disposed(by: disposeBag) searchBar.rx.textDidEndEditing .map { false } .bind(to: showsCancelButton) .disposed(by: disposeBag) } private var keyboardWillShow: AnyObserver<UIKeyboardInfo> { return Binder(self) { me, keyboardInfo in me.view.layoutIfNeeded() let extra = me.tabBarController?.tabBar.bounds.height ?? 0 me.tableViewBottomConstraint.constant = keyboardInfo.frame.size.height - extra UIView.animate(withDuration: keyboardInfo.animationDuration, delay: 0, options: keyboardInfo.animationCurve, animations: { me.view.layoutIfNeeded() }, completion: nil) }.asObserver() } private var keyboardWillHide: AnyObserver<UIKeyboardInfo> { return Binder(self) { me, keyboardInfo in me.view.layoutIfNeeded() me.tableViewBottomConstraint.constant = 0 UIView.animate(withDuration: keyboardInfo.animationDuration, delay: 0, options: keyboardInfo.animationCurve, animations: { me.view.layoutIfNeeded() }, completion: nil) }.asObserver() } private var reloadData: AnyObserver<Void> { return Binder(self) { me, _ in me.tableView.reloadData() }.asObserver() } private var resignFirstResponder: AnyObserver<Void> { return Binder(self) { me, _ in me.searchBar.resignFirstResponder() }.asObserver() } private var showsCancelButton: AnyObserver<Bool> { return Binder(self) { me, showsCancelButton in me.searchBar.showsScopeBar = showsCancelButton }.asObserver() } private var showUserRepository: AnyObserver<Void> { return Binder(self) { me, _ in let vc = UserRepositoryViewController() me.navigationController?.pushViewController(vc, animated: true) }.asObserver() } }
a93eeef23f6a42f0aa5ab8d561937e1c
32.987421
93
0.605848
false
false
false
false
hejunbinlan/Operations
refs/heads/development
Operations/Operations/GroupOperation.swift
mit
1
// // GroupOperation.swift // Operations // // Created by Daniel Thorpe on 18/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation /** An `Operation` subclass which enables the grouping of other operations. Use `GroupOperation`s to associate related operations together, thereby creating higher levels of abstractions. Additionally, `GroupOperation`s are useful as a way of creating Operations which may repeat themselves before subsequent operations can run. For example, authentication operations. */ public class GroupOperation: Operation { private let queue = OperationQueue() private let operations: [NSOperation] private let finishingOperation = NSBlockOperation(block: {}) private var aggregateErrors = Array<ErrorType>() /** Designated initializer. :park: operations, an array of `NSOperation`s. */ public init(operations ops: [NSOperation]) { operations = ops super.init() queue.suspended = true queue.delegate = self } public convenience init(operations: NSOperation...) { self.init(operations: operations) } /** Cancels all the groups operations. */ public override func cancel() { queue.cancelAllOperations() super.cancel() } public override func execute() { for operation in operations { queue.addOperation(operation) } queue.suspended = false queue.addOperation(finishingOperation) } /** Add an `NSOperation` to the group's queue. :param: operation, an `NSOperation` */ public func addOperation(operation: NSOperation) { queue.addOperation(operation) } public func addOperations(operations: [NSOperation]) { queue.addOperations(operations, waitUntilFinished: false) } final func aggregateError(error: ErrorType) { aggregateErrors.append(error) } /** This method is called every time one of the groups child operations finish. Over-ride this method to enable the following sort of behavior: ## Error handling. Typically you will want to have code like this: if !errors.isEmpty { if operation is MyOperation, let error = errors.first as? MyOperation.Error { switch error { case .AnError: println("Handle the error case") } } } So, if the errors array is not empty, it is important to know which kind of errors the operation may have encountered, and then implement handling of any that are necessary. Note that if an operation has conditions, which fail, they will be returned as the first errors. ## Move results between operations. Typically we use `GroupOperation` to compose and manage multiple operations into a single unit. This might often need to move the results of one operation into the next one. So this can be done here. :param: operation, an `NSOperation` :param:, errors, an array of `ErrorType`s. */ public func operationDidFinish(operation: NSOperation, withErrors errors: [ErrorType]) { // no-op, subclasses can override for their own functionality. } } extension GroupOperation: OperationQueueDelegate { public func operationQueue(queue: OperationQueue, willAddOperation operation: NSOperation) { assert(!finishingOperation.finished && !finishingOperation.executing, "Cannot add new operations to a group after the group has completed.") if operation !== finishingOperation { finishingOperation.addDependency(operation) } } public func operationQueue(queue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [ErrorType]) { aggregateErrors.appendContentsOf(errors) if operation === finishingOperation { queue.suspended = true finish(aggregateErrors) } else { operationDidFinish(operation, withErrors: errors) } } }
af9a0861ae10227ccf13647ff785212e
28.140845
148
0.666989
false
false
false
false
carabina/ActionSwift3
refs/heads/master
ActionSwift3/media/Sound.swift
mit
1
// // Sound.swift // ActionSwift // // Created by Craig on 6/08/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import SpriteKit /** Be sure to store either the sound or soundChannel in an instance variable, as the sound will be "garbage collected" (or the Swift equivalent at least, *deinitialized* when there are no references to it) */ public class Sound: EventDispatcher { private var name:String private var soundChannel:SoundChannel = SoundChannel() public init(name:String) { self.name = name } public func load(name:String) { self.name = name } ///Returns a SoundChannel, which you can use to *stop* the Sound. public func play(startTime:Number = 0, loops:int = 0)->SoundChannel { soundChannel = SoundChannel() soundChannel.play(self.name,startTime:startTime, loops:loops) return soundChannel } }
5e007bad8e03f2030ef7a734941b2c47
27.9375
115
0.677106
false
false
false
false
zwaldowski/ParksAndRecreation
refs/heads/master
Swift-2/UI Geometry.playground/Sources/Scaling.swift
mit
1
import UIKit private func rroundBy<T: GeometricMeasure>(value: T, _ scale: T = T.identity, _ function: T -> T) -> T { return (scale > T.identity) ? (function(value * scale) / scale) : function(value) } public func rround(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, round) } public func rceil(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, ceil) } public func rfloor(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, floor) } func rceilSmart(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale) { v in let vFloor = floor(v) if vFloor ~== v { return vFloor } return ceil(v) } } public extension UIView { func rround(value: CGFloat) -> CGFloat { return rroundBy(value, scale, round) } func rceil(value: CGFloat) -> CGFloat { return rroundBy(value, scale, ceil) } func rfloor(value: CGFloat) -> CGFloat { return rroundBy(value, scale, floor) } } public extension UIViewController { func rround(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, round) } func rceil(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, ceil) } func rfloor(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, floor) } } // MARK: Rotations public func toRadians<T: GeometricMeasure>(value: T) -> T { return (value * T(M_PI)) / T(180.0) } public func toDegrees<T: GeometricMeasure>(value: T) -> T { return ((value * T(180.0)) / T(M_PI)) }
11c53310b935c687f583a9961a2c0135
36.860465
121
0.66769
false
false
false
false
youngsoft/TangramKit
refs/heads/master
TangramKitDemo/FloatLayoutDemo/FOLTest2ViewController.swift
mit
1
// // FOLTest2ViewController.swift // TangramKit // // Created by apple on 16/5/8. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit //布局模型类,用于实现不同的布局展示风格 struct FOLTest2LayoutTemplate { var layoutSelector:Selector //布局实现的方法 var width:CGFloat //布局宽度,如果设置的值<=1则是相对宽度 var height:CGFloat //布局高度,如果设置的值<=1则是相对高度 } //数据模型。 @objcMembers class FOLTest2DataModel : NSObject { @objc var title:String! //标题 @objc var subTitle:String! //副标题 @objc var desc:String! //描述 @objc var price:String! //价格 @objc var image:String! //图片 @objc var subImage:String! //子图片 @objc var templateIndex = 0 //数据模型使用布局的索引。通常由服务端决定使用的布局模型,所以这里作为一个属性保存在模型数据结构中。 } //数据片段模型 @objcMembers class FOLTest2SectionModel:NSObject { var title:String! var datas:[FOLTest2DataModel]! } /** *2.FloatLayout - Jagged */ class FOLTest2ViewController: UIViewController { weak var rootLayout:TGLinearLayout! static var sItemLayoutHeight = 90.0 static var sBaseTag = 100000 lazy var layoutTemplates:[FOLTest2LayoutTemplate]={ //所有的布局模板数组 let templateSources:[[String:Any]] = [ [ "selector":#selector(createItemLayout1_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight*2) ], [ "selector":#selector(createItemLayout1_2), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout1_3), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(1.0), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout3_1), "width":CGFloat(0.4), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout3_2), "width":CGFloat(0.6), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout3_2), "width":CGFloat(0.4), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout4_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout4_2), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight + 20), ], [ "selector":#selector(createItemLayout5_1), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight + 20), ] ] var _layoutTemplates = [FOLTest2LayoutTemplate]() for dict in templateSources { let template = FOLTest2LayoutTemplate(layoutSelector:dict["selector"] as! Selector, width:CGFloat(dict["width"] as! CGFloat), height:dict["height"] as! CGFloat) _layoutTemplates.append(template) } return _layoutTemplates; }() lazy var sectionDatas:[FOLTest2SectionModel] = { //片段数据数组,FOLTest2SectionModel类型的元素。 let file:String! = Bundle.main.path(forResource: "FOLTest2DataModel",ofType:"plist") let dataSources = NSArray(contentsOfFile: file) as! [[String:AnyObject]] var _sectionDatas = [FOLTest2SectionModel]() for sectionDict:[String:AnyObject] in dataSources { let sectionModel = FOLTest2SectionModel() sectionModel.title = sectionDict["title"] as? String sectionModel.datas = [FOLTest2DataModel]() let dicts = sectionDict["datas"] as! [[String:AnyObject]] for dict in dicts { let model = FOLTest2DataModel() for (key,val) in dict { model.setValue(val, forKey:key) } sectionModel.datas.append(model); } _sectionDatas.append(sectionModel) } return _sectionDatas }() override func loadView() { let scrollView = UIScrollView() self.view = scrollView; let rootLayout = TGLinearLayout(.vert) rootLayout.tg_width.equal(.fill) rootLayout.tg_height.equal(.wrap) rootLayout.tg_gravity = TGGravity.horz.fill rootLayout.backgroundColor = UIColor(white:0xe7/255.0, alpha:1) rootLayout.tg_intelligentBorderline = TGBorderline(color: .lightGray) //设置智能边界线,布局里面的子视图会根据布局自动产生边界线。 scrollView.addSubview(rootLayout) self.rootLayout = rootLayout } override func viewDidLoad() { super.viewDidLoad() for i in 0 ..< self.sectionDatas.count { self.addSectionLayout(sectionIndex: i) } // 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //MARK: Layout Construction extension FOLTest2ViewController { //添加片段布局 func addSectionLayout(sectionIndex:Int) { let sectionModel = self.sectionDatas[sectionIndex] //如果有标题则创建标题文本 if sectionModel.title != nil { let sectionTitleLabel = UILabel() sectionTitleLabel.text = sectionModel.title; sectionTitleLabel.font = .boldSystemFont(ofSize: 15) sectionTitleLabel.backgroundColor = .white sectionTitleLabel.tg_height.equal(30) sectionTitleLabel.tg_top.equal(10) self.rootLayout.addSubview(sectionTitleLabel) } //创建条目容器布局。 let itemContainerLayout = TGFloatLayout(.vert) itemContainerLayout.backgroundColor = .white itemContainerLayout.tg_height.equal(.wrap) itemContainerLayout.tg_intelligentBorderline = TGBorderline(color: .lightGray) self.rootLayout.addSubview(itemContainerLayout) //创建条目布局,并加入到容器布局中去。 for i in 0 ..< sectionModel.datas.count { let model = sectionModel.datas[i]; let layoutTemplate = self.layoutTemplates[model.templateIndex]; //取出数据模型对应的布局模板对象。 //布局模型对象的layoutSelector负责建立布局,并返回一个布局条目布局视图。 let itemLayout = self.perform(layoutTemplate.layoutSelector,with:model).takeUnretainedValue() as! TGBaseLayout itemLayout.tag = sectionIndex * FOLTest2ViewController.sBaseTag + i; itemLayout.tg_setTarget(self,action:#selector(handleItemLayoutTap), for:.touchUpInside) itemLayout.tg_highlightedOpacity = 0.4 //根据上面布局模型对高度和宽度的定义指定条目布局的尺寸。如果小于等于1则用相对尺寸,否则用绝对尺寸。 if layoutTemplate.width <= 1 { itemLayout.tg_width.equal(itemContainerLayout.tg_width, multiple:layoutTemplate.width) } else { itemLayout.tg_width.equal(layoutTemplate.width) } if layoutTemplate.height <= 1 { itemLayout.tg_height.equal(itemContainerLayout.tg_height, multiple:layoutTemplate.height) } else { itemLayout.tg_height.equal(layoutTemplate.height) } itemContainerLayout.addSubview(itemLayout) } } //品牌特卖主条目布局,这是一个从上到下的布局,因此可以用上下浮动来实现。 @objc func createItemLayout1_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { /* 这个例子是为了重点演示浮动布局,所以里面的所有条目布局都用了浮动布局。您也可以使用其他布局来建立您的条目布局。 */ //建立上下浮动布局 let itemLayout = TGFloatLayout(.horz) //向上浮动,左边顶部边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = .boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向上浮动,左边顶部边距为5,高度为20 let subImageView = UIImageView(image:UIImage(named:dataModel.subImage)) subImageView.tg_leading.equal(5) subImageView.tg_top.equal(5) subImageView.tg_height.equal(20) subImageView.sizeToFit() itemLayout.addSubview(subImageView) //向上浮动,高度占用剩余的高度,宽度和父布局保持一致。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_height.equal(.fill) imageView.tg_width.equal(itemLayout.tg_width) itemLayout.addSubview(imageView) return itemLayout; } //天猫超时条目布局,这是一个整体左右结构,因此用左右浮动布局来实现。 @objc func createItemLayout1_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { //建立左右浮动布局 let itemLayout = TGFloatLayout(.vert) //向左浮动,宽度和父视图宽度保持一致,顶部和左边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_width.equal(itemLayout.tg_width) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向左浮动,因为上面占据了全部宽度,这里会自动换行显示并且也是全宽。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 12) subTitleLabel.textColor = .lightGray subTitleLabel.tg_width.equal(itemLayout.tg_width) subTitleLabel.tg_leading.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //图片向右浮动,并且右边距为5,上面因为占据了全宽,因此这里会另起一行向右浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_reverseFloat = true imageView.tg_trailing.equal(5) imageView.sizeToFit() itemLayout.addSubview(imageView) return itemLayout; } //建立品牌特卖的其他条目布局,这种布局整体是左右结构,因此建立左右浮动布局。 @objc func createItemLayout1_3(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.vert) //因为图片要占据全高,所以必须优先向右浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_height.equal(itemLayout.tg_height) imageView.tg_reverseFloat = true; imageView.sizeToFit() itemLayout.addSubview(imageView) //向左浮动,并占据剩余的宽度,边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(.fill) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向左浮动,直接另起一行,占据剩余宽度,内容高度动态。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 12) subTitleLabel.textColor = UIColor.lightGray; subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_clearFloat = true; subTitleLabel.tg_width.equal(.fill) subTitleLabel.tg_height.equal(.wrap) itemLayout.addSubview(subTitleLabel) //如果有小图片则图片另起一行,向左浮动。 if (dataModel.subImage != nil) { let subImageView = UIImageView(image:UIImage(named:dataModel.subImage)) subImageView.tg_clearFloat = true; subImageView.tg_leading.equal(5) subImageView.sizeToFit() itemLayout.addSubview(subImageView) } return itemLayout; } //建立超级品牌日布局,这里因为就只有一张图,所以设置布局的背景图片即可。 @objc func createItemLayout2_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.vert) //直接设置背景图片。 itemLayout.tg_backgroundImage = UIImage(named:dataModel.image) return itemLayout; } //精选市场主条目布局,这个布局整体从上到下因此用上下浮动布局建立。 @objc func createItemLayout3_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) //向上浮动 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //继续向上浮动。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.title; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //价格部分在底部,因此改为向下浮动。 let priceLabel = UILabel() priceLabel.text = dataModel.price; priceLabel.font = UIFont.systemFont(ofSize: 11) priceLabel.textColor = UIColor.red priceLabel.tg_leading.equal(5) priceLabel.tg_bottom.equal(5) priceLabel.tg_reverseFloat = true priceLabel.sizeToFit() itemLayout.addSubview(priceLabel) //描述部分在价格的上面,因此改为向下浮动。 let descLabel = UILabel() descLabel.text = dataModel.desc; descLabel.font = UIFont.systemFont(ofSize: 11) descLabel.textColor = UIColor.lightGray descLabel.tg_leading.equal(5) descLabel.tg_reverseFloat = true descLabel.sizeToFit() itemLayout.addSubview(descLabel) //向上浮动,并占用剩余的空间高度。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width); imageView.tg_height.equal(100%) itemLayout.addSubview(imageView) return itemLayout; } //建立精选市场其他条目布局,这个布局整体还是从上到下,因此用上下浮动布局 @objc func createItemLayout3_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) //向上浮动 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5, multiple:0.5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //继续向上浮动 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //价格向下浮动 let priceLabel = UILabel() priceLabel.text = dataModel.price; priceLabel.font = UIFont.systemFont(ofSize: 11) priceLabel.textColor = UIColor.red priceLabel.tg_leading.equal(5) priceLabel.tg_bottom.equal(5) priceLabel.tg_reverseFloat = true priceLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) priceLabel.sizeToFit() itemLayout.addSubview(priceLabel) //描述向下浮动 let descLabel = UILabel() descLabel.text = dataModel.desc; descLabel.font = UIFont.systemFont(ofSize: 11) descLabel.textColor = UIColor.lightGray descLabel.tg_leading.equal(5) descLabel.tg_reverseFloat = true descLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) descLabel.sizeToFit() itemLayout.addSubview(descLabel) //向上浮动,因为宽度无法再容纳,所以这里会换列继续向上浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) imageView.tg_height.equal(itemLayout.tg_height); itemLayout.addSubview(imageView) return itemLayout; } //热门市场主条目布局,这个结构可以用上下浮动布局也可以用左右浮动布局。 @objc func createItemLayout4_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //继续向上浮动,这里因为高度和父布局高度一致,因此会换列浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) imageView.tg_height.equal(itemLayout.tg_height); itemLayout.addSubview(imageView) return itemLayout; } //热门市场其他条目布局,这个整体是上下布局,因此用上下浮动布局。 @objc func createItemLayout4_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //继续向上浮动,占据剩余高度。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width) imageView.tg_height.equal(100%) itemLayout.addSubview(imageView) return itemLayout; } //主题市场条目布局,这个整体就是上下浮动布局 @objc func createItemLayout5_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.textColor = UIColor.red subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width) imageView.tg_height.equal(100%) //图片占用剩余的全部高度 itemLayout.addSubview(imageView) return itemLayout; } } //MARK: Handle Method extension FOLTest2ViewController { @objc func handleItemLayoutTap(sender:UIView!) { let sectionIndex = sender.tag / FOLTest2ViewController.sBaseTag; let itemIndex = sender.tag % FOLTest2ViewController.sBaseTag; let message = "You have select\nSectionIndex:\(sectionIndex) ItemIndex:\(itemIndex)" UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "OK").show() } }
9620365615240204489c08212851205f
33.130568
122
0.599307
false
true
false
false
ngageoint/mage-ios
refs/heads/master
MageTests/Categories/LocationUtilitiesTests.swift
apache-2.0
1
// // CoordinateDisplayTests.swift // MAGETests // // Created by Daniel Barela on 1/7/22. // Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import Quick import Nimble import CoreLocation @testable import MAGE class LocationUtilitiesTests: QuickSpec { override func spec() { describe("LocationUtilitiesTests Tests") { it("should display the coordinate") { UserDefaults.standard.locationDisplay = .latlng expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("15.48000, 20.47000")) UserDefaults.standard.locationDisplay = .mgrs expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("34PDC4314911487")) UserDefaults.standard.locationDisplay = .dms expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("15° 28' 48\" N, 20° 28' 12\" E")) expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay(short: true)).to(equal("15° 28' 48\" N, 20° 28' 12\" E")) UserDefaults.standard.locationDisplay = .dms expect(LocationUtilities.latitudeDMSString(coordinate:11.186388888888889)).to(equal("11° 11' 11\" N")) expect(CLLocationCoordinate2D.parse(coordinates:"111111N, 121212E").toDisplay()).to(equal("11° 11' 11\" N, 12° 12' 12\" E")) expect(LocationUtilities.latitudeDMSString(coordinate:0.186388888888889)).to(equal("0° 11' 11\" N")) expect(CLLocationCoordinate2D.parse(coordinates:"01111N, 01212E").toDisplay()).to(equal("0° 11' 11\" N, 0° 12' 12\" E")) } it("should split the coordinate string") { expect(CLLocationCoordinate2D.splitCoordinates(coordinates: nil)).to(equal([])) var coordinates = "112233N 0152144W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["112233N","0152144W"])) coordinates = "N 11 ° 22'33 \"- W 15 ° 21'44" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["N11°22'33\"","W15°21'44"])) coordinates = "N 11 ° 22'30 \"" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["N11°22'30\""])) coordinates = "11 ° 22'33 \"N - 15 ° 21'44\" W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11°22'33\"N","15°21'44\"W"])) coordinates = "11° 22'33 N 015° 21'44 W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11°22'33N","015°21'44W"])) coordinates = "11.4584 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","15.6827"])) coordinates = "-11.4584 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["-11.4584","15.6827"])) coordinates = "11.4584 -15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","-15.6827"])) coordinates = "11.4584, 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","15.6827"])) coordinates = "-11.4584, 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["-11.4584","15.6827"])) coordinates = "11.4584, -15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","-15.6827"])) } it("should parse the coordinate string") { expect(CLLocationCoordinate2D.parse(coordinate:nil)).to(beNil()) var coordinates = "112230N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(11.375)) coordinates = "112230" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(11.375)) coordinates = "purple" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beNil()) coordinates = "N 11 ° 22'30 \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "N 11 ° 22'30.36 \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "N 11 ° 22'30.remove \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11 ° 22'30 \"N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11° 22'30 N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11.4584" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.4584))) coordinates = "-11.4584" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-11.4584))) coordinates = "0151545W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "W 15 ° 15'45" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "15 ° 15'45\" W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "015° 15'45 W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "15.6827" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(15.6827))) coordinates = "-15.6827" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.6827))) coordinates = "0.186388888888889" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(0.186388888888889))) coordinates = "0° 11' 11\" N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beCloseTo(CLLocationDegrees(0.186388888888889))) coordinates = "705600N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beCloseTo(CLLocationDegrees(70.9333))) } it("should parse the coordinate string to a DMS string") { expect(LocationUtilities.parseToDMSString(nil)).to(beNil()) var coordinates = "112230N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "112230" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" ")) coordinates = "30N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("30° N")) coordinates = "3030N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("30° 30' N")) coordinates = "purple" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("E")) coordinates = "" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("")) coordinates = "N 11 ° 22'30 \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "N 11 ° 22'30.36 \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "112233.99N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 34\" N")) coordinates = "11.999999N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("12° 00' 00\" N")) coordinates = "N 11 ° 22'30.remove \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11 ° 22'30 \"N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11° 22'30 N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° ")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" N")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" S")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("11° 27' 30\" E")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("11° 27' 30\" W")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" N")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" S")) coordinates = "0151545W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("015° 15' 45\" W")) coordinates = "113000W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 30' 00\" W")) coordinates = "W 15 ° 15'45" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 15' 45\" W")) coordinates = "15 ° 15'45\" W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 15' 45\" W")) coordinates = "015° 15'45 W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("015° 15' 45\" W")) coordinates = "15.6827" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 40' 58\" ")) coordinates = "-15.6827" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 40' 58\" ")) coordinates = "15.6827" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("15° 40' 58\" E")) coordinates = "-15.6827" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("15° 40' 58\" W")) coordinates = "113000NNNN" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 30' 00\" N")) coordinates = "0.186388888888889" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("0° 11' 11\" E")) coordinates = "0° 11' 11\" N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("0° 11' 11\" N")) coordinates = "705600N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("70° 56' 00\" N")) coordinates = "70° 560'" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("7° 05' 60\" ")) } it("should parse to DMS") { let coordinate = "113000NNNN" let parsed = LocationUtilities.parseDMS(coordinate: coordinate) expect(parsed.direction).to(equal("N")) expect(parsed.seconds).to(equal(0)) expect(parsed.minutes).to(equal(30)) expect(parsed.degrees).to(equal(11)) } it("should parse to DMS 2") { let coordinate = "70560" let parsed = LocationUtilities.parseDMS(coordinate: coordinate) expect(parsed.direction).to(beNil()) expect(parsed.seconds).to(equal(60)) expect(parsed.minutes).to(equal(5)) expect(parsed.degrees).to(equal(7)) } it("should split the coordinate string") { var coordinates = "112230N 0151545W" var parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "N 11 ° 22'30 \"- W 15 ° 15'45" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11 ° 22'30 \"N - 15 ° 15'45\" W" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11° 22'30 N 015° 15'45 W" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "N 11° 22'30 W 015° 15'45 " parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11.4584 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "-11.4584 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(-11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "11.4584 -15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(-15.6827)) coordinates = "11.4584, 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "-11.4584, 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(-11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "11.4584, -15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(-15.6827)) coordinates = "11.4584" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude.isNaN).to(beTrue()) expect(parsed.longitude).to(equal(11.4584)) coordinates = "11 ° 22'30 \"N" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude.isNaN).to(beTrue()) // TODO: is this wrong? shouldn't this be latitude? expect(parsed.longitude).to(equal(11.375)) // future test // coordinates = "11-22-30N 015-15-45W" // parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) // expect(parsed.latitude.isNaN).to(beTrue()) // expect(parsed.latitude).to(equal(11.375)) // expect(parsed.longitude).to(equal(-15.2625)) } it("should validate DMS latitude input") { expect(LocationUtilities.validateLatitudeFromDMS(latitude: nil)).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "NS1122N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "002233.NS")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "ABCDEF.NS")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "11NSNS.1N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "1111NS.1N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "113000NNN")).to(beFalse()) var validString = "112233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "02233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "12233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233.2384S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "1800000E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: validString)).to(beTrue()) validString = "1800000W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: validString)).to(beTrue()) validString = "900000S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "900000N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) var invalidString = "2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "33N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "2N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = ".123N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "2233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "33W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "2W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = ".123W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "112233" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1a2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1a2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "11a233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1122a3N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "912233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "-112233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "116033N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "112260N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1812233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "-112233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "002233E" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "002233N" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800001E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800000.1E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800001W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800000.1W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "900001N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900000.1N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900001S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900000.1S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "108900S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "100089S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) } it("should return a latitude dms string") { var coordinate = CLLocationDegrees(11.1) expect(LocationUtilities.latitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" N")) coordinate = CLLocationDegrees(-11.1) expect(LocationUtilities.latitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" S")) } it("should return a longitude dms string") { var coordinate = CLLocationDegrees(11.1) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" E")) coordinate = CLLocationDegrees(-11.1) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" W")) coordinate = CLLocationDegrees(18.077251) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("18° 04' 38\" E")) } } } }
dba5d8bee9b0e4925063786c54ea5995
55.012876
148
0.598345
false
false
false
false
exchangegroup/calayer-with-tint-colored-image
refs/heads/master
calayer-with-tint-colored-image/ViewController.swift
mit
2
// // ViewController.swift // calayer-with-tint-colored-image // // Created by Evgenii Neumerzhitckii on 17/11/2014. // Copyright (c) 2014 The Exchange Group Pty Ltd. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var viewForCALayer: UIView! override func viewDidLoad() { super.viewDidLoad() viewForCALayer.backgroundColor = nil if let currentImage = UIImage(named: "star.png") { ViewController.setImageViewImage(imageView, image: currentImage) ViewController.setCALayerImage(viewForCALayer.layer, image: currentImage) } } private class func setImageViewImage(imageView: UIImageView, image: UIImage) { imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) } private class func setCALayerImage(layer: CALayer, image: UIImage) { let tintedImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) layer.contents = tintedImage.CGImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e6fe879dc1f6fe618f0ae9d8ff5bb898
27.380952
87
0.744128
false
false
false
false
GroundSpeed/BreakingGround
refs/heads/master
CodeMashQuality/CodeMashQuality/Products.swift
mit
1
// // Products.swift // CodeMashQuality // // Created by Don Miller on 1/7/16. // Copyright © 2016 GroundSpeed. All rights reserved. // import UIKit import Parse class Products { var objectId : String? var productId : Int? var photo : String? var photoFile : PFFile = PFFile() var photoImage : UIImage? var title : String? var flyer : String? var productDesc : String? var itemCode : String? var packagingOptions : String? var fragrances : String? var categories : String? var location : String? var msdsLink : String? var videoLink : String? var innerCase : Int? var masterCase : Int? func getAllProductsFromParse() -> Array<Products> { let query = PFQuery(className:"Products") var arrayProducts : Array<Products> = [] do { let objects = try query.findObjects() for object in objects { self.objectId = object["objectId"] as? String self.productId = object["Id"] as? Int self.photoImage = object["PhotoImage"] as? UIImage self.title = object["Title"] as? String self.productDesc = object["Description"] as? String arrayProducts.append(self) } } catch let e as NSError { print("Parse load error: \(e)") } return arrayProducts } }
33558015255493a7df2458f4df35fa15
26.576923
67
0.576011
false
false
false
false
Sajjon/ViewComposer
refs/heads/master
Example/Source/ViewControllers/ViewComposer/LoginViewController.swift
mit
1
// // LoginViewController.swift // Example // // Created by Alexander Cyon on 2017-06-10. // Copyright © 2017 Alexander Cyon. All rights reserved. // import UIKit import ViewComposer private let height: CGFloat = 50 private let style: ViewStyle = [.font(.big), .height(height), .clipsToBounds(true) ] private let borderStyle = style <<- .borderWidth(2) private let borderColorNormal: UIColor = .blue final class LoginViewController: UIViewController, StackViewOwner { lazy var emailField: UITextField = borderStyle <<- [.placeholder("Email"), .delegate(self)] lazy var passwordField: UITextField = borderStyle <<- [.placeholder("Password"), .delegate(self)] lazy var loginButton: Button = borderStyle <<- .states([ Normal("Login", titleColor: .blue, backgroundColor: .green, borderColor: borderColorNormal), Highlighted("Logging in...", titleColor: .red, backgroundColor: .yellow, borderColor: .red) ]) <- .target(self.target(#selector(loginButtonPressed))) <- [.roundedBy(.height)] var views: [UIView] { return [emailField, passwordField, loginButton] } lazy var stackView: UIStackView = .axis(.vertical) <- .views(self.views) <- [.spacing(20), .margin(20)] override func viewDidLoad() { super.viewDidLoad() setupViews() title = "ViewComposer - LoginViewController" } } extension LoginViewController: UITextFieldDelegate { public func textFieldDidEndEditing(_ textField: UITextField) { textField.validate() } } private extension LoginViewController { @objc func loginButtonPressed() { print("should login") } }
e34687fc60bb875409a67ec915069da3
32.117647
104
0.672587
false
false
false
false
sammeadley/TopStories
refs/heads/master
TopStories/Story.swift
mit
1
// // Story.swift // TopStories // // Created by Sam Meadley on 20/04/2016. // Copyright © 2016 Sam Meadley. All rights reserved. // import Foundation import CoreData class Story: NSManagedObject { /** Default fetch request for Story entities. Returns a fetch request configured to return Story entities, sorted by date created descending. - returns: NSFetchRequest instance for Story entities. */ override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: self)) fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "createdDate", ascending: false) ] return fetchRequest } /** Lookup Story instances by contentURL value. Looks up Story instances based on contentURL value. Ideally we would use something like a unique identifier here to refer to unique instances. The API doesn't provide us with such, so we'll key off contentURL. - parameter URLs: Array of contentURLs used to perform the story lookup. - parameter managedObjectContext: The managedObjectContext instance to execute a fetch against. - returns: Array Story entities matching the contentURLs. */ class func instancesForContentURLs(_ URLs: [String], managedObjectContext: NSManagedObjectContext) -> [Story]? { let results = self.instancesInManagedObjectContext(managedObjectContext, predicate: NSPredicate(format: "contentURL in %@", URLs)) return results } /** Lookup Story instances by predicate. Looks up Story instances based on a supplied predicate. - parameter managedObjectContext: The managedObjectContext instance to execute a fetch against. - parameter predicate: The predicate to use in the fetch request. - returns: Array Story entities matching the predicate. */ class func instancesInManagedObjectContext(_ managedObjectContext: NSManagedObjectContext, predicate: NSPredicate? = nil) -> [Story]? { let fetchRequest = self.fetchRequest() fetchRequest.predicate = predicate do { let results = try managedObjectContext.fetch(fetchRequest) return results as? [Story] } catch { // TODO: Handle error return nil } } /** Return image URL by desired size. - parameter imageSize: The desired image size, see ImageSize for options. - returns: Image URL string. */ func imageURL(for imageSize: ImageSize) -> String? { switch imageSize { case .default: return imageURL case .thumbnail: return thumbnailURL } } /** Use with imageURLForSize(_:) to return the correct URL for the desired size. */ enum ImageSize: Int { case `default` case thumbnail } }
03254539e611815e670ee56a378024a5
31.272727
116
0.620344
false
false
false
false
koba-uy/chivia-app-ios
refs/heads/master
src/Chivia/Views/ReportTypeCollectionViewCell.swift
lgpl-3.0
1
// // ReportTypeCollectionViewCell.swift // Chivia // // Created by Agustín Rodríguez on 10/29/17. // Copyright © 2017 Agustín Rodríguez. All rights reserved. // import LGButton import UIKit class ReportTypeCollectionViewCell : UICollectionViewCell { @IBOutlet var view: UIView! @IBOutlet var button: LGButton! @IBOutlet var label: UILabel! public var delegate: ReportTypeCollectionViewCellDelegate? public var reportType: ReportType? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) Bundle.main.loadNibNamed("ReportTypeCollectionViewCell", owner: self, options: nil) addSubview(view) view.frame = self.bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] } override func layoutSubviews() { super.layoutSubviews() button.bgColor = reportType!.iconColor button.leftIconString = reportType!.iconString label.text = reportType!.name } @IBAction func button(_ sender: LGButton) { delegate?.reportTypeCollectionViewCell(clicked: reportType!) } }
cf636af783bd725919f11f87b7fc3cee
25.813953
91
0.67216
false
false
false
false
gxf2015/DYZB
refs/heads/master
DYZB/DYZB/Classes/Main/View/CollectionBaseCell.swift
mit
1
// // CollectionBaseCell.swift // DYZB // // Created by guo xiaofei on 2017/8/14. // Copyright © 2017年 guo xiaofei. All rights reserved. // import UIKit import Kingfisher class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor : AncnorModel? { didSet{ //0 guard let anchor = anchor else { return } //1 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" }else{ onlineStr = "\(anchor.online)万在线" } onlineBtn.setTitle(onlineStr, for: .normal) nickNameLabel.text = anchor.nickname guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
ab414218add941ec3248520938a40512
24.204545
71
0.52119
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Characteristics/Characteristic.TargetHumidifierDehumidifierState.swift
mit
1
import Foundation public extension AnyCharacteristic { static func targetHumidifierDehumidifierState( _ value: Enums.TargetHumidifierDehumidifierState = .auto, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Humidifier-Dehumidifier State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.targetHumidifierDehumidifierState( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func targetHumidifierDehumidifierState( _ value: Enums.TargetHumidifierDehumidifierState = .auto, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Humidifier-Dehumidifier State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Enums.TargetHumidifierDehumidifierState> { GenericCharacteristic<Enums.TargetHumidifierDehumidifierState>( type: .targetHumidifierDehumidifierState, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
dc62afb512846544c655bc41689619d4
36.885246
75
0.619645
false
false
false
false
hlts2/SwiftyLogger
refs/heads/master
Sources/LoggerSettings.swift
mit
1
import Foundation public struct LoggerSettings { public var dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" public var filePath = "/tmp/SwiftyLogger.log" public var logHidden = false public var showEmoji = true public var showDate = true public var showFunctionName = true public var showFileName = true public var isFileWrite = false }
6110a67cb530a4f5bc06504380546ff2
33.076923
63
0.582393
false
false
false
false
meetkei/KeiSwiftFramework
refs/heads/master
KeiSwiftFramework/Notification/KNotification.swift
mit
1
// // KNotification.swift // // Copyright (c) 2016 Keun young Kim <app@meetkei.com> // // 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 open class KNotification { open class func post(_ name: String, object: AnyObject? = nil) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } open class func postDelayedOnMainQueue(_ name: String, delay: Double = 0.3, object: AnyObject? = nil) { AsyncGCD.performDelayedOnMainQueue(delay) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } } open class func postDelayedOnGlobalQueue(_ name: String, delay: Double = 0.3, object: AnyObject? = nil) { AsyncGCD.performDelayedOnGlobalQueue(delay) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } } }
9bad44fb9592e6fdd861f9ae764e5b24
41.297872
109
0.712777
false
false
false
false
accatyyc/Buildasaur
refs/heads/master
BuildaKit/PersistenceMigrator.swift
mit
2
// // PersistenceMigrator.swift // Buildasaur // // Created by Honza Dvorsky on 10/12/15. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils public protocol MigratorType { init(persistence: Persistence) var persistence: Persistence { get set } func isMigrationRequired() -> Bool func attemptMigration() throws } extension MigratorType { func config() -> NSDictionary { let config = self.persistence.loadDictionaryFromFile("Config.json") ?? [:] return config } func persistenceVersion() -> Int? { let config = self.config() let version = config.optionalIntForKey(kPersistenceVersion) return version } } public class CompositeMigrator: MigratorType { public var persistence: Persistence { get { preconditionFailure("No persistence here") } set { for var i in self.childMigrators { i.persistence = newValue } } } internal let childMigrators: [MigratorType] public required init(persistence: Persistence) { self.childMigrators = [ Migrator_v0_v1(persistence: persistence), Migrator_v1_v2(persistence: persistence) ] } public func isMigrationRequired() -> Bool { return self.childMigrators.filter { $0.isMigrationRequired() }.count > 0 } public func attemptMigration() throws { try self.childMigrators.forEach { try $0.attemptMigration() } } } let kPersistenceVersion = "persistence_version" /* - Config.json: persistence_version: null -> 1 */ class Migrator_v0_v1: MigratorType { internal var persistence: Persistence required init(persistence: Persistence) { self.persistence = persistence } func isMigrationRequired() -> Bool { //we need to migrate if there's no persistence version, assume 1 let version = self.persistenceVersion() return (version == nil) } func attemptMigration() throws { let pers = self.persistence //make sure the config file has a persistence version number let version = self.persistenceVersion() guard version == nil else { //all good return } let config = self.config() let mutableConfig = config.mutableCopy() as! NSMutableDictionary mutableConfig[kPersistenceVersion] = 1 //save the updated config pers.saveDictionary("Config.json", item: mutableConfig) //copy the rest pers.copyFileToWriteLocation("Builda.log", isDirectory: false) pers.copyFileToWriteLocation("Projects.json", isDirectory: false) pers.copyFileToWriteLocation("ServerConfigs.json", isDirectory: false) pers.copyFileToWriteLocation("Syncers.json", isDirectory: false) pers.copyFileToWriteLocation("BuildTemplates", isDirectory: true) } } /* - ServerConfigs.json: each server now has an id - Config.json: persistence_version: 1 -> 2 */ class Migrator_v1_v2: MigratorType { internal var persistence: Persistence required init(persistence: Persistence) { self.persistence = persistence } func isMigrationRequired() -> Bool { return self.persistenceVersion() == 1 } func attemptMigration() throws { let serverRef = self.migrateServers() let (templateRef, projectRef) = self.migrateProjects() self.migrateSyncers(serverRef, project: projectRef, template: templateRef) self.migrateBuildTemplates() self.migrateConfigAndLog() } func fixPath(path: String) -> String { let oldUrl = NSURL(string: path) let newPath = oldUrl!.path! return newPath } func migrateBuildTemplates() { //first pull all triggers from all build templates and save them //as separate files, keeping the ids around. let templates = self.persistence.loadArrayOfDictionariesFromFolder("BuildTemplates") ?? [] guard templates.count > 0 else { return } let mutableTemplates = templates.map { $0.mutableCopy() as! NSMutableDictionary } //go through templates and replace full triggers with just ids var triggers = [NSDictionary]() for template in mutableTemplates { guard let tempTriggers = template["triggers"] as? [NSDictionary] else { continue } let mutableTempTriggers = tempTriggers.map { $0.mutableCopy() as! NSMutableDictionary } //go through each trigger and each one an id let trigWithIds = mutableTempTriggers.map { trigger -> NSDictionary in trigger["id"] = Ref.new() return trigger.copy() as! NSDictionary } //add them to the big list of triggers that we'll save later triggers.appendContentsOf(trigWithIds) //now gather those ids let triggerIds = trigWithIds.map { $0.stringForKey("id") } //and replace the "triggers" array in the build template with these ids template["triggers"] = triggerIds } //now save all triggers into their own folder self.persistence.saveArrayIntoFolder("Triggers", items: triggers, itemFileName: { $0.stringForKey("id") }, serialize: { $0 }) //and save the build templates self.persistence.saveArrayIntoFolder("BuildTemplates", items: mutableTemplates, itemFileName: { $0.stringForKey("id") }, serialize: { $0 }) } func migrateSyncers(server: RefType?, project: RefType?, template: RefType?) { let syncers = self.persistence.loadArrayOfDictionariesFromFile("Syncers.json") ?? [] let mutableSyncers = syncers.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableSyncers.map { syncer -> NSMutableDictionary in syncer["id"] = Ref.new() return syncer } //remove server host and project path and add new ids let updated = withIds.map { syncer -> NSMutableDictionary in syncer.removeObjectForKey("server_host") syncer.removeObjectForKey("project_path") syncer.optionallyAddValueForKey(server, key: "server_ref") syncer.optionallyAddValueForKey(project, key: "project_ref") syncer.optionallyAddValueForKey(template, key: "preferred_template_ref") return syncer } self.persistence.saveArray("Syncers.json", items: updated) } func migrateProjects() -> (template: RefType?, project: RefType?) { let projects = self.persistence.loadArrayOfDictionariesFromFile("Projects.json") ?? [] let mutableProjects = projects.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableProjects.map { project -> NSMutableDictionary in project["id"] = Ref.new() return project } //fix internal urls to be normal paths instead of the file:/// paths let withFixedUrls = withIds.map { project -> NSMutableDictionary in project["url"] = self.fixPath(project.stringForKey("url")) project["ssh_public_key_url"] = self.fixPath(project.stringForKey("ssh_public_key_url")) project["ssh_private_key_url"] = self.fixPath(project.stringForKey("ssh_private_key_url")) return project } //remove preferred_template_id, will be moved to syncer let removedTemplate = withFixedUrls.map { project -> (RefType?, NSMutableDictionary) in let template = project["preferred_template_id"] as? RefType project.removeObjectForKey("preferred_template_id") return (template, project) } //get just the projects let finalProjects = removedTemplate.map { $0.1 } let firstTemplate = removedTemplate.map { $0.0 }.first ?? nil let firstProject = finalProjects.first?["id"] as? RefType //save self.persistence.saveArray("Projects.json", items: finalProjects) return (firstTemplate, firstProject) } func migrateServers() -> (RefType?) { let servers = self.persistence.loadArrayOfDictionariesFromFile("ServerConfigs.json") ?? [] let mutableServers = servers.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableServers.map { server -> NSMutableDictionary in server["id"] = Ref.new() return server } //save self.persistence.saveArray("ServerConfigs.json", items: withIds) //return the first/only one (there should be 0 or 1) let firstId = withIds.first?["id"] as? RefType return firstId } func migrateConfigAndLog() { //copy log self.persistence.copyFileToWriteLocation("Builda.log", isDirectory: false) let config = self.config() let mutableConfig = config.mutableCopy() as! NSMutableDictionary mutableConfig[kPersistenceVersion] = 2 //save the updated config self.persistence.saveDictionary("Config.json", item: mutableConfig) } }
31a5c915ffb14a3f65a739f334b25f79
34.205128
147
0.618458
false
true
false
false
PrimarySA/Hackaton2015
refs/heads/master
stocker/BachiTrading/OrdersViewController.swift
gpl-3.0
1
// // OrdersViewController.swift // BachiTrading // // Created by Emiliano Bivachi on 15/11/15. // Copyright (c) 2015 Emiliano Bivachi. All rights reserved. // import UIKit class OrdersViewController: UIViewController { private var orders: [Order]? { didSet { tableView.reloadData() } } @IBOutlet private weak var tableView: UITableView! init() { super.init(nibName: "MarketDataViewController", bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(OrderCell.cellNib(), forCellReuseIdentifier: OrderCell.identifier()) title = "Ordenes" navigationItem.leftBarButtonItem?.tintColor = Styler.Color.greenColor OrderStore.sharedInstance().getOrdersForAccountId("20", withCompletionBlock: { [weak self] (ordersResponse, error) -> Void in if let ordersResponse = ordersResponse as? ListOfOrdersResponse, let orders = ordersResponse.orders as? [Order], let weakSelf = self { weakSelf.orders = orders } }) } } extension OrdersViewController: UITableViewDelegate, UITableViewDataSource { //TableView Delegate and Datasource func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orders?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(OrderCell.identifier(), forIndexPath: indexPath) as! OrderCell if let orders = self.orders { cell.order = orders[indexPath.row] } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return OrderCell.cellHeight() } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } }
25f4aa93f1618cbb7de8fb9c514d84d5
30.09589
133
0.657269
false
false
false
false
lovesunstar/network
refs/heads/master
Network/Classes/HTTPBuilder.swift
mit
1
// // HTTPBuilder.swift // Alamofire // // Created by 孙江挺 on 2018/6/6. // import Foundation import Alamofire public extension Network { public class HTTPBuilder: NSObject { internal let manager: AFManager internal init(url: String, manager: AFManager) { urlString = url self.manager = manager super.init() } @discardableResult open func method(_ method: Alamofire.HTTPMethod) -> Self { httpMethod = method return self } @discardableResult open func appendCommonParameters(_ append: Bool) -> Self { vappendCommonParameters = append return self } @discardableResult open func query(_ parameters: [String : Any]?) -> Self { queryParameters = parameters return self } @discardableResult open func post(_ parameters: [String : Any]?) -> Self { postParameters = parameters if let p = parameters , !p.isEmpty { let _ = method(.post) } return self } @discardableResult open func headers(_ headers: [String : String]?) -> Self { vheaders = headers return self } @discardableResult open func gzipEnabled(_ enabled: Bool) -> Self { vgzipEnabled = enabled return self } @discardableResult open func retry(_ retryTimes: UInt16) -> Self { self.retryTimes = retryTimes return self } @discardableResult open func timeout(_ timeout: TimeInterval) -> Self { timeoutInterval = timeout return self } @discardableResult open func cachePolicy(_ policy: NSURLRequest.CachePolicy) -> Self { vcachePolicy = policy return self } @discardableResult open func priority(_ priority: Network.Priority) -> Self { vpriority = priority return self } @discardableResult open func downloadProgress(on queue: DispatchQueue = DispatchQueue.main, callback:((Progress)->Void)?) -> Self { downloadProgressQueue = queue downloadProgressCallback = callback return self } fileprivate func append(_ parameters: [String : Any]?, to absoluteString: String) -> String { guard let parameters = parameters , !parameters.isEmpty else { return absoluteString } var results = absoluteString var components: [(String, String)] = [] for key in Array(parameters.keys).sorted(by: <) { let value = parameters[key]! components += Alamofire.URLEncoding.queryString.queryComponents(fromKey: key, value: value) } let query = (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") if !query.isEmpty { if absoluteString.contains("?") { results.append("&") } else { results.append("?") } results.append(query) } return results } open func build() -> Request? { return nil } internal var urlString: String internal var vheaders: [String : String]? internal var queryParameters: [String : Any]? internal var parameterEncoding: ParameterEncoding = .url internal var vappendCommonParameters = true internal var retryTimes: UInt16 = 0 internal var timeoutInterval: TimeInterval = 30 internal var vcachePolicy = NSURLRequest.CachePolicy.useProtocolCachePolicy internal var vpriority = Network.Priority.default internal var downloadProgressQueue: DispatchQueue? internal var downloadProgressCallback: ((Progress)->Void)? internal var vgzipEnabled = true /// 发送请求的时间(unix时间戳) internal var requestTimestamp: TimeInterval = 0 internal var httpMethod: AFMethod = .get internal var postParameters: [String : Any]? } /** 网络请求 <br /> Usage: <br /> NewsMaster.Network.request(url) .method([GET|POST|HEAD|PATCH|DELETE...])?<br /> .get([String:Any])?<br /> .post([String:Any])?<br /> .retry(retryTimes)?<br /> .headers(["Accept": "xxx"])?<br /> .encoding(FormData|Mutilpart|JSON|...)?<br /> .priority(Network.Default)?<br /> .timeout(seconds)?<br /> .append(commonParameters)?<br /> .pack() unwrap?.pon_response { _, _, results, error in logic } */ public class RequestBuilder: HTTPBuilder { @discardableResult open func encoding(_ encoding: ParameterEncoding) -> Self { parameterEncoding = encoding return self } /// NOTE: never use this way on main thread open func syncResponseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> (URLResponse?, Any?, NSError?) { if let request = build() { var response: URLResponse? var responseData: Any? var responseError: NSError? let semaphore = DispatchSemaphore(value: 0) let _ = request.responseJSON(queue: DispatchQueue.global(qos: .default), options: options, completionHandler: { (_, URLResponse, data, error) -> Void in response = URLResponse responseData = data responseError = error semaphore.signal() }) let _ = semaphore.wait(timeout: DispatchTime.distantFuture) return (response, responseData, responseError) } return (nil, nil, nil) } open override func build() -> Request? { if self.urlString.isEmpty { return nil } var absoluteString = append(queryParameters, to: self.urlString) if vappendCommonParameters { // 从CommonParams中删除 getParameters if let commonParameters = Network.client?.commonParameters { let restCommonParameters = commonParameters - queryParameters absoluteString = append(restCommonParameters, to: absoluteString) } } var headers = [String : String]() if let defaultHeaders = Network.client?.requestHeaders { headers += defaultHeaders } headers += vheaders var URLString = absoluteString as String var postParameters = self.postParameters Network.client?.willProcessRequestWithURL(&URLString, headers: &headers, parameters: &postParameters) guard var mutableURLRequest = mutableRequest(URLString, method: httpMethod, headers: headers) else { return nil } requestTimestamp = Date().timeIntervalSince1970 if timeoutInterval != 0 { mutableURLRequest.timeoutInterval = timeoutInterval } mutableURLRequest.cachePolicy = vcachePolicy guard var encodedURLRequest = try? parameterEncoding.asAFParameterEncoding().encode(mutableURLRequest, with: postParameters) else { return nil } // GZIP Compress if vgzipEnabled { if let HTTPBody = encodedURLRequest.httpBody, let client = Network.client { var newHTTPBody = HTTPBody let compressed = client.compressDataUsingGZip(&newHTTPBody) if newHTTPBody.count > 0 && compressed { encodedURLRequest.setValue("gzip", forHTTPHeaderField: "Content-Encoding") encodedURLRequest.httpBody = newHTTPBody } } } let afRequest = manager.request(encodedURLRequest) afRequest.task?.priority = vpriority.rawValue if let dc = downloadProgressCallback { afRequest.downloadProgress(queue: downloadProgressQueue ?? DispatchQueue.main, closure: dc) } let resultRequest = Network.NormalRequest(builder: self, request: afRequest) resultRequest.maximumNumberOfRetryTimes = retryTimes return resultRequest } fileprivate func mutableRequest(_ URLString: String, method: AFMethod, headers: [String : String]?) -> URLRequest? { guard let URL = URL(string: URLString) else { return nil } var request = URLRequest(url: URL) request.httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { request.setValue(headerValue, forHTTPHeaderField: headerField) } } return request } } public class UploadBuilder: HTTPBuilder { private class Part { var name: String var fileName: String? var mimeType: String? init(name: String) { self.name = name } } internal var uploadProgressQueue: DispatchQueue? internal var uploadProgressCallback: ((Progress)->Void)? private class Data: Part { var data: Foundation.Data init(name: String, data: Foundation.Data) { self.data = data super.init(name: name) } } override init(url: String, manager: AFManager) { super.init(url: url, manager: manager) timeoutInterval = 180 } open func append(data: Foundation.Data, name: String, fileName: String? = nil, mimeType: String? = nil) -> Self { let part = Data(name: name, data: data) part.fileName = fileName part.mimeType = mimeType dataParts.append(part) return self } private class File: Part { var fileURL: URL init(name: String, fileURL: URL) { self.fileURL = fileURL super.init(name: name) } } open func append(file fileURL: URL, name: String, fileName: String, mimeType: String? = nil) -> Self { let part = File(name: name, fileURL: fileURL) part.fileName = fileName part.mimeType = mimeType fileParts.append(part) return self } @discardableResult open func uploadProgress(on queue: DispatchQueue = DispatchQueue.main, callback:((Progress)->Void)?) -> Self { uploadProgressQueue = queue uploadProgressCallback = callback return self } open override func build() -> Request? { if self.urlString.isEmpty { return nil } let request = Network.UploadRequest(builder: self) request.maximumNumberOfRetryTimes = retryTimes var absoluteString = append(queryParameters, to: self.urlString) if vappendCommonParameters { // 从CommonParams中删除 getParameters if let commonParameters = Network.client?.commonParameters { let restCommonParameters = commonParameters - queryParameters absoluteString = append(restCommonParameters, to: absoluteString) } } var headers = [String : String]() if let defaultHeaders = Network.client?.requestHeaders { headers += defaultHeaders } headers += vheaders var postParameters = self.postParameters Network.client?.willProcessRequestWithURL(&absoluteString, headers: &headers, parameters: &postParameters) let dataParts = self.dataParts let fileParts = self.fileParts let postParts = postParameters guard let url = URL(string: absoluteString) else { return nil } var urlRequest = URLRequest(url: url) for (headerField, headerValue) in headers { urlRequest.setValue(headerValue, forHTTPHeaderField: headerField) } urlRequest.httpMethod = "POST" Alamofire.upload(multipartFormData: { (multipartFormData) in postParts?.forEach({ k, v in if let data = ((v as? String) ?? "\(v)").data(using: .utf8) { multipartFormData.append(data, withName: k) } }) dataParts.forEach({self.append($0, to: multipartFormData)}) fileParts.forEach({self.append($0, to: multipartFormData)}) }, usingThreshold:UInt64(2_000_000), with: urlRequest) { (encodingResult) in switch encodingResult { case .success(let upload, _, _): upload.task?.priority = self.vpriority.rawValue self.requestTimestamp = NSDate().timeIntervalSince1970 if let pq = self.uploadProgressCallback { upload.uploadProgress(queue: self.uploadProgressQueue ?? DispatchQueue.main, closure: pq) } if let dc = self.downloadProgressCallback { upload.downloadProgress(queue: self.downloadProgressQueue ?? DispatchQueue.main, closure: dc) } request.request = upload request.startUploading() case .failure(let encodingError): request.notifyError(encodingError) } } request.maximumNumberOfRetryTimes = self.retryTimes return request } private func append(_ data: Data, to multipartFormData: Alamofire.MultipartFormData) { if let mimeType = data.mimeType { if let fileName = data.fileName { multipartFormData.append(data.data, withName: data.name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(data.data, withName: data.name, mimeType: mimeType) } } else { multipartFormData.append(data.data, withName: data.name) } } private func append(_ file: File, to multipartFormData: Alamofire.MultipartFormData) { if let mimeType = file.mimeType { if let fileName = file.fileName { multipartFormData.append(file.fileURL, withName: file.name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(file.fileURL, withName: file.name, fileName: "\(Date().timeIntervalSince1970)", mimeType: mimeType) } } else { multipartFormData.append(file.fileURL, withName: file.name) } } private var dataParts = [Data]() private var fileParts = [File]() } }
05c54150aa23177580dd72e9d3f7ee94
38.089552
168
0.547665
false
false
false
false
russbishop/Swift-Flow
refs/heads/master
SwiftFlowTests/TestFakes.swift
mit
1
// // Fakes.swift // SwiftFlow // // Created by Benji Encz on 12/24/15. // Copyright © 2015 Benjamin Encz. All rights reserved. // import Foundation @testable import SwiftFlow struct TestAppState: StateType { var testValue: Int? init() { testValue = nil } } struct TestStringAppState: StateType { var testValue: String? init() { testValue = nil } } struct SetValueAction: StandardActionConvertible { let value: Int static let type = "SetValueAction" init (_ value: Int) { self.value = value } init(_ standardAction: StandardAction) { self.value = standardAction.payload!["value"] as! Int } func toStandardAction() -> StandardAction { return StandardAction(type: SetValueAction.type, payload: ["value": value]) } } struct SetValueStringAction: StandardActionConvertible { var value: String static let type = "SetValueStringAction" init (_ value: String) { self.value = value } init(_ standardAction: StandardAction) { self.value = standardAction.payload!["value"] as! String } func toStandardAction() -> StandardAction { return StandardAction(type: SetValueStringAction.type, payload: ["value": value]) } } struct TestReducer: Reducer { func handleAction(var state: TestAppState, action: Action) -> TestAppState { switch action { case let action as SetValueAction: state.testValue = action.value return state default: return state } } } struct TestValueStringReducer: Reducer { func handleAction(var state: TestStringAppState, action: Action) -> TestStringAppState { switch action { case let action as SetValueStringAction: state.testValue = action.value return state default: return state } } } class TestStoreSubscriber<T>: StoreSubscriber { var receivedStates: [T] = [] func newState(state: T) { receivedStates.append(state) } }
c4efda643483f608a63335da6c8854be
20.666667
92
0.631731
false
true
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/JSONFormBuilderTextEditor.swift
apache-2.0
1
// // JSONFormBuilderTextEditor.swift // edX // // Created by Michael Katz on 10/1/15. // Copyright © 2015 edX. All rights reserved. // import Foundation class JSONFormBuilderTextEditorViewController: TDSwiftBaseViewController { let textView = OEXPlaceholderTextView() let handInBtn = UIButton.init(type: .Custom) var text: String { return textView.text } var doneEditing: ((value: String)->())? init(text: String?, placeholder: String?) { super.init(nibName: nil, bundle: nil) self.view = UIView() self.view.backgroundColor = UIColor.whiteColor() textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets textView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes // textView.placeholder = "请输入昵称" textView.placeholderTextColor = OEXStyles.sharedStyles().neutralBase() textView.textColor = OEXStyles.sharedStyles().neutralBlackT() textView.font = UIFont.init(name: "OpenSans", size: 16) textView.backgroundColor = UIColor.whiteColor() textView.layer.cornerRadius = 4.0 textView.layer.borderColor = UIColor.init(RGBHex: 0xccd1d9, alpha: 1).CGColor textView.layer.borderWidth = 0.5; textView.delegate = self textView.text = text ?? "" if let placeholder = placeholder { textView.placeholder = placeholder } handInBtn.setTitle(Strings.submit, forState: .Normal) handInBtn.addTarget(self, action: #selector(JSONFormBuilderTextEditorViewController.handinButtonAction), forControlEvents: .TouchUpInside) handInBtn.backgroundColor = OEXStyles.sharedStyles().baseColor1() handInBtn.layer.cornerRadius = 4.0 setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) OEXAnalytics.sharedAnalytics().trackScreenWithName(OEXAnalyticsScreenEditTextFormValue) } private func setupViews() { view.addSubview(textView) textView.snp_makeConstraints { (make) -> Void in make.top.equalTo(view.snp_topMargin).offset(18) make.leading.equalTo(view.snp_leadingMargin) make.trailing.equalTo(view.snp_trailingMargin) make.height.equalTo(41) } view.addSubview(handInBtn) handInBtn.snp_makeConstraints { (make) in make.top.equalTo(view.snp_topMargin).offset(77) make.leading.equalTo(view.snp_leadingMargin) make.trailing.equalTo(view.snp_trailingMargin) make.height.equalTo(41) } } func handinButtonAction() { self.textView.resignFirstResponder() if textView.text.characters.count == 0 { //昵称不能为空 let alertView = UIAlertView.init(title: Strings.reminder, message: Strings.nicknameNull, delegate: self, cancelButtonTitle: Strings.ok) alertView.show() } else if textView.text.characters.count <= 6 { let baseTool = TDBaseToolModel.init() baseTool.checkNickname(textView.text, view: self.view) baseTool.checkNickNameHandle = {(AnyObject) -> () in if AnyObject == true { self.doneEditing?(value: self.textView.text) //block 反向传值 let dic : NSDictionary = ["nickName" : self.textView.text] NSNotificationCenter.defaultCenter().postNotificationName("NiNameNotification_Change", object:dic) self.navigationController?.popViewControllerAnimated(true) } } } else { //不能超过六个字 let alertView = UIAlertView.init(title: Strings.reminder, message: Strings.nicknameNumber, delegate: self, cancelButtonTitle: Strings.ok) alertView.show() } } // override func willMoveToParentViewController(parent: UIViewController?) { // if parent == nil { //removing from the hierarchy // doneEditing?(value: textView.text) // } // } } extension JSONFormBuilderTextEditorViewController : UITextViewDelegate { func textViewShouldEndEditing(textView: UITextView) -> Bool { textView.resignFirstResponder() return true } }
a580fb9b05db4b5a668201354629c64d
37.813559
149
0.637773
false
false
false
false
LiuDeng/LazyCocoa
refs/heads/master
Source/LazyCocoa-MacApp/Core/NewScanningMechanism.swift
mit
2
// // NewScanningMechanism.swift // The Lazy Cocoa Project // // Copyright (c) 2015 Yichi Zhang. All rights reserved. // // 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 class ConfigurationModel: Printable { var key = "" var value = "" init(key:String, value:String) { self.key = key self.value = value } var description:String { return "\n<Configuration: Key = \(key), Value = \(value)>" } } class StatementModel: Printable { var added = false var index:Int = -1 var identifiers:[String] = [] // Strings within double quotation marks; "strings that contains white spaces" var names:[String] = [] var colorCodes:[String] = [] var numbers:[String] = [] func copy() -> StatementModel { let s = StatementModel() s.index = self.index s.identifiers = self.identifiers s.names = self.names s.colorCodes = self.colorCodes s.numbers = self.numbers return s } var isEmpty:Bool { if identifiers.count + names.count + colorCodes.count + numbers.count > 0 { return false } else { return true } } var description:String { let arrayToString = { (array:[String]) -> String in if array.isEmpty { return "NONE" } else { return "(" + join(", ", array) + ")" } } return "\n<Statement #\(index): IDS = \(arrayToString(identifiers)), names = \(arrayToString(names)), colorCodes = \(arrayToString(colorCodes)), numbers = \(arrayToString(numbers))>" } func add(#statementItem:String) { if statementItem.isValidNumber { numbers.append(statementItem) } else if statementItem.isValidColorCode { colorCodes.append(statementItem) } else { identifiers.append(statementItem) } } func addAsName(#statementItem:String) { names.append(statementItem) } } class SourceCodeScanner { // statementArray contains StatementModel, ConfigurationModel and String objects var statementArray = [AnyObject]() var statementCounter = 0 var currentStatementModel:StatementModel! private func addProcessMode(processMode:String) { statementArray.append(processMode) } private func createNewStatementModel() { currentStatementModel = StatementModel() } private func addCurrentStatementModel() { if !currentStatementModel.added && !currentStatementModel.isEmpty { statementArray.append(currentStatementModel) currentStatementModel.index = statementCounter++ currentStatementModel.added == true } } private func add(#statementItem:String) { currentStatementModel.add(statementItem: statementItem) } private func addAsName(#statementItem:String) { currentStatementModel.addAsName(statementItem: statementItem) } private func addParameter(#parameterKey:String, parameterValue:String) { statementArray.append(ConfigurationModel(key: parameterKey, value: parameterValue)) } func processSourceString(string:String) { statementArray.removeAll(keepCapacity: true) statementCounter = 0 currentStatementModel = StatementModel() let scanner = NSScanner(string: string) let whitespaceAndNewline = NSCharacterSet.whitespaceAndNewlineCharacterSet() let whitespace = NSCharacterSet.whitespaceCharacterSet() let newline = NSCharacterSet.newlineCharacterSet() let whitespaceNewlineAndSemicolon = whitespaceAndNewline.mutableCopy() as! NSMutableCharacterSet whitespaceNewlineAndSemicolon.addCharactersInString(";") let newlineAndSemicolon = newline.mutableCopy() as! NSMutableCharacterSet newlineAndSemicolon.addCharactersInString(";") var resultString:NSString? while scanner.scanLocation < count(scanner.string) { let currentChar = scanner.string.characterAtIndex(scanner.scanLocation) let twoCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 2) let threeCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 3) if threeCharString == "!!!" { //This is the string after !!!, before any white space or new line characters. scanner.scanLocation += threeCharString.length scanner.scanUpToCharactersFromSet(whitespaceAndNewline, intoString: &resultString) if let resultString = resultString { addProcessMode(resultString as String) } } else if twoCharString == StringConst.SigleLineComment { scanner.scanLocation += twoCharString.length scanner.scanUpToCharactersFromSet(newline, intoString: &resultString) } else if twoCharString == StringConst.MultiLineCommentStart { scanner.scanLocation += twoCharString.length scanner.scanUpToString(StringConst.MultiLineCommentEnd, intoString: &resultString) scanner.scanLocation += StringConst.MultiLineCommentEnd.length } else if twoCharString == "!!" { //This is a parameter scanner.scanLocation += twoCharString.length scanner.scanUpToCharactersFromSet(whitespace, intoString: &resultString) let parameterKey = resultString scanner.scanUpToCharactersFromSet(newline, intoString: &resultString) let parameterValue = resultString if parameterKey != nil && parameterValue != nil { let processedParameterValue = (parameterValue as! String).stringByRemovingSingleLineComment() self.addParameter(parameterKey: parameterKey as! String, parameterValue: processedParameterValue) } } else { if currentChar == Character(StringConst.DoubleQuote) { scanner.scanLocation++ scanner.scanUpToString(StringConst.DoubleQuote, intoString: &resultString) scanner.scanLocation += StringConst.DoubleQuote.length addAsName(statementItem: resultString as! String) } else { scanner.scanUpToCharactersFromSet(whitespaceNewlineAndSemicolon, intoString: &resultString) add(statementItem: resultString as! String) } } var oneCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 1) if oneCharString.containsCharactersInSet(newlineAndSemicolon) { addCurrentStatementModel() createNewStatementModel() } while scanner.scanLocation < count(scanner.string) && oneCharString.containsCharactersInSet(whitespaceNewlineAndSemicolon) { scanner.scanLocation++ oneCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 1) } } addCurrentStatementModel() // println("--\n\n\n--") // println(self.statementArray) } }
aba87191247ca093889caa1722ee54f2
30.315126
184
0.73497
false
false
false
false
3vts/OnTheMap
refs/heads/master
OnTheMap/Student.swift
mit
1
// // Student.swift // OnTheMap // // Created by Alvaro Santiesteban on 6/16/17. // Copyright © 2017 3vts. All rights reserved. // import Foundation struct Student { let createdAt: Date let firstName: String let lastName: String let latitude: Double let longitude: Double let mapString: String let mediaURL: String let objectId: String let uniqueKey: String let updatedAt: Date init(dictionary: [String:AnyObject]) { let isoFormatter = ISO8601DateFormatter() createdAt = isoFormatter.date(from: dictionary[UdacityClient.JSONResponseKeys.createdAt] as! String) ?? Date(timeIntervalSince1970: 0) firstName = dictionary[UdacityClient.JSONResponseKeys.firstName] as? String ?? "" lastName = dictionary[UdacityClient.JSONResponseKeys.lastName] as? String ?? "" latitude = dictionary[UdacityClient.JSONResponseKeys.latitude] as? Double ?? 0 longitude = dictionary[UdacityClient.JSONResponseKeys.longitude] as? Double ?? 0 mapString = dictionary[UdacityClient.JSONResponseKeys.mapString] as? String ?? "" mediaURL = dictionary[UdacityClient.JSONResponseKeys.mediaURL] as? String ?? "" objectId = dictionary[UdacityClient.JSONResponseKeys.objectId] as? String ?? "" uniqueKey = dictionary[UdacityClient.JSONResponseKeys.uniqueKey] as? String ?? "" updatedAt = isoFormatter.date(from: dictionary[UdacityClient.JSONResponseKeys.updatedAt] as! String) ?? Date(timeIntervalSince1970: 0) } static func studentsFromResults(_ results: [[String:AnyObject]]) -> [Student] { var students = [Student]() for result in results { students.append(Student(dictionary: result)) } return students } } extension Student: Equatable {} func ==(lhs: Student, rhs: Student) -> Bool { return lhs.uniqueKey == rhs.uniqueKey }
ccc1cd94d0926590eddb49b1b08851e3
33.446429
142
0.682737
false
false
false
false
askari01/DailySwift
refs/heads/master
oddOccurenceInArray.swift
mit
1
// pair same occurence in array and point the odd var count = 0 var odd = 0 public func solution(_ A : [Int]) -> Int{ odd = A[0] if (A.count == 1){ return A[0] } for i in 1...((A.count)-1){ odd = odd ^ A[i] } return odd } var a = [-1] count = solution(a) print(count)
27ca54053299f94c6bb3f89b26fd6f10
13.714286
49
0.521036
false
false
false
false
coderQuanjun/PigTV
refs/heads/master
GYJTV/GYJTV/Classes/Live/Model/GiftAnimationModel.swift
mit
1
// // GiftAnimationModel.swift // GYJTV // // Created by zcm_iOS on 2017/6/8. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class GiftAnimationModel: NSObject { var senderName : String = "" //送礼物者 var senderUrl : String = "" // var giftName : String = "" //礼物名称 var giftUrl : String = "" init(senderName : String, senderUrl : String, giftName : String, giftUrl : String) { self.senderName = senderName self.senderUrl = senderUrl self.giftName = giftName self.giftUrl = giftUrl } override func isEqual(_ object: Any?) -> Bool { guard let obj = object as? GiftAnimationModel else { return false } guard obj.senderName == senderName && obj.giftName == giftName else { return false } return true } }
ea6b1c11ad83d1dd4fa12b35fef61ed3
23.742857
88
0.590069
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/CollectionViewPagingLayout/Lib/Snapshot/SnapshotTransformView.swift
mit
1
// // SnapshotTransformView.swift // CollectionViewPagingLayout // // Created by Amir on 07/03/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit public protocol SnapshotTransformView: TransformableView { /// Options for controlling the effects, see `SnapshotTransformViewOptions.swift` var snapshotOptions: SnapshotTransformViewOptions { get } /// The view to apply the effect on var targetView: UIView { get } /// A unique identifier for the snapshot, a new snapshot won't be made if /// there is a cashed snapshot with the same identifier var snapshotIdentifier: String { get } /// the function for getting the cached snapshot or make a new one and cache it func getSnapshot() -> SnapshotContainerView? /// the main function for applying transforms on the snapshot func applySnapshotTransform(snapshot: SnapshotContainerView, progress: CGFloat) /// Check if the snapshot can be reused func canReuse(snapshot: SnapshotContainerView) -> Bool } public extension SnapshotTransformView where Self: UICollectionViewCell { /// Default `targetView` for `UICollectionViewCell` is the first subview of /// `contentView` or the content view itself in case of no subviews var targetView: UIView { contentView.subviews.first ?? contentView } /// Default `identifier` for `UICollectionViewCell` is it's index /// if you have the same content with different indexes (like an infinite list) /// you should override this and provide a content-based identifier var snapshotIdentifier: String { var collectionView: UICollectionView? var superview = self.superview while superview != nil { if let view = superview as? UICollectionView { collectionView = view break } superview = superview?.superview } var identifier = "\(collectionView?.indexPath(for: self) ?? IndexPath())" if let scrollView = targetView as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } if let scrollView = targetView.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } return identifier } /// Default implementation only compares the size of snapshot with the view func canReuse(snapshot: SnapshotContainerView) -> Bool { snapshot.snapshotSize == targetView.bounds.size } } public extension SnapshotTransformView { // MARK: Properties var snapshotOptions: SnapshotTransformViewOptions { .init() } // MARK: TransformableView func transform(progress: CGFloat) { guard let snapshot = getSnapshot() else { return } applySnapshotTransform(snapshot: snapshot, progress: progress) } // MARK: Public functions func getSnapshot() -> SnapshotContainerView? { findSnapshot() ?? makeSnapshot() } func applySnapshotTransform(snapshot: SnapshotContainerView, progress: CGFloat) { if progress == 0 { targetView.transform = .identity snapshot.alpha = 0 } else { snapshot.alpha = 1 // hide the original view, we apply transform on the snapshot targetView.transform = CGAffineTransform.identity.translatedBy(x: 0, y: -2 * UIScreen.main.bounds.height) } snapshot.transform(progress: progress, options: snapshotOptions) } // MARK: Private functions private func hideOtherSnapshots() { targetView.superview?.subviews.filter { $0 is SnapshotContainerView }.forEach { guard let snapshot = $0 as? SnapshotContainerView else { return } if snapshot.identifier != snapshotIdentifier { snapshot.alpha = 0 } } } private func findSnapshot() -> SnapshotContainerView? { hideOtherSnapshots() let snapshot = targetView.superview?.subviews.first { ($0 as? SnapshotContainerView)?.identifier == snapshotIdentifier } as? SnapshotContainerView if let snapshot = snapshot, snapshot.pieceSizeRatio != snapshotOptions.pieceSizeRatio { snapshot.removeFromSuperview() return nil } if let snapshot = snapshot, !canReuse(snapshot: snapshot) { snapshot.removeFromSuperview() return nil } snapshot?.alpha = 1 return snapshot } private func makeSnapshot() -> SnapshotContainerView? { targetView.superview?.subviews.first { ($0 as? SnapshotContainerView)?.identifier == snapshotIdentifier }? .removeFromSuperview() guard let view = SnapshotContainerView(targetView: targetView, pieceSizeRatio: snapshotOptions.pieceSizeRatio, identifier: snapshotIdentifier) else { return nil } targetView.superview?.insertSubview(view, aboveSubview: targetView) targetView.equalSize(to: view) targetView.center(to: view) return view } } private extension SnapshotContainerView { func transform(progress: CGFloat, options: SnapshotTransformViewOptions) { let scale = max(1 - abs(progress) * options.containerScaleRatio, 0) var translateX = progress * frame.width * options.containerTranslationRatio.x var translateY = progress * frame.height * options.containerTranslationRatio.y if let min = options.containerMinTranslationRatio { translateX = max(translateX, frame.width * min.x) translateY = max(translateX, frame.width * min.y) } if let max = options.containerMaxTranslationRatio { translateX = min(translateX, frame.width * max.x) translateY = min(translateY, frame.height * max.y) } transform = CGAffineTransform.identity .translatedBy(x: translateX, y: translateY) .scaledBy(x: scale, y: scale) var sizeRatioRow = options.pieceSizeRatio.height if abs(sizeRatioRow) < 0.01 { sizeRatioRow = 0.01 } var sizeRatioColumn = options.pieceSizeRatio.width if abs(sizeRatioColumn) < 0.01 { sizeRatioColumn = 0.01 } let rowCount = Int(1.0 / sizeRatioRow) let columnCount = Int(1.0 / sizeRatioColumn) snapshots.enumerated().forEach { index, view in let position = SnapshotTransformViewOptions.PiecePosition( index: index, row: Int(index / columnCount), column: Int(index % columnCount), rowCount: rowCount, columnCount: columnCount ) let pieceScale = abs(progress) * options.piecesScaleRatio.getRatio(position: position) let pieceTransform = options.piecesTranslationRatio.getRatio(position: position) * abs(progress) let minPieceTransform = options.minPiecesTranslationRatio?.getRatio(position: position) let maxPieceTransform = options.maxPiecesTranslationRatio?.getRatio(position: position) var translateX = pieceTransform.x * view.frame.width var translateY = pieceTransform.y * view.frame.height if let min = minPieceTransform { translateX = max(translateX, view.frame.width * min.x) translateY = max(translateY, view.frame.height * min.y) } if let max = maxPieceTransform { translateX = min(translateX, view.frame.width * max.x) translateY = min(translateY, view.frame.height * max.y) } view.transform = CGAffineTransform.identity .translatedBy(x: translateX, y: translateY) .scaledBy(x: max(0, 1 - pieceScale.width), y: max(0, 1 - pieceScale.height)) view.alpha = 1 - options.piecesAlphaRatio.getRatio(position: position) * abs(progress) view.layer.cornerRadius = options.piecesCornerRadiusRatio.getRatio(position: position) * abs(progress) * min(view.frame.height, view.frame.width) view.layer.masksToBounds = true } } }
823d71998c39897181e9c86bd983523b
36.946667
157
0.627079
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/LowEnergyEvent.swift
mit
1
// // LowEnergyEvent.swift // Bluetooth // // Created by Alsey Coleman Miller on 3/2/16. // Copyright © 2016 PureSwift. All rights reserved. // /// Bluetooth Low Energy HCI Events @frozen public enum LowEnergyEvent: UInt8, HCIEvent { /// LE Connection Complete case connectionComplete = 0x01 /// LE Advertising Report case advertisingReport = 0x02 /// LE Connection Update Complete case connectionUpdateComplete = 0x03 /// LE Read Remote Used Features Complete case readRemoteUsedFeaturesComplete = 0x04 /// LE Long Term Key Request case longTermKeyRequest = 0x05 /// LE Remote Connection Parameter Request Event case remoteConnectionParameterRequest = 0x06 /// LE Data Length Change Event case dataLengthChange = 0x07 /// LE Read Local P-256 Public Key Complete Event case readLocalP256PublicKeyComplete = 0x08 /// LE Generate DHKey Complete Event case generateDHKeyComplete = 0x09 /// LE Enhanced Connection Complete Event case enhancedConnectionComplete = 0x0A /// LE Directed Advertising Report Event case directedAdvertisingReport = 0x0B /// LE PHY Update Complete Event case phyUpdateComplete = 0x0C /// LE Extended Advertising Report Event case extendedAdvertisingReport = 0x0D /// LE Periodic Advertising Sync Established Event case periodicAdvertisingSyncEstablished = 0x0E /// LE Periodic Advertising Report Event case periodicAdvertisingReport = 0x0F /// LE Periodic Advertising Sync Lost Event case periodicAdvertisingSyncLost = 0x10 /// LE Scan Timeout Event case scanTimeout = 0x11 /// LE Advertising Set Terminated Event case advertisingSetTerminated = 0x12 /// LE Scan Request Received Event case scanRequestReceived = 0x13 /// LE Channel Selection Algorithm Event case channelSelectionAlgorithm = 0x14 } // MARK: - Name public extension LowEnergyEvent { var name: String { switch self { case .connectionComplete: return "LE Connection Complete" case .advertisingReport: return "LE Advertising Report" case .connectionUpdateComplete: return "LE Connection Update Complete" case .readRemoteUsedFeaturesComplete: return "LE Read Remote Used Features Complete" case .longTermKeyRequest: return "LE Long Term Key Request" case .remoteConnectionParameterRequest: return "LE Remote Connection Parameter Request Event" case .dataLengthChange: return "LE Data Length Change Event" case .readLocalP256PublicKeyComplete: return "LE Read Local P-256 Public Key Complete Event" case .generateDHKeyComplete: return "LE Generate DHKey Complete Event" case .enhancedConnectionComplete: return "LE Enhanced Connection Complete" case .directedAdvertisingReport: return "LE Directed Advertising Report Event" case .phyUpdateComplete: return "LE PHY Update Complete" case .extendedAdvertisingReport: return "LE Extended Advertising Report Event" case .periodicAdvertisingSyncEstablished: return "LE Periodic Advertising Sync Established Event" case .periodicAdvertisingReport: return "LE Periodic Advertising Report Event" case .periodicAdvertisingSyncLost: return "LE Periodic Advertising Sync Lost Event" case .scanTimeout: return "LE Scan Timeout Event" case .advertisingSetTerminated: return "LE Advertising Set Terminated Event" case .scanRequestReceived: return "LE Scan Request Received Event" case .channelSelectionAlgorithm: return "LE Channel Selection Algorithm Event" } } }
29cd2997a53d6340bce72d8df51fc982
37.485437
105
0.672553
false
false
false
false
belkhadir/Beloved
refs/heads/master
Beloved/FriendSearchViewController.swift
mit
1
// // FriendSearchViewController.swift // Beloved // // Created by Anas Belkhadir on 21/01/2016. // Copyright © 2016 Anas Belkhadir. All rights reserved. // import UIKit import CoreData class FriendSearchViewController: UITableViewController{ @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let searchController = UISearchController(searchResultsController: nil) var friendUsers = [Friend]() var currentUser: CurrentUserConnected? //it's make easy to know fetchAllFriendFromFirebase function start getting data from the server var startGettingFriendFromFirebase: Bool = false { didSet { if startGettingFriendFromFirebase { activityIndicator.startAnimating() activityIndicator.hidden = false }else{ activityIndicator.stopAnimating() activityIndicator.hidden = true } } } override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() navigationController?.navigationBar.topItem?.title = "Logout" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: "logOut:") tableView.tableHeaderView = searchController.searchBar searchController.searchBar.delegate = self friendUsers = fetchedAllFriend() //if ther's no friend saved in CoreData look at his friend on the server if friendUsers.count == 0 { fetchAllFriendFromFirebase() } } //fetch all friend from the server func fetchAllFriendFromFirebase() { //Mark- start getting data from server startGettingFriendFromFirebase = true FirebaseHelper.sharedInstance().getAllCurrentUserFirends({ userIdKey in for element in self.friendUsers { if element.uid == userIdKey! { self.startGettingFriendFromFirebase = false return } } FirebaseHelper.sharedInstance().getSingleUser(userIdKey!, completionHandler: { (error, userFriend) in guard error == nil else{ self.startGettingFriendFromFirebase = false self.showAlert(.custom("erro occur", error!)) return } //The user friend was picked from the server //we need to make a new Friend. To be easy to save in CoreData //The easiest way to do that is to make a dictionary. let dictionary: [String : AnyObject] = [ Friend.Keys.username: userFriend!.userName!, Friend.Keys.uid: userIdKey!, ] // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue(), { //Init - Friend user let friendToBeAdd = Friend(parameter: dictionary, context: self.sharedContext) friendToBeAdd.currentUser = CurrentUser.sharedInstance().currentUserConnected! self.friendUsers.append(friendToBeAdd) self.tableView.reloadData() self.startGettingFriendFromFirebase = false //Save in the context CoreDataStackManager.sharedInstance().saveContext() }) }) }) startGettingFriendFromFirebase = false //Mark- finishing getting data from server } var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext } //fetch all friend from the CoreData func fetchedAllFriend() -> [Friend] { let fetchedRequest = NSFetchRequest(entityName: "Friend") let predicate = NSPredicate(format: "currentUser = %@", CurrentUser.sharedInstance().currentUserConnected!) fetchedRequest.predicate = predicate do { return try sharedContext.executeFetchRequest(fetchedRequest) as! [Friend] }catch _ { return [Friend]() } } func logOut() { FirebaseHelper.sharedInstance().messageRef.removeAllObservers() FirebaseHelper.sharedInstance().userRef.removeAllObservers() FirebaseHelper.sharedInstance().ref.unauth() //using presentViewController instead of pushViewController because: //when the first time user singUp and try to logout it's showing the //previews task . let nvg = storyboard?.instantiateViewControllerWithIdentifier("singInViewController") as! SingInViewController navigationController?.presentViewController(nvg, animated: true, completion: nil) } // MARK: - Table View override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friendUsers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! FriendSearchTableViewCell cell.user = friendUsers[indexPath.row] cell.delegate = self return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedUser = friendUsers[indexPath.row] let listOfMessageVC = self.storyboard?.instantiateViewControllerWithIdentifier("StartchattingViewController") as! StartChattingViewController listOfMessageVC.friend = selectedUser listOfMessageVC.senderId = CurrentUser.sharedInstance().user?.userName dispatch_async(dispatch_get_main_queue(), { self.navigationController?.pushViewController(listOfMessageVC, animated: true) }) } } extension FriendSearchViewController: FriendSearchTableViewCellDelegate { func cell(cell: FriendSearchTableViewCell, didSelectFriendUser user: Friend) { FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: true, willBecomeFriend: { (_,_) in }) } func cell(cell: FriendSearchTableViewCell, didSelectUnFriendUser user: Friend){ FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: false, willBecomeFriend:{ _,_ in }) } } extension FriendSearchViewController: UISearchBarDelegate{ func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !isConnectedToNetwork() { showAlert(.connectivity) return } activityIndicator.startAnimating() activityIndicator.hidden = false let lowercaseSearchBarText = searchBar.text?.lowercaseString // Check to see if we already have this friend . If so , return if let _ = friendUsers.indexOf({$0.username == lowercaseSearchBarText}) { return } FirebaseHelper.sharedInstance().searchByUserName(lowercaseSearchBarText!, didPickUser: { (exist, user) in if exist { // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue()) { //init the friend user let userFriend = Friend(parameter: user!, context: self.sharedContext) //Mark - relation userFriend.currentUser = CurrentUser.sharedInstance().currentUserConnected! // append friendUser to array self.friendUsers.insert(userFriend, atIndex: 0) self.tableView.reloadData() // Save the context. do { try self.sharedContext.save() } catch _ {} } } self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() }) } }
e23819d53639c9d0d8145cd8254cff57
30.773723
149
0.583735
false
false
false
false
MaddTheSane/WWDC
refs/heads/master
WWDC/VideoStore.swift
bsd-2-clause
1
// // VideoDownloader.swift // WWDC // // Created by Guilherme Rambo on 22/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa public let VideoStoreDownloadedFilesChangedNotification = "VideoStoreDownloadedFilesChangedNotification" public let VideoStoreNotificationDownloadStarted = "VideoStoreNotificationDownloadStarted" public let VideoStoreNotificationDownloadCancelled = "VideoStoreNotificationDownloadCancelled" public let VideoStoreNotificationDownloadPaused = "VideoStoreNotificationDownloadPaused" public let VideoStoreNotificationDownloadResumed = "VideoStoreNotificationDownloadResumed" public let VideoStoreNotificationDownloadFinished = "VideoStoreNotificationDownloadFinished" public let VideoStoreNotificationDownloadProgressChanged = "VideoStoreNotificationDownloadProgressChanged" private let _SharedVideoStore = VideoStore() private let _BackgroundSessionIdentifier = "WWDC Video Downloader" class VideoStore : NSObject, NSURLSessionDownloadDelegate { private let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(_BackgroundSessionIdentifier) private var backgroundSession: NSURLSession! private var downloadTasks: [String : NSURLSessionDownloadTask] = [:] private let defaults = NSUserDefaults.standardUserDefaults() class func SharedStore() -> VideoStore { return _SharedVideoStore; } override init() { super.init() backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) } func initialize() { backgroundSession.getTasksWithCompletionHandler { _, _, pendingTasks in for task in pendingTasks { if let key = task.originalRequest?.URL!.absoluteString { self.downloadTasks[key] = task } } } NSNotificationCenter.defaultCenter().addObserverForName(LocalVideoStoragePathPreferenceChangedNotification, object: nil, queue: nil) { _ in self.monitorDownloadsFolder() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil) } monitorDownloadsFolder() } // MARK: Public interface func allTasks() -> [NSURLSessionDownloadTask] { return Array(self.downloadTasks.values) } func download(url: String) { if isDownloading(url) || hasVideo(url) { return } let task = backgroundSession.downloadTaskWithURL(NSURL(string: url)!) if let key = task.originalRequest?.URL!.absoluteString { self.downloadTasks[key] = task } task.resume() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadStarted, object: url) } func pauseDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.suspend() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadPaused, object: url) return true } print("VideoStore was asked to pause downloading URL \(url), but there's no task for that URL") return false } func resumeDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.resume() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadResumed, object: url) return true } print("VideoStore was asked to resume downloading URL \(url), but there's no task for that URL") return false } func cancelDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.cancel() self.downloadTasks.removeValueForKey(url) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadCancelled, object: url) return true } print("VideoStore was asked to cancel downloading URL \(url), but there's no task for that URL") return false } func isDownloading(url: String) -> Bool { let downloading = downloadTasks.keys.filter { taskURL in return url == taskURL } return (downloading.count > 0) } func localVideoPath(remoteURL: String) -> String { return (Preferences.SharedPreferences().localVideoStoragePath as NSString).stringByAppendingPathComponent((remoteURL as NSString).lastPathComponent) } func localVideoAbsoluteURLString(remoteURL: String) -> String { return NSURL(fileURLWithPath: localVideoPath(remoteURL)).absoluteString } func hasVideo(url: String) -> Bool { return (NSFileManager.defaultManager().fileExistsAtPath(localVideoPath(url))) } // MARK: URL Session func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { let originalURL = downloadTask.originalRequest!.URL! let originalAbsoluteURLString = originalURL.absoluteString let fileManager = NSFileManager.defaultManager() if (fileManager.fileExistsAtPath(Preferences.SharedPreferences().localVideoStoragePath) == false) { do { try fileManager.createDirectoryAtPath(Preferences.SharedPreferences().localVideoStoragePath, withIntermediateDirectories: false, attributes: nil) } catch _ { } } let localURL = NSURL(fileURLWithPath: localVideoPath(originalAbsoluteURLString)) do { try fileManager.moveItemAtURL(location, toURL: localURL) WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithURL(originalAbsoluteURLString, downloaded: true) } catch _ { print("VideoStore was unable to move \(location) to \(localURL)") } downloadTasks.removeValueForKey(originalAbsoluteURLString) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadFinished, object: originalAbsoluteURLString) } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let originalURL = downloadTask.originalRequest!.URL!.absoluteString let info = ["totalBytesWritten": Int(totalBytesWritten), "totalBytesExpectedToWrite": Int(totalBytesExpectedToWrite)] NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadProgressChanged, object: originalURL, userInfo: info) } // MARK: File observation private var folderMonitor: DTFolderMonitor! private var existingVideoFiles = [String]() func monitorDownloadsFolder() { if folderMonitor != nil { folderMonitor.stopMonitoring() folderMonitor = nil } let videosPath = Preferences.SharedPreferences().localVideoStoragePath enumerateVideoFiles(videosPath) folderMonitor = DTFolderMonitor(forURL: NSURL(fileURLWithPath: videosPath)) { self.enumerateVideoFiles(videosPath) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil) } folderMonitor.startMonitoring() } /// Updates the downloaded status for the sessions on the database based on the existence of the downloaded video file private func enumerateVideoFiles(path: String) { guard let enumerator = NSFileManager.defaultManager().enumeratorAtPath(path) else { return } guard let files = enumerator.allObjects as? [String] else { return } // existing/added files for file in files { WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: true) } if existingVideoFiles.count == 0 { existingVideoFiles = files return } // removed files let removedFiles = existingVideoFiles.filter { !files.contains($0) } for file in removedFiles { WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: false) } } // MARK: Teardown deinit { if folderMonitor != nil { folderMonitor.stopMonitoring() } } }
69121b048f9444482286c16070db37af
38.231481
178
0.705688
false
false
false
false
krevi27/TestExerciseProject
refs/heads/master
TestStudyExerciseTests/CotacaoTests.swift
mit
1
// // CotacaoTests.swift // TestStudyExerciseTests // // Created by Marcos Fellipe Costa Silva on 19/10/17. // Copyright © 2017 Victor Oliveira Kreniski. All rights reserved. // import XCTest class CotacaoTests: XCTestCase { func testGetDolar(){ var retorno = "" let expect = XCTestExpectation(description: "Teste de integração") let url = URL(string: "http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json") URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in expect.fulfill() guard let data = data, error == nil else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any] let dados = json["valores"] as! [String: Any] let moeda = dados["USD"] as! [String: Any] let valor = moeda["valor"] retorno = valor! as! String print(retorno) XCTAssert(!retorno.isEmpty, "") } catch let error as NSError { print(error) } }).resume() self.wait(for: [expect], timeout: 6) } }
f7d4277c8b296670ade6af7539af81a0
33.444444
114
0.568548
false
true
false
false
MobileToolkit/UIKitExtensions
refs/heads/master
Sources/UIColor+HexColor.swift
mit
1
// // UIColor+HexColor.swift // UIKitExtensions // // Created by Sebastian Owodzin on 04/08/2016. // Copyright © 2016 mobiletoolkit.org. All rights reserved. // import UIKit extension UIColor { public convenience init(rgba: UInt32) { let red = CGFloat((rgba & 0xFF000000) >> 24)/255 let green = CGFloat((rgba & 0xFF0000) >> 16)/255 let blue = CGFloat((rgba & 0xFF00) >> 8)/255 let alpha = CGFloat(rgba & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(argb: UInt32) { let alpha = CGFloat((argb & 0xFF000000) >> 24)/255 let red = CGFloat((argb & 0xFF0000) >> 16)/255 let green = CGFloat((argb & 0xFF00) >> 8)/255 let blue = CGFloat(argb & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(rgb: UInt32) { let red = CGFloat((rgb & 0xFF0000) >> 16)/255 let green = CGFloat((rgb & 0xFF00) >> 8)/255 let blue = CGFloat(rgb & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: 1.0) } public convenience init(rgbaString: String) { let hexString = rgbaString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(rgba: color) } public convenience init(argbString: String) { let hexString = argbString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(argb: color) } public convenience init(rgbString: String) { let hexString = rgbString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(rgb: color) } }
692a0118a85b21f231c31cb4fd651b19
26.888889
83
0.602922
false
false
false
false
LeoNatan/LNPopupController
refs/heads/master
LNPopupControllerExample/LNPopupControllerExample/ManualLayoutCustomBarViewController.swift
mit
1
// // ManualLayoutCustomBarViewController.swift // LNPopupControllerExample // // Created by Leo Natan on 9/1/20. // Copyright © 2015-2021 Leo Natan. All rights reserved. // #if LNPOPUP class ManualLayoutCustomBarViewController: LNPopupCustomBarViewController { let centeredButton = UIButton(type: .system) let leftButton = UIButton(type: .system) let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial)) override func viewDidLoad() { super.viewDidLoad() backgroundView.layer.masksToBounds = true backgroundView.layer.cornerCurve = .continuous backgroundView.layer.cornerRadius = 15 view.addSubview(backgroundView) centeredButton.setTitle("Centered", for: .normal) centeredButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) centeredButton.sizeToFit() view.addSubview(centeredButton) leftButton.setTitle("<- Left", for: .normal) leftButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) leftButton.sizeToFit() view.addSubview(leftButton) preferredContentSize = CGSize(width: 0, height: 50) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() backgroundView.frame = view.bounds.insetBy(dx: view.layoutMargins.left, dy: 0) centeredButton.center = view.center leftButton.frame = CGRect(x: view.layoutMargins.left + 20, y: view.center.y - leftButton.bounds.size.height / 2, width: leftButton.bounds.size.width, height: leftButton.bounds.size.height) } override var wantsDefaultTapGestureRecognizer: Bool { return false } override var wantsDefaultPanGestureRecognizer: Bool { return false } override var wantsDefaultHighlightGestureRecognizer: Bool { return false } } #endif
0e32573791baa5aef931fedda2171bfa
30.214286
190
0.768879
false
false
false
false
xivol/MCS-V3-Mobile
refs/heads/master
examples/graphics/ViewAnimation.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
mit
1
// https://github.com/shu223/iOS-10-Sampler/blob/master/iOS-10-Sampler/Samples/PropertyAnimatorViewController.swift // // PropertyAnimatorViewController.swift // Created by Shuichi Tsutsumi on 9/10/16. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // import UIKit import PlaygroundSupport class PropertyAnimatorViewController: UIViewController { private var targetLocation: CGPoint! private var objectView: UIView! private let spring = true override func viewDidLoad() { super.viewDidLoad() objectView = UIView(frame: CGRect(origin: view.bounds.origin, size: CGSize(width: 50, height: 50))) objectView.backgroundColor = colorAt(location: objectView.center) view.addSubview(objectView) targetLocation = objectView.center } private func colorAt(location: CGPoint) -> UIColor { let hue: CGFloat = (location.x / UIScreen.main.bounds.width + location.y / UIScreen.main.bounds.height) / 2 return UIColor(hue: hue, saturation: 0.78, brightness: 0.75, alpha: 1) } private func processTouches(_ touches: Set<UITouch>) { guard let touch = touches.first else {return} let loc = touch.location(in: view) if loc == targetLocation { return } animateTo(location: loc) } private func animateTo(location: CGPoint) { var duration: TimeInterval var timing: UITimingCurveProvider if !spring { duration = 0.4 timing = UICubicTimingParameters(animationCurve: .easeOut) } else { duration = 0.6 timing = UISpringTimingParameters(dampingRatio: 0.5) } let animator = UIViewPropertyAnimator( duration: duration, timingParameters: timing) animator.addAnimations { self.objectView.center = location self.objectView.backgroundColor = self.colorAt(location: location) } animator.startAnimation() targetLocation = location } // ========================================================================= // MARK: - Touch handlers override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { processTouches(touches) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { processTouches(touches) } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = PropertyAnimatorViewController()
ccdcfde97a1e742b6407724e6d50bb38
32.448718
116
0.620161
false
false
false
false
instant-solutions/ISTimeline
refs/heads/master
ISTimeline/ISTimeline/ISPoint.swift
apache-2.0
1
// // ISPoint.swift // ISTimeline // // Created by Max Holzleitner on 13.05.16. // Copyright © 2016 instant:solutions. All rights reserved. // import UIKit open class ISPoint { open var title:String open var description:String? open var pointColor:UIColor open var lineColor:UIColor open var touchUpInside:Optional<(_ point:ISPoint) -> Void> open var fill:Bool public init(title:String, description:String, pointColor:UIColor, lineColor:UIColor, touchUpInside:Optional<(_ point:ISPoint) -> Void>, fill:Bool) { self.title = title self.description = description self.pointColor = pointColor self.lineColor = lineColor self.touchUpInside = touchUpInside self.fill = fill } public convenience init(title:String, description:String, touchUpInside:Optional<(_ point:ISPoint) -> Void>) { let defaultColor = UIColor.init(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0) self.init(title: title, description: description, pointColor: defaultColor, lineColor: defaultColor, touchUpInside: touchUpInside, fill: false) } public convenience init(title:String, touchUpInside:Optional<(_ point:ISPoint) -> Void>) { self.init(title: title, description: "", touchUpInside: touchUpInside) } public convenience init(title:String) { self.init(title: title, touchUpInside: nil) } }
50a11d44d90ab9fb387ad9b9eae37636
33.780488
152
0.677419
false
false
false
false
TTVS/NightOut
refs/heads/master
Clubber/AFNetworking Usage Lines.swift
apache-2.0
1
// SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: //Alamofire.request(.GET, url, parameters: parameters) // .responseJSON { (req, res, json, error) in // if(error != nil) { // NSLog("Error: \(error)") // println(req) // println(res) // } // else { // NSLog("Success: \(url)") // var json = JSON(json!) // } //} // COPY OF REQUEST (GET) //func makeSignInRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/" // let parameter = nil // // manager.requestSerializer = AFJSONRequestSerializer() // // manager.GET(url, // parameters: nil, // success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in // print("JSON: " + responseObject.description) // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RootPaperNavigationVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // let successMenu = UIAlertController(title: nil, message: "Successfully get from server", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Success") // }) // successMenu.addAction(okAction) // // self.presentViewController(successMenu, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in // print("Error: " + error.localizedDescription) // // // let errorMenu = UIAlertController(title: nil, message: "Failed to get from server.", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Cancelled") // }) // errorMenu.addAction(okAction) // // self.presentViewController(errorMenu, animated: true, completion: nil) // }) // // // // COPY OF RESPONSE (POST) //func makeSignUpRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/users?" // let signUpParams = [ // "user[email]" : "\(emailTextField.text!)", // "user[password]" : "\(passwordTextField.text!)", // "user[password_confirmation]" : "\(passwordConfirmationTextField.text!)", // "user[first_name]" : "\(firstNameTextField.text!)", // "user[last_name]" : "\(lastNameTextField.text!)", // "user[type]" : "Guest" // ] // // print("\(emailTextField.text)") // print("\(passwordTextField.text)") // print("\(passwordConfirmationTextField.text)") // print("\(firstNameTextField.text)") // print("\(lastNameTextField.text)") // // manager.responseSerializer = AFJSONResponseSerializer() // // manager.POST(url, // parameters: signUpParams, // success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in // print("Yes this was a success.. \(responseObject.description)") // // self.displayAlertMessage("Success", alertDescription: "Account has been created") // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("signInVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in // print("We got an error here.. \(error.localizedDescription)") // }) //} // // // // // //[self GET:@"weather.ashx" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didUpdateWithWeather:)]) { // [self.delegate weatherHTTPClient:self didUpdateWithWeather:responseObject]; // } //} failure:^(NSURLSessionDataTask *task, NSError *error) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didFailWithError:)]) { // [self.delegate weatherHTTPClient:self didFailWithError:error]; // } //}]; // ///////////////////////////// // //- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex //{ // if (buttonIndex == [actionSheet cancelButtonIndex]) { // // User pressed cancel -- abort // return; // } // // // 1 // NSURL *baseURL = [NSURL URLWithString:BaseURLString]; // NSDictionary *parameters = @{@"format": @"json"}; // // // 2 // AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL]; // manager.responseSerializer = [AFJSONResponseSerializer serializer]; // // // 3 //if (buttonIndex == 0) { // [manager GET:@"weather.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // self.weather = responseObject; // self.title = @"HTTP GET"; // [self.tableView reloadData]; // } failure:^(NSURLSessionDataTask *task, NSError *error) { // UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" // message:[error localizedDescription] // delegate:nil // cancelButtonTitle:@"Ok" // otherButtonTitles:nil]; // [alertView show]; // }]; //} // // // //
c11ac747a07e747d86e90100ce5b9f20
33.608434
148
0.604178
false
false
false
false
microtherion/Octarine
refs/heads/master
Octarine/OctTree.swift
bsd-2-clause
1
// // OctTree.swift // Octarine // // Created by Matthias Neeracher on 20/04/16. // Copyright © 2016 Matthias Neeracher. All rights reserved. // import AppKit let kOctPasteboardType = "OctPasteboardType" var gOctTreeRoots = [OctTreeNode]() class OctTreeNode : NSObject { var parent : OctTreeNode? let item : OctItem let path : NSIndexPath private init(parent: OctTreeNode?, index: Int) { self.parent = parent let parentItem = parent?.item ?? OctItem.rootFolder() self.item = parentItem.children![index] as! OctItem self.path = parent?.path.indexPathByAddingIndex(index) ?? NSIndexPath(index: index) super.init() } var isExpandable : Bool { return !item.isPart } var numberOfChildren : Int { return item.children?.count ?? 0 } var parentItem : OctItem { return parent?.item ?? OctItem.rootFolder() } var persistentIdentifier : String { return item.ident + "[" + parentItem.ident + "]" } class func numberOfRootItems() -> Int { if gOctTreeRoots.count == 0 { // Lazy initialization if let roots = OctItem.rootFolder().children { for index in 0..<roots.count { gOctTreeRoots.append(OctTreeNode(parent: nil, index: index)) } } } return gOctTreeRoots.count } class func rootItem(index: Int) -> OctTreeNode { return gOctTreeRoots[index] } var children = [OctTreeNode]() func child(index: Int) -> OctTreeNode { if children.count == 0 { // Lazy initialization for index in 0..<numberOfChildren { children.append(OctTreeNode(parent: self, index: index)) } } return children[index] } func isDescendantOf(node: OctTreeNode) -> Bool { if self == node { return true } else if path.length <= node.path.length { return false } else { return parent!.isDescendantOf(node) } } func isDescendantOfOneOf(nodes: [OctTreeNode]) -> Bool { for node in nodes { if isDescendantOf(node) { return true } } return false } func removeFromParent() { parentItem.mutableOrderedSetValueForKey("children").removeObject(item) } func deleteIfOrphaned() { if item.parents.count == 0 { item.managedObjectContext?.deleteObject(item) } } class func mapNode(node: OctTreeNode, f : (OctTreeNode) -> Bool) { if f(node) { for i in 0..<node.numberOfChildren { mapNode(node.child(i), f: f) } } } class func map(f : (OctTreeNode) -> Bool) { for i in 0..<numberOfRootItems() { mapNode(rootItem(i), f: f) } } } var OCT_FOLDER : NSImage? var OCT_PART : NSImage? class OctTree : NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate { @IBOutlet weak var outline : NSOutlineView! @IBOutlet weak var search: OctSearch! @IBOutlet weak var details: OctDetails! @IBOutlet weak var sheets: OctSheets! @IBOutlet weak var octApp : OctApp! override func awakeFromNib() { outline.registerForDraggedTypes([kOctPasteboardType]) outline.setDraggingSourceOperationMask([.Move, .Copy], forLocal: true) outline.setDraggingSourceOperationMask([.Delete], forLocal: false) NSNotificationCenter.defaultCenter().addObserverForName(OCTARINE_DATABASE_RESET, object: nil, queue: NSOperationQueue.mainQueue()) { (_: NSNotification) in gOctTreeRoots = [] self.outline.reloadData() } } var oldTreeRoots = [OctTreeNode]() func reloadTree(expanding item: OctTreeNode? = nil) { var expandedGroups = [String]() for row in 0..<outline.numberOfRows { if outline.isItemExpanded(outline.itemAtRow(row)) { expandedGroups.append((outline.itemAtRow(row) as! OctTreeNode).persistentIdentifier) } } if let item=item { let identifier = item.persistentIdentifier if !expandedGroups.contains(identifier) { expandedGroups.append(identifier) } } oldTreeRoots = gOctTreeRoots gOctTreeRoots = [] outline.reloadData() OctTreeNode.map() { (group: OctTreeNode) -> Bool in if expandedGroups.contains(group.persistentIdentifier) { self.outline.expandItem(group) return true } else { return false } } } @IBAction func newGroup(sender: AnyObject) { let selectedNode = outline.itemAtRow(outline.selectedRowIndexes.firstIndex) as? OctTreeNode let parentItem = selectedNode?.parent?.item ?? OctItem.rootFolder() let insertAt : Int if let path = selectedNode?.path { insertAt = path.indexAtPosition(path.length-1)+sender.tag() } else { insertAt = parentItem.children?.count ?? 0 } let group = OctItem.createFolder("") group.name = "New Group "+group.ident.substringToIndex(group.ident.startIndex.advancedBy(6)) var contents = [OctTreeNode]() if sender.tag()==0 { for row in outline.selectedRowIndexes { contents.append(outline.itemAtRow(row) as! OctTreeNode) } } outline.beginUpdates() let kids = parentItem.mutableOrderedSetValueForKey("children") kids.insertObject(group, atIndex: insertAt) let groupKids = group.mutableOrderedSetValueForKey("children") for node in contents { node.removeFromParent() groupKids.addObject(node.item) } outline.endUpdates() reloadTree() OctTreeNode.map { (node: OctTreeNode) -> Bool in if node.item == group { self.outline.editColumn(0, row: self.outline.rowForItem(node), withEvent: nil, select: true) return false } else { return !node.item.isPart } } } func newCustomPart(part: OctItem) { let selectedNode = outline.itemAtRow(outline.selectedRowIndexes.firstIndex) as? OctTreeNode let parentItem = selectedNode?.parent?.item ?? OctItem.rootFolder() let insertAt : Int if let path = selectedNode?.path { insertAt = path.indexAtPosition(path.length-1)+1 } else { insertAt = parentItem.children?.count ?? 0 } outline.beginUpdates() let kids = parentItem.mutableOrderedSetValueForKey("children") kids.insertObject(part, atIndex: insertAt) outline.endUpdates() reloadTree() OctTreeNode.map { (node: OctTreeNode) -> Bool in if node.item == part { self.outline.selectRowIndexes(NSIndexSet(index: self.outline.rowForItem(node)), byExtendingSelection: false) } return !node.item.isPart } } func outlineView(outlineView: NSOutlineView, persistentObjectForItem item: AnyObject?) -> AnyObject? { return (item as? OctTreeNode)?.persistentIdentifier } func outlineView(outlineView: NSOutlineView, itemForPersistentObject object: AnyObject) -> AnyObject? { if let identifier = object as? String { var found : OctTreeNode? OctTreeNode.map() { (node: OctTreeNode) -> Bool in guard found==nil else { return false } if node.persistentIdentifier == identifier { found = node return false } else { return true } } return found } else { return nil } } func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { return (item as! OctTreeNode).isExpandable } func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { return (item as? OctTreeNode)?.numberOfChildren ?? OctTreeNode.numberOfRootItems() } func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { if let node = item as? OctTreeNode { return node.child(index) } else { return OctTreeNode.rootItem(index) } } func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? { guard let tableColumn = tableColumn else { return nil } guard let octItem = (item as? OctTreeNode)?.item else { return nil } switch tableColumn.identifier { case "name": return octItem.name case "desc": return octItem.desc default: return nil } } @IBAction func updateOutlineValue(sender: AnyObject) { guard let view = sender as? NSView else { return } let row = outline.rowForView(view) let col = outline.columnForView(view) guard let octItem = (outline.itemAtRow(row) as? OctTreeNode)?.item else { return } guard let value = (sender as? NSTextField)?.stringValue else { return } let tableColumn = outline.tableColumns[col] switch tableColumn.identifier { case "name": octItem.name = value case "desc": octItem.desc = value default: break } outlineViewSelectionDidChange(NSNotification(name:"dummy", object:self)) } func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { guard let tableColumn = tableColumn else { return nil } let view = outlineView.makeViewWithIdentifier(tableColumn.identifier, owner: self) as! NSTableCellView guard let octItem = (item as? OctTreeNode)?.item else { return nil } switch tableColumn.identifier { case "name": if OCT_FOLDER == nil { let frameSize = view.imageView!.frame.size OCT_FOLDER = NSImage(named: "oct_folder") let folderSize = OCT_FOLDER!.size OCT_FOLDER!.size = NSMakeSize(folderSize.width*(frameSize.height/folderSize.height), frameSize.height) OCT_PART = NSImage(named: "oct_part") let partSize = OCT_PART!.size OCT_PART!.size = NSMakeSize(partSize.width*(frameSize.height/partSize.height), frameSize.height) } if octItem.isPart { view.imageView?.image = OCT_PART } else { view.imageView?.image = OCT_FOLDER } default: break } return view } var draggedItems = [OctItem]() var draggedNodes = [OctTreeNode]() func outlineView(outlineView: NSOutlineView, writeItems items: [AnyObject], toPasteboard pboard: NSPasteboard) -> Bool { draggedNodes = items as! [OctTreeNode] draggedItems = draggedNodes.map { (node: OctTreeNode) -> OctItem in node.item } let serialized = draggedItems.map { (item: OctItem) -> [String: AnyObject] in item.serialized() } pboard.declareTypes([kOctPasteboardType], owner: self) pboard.setPropertyList(serialized, forType: kOctPasteboardType) return true } func outlineView(outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: AnyObject?, proposedChildIndex index: Int) -> NSDragOperation { guard info.draggingPasteboard().availableTypeFromArray([kOctPasteboardType]) != nil else { return .None } guard let draggingSource = info.draggingSource() as? NSOutlineView where draggingSource == outlineView else { return [.Generic, .Copy] // Drags from outside the outline always OK } guard let octNode = item as? OctTreeNode else { return [.Move, .Copy] // Drags into root always OK } if !octNode.isExpandable { return .None // Don't allow dragging on a part } else if octNode.isDescendantOfOneOf(draggedNodes) { return .None // Don't allow drag on dragged items or their descendents } else { return [.Move, .Copy] // Otherwise we're good } } func outlineView(outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: AnyObject?, childIndex: Int) -> Bool { if let draggingSource = info.draggingSource() as? NSOutlineView where draggingSource == outlineView { // draggedNodes and draggedItems already contain an accurate representation } else { // Deserialize draggedItems from pasteboard draggedNodes = [] let serialized = info.draggingPasteboard().propertyListForType(kOctPasteboardType) as! [[String: AnyObject]] draggedItems = serialized.map({ (item: [String: AnyObject]) -> OctItem in return OctItem.itemFromSerialized(item) }) } let newParentNode = item as? OctTreeNode let newParent = newParentNode?.item ?? OctItem.rootFolder() var insertAtIndex = childIndex if insertAtIndex == NSOutlineViewDropOnItemIndex { insertAtIndex = newParent.children?.count ?? 0 } var insertAtRow = outlineView.rowForItem(item) if insertAtRow < 0 { insertAtRow = outlineView.numberOfRows } outlineView.beginUpdates() // // If this is a move, remove from previous parent, if any // if info.draggingSourceOperationMask().contains(.Move) { for node in draggedNodes.reverse() { let path = node.path let parent = node.parentItem let index = path.indexAtPosition(path.length-1) if parent == newParent && index < insertAtIndex { insertAtIndex -= 1 } if outlineView.rowForItem(node) < insertAtRow { insertAtRow -= 1 } node.removeFromParent() } } for item in draggedItems { let kids = newParent.mutableOrderedSetValueForKey("children") kids.insertObject(item, atIndex: insertAtIndex) insertAtIndex += 1 } outlineView.endUpdates() reloadTree(expanding: newParentNode) let insertedIndexes = NSIndexSet(indexesInRange: NSMakeRange(insertAtRow, draggedItems.count)) outlineView.selectRowIndexes(insertedIndexes, byExtendingSelection: false) return true } func outlineView(outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) { if operation.contains(.Delete) { outlineView.beginUpdates() for node in draggedNodes { node.removeFromParent() node.deleteIfOrphaned() } outlineView.endUpdates() reloadTree() } dispatch_async(dispatch_get_main_queue()) { self.oldTreeRoots = [] } } func selectedItems() -> [OctItem] { return outline.selectedRowIndexes.map() { (row: Int) -> OctItem in (outline.itemAtRow(row) as! OctTreeNode).item } } func outlineViewSelectionDidChange(_: NSNotification) { let selection = selectedItems() let standardParts = selection.filter { (item: OctItem) -> Bool in !item.isCustomPart } var newResults = selection.map { (item: OctItem) -> [String: AnyObject] in item.serialized() } dispatch_async(dispatch_get_main_queue()) { self.search.searchResults = newResults } guard standardParts.count > 0 else { return } search.partsFromUIDs(standardParts.map {$0.ident}) { (parts: [[String : AnyObject]]) in for part in parts { let index = try? newResults.indexOf { (result: [String : AnyObject]) throws -> Bool in return result["ident"] as! String == part["ident"] as! String } if let index = index ?? nil { let storedPart = newResults[index] var newPart = part newPart["name"] = storedPart["name"] newPart["desc"] = storedPart["desc"] newResults[index] = newPart } else { newResults.append(part) } } dispatch_async(dispatch_get_main_queue()) { self.search.searchResults = newResults } } } func selectedItem() -> OctItem { return (outline.itemAtRow(outline.selectedRow) as! OctTreeNode).item } } class OctOutlineView : NSOutlineView { @IBAction func delete(_: AnyObject) { let nodes = selectedRowIndexes.map { (index: Int) -> OctTreeNode in itemAtRow(index) as! OctTreeNode } beginUpdates() for node in nodes { node.removeFromParent() node.deleteIfOrphaned() } endUpdates() (dataSource() as? OctTree)?.reloadTree() } override func validateUserInterfaceItem(item: NSValidatedUserInterfaceItem) -> Bool { if item.action() == #selector(OctOutlineView.delete(_:)) { return selectedRowIndexes.count > 0 } return super.validateUserInterfaceItem(item) } }
fe13d8c89fa5b08ed3e0ab099ae89284
34.500978
163
0.586462
false
false
false
false
jayb967/twitter-client-clone-
refs/heads/master
TwitterClient/TwitterClient/Tweet.swift
mit
1
// // Tweet.swift // TwitterClient // // Created by Rio Balderas on 3/20/17. // Copyright © 2017 Jay Balderas. All rights reserved. // import Foundation class Tweet { let text : String let id : String let retweeted : Bool var user : User? init?(json: [String: Any]) { //string is there to represent keys, any is the values in the JSON file if let text = json["text"] as? String, let id = json["id_str"] as? String {//retrieves it as a string self.text = text self.id = id if let userDictionary = json["user"] as? [String : Any] { self.user = User(json: userDictionary) } if json["retweeted_status"] == nil { self.retweeted = false }else { self.retweeted = true print("true") } } else { return nil } } }
6a79470370229cc80e418585c2165b40
21.097561
107
0.529801
false
false
false
false
artursDerkintis/Starfly
refs/heads/master
Starfly/SFSearchTable.swift
mit
1
// // SFSearchTable.swift // Starfly // // Created by Arturs Derkintis on 10/3/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit import CoreData let querie = "http://suggestqueries.google.com/complete/search?client=toolbar&hl=en&q=" class SFSearchTable: UIView, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate{ private var googleTable : UITableView? private var historyTable : UITableView? private var array = [String]() let app = UIApplication.sharedApplication().delegate as! AppDelegate private var fetchController : NSFetchedResultsController? private var textForSearch = "" override init(frame: CGRect) { super.init(frame: frame) fetchController = NSFetchedResultsController(fetchRequest: simpleHistoryRequest, managedObjectContext: SFDataHelper.sharedInstance.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchController?.delegate = self googleTable = UITableView(frame: CGRect.zero) googleTable!.registerClass(SFSearchTableCell.self, forCellReuseIdentifier: "search") googleTable!.delegate = self googleTable!.dataSource = self googleTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0) googleTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) historyTable = UITableView(frame: CGRect.zero) historyTable!.registerClass(SFHistoryCellSearch.self, forCellReuseIdentifier: "search2") historyTable!.delegate = self historyTable!.dataSource = self historyTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0) historyTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) let stackView = UIStackView(arrangedSubviews: [googleTable!, historyTable!]) stackView.distribution = .FillEqually stackView.spacing = 20 addSubview(stackView) stackView.snp_makeConstraints { (make) -> Void in make.top.bottom.right.left.equalTo(0) } } lazy var simpleHistoryRequest : NSFetchRequest = { let request : NSFetchRequest = NSFetchRequest(entityName: "HistoryHit") request.sortDescriptors = [NSSortDescriptor(key: "arrangeIndex", ascending: false)] return request }() func getSuggestions(forText string : String){ if string != ""{ textForSearch = string let what : NSString = string.stringByReplacingOccurrencesOfString(" ", withString: "+") let set = NSCharacterSet.URLQueryAllowedCharacterSet() let formated : String = NSString(format: "%@%@", querie, what).stringByAddingPercentEncodingWithAllowedCharacters(set)! NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: NSURL(string: formated)!)) { (data : NSData?, res, error : NSError?) -> Void in if error == nil{ do { let xmlDoc = try AEXMLDocument(xmlData: data! as NSData) self.array.removeAll() for chilcd in xmlDoc["toplevel"].children { let string = chilcd["suggestion"].attributes["data"] as String? if let str = string{ self.array.append(str) } } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.googleTable!.delegate = self self.googleTable!.reloadData() }) } catch _ { } }else{ print(error?.localizedDescription) } }.resume() let resultPredicate1 : NSPredicate = NSPredicate(format: "titleOfIt CONTAINS[cd] %@", string) let resultPredicate2 : NSPredicate = NSPredicate(format: "urlOfIt CONTAINS[cd] %@", string) let compound = NSCompoundPredicate(orPredicateWithSubpredicates: [resultPredicate1, resultPredicate2]) fetchController?.fetchRequest.predicate = compound do{ try fetchController?.performFetch() historyTable?.reloadData() }catch _{ } } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if tableView == googleTable{ if array.count > 0{ if let url = NSURL(string: parseUrl(array[indexPath.row])!){ print("google \(url)") NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object:url) } } }else if tableView == historyTable{ let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit print("google \(object.getURL())") NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object: object.getURL()) } UIApplication.sharedApplication().delegate?.window!?.endEditing(true) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView == self.googleTable{ let cell = tableView.dequeueReusableCellWithIdentifier("search", forIndexPath: indexPath) as! SFSearchTableCell if array.count > indexPath.row{ let text = array[indexPath.row] cell.label?.text = text } return cell }else if tableView == self.historyTable{ let cell = tableView.dequeueReusableCellWithIdentifier("search2", forIndexPath: indexPath) as! SFHistoryCellSearch let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit let title = NSMutableAttributedString(string: object.titleOfIt!) let rangeT = (object.titleOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch) title.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, title.length)) title.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.75, alpha: 1.0), range: rangeT) let url = NSMutableAttributedString(string: object.urlOfIt!) let rangeU = (object.urlOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch) url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.9, alpha: 1.0), range: NSMakeRange(0, url.length)) url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.8, alpha: 1.0), range: rangeU) cell.titleLabel?.textColor = nil cell.urlLabel?.textColor = nil cell.titleLabel?.attributedText = title cell.urlLabel?.attributedText = url return cell } return UITableViewCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == googleTable{ return array.count }else if tableView == historyTable{ if self.fetchController!.sections != nil{ let sectionInfo = self.fetchController!.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } } return 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0b8f430b00cdc5dde4b44b28fc8238db
46.390533
201
0.611437
false
false
false
false
hibu/apptentive-ios
refs/heads/master
Example/iOSExample/AppDelegate.swift
bsd-3-clause
1
// // AppDelegate.swift // ApptentiveExample // // Created by Frank Schmitt on 8/6/15. // Copyright (c) 2015 Apptentive, Inc. All rights reserved. // import UIKit import Apptentive @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Apptentive.sharedConnection().APIKey = "<Your Apptentive API Key>" precondition(Apptentive.sharedConnection().APIKey != "<Your Apptentive API Key>", "Please set your Apptentive API key above") if let tabBarController = self.window?.rootViewController as? UITabBarController { tabBarController.delegate = self } return true } // MARK: Tab bar controller delegate func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) { if tabBarController.viewControllers?.indexOf(viewController) ?? 0 == 0 { Apptentive.sharedConnection().engage("photos_tab_selected", fromViewController: tabBarController) } else { Apptentive.sharedConnection().engage("favorites_tab_selected", fromViewController: tabBarController) } } }
05d89899ee1c7ff891713c61c4871320
31.763158
127
0.772691
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
cocoa_programming_for_osx/29_UnitTesting/RanchForecast/RanchForecast/Course.swift
apache-2.0
3
// // Course.swift // RanchForecast // // Created by mcxiaoke on 16/5/23. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Foundation public class Course: NSObject { public let title:String public let url:NSURL public let nextStartDate: NSDate public init(title: String, url: NSURL, nextStartDate: NSDate) { self.title = title self.url = url self.nextStartDate = nextStartDate super.init() } override public var description: String { return "Course(title:\(title) url:\(url))" } } public func ==(lhs: Course, rhs: Course) -> Bool { return lhs.title == rhs.title && lhs.url == rhs.url && lhs.nextStartDate == rhs.nextStartDate }
7684bf7cbda3cd08369ad0a0ca360264
20.181818
65
0.664756
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
refs/heads/Development
MemorizeItForever/MemorizeItForever/General/Extensions/SwinjectStoryboardExtension.swift
mit
1
// // SwinjectStoryboardExtension.swift // MemorizeItForever // // Created by Hadi Zamani on 11/12/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import Swinject import SwinjectStoryboard import MemorizeItForeverCore import BaseLocalDataAccess import CoreData extension SwinjectStoryboard { @objc class func setup() { defaultContainer.storyboardInitCompleted(TabBarController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) } defaultContainer.storyboardInitCompleted(MemorizeItViewController.self) { r, c in c.selectionFeedback = UISelectionFeedbackGenerator() } defaultContainer.storyboardInitCompleted(SetViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) c.dataSource = r.resolve(SetTableDataSourceProtocol.self, name: "SetTableDataSource") } defaultContainer.storyboardInitCompleted(SetItemViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) } defaultContainer.storyboardInitCompleted(ChangeSetViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) c.dataSource = r.resolve(SetTableDataSourceProtocol.self, name: "ChangeSetTableDataSource") } defaultContainer.storyboardInitCompleted(AddPhraseViewController.self) { r, c in c.wordService = r.resolve(WordServiceProtocol.self) c.validator = r.resolve(ValidatorProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(ReviewPhraseViewController.self) { r, c in c.wordFlowService = r.resolve(WordFlowServiceProtocol.self) } defaultContainer.register(SetTableDataSourceProtocol.self, name: "SetTableDataSource") { r in SetTableDataSource(setService: r.resolve(SetServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.register(SetTableDataSourceProtocol.self, name: "ChangeSetTableDataSource") { r in ChangeSetTableDataSource(setService: r.resolve(SetServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.register(ValidatorProtocol.self){ r in Validator() } defaultContainer.storyboardInitCompleted(TakeTestViewController.self) { r, c in c.wordFlowService = r.resolve(WordFlowServiceProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(PhraseViewController.self) { r, c in c.dataSource = r.resolve(PhraseTableDataSourceProtocol.self, name: "PhraseTableDataSource") c.wordService = r.resolve(WordServiceProtocol.self) } defaultContainer.register(PhraseTableDataSourceProtocol.self, name: "PhraseTableDataSource"){ r in PhraseTableDataSource(wordService: r.resolve(WordServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.storyboardInitCompleted(PhraseHistoryViewController.self) { r, c in c.dataSource = r.resolve(PhraseTableDataSourceProtocol.self, name: "PhraseHistoryTableDataSource") c.wordService = r.resolve(WordServiceProtocol.self) } defaultContainer.register(PhraseTableDataSourceProtocol.self, name: "PhraseHistoryTableDataSource"){ r in PhraseHistoryTableDataSource(wordService: nil) }.inObjectScope(.weak) defaultContainer.register(ServiceFactoryProtocol.self, name: "SetServiceFactory"){ r in SetServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "WordServiceFactory"){ r in WordServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "WordFlowServiceFactory"){ r in WordFlowServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "DepotPhraseServiceFactory"){ r in DepotPhraseServiceFactory() } defaultContainer.register(SetServiceProtocol.self){ r in let setServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "SetServiceFactory")! let setService: SetService = setServiceFactory.create() return setService } defaultContainer.register(WordServiceProtocol.self){ r in let wordServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "WordServiceFactory")! let wordService: WordService = wordServiceFactory.create() return wordService } defaultContainer.register(WordFlowServiceProtocol.self){ r in let wordFlowServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "WordFlowServiceFactory")! let wordFlowService: WordFlowService = wordFlowServiceFactory.create() return wordFlowService } defaultContainer.storyboardInitCompleted(TemporaryPhraseListViewController.self) { r, c in c.dataSource = r.resolve(DepotTableDataSourceProtocol.self, name: "TemporaryPhraseListDataSource") c.service = r.resolve(DepotPhraseServiceProtocol.self) } defaultContainer.register(DepotPhraseServiceProtocol.self){ r in let depotPhraseServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "DepotPhraseServiceFactory")! let depotPhraseService: DepotPhraseService = depotPhraseServiceFactory.create() return depotPhraseService } defaultContainer.register(DepotTableDataSourceProtocol.self, name: "TemporaryPhraseListDataSource"){ r in TemporaryPhraseListDataSource() }.inObjectScope(.weak) defaultContainer.register(EditPhrasePickerViewDataSourceProtocol.self){ r in EditPhrasePickerViewDataSource() }.inObjectScope(.weak) defaultContainer.storyboardInitCompleted(EditPhraseViewController.self) { r, c in c.wordService = r.resolve(WordServiceProtocol.self) c.setService = r.resolve(SetServiceProtocol.self) c.pickerDataSource = r.resolve(EditPhrasePickerViewDataSourceProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(DepotViewController.self) { r, c in c.dataSource = r.resolve(DepotTableDataSourceProtocol.self, name: "DepotDataSource") c.service = r.resolve(DepotPhraseServiceProtocol.self) } defaultContainer.register(DepotTableDataSourceProtocol.self, name: "DepotDataSource"){ r in DepotDataSource(service: r.resolve(DepotPhraseServiceProtocol.self)!) }.inObjectScope(.weak) } }
64eaf217db7dec77f00515c856915f04
45.168831
118
0.683263
false
false
false
false
loisie123/Cuisine-Project
refs/heads/master
Cuisine/WeekTableViewController.swift
mit
1
// // WeekTableViewController.swift // Cuisine // // Created by Lois van Vliet on 15-01-17. // Copyright © 2017 Lois van Vliet. All rights reserved. // import UIKit import Firebase class WeekTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableViewImage: UITableView! var ref:FIRDatabaseReference? var databaseHandle: FIRDatabaseHandle? var days = [String]() var selectedDay = String() var array = [String]() override func viewDidLoad() { getweek() super.viewDidLoad() if days.isEmpty{ days = ["No information available"] } ref = FIRDatabase.database().reference() self.tableViewImage.reloadData() } //MARK:- Get the available dates. func getweek(){ let ref = FIRDatabase.database().reference() ref.child("cormet").child("different days").observeSingleEvent(of: .value, with: { (snapshot) in self.days = self.getWeekDays(snapshot: snapshot) self.tableViewImage.reloadData() }) } //MARK:- Make tableview func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "weekCell", for: indexPath) as! WeekTableViewCell cell.weekLabel.text = days[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return days.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedDay = days[indexPath.row] self.performSegue(withIdentifier: "mealsVC", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mealsVC"{ let controller = segue.destination as! TodayMealsViewController controller.day = selectedDay } } }
8249d37a500e1ca891379930126801ed
24.823529
114
0.599089
false
false
false
false
sebk/BeaconMonitor
refs/heads/master
BeaconMonitor/BeaconSender.swift
mit
1
// // BeaconSender.swift // BeaconMonitor // // Created by Sebastian Kruschwitz on 16.09.15. // Copyright © 2015 seb. All rights reserved. // import Foundation import CoreLocation import CoreBluetooth public class BeaconSender: NSObject { public static let sharedInstance = BeaconSender() fileprivate var _region: CLBeaconRegion? fileprivate var _peripheralManager: CBPeripheralManager! fileprivate var _uuid = "" fileprivate var _identifier = "" public func startSending(uuid: String, majorID: CLBeaconMajorValue, minorID: CLBeaconMinorValue, identifier: String) { _uuid = uuid _identifier = identifier stopSending() //stop sending when it's active // create the region that will be used to send _region = CLBeaconRegion( proximityUUID: UUID(uuidString: uuid)!, major: majorID, minor: minorID, identifier: identifier) _peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } open func stopSending() { _peripheralManager?.stopAdvertising() } } //MARK: - CBPeripheralManagerDelegate extension BeaconSender: CBPeripheralManagerDelegate { public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { if peripheral.state == .poweredOn { let data = ((_region?.peripheralData(withMeasuredPower: nil))! as NSDictionary) as! Dictionary<String, Any> peripheral.startAdvertising(data) print("Powered On -> start advertising") } else if peripheral.state == .poweredOff { peripheral.stopAdvertising() print("Powered Off -> stop advertising") } } public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if let error = error { print("Error starting advertising: \(error)") } else { print("Did start advertising") } } }
595edbe2526b753ca3f55b4e63d72f1c
26.641026
122
0.608998
false
false
false
false
wangyuxianglove/TestKitchen1607
refs/heads/master
Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/main(主要模块)/view/IngreRecommendView.swift
mit
1
// // IngreRecommendView.swift // Testkitchen1607 // // Created by qianfeng on 16/10/25. // Copyright © 2016年 zhb. All rights reserved. // import UIKit public enum IngreWidgetType:Int{ case GuessYouLike = 1//猜你喜欢 case RedPacket = 2//红包入口 case TodayNew=5//今日新品 case Scene=3//早餐 case SceneList=9//全部场景 } class IngreRecommendView: UIView { //数据 var jumpClosure:IngreJumpClourse? var model:IngreRcommend?{ didSet{ //set方法调用之后会调用这里方法 tableView?.reloadData() } } //表格 private var tableView:UITableView? //重新实现初始化方法 override init(frame: CGRect) { super.init(frame: frame) //创建表格视图 tableView=UITableView(frame: CGRectZero, style: .Plain) tableView?.dataSource=self tableView?.delegate=self addSubview(tableView!) //约束 tableView?.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView代理方法 extension IngreRecommendView:UITableViewDelegate,UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { //banner广告部分显示一个分组 var section=1 if model?.data?.widgetList?.count>0{ section+=(model?.data?.widgetList?.count)! } return section } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //banner广告Section显示一行 var row=0 if section==0{ //广告 row=1 }else{ //获取list对象 let listModel = model?.data?.widgetList![section-1] if (listModel?.widget_type?.integerValue)! == IngreWidgetType.GuessYouLike.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.RedPacket.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.TodayNew.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.Scene.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.SceneList.rawValue{ //猜你喜欢 //红包入口 //今日新品 //早餐日记 //全部场景 row=1 } } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat=0 if indexPath.section==0{ height=140 }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢 height=70 }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //红包入口 height=75 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //今日新品 height=280 }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //早餐日记 height=200 }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //全部场景 height=70 } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section==0{ let cell=IngreBannerCell.creatBannerCellFor(tableView, atIndexPath: indexPath, bannerArray: model?.data?.bannerArray) //点击事件 cell.jumpClosure=jumpClosure return cell }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢 let cell = IngreLikeCell.creatLikeCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //红包入口 let cell = IngreRedPacketCell.creatRedPackCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //今日新品 let cell = IngreTodayCell.creatRedTodayCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //早餐 let cell = IngrescenCell.creatSceneCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //全部 let cell = IngreSceneListCell.creatSceneListCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell } } return UITableViewCell() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section>0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢分组的header let likeHeaderView=IngreLikeHeaderView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44)) return likeHeaderView }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //今日新品 let headerView=IngreHeaderView(frame: CGRect(x: 0, y: 0, width:kScreenWidth , height: 54)) //headerView.configText((listModel?.title)!) headerView.jumpClosure=jumpClosure headerView.listModel=listModel return headerView } } return nil } //设置header的高度 func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { var height:CGFloat=0 if section > 0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ height=44 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ // height=54 } } return height } }
f1c2a23aa22aaec988a65e50f67f9526
34.209524
412
0.585204
false
false
false
false
Foild/SwiftForms
refs/heads/master
SwiftForms/descriptors/FormRowDescriptor.swift
mit
5
// // FormRowDescriptor.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public enum FormRowType { case Unknown case Text case URL case Number case NumbersAndPunctuation case Decimal case Name case Phone case NamePhone case Email case Twitter case ASCIICapable case Password case Button case BooleanSwitch case BooleanCheck case SegmentedControl case Picker case Date case Time case DateAndTime case Stepper case Slider case MultipleSelector case MultilineText } public typealias DidSelectClosure = (Void) -> Void public typealias UpdateClosure = (FormRowDescriptor) -> Void public typealias TitleFormatterClosure = (NSObject) -> String! public typealias VisualConstraintsClosure = (FormBaseCell) -> NSArray public class FormRowDescriptor: NSObject { /// MARK: Types public struct Configuration { public static let Required = "FormRowDescriptorConfigurationRequired" public static let CellClass = "FormRowDescriptorConfigurationCellClass" public static let CheckmarkAccessoryView = "FormRowDescriptorConfigurationCheckmarkAccessoryView" public static let CellConfiguration = "FormRowDescriptorConfigurationCellConfiguration" public static let Placeholder = "FormRowDescriptorConfigurationPlaceholder" public static let WillUpdateClosure = "FormRowDescriptorConfigurationWillUpdateClosure" public static let DidUpdateClosure = "FormRowDescriptorConfigurationDidUpdateClosure" public static let MaximumValue = "FormRowDescriptorConfigurationMaximumValue" public static let MinimumValue = "FormRowDescriptorConfigurationMinimumValue" public static let Steps = "FormRowDescriptorConfigurationSteps" public static let Continuous = "FormRowDescriptorConfigurationContinuous" public static let DidSelectClosure = "FormRowDescriptorConfigurationDidSelectClosure" public static let VisualConstraintsClosure = "FormRowDescriptorConfigurationVisualConstraintsClosure" public static let Options = "FormRowDescriptorConfigurationOptions" public static let TitleFormatterClosure = "FormRowDescriptorConfigurationTitleFormatterClosure" public static let SelectorControllerClass = "FormRowDescriptorConfigurationSelectorControllerClass" public static let AllowsMultipleSelection = "FormRowDescriptorConfigurationAllowsMultipleSelection" public static let ShowsInputToolbar = "FormRowDescriptorConfigurationShowsInputToolbar" public static let DateFormatter = "FormRowDescriptorConfigurationDateFormatter" } /// MARK: Properties public var title: String! public var rowType: FormRowType = .Unknown public var tag: String! public var value: NSObject! { willSet { if let willUpdateBlock = self.configuration[Configuration.WillUpdateClosure] as? UpdateClosure { willUpdateBlock(self) } } didSet { if let didUpdateBlock = self.configuration[Configuration.DidUpdateClosure] as? UpdateClosure { didUpdateBlock(self) } } } public var configuration: [NSObject : Any] = [:] /// MARK: Init public override init() { super.init() configuration[Configuration.Required] = true configuration[Configuration.AllowsMultipleSelection] = false configuration[Configuration.ShowsInputToolbar] = false } public convenience init(tag: String, rowType: FormRowType, title: String, placeholder: String! = nil) { self.init() self.tag = tag self.rowType = rowType self.title = title if placeholder != nil { configuration[FormRowDescriptor.Configuration.Placeholder] = placeholder } } /// MARK: Public interface public func titleForOptionAtIndex(index: Int) -> String! { if let options = configuration[FormRowDescriptor.Configuration.Options] as? NSArray { return titleForOptionValue(options[index] as! NSObject) } return nil } public func titleForOptionValue(optionValue: NSObject) -> String! { if let titleFormatter = configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] as? TitleFormatterClosure { return titleFormatter(optionValue) } else if optionValue is String { return optionValue as! String } return "\(optionValue)" } }
0109412ac8e06230dcb600dd1fe48729
32.84507
128
0.6933
false
true
false
false
le-lerot/altim
refs/heads/master
Altim/CameraViewController.swift
gpl-3.0
1
// // CameraViewController.swift // Altim // // Created by Martin Delille on 23/12/2016. // Copyright © 2016 Phonations. All rights reserved. // import UIKit import AVFoundation import CoreMotion class CameraViewController: UIViewController { var cameraPreviewLayer: AVCaptureVideoPreviewLayer? var hudLayer = CAShapeLayer() var motionManager = CMMotionManager() @IBOutlet weak var cameraView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetHigh let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: device) session.addInput(input) // Create video preview layer and add it to the UI if let newCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) { let viewLayer = self.cameraView.layer let size = self.cameraView.bounds newCaptureVideoPreviewLayer.frame = size; viewLayer.addSublayer(newCaptureVideoPreviewLayer) self.cameraPreviewLayer = newCaptureVideoPreviewLayer; session.startRunning() let textLayer = CATextLayer() textLayer.string = "coucou" textLayer.frame = CGRect(x: 0, y: 20, width: size.width, height: 40) viewLayer.addSublayer(textLayer) hudLayer.backgroundColor = UIColor.red.cgColor hudLayer.frame = CGRect(x: size.width / 2 - 20, y: 0, width: 40, height: size.height) viewLayer.addSublayer(hudLayer) } } catch { print(error) } motionManager.deviceMotionUpdateInterval = 0.1 motionManager.startDeviceMotionUpdates(to: OperationQueue.main) { (deviceMotion, error) in if let yaw = deviceMotion?.attitude.yaw { let size = self.cameraView.bounds let x = CGFloat(yaw) * size.width self.hudLayer.frame = CGRect(x: x, y: 0, width: 10, height: size.height) } } } /* // 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. } */ }
12a03623b30528831346da16e54061e3
31.55
107
0.63172
false
false
false
false
kumabook/StickyNotesiOS
refs/heads/master
StickyNotes/DateFormatter.swift
mit
1
// // DateFormatter.swift // StickyNotes // // Created by Hiroki Kumamoto on 8/14/16. // Copyright © 2016 kumabook. All rights reserved. // import Foundation import Breit class DateFormatter { private static var __once: () = { dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let posix = Locale(identifier: "en_US_POSIX") dateFormatter.locale = posix }() fileprivate static var dateFormatter = Foundation.DateFormatter() fileprivate static var onceToken : Int = 0 static var shared: Foundation.DateFormatter { _ = DateFormatter.__once return dateFormatter } } extension Date { var passedTime: String { return "\(elapsedTime.value) \(elapsedTime.unit.rawValue.localize())" } }
67d812470faa25a73675da32876b5f56
25.2
77
0.647583
false
false
false
false
khoren93/SwiftHub
refs/heads/master
SwiftHub/Modules/Search/TrendingUserCellViewModel.swift
mit
1
// // TrendingUserCellViewModel.swift // SwiftHub // // Created by Sygnoos9 on 12/18/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import Foundation import RxSwift import RxCocoa class TrendingUserCellViewModel: DefaultTableViewCellViewModel { let user: TrendingUser init(with user: TrendingUser) { self.user = user super.init() title.accept("\(user.username ?? "") (\(user.name ?? ""))") detail.accept(user.repo?.fullname) imageUrl.accept(user.avatar) badge.accept(R.image.icon_cell_badge_user()?.template) badgeColor.accept(UIColor.Material.green900) } } extension TrendingUserCellViewModel { static func == (lhs: TrendingUserCellViewModel, rhs: TrendingUserCellViewModel) -> Bool { return lhs.user == rhs.user } }
9806513ba57a0642e6f61b04db8da738
24.9375
93
0.675904
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/SetupCustomizationItemView.swift
gpl-3.0
1
// // SetupCustomizationItemView.swift // Habitica // // Created by Phillip on 07.08.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit class SetupCustomizationItemView: UIView { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var labelView: UILabel! @IBOutlet weak var borderView: UIView! var isActive = false { didSet { updateViewsForActivity() } } override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { if let view = loadViewFromNib() { view.frame = bounds view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] addSubview(view) borderView.layer.borderColor = UIColor.purple400.cgColor } } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView return view } func setItem(_ item: SetupCustomization) { if let icon = item.icon { iconView.image = icon } if let color = item.color { iconView.backgroundColor = color } if let text = item.text { labelView.text = text } else { labelView.isHidden = true } } private func updateViewsForActivity() { if isActive { borderView.layer.borderWidth = 4 labelView.textColor = .white } else { borderView.layer.borderWidth = 0 labelView.textColor = UIColor.white.withAlphaComponent(0.5) } } }
66c4bf6b98e4dec39d60a14e0b68a0c3
25.739726
115
0.577869
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/Welcome/WhatsNew/WhatsNewBuilder.swift
apache-2.0
4
class WhatsNewBuilder { static var configs:[WhatsNewPresenter.WhatsNewConfig] { return [ WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"), title: "whatsnew_lp_title", text: "whatsnew_lp_message", buttonNextTitle: "whatsnew_trial_cta", isCloseButtonHidden: false, action: { let subscribeViewController = SubscriptionViewBuilder.buildLonelyPlanet(parentViewController: MapViewController.shared(), source: kStatWhatsNew, successDialog: .goToCatalog, completion: nil) MapViewController.shared().present(subscribeViewController, animated: true) }), WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"), title: "whatsnew_lp_title", text: "whatsnew_lp_message", buttonNextTitle: "done") ] } static func build(delegate: WelcomeViewDelegate) -> [UIViewController] { return WhatsNewBuilder.configs.map { (config) -> UIViewController in let sb = UIStoryboard.instance(.welcome) let vc = sb.instantiateViewController(ofType: WelcomeViewController.self); let router = WelcomeRouter(viewController: vc, delegate: delegate) let presenter = WhatsNewPresenter(view: vc, router: router, config: config) vc.presenter = presenter return vc } } }
7dce2a7cdf490262310eac95204a45bb
54.675676
161
0.454369
false
true
false
false
gistya/Functional-Swift-Graph
refs/heads/master
Functional Graph.playground/Sources/Node.swift
gpl-3.0
1
import Foundation public struct Node<_Content:Hashable>:Hashable { public var createdTime: Date = Date() public var id: Id public var value: _Content public static func ==(lhs: Node, rhs: Node) -> Bool { return lhs.createdTime == rhs.createdTime && lhs.value == rhs.value } public init(id:Id, value:_Content) { self.id = id self.value = value } public var hashValue: Int { get { return Int(createdTime.timeIntervalSince1970) } } } extension Node: CustomStringConvertible { public var description:String { get { return "Id: \(id), Value: \(value)" } } }
4ff6782add4f9ca60b2616621b75a276
24.148148
75
0.587629
false
false
false
false
c650/Caesar-Cipher
refs/heads/master
caesar/swift/caesar-cipher.swift
mit
2
/**************************************************************************** Charles Bailey caesar.swift It encrypts/decrypts a phrase according to a certain caesar cipher key. ****************************************************************************/ import Foundation /* Encryption Function: Takes a key and mutates any alphabetical character by it. Note: lines 29 and 32 hopefully can be trimmed */ func encrypt(key: Int, phrase: String) -> String { let key = key % 26 // very important to get key within 0-25 range! var arr = [Character]() // make an Array ("collection") to store encryped result phrase for character in phrase.unicodeScalars { // iterate throught each UnicodeScalar in phrase if character.value >= 65 && character.value <= 90 { // check if capital Alpha // append to arr: get the UnicodeScalar of the current character + key + 7 (for some reason) // mod it by 26 to get it within Alpha range, add 65 to get it to ASCII Alpha range arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 65))) } else if character.value >= 97 && character.value <= 122 { // check if lower Alpha // see ln25-26; same except for the lower case arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 97))) } else { // just append the original if it isn't alphabetical arr.append(Character(character)) } } // return a String composed of the array from ln21 return String(arr) } /* Decryption Function: Simply calls encrypt(...) with a negated key. */ func decrypt(key: Int, phrase: String) -> String { return encrypt(-key, phrase: phrase) } /* "main()" The controller for the program. */ if Process.arguments.count != 2 { // ln 57-60: check for correct number of arguments print("\nWrong number of arguments.") print("Usuage: caesar <key>") } else { print("Put in the phrase to encrypt: ") // prompt for input, duh if let input = readLine() { // will exit if getting a string fails if let key = Int(Process.arguments[1]) { // assigns the key, exits if fails // ln67-71: presents user with the results print("Encrypting...") print(encrypt(key, phrase: input)) print("Decrypting...") print(decrypt(key, phrase: encrypt(key, phrase: input))) } // curly brace } // another curly } // i'm just trolling
76c6cf962ef019a1ced1adbe8cf0cb5d
30.648649
95
0.639897
false
false
false
false
X140Yu/Lemon
refs/heads/master
Lemon/Library/Protocol/LoadableView.swift
gpl-3.0
1
import UIKit import RxSwift import RxCocoa protocol Loadable { var ld_contentView: UIView { get } func startLoading() func stopLoading() } class LoadableViewProvider: Loadable { var ld_contentView: UIView let isLoading = Variable<Bool>(false) lazy var loadingView: UIView = { let v = UIView() v.backgroundColor = UIColor.white let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) v.addSubview(spinner) spinner.startAnimating() spinner.snp.makeConstraints({ (maker) in maker.center.equalTo(v) }) return v }() init(contentView: UIView) { ld_contentView = contentView isLoading.value = false } func startLoading() { stopLoading() isLoading.value = true ld_contentView.addSubview(loadingView) loadingView.snp.makeConstraints { (maker) in maker.edges.equalTo(ld_contentView) } } func stopLoading() { isLoading.value = false loadingView.removeFromSuperview() } }
b23a556679e3350e69675e3f6cde4744
20.888889
72
0.694416
false
false
false
false
MarcoSantarossa/SwiftyToggler
refs/heads/develop
Source/FeaturesList/ViewModel/FeaturesListViewModel.swift
mit
1
// // FeaturesListViewModel.swift // // Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/) // // 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. // final class FeaturesListViewModel: FeaturesListViewModelProtocol { private struct Constants { static let defaultCloseButtonHeight: CGFloat = 44 static let defaultTitleLabelHeight: CGFloat = 50 } weak var delegate: FeaturesListViewModelDelegate? var featuresCount: Int { return featuresStatus.count } var titleLabelHeight: CGFloat { guard case PresentingMode.modal(_) = self.presentingMode else { return 0 } return Constants.defaultTitleLabelHeight } var closeButtonHeight: CGFloat { guard case PresentingMode.modal(_) = self.presentingMode else { return 0 } return Constants.defaultCloseButtonHeight } var shouldShowPlaceholder: Bool { return featuresCount == 0 } fileprivate let featuresManager: FeaturesManagerTogglerProtocol fileprivate let featuresStatus: [FeatureStatus] private let presentingMode: PresentingMode init(featuresManager: FeaturesManagerTogglerProtocol = FeaturesManager.shared, presentingMode: PresentingMode) { self.featuresManager = featuresManager self.presentingMode = presentingMode self.featuresStatus = featuresManager.featuresStatus } } extension FeaturesListViewModel: FeaturesListViewModelUIBindingProtocol { func featureStatus(at indexPath: IndexPath) -> FeatureStatus? { guard indexPath.row < featuresStatus.count else { return nil } return featuresStatus[indexPath.row] } func updateFeature(name: String, isEnabled: Bool) { try? featuresManager.setEnable(isEnabled, featureName: name) } func closeButtonDidTap() { delegate?.featuresListViewModelNeedsClose() } }
c508b3f608825cbb281ad463eb8f8cde
36.648649
82
0.77028
false
false
false
false
twoefay/ios-client
refs/heads/master
Twoefay/Controller/RegistrationPageViewController.swift
gpl-3.0
1
// // RegistrationPageViewController.swift // Twoefay // // Created by Jonathan Woong on 5/11/16. // Copyright © 2016 Twoefay. All rights reserved. // import UIKit class RegistrationPageViewController: UIViewController { @IBOutlet weak var firstNameField: UITextField! @IBOutlet weak var lastNameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var rePasswordField: UITextField! override func viewDidLoad() { super.viewDidLoad() // this is a comment // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func submitRegistration(sender: AnyObject) { // Get textfield data let userFirstName = firstNameField.text; let userLastName = lastNameField.text; let userEmail = emailField.text; let userPassword = passwordField.text; let userRePassword = rePasswordField.text; // Check for empty fields if(userFirstName!.isEmpty || userLastName!.isEmpty || userEmail!.isEmpty || userPassword!.isEmpty || userRePassword!.isEmpty) { // Display alert message displayAlert("All fields are required"); return; } // Check if passwords match if (userPassword != userRePassword) { // Display alert message displayAlert("Passwords do not match"); return; } // Store data (locally) // TODO: store data remotely NSUserDefaults.standardUserDefaults().setObject(userFirstName, forKey:"userFirstName"); NSUserDefaults.standardUserDefaults().setObject(userLastName, forKey:"userLastName"); NSUserDefaults.standardUserDefaults().setObject(userEmail, forKey:"userEmail"); NSUserDefaults.standardUserDefaults().setObject(userPassword, forKey:"userPassword"); NSUserDefaults.standardUserDefaults().setObject(userRePassword, forKey:"userRePassword"); NSUserDefaults.standardUserDefaults().synchronize(); // Confirm submission let Alert = UIAlertController(title:"Alert", message:"Registration Successful", preferredStyle: UIAlertControllerStyle.Alert); let OK = UIAlertAction(title:"OK", style:UIAlertActionStyle.Default) { action in self.dismissViewControllerAnimated(true, completion:nil); } Alert.addAction(OK); self.presentViewController(Alert, animated:true,completion:nil); } // Display alert with message userMessage func displayAlert(userMessage:String) { let Alert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.Alert); let OK = UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil); Alert.addAction(OK); self.presentViewController(Alert, animated:true, completion:nil); } }
8e7ccf8bd4ae81b058fe64c22da04141
36.845238
135
0.663102
false
false
false
false
tsalvo/nes-chr-editor
refs/heads/master
NES CHR Editor/NES CHR Editor/ViewControllers/FullGridCollectionViewController.swift
apache-2.0
1
// // FullGridCollectionViewController.swift // NES CHR Editor // // Created by Tom Salvo on 11/5/16. // Copyright © 2016 Tom Salvo. All rights reserved. // import AppKit class FullGridCollectionViewController: NSViewController, NSCollectionViewDelegateFlowLayout, NSCollectionViewDataSource, CHREditProtocol, CHRGridHistoryProtocol { @IBOutlet weak private var gridCollectionView:NSCollectionView! var CHRGridHistory:[CHRGrid] = [] // for tracking undo operations, most recent = beginning var CHRGridFuture:[CHRGrid] = [] // for tracking redo operations var tileSelectionDelegate:CHRSelectionProtocol? var fileEditDelegate:FileEditProtocol? var grid:CHRGrid = CHRGrid() { didSet { self.gridCollectionView.reloadData() } } static var CHRClipboard:CHR? var brushColor:PaletteColor = .Color3 override func viewDidLoad() { super.viewDidLoad() self.gridCollectionView.allowsMultipleSelection = false self.gridCollectionView.allowsEmptySelection = false self.gridCollectionView.register(GridCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "gridCollectionItem")) self.gridCollectionView.delegate = self self.gridCollectionView.dataSource = self } override func updateViewConstraints() { super.updateViewConstraints() self.gridCollectionView.collectionViewLayout?.invalidateLayout() } // MARK: - NSCollectionViewDelegateFlowLayout func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize { let possibleNumbersOfItemsPerRow:[CGFloat] = [32, 16, 8, 4, 2] let collectionViewWidth = collectionView.bounds.width let minimumItemWidth:CGFloat = min(collectionViewWidth, 50) var itemWidth:CGFloat = collectionViewWidth // default for possibleNumberOfItemsPerRow in possibleNumbersOfItemsPerRow { if collectionViewWidth / possibleNumberOfItemsPerRow >= minimumItemWidth { itemWidth = collectionViewWidth / possibleNumberOfItemsPerRow break } } return NSSize(width: itemWidth, height: itemWidth) } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets { return NSEdgeInsetsZero } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize { return NSSize.zero } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForFooterInSection section: Int) -> NSSize { return NSSize.zero } func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) { if let safeFirstIndexPath = indexPaths.first { let previousIndexPath = IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0) self.grid.selectedCHRIndex = UInt(safeFirstIndexPath.item) collectionView.reloadItems(at: [previousIndexPath, IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } // MARK: - NSCollectionViewDataSource func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return Int(ChrFileSize(numChrBlocks: grid.numChrBlocks).numCHRsInFile) } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { // Recycle or create an item. guard let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "gridCollectionItem"), for: indexPath) as? GridCollectionViewItem else { return NSCollectionViewItem() } item.itemView.chr = self.grid.getCHR(atIndex: UInt(indexPath.item)) item.itemView.isSelected = UInt(indexPath.item) == self.grid.selectedCHRIndex item.itemView.setNeedsDisplay(item.itemView.bounds) return item } // MARK: - TileEditProtocol func tileEdited(withCHR aCHR: CHR) { self.grid.setCHR(chr: aCHR, atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) } // MARK : - CHRGridHistoryProtocol func CHRGridWillChange() { // remove the oldest CHR grids from the history until we're below the maximum allowed while self.CHRGridHistory.count >= Int(Constants.maxCHRGridHistory) { let _ = self.CHRGridHistory.popLast() } // if the user edited the grid, there should be no grid future for Redo operations self.CHRGridFuture.removeAll() self.CHRGridHistory.insert(self.grid, at: 0) // add most recent grid to the front of the history self.fileEditDelegate?.fileWasEdited() } func undo() { // if there's a CHR grid in the history if let safeMostRecentGrid = self.CHRGridHistory.first { // remove the oldest CHR grids from the grid future until we're below the maximum allowed while self.CHRGridFuture.count >= Int(Constants.maxCHRGridHistory) { let _ = self.CHRGridFuture.popLast() } self.CHRGridFuture.insert(self.grid, at: 0) // add current grid to the front of the future self.grid = safeMostRecentGrid self.gridCollectionView.reloadData() self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) self.CHRGridHistory.removeFirst() // remove most recent grid from the front of the history } } func redo() { // if there's a CHR Grid in the future if let safeNextFutureGrid = self.CHRGridFuture.first { self.CHRGridHistory.insert(self.grid, at: 0) // add current grid to the front of the history self.grid = safeNextFutureGrid self.gridCollectionView.reloadData() self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) self.CHRGridFuture.removeFirst() // remove most recent grid from the front of the future } } func cutCHR() { FullGridCollectionViewController.CHRClipboard = self.grid.getCHR(atIndex: self.grid.selectedCHRIndex) if let safeCHRClipboard = FullGridCollectionViewController.CHRClipboard, !safeCHRClipboard.isEmpty() { self.CHRGridWillChange() self.grid.setCHR(chr: CHR(), atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } func copyCHR() { FullGridCollectionViewController.CHRClipboard = self.grid.getCHR(atIndex: self.grid.selectedCHRIndex) } func pasteCHR() { if let safeCHRClipboard = FullGridCollectionViewController.CHRClipboard { self.CHRGridWillChange() self.grid.setCHR(chr: safeCHRClipboard, atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } }
9bbab9932ef7f39b1675e550a6a26422
40.898551
209
0.676237
false
false
false
false
kosua20/PtahRenderer
refs/heads/master
PtahRenderer/Geometry.swift
mit
1
// // Geometry.swift // PtahRenderer // // Created by Simon Rodriguez on 14/02/2016. // Copyright © 2016 Simon Rodriguez. All rights reserved. // import Foundation #if os(macOS) import simd #endif /*--Barycentre-------*/ func barycentre(_ p: Point3, _ v0: Point3, _ v1: Point3, _ v2: Point3) -> Point3{ let ab = v1 - v0 let ac = v2 - v0 let pa = v0 - p let uv1 = cross(Point3(ac.x, ab.x, pa.x), Point3(ac.y, ab.y, pa.y)) if abs(uv1.z) < 1e-2 { return Point3(-1, 1, 1) } return (1.0/uv1.z)*Point3(uv1.z-(uv1.x+uv1.y), uv1.y, uv1.x) } func barycentricInterpolation(coeffs: Point3, t1: Point2, t2: Point2, t3: Point2) -> Point2{ return coeffs.x * t1 + coeffs.y * t2 + coeffs.z * t3 } func barycentricInterpolation(coeffs: Point3, t1: Point3, t2: Point3, t3: Point3) -> Point3{ return coeffs.x * t1 + coeffs.y * t2 + coeffs.z * t3 } func barycentricInterpolation(coeffs: Point3, t1: [Scalar], t2: [Scalar], t3: [Scalar]) -> [Scalar]{ var newOthers : [Scalar] = [] for i in 0..<t1.count { newOthers.append(coeffs.x * t1[i] + coeffs.y * t2[i] + coeffs.z * t3[i]) } return newOthers } /*--Bounding box-------------*/ func boundingBox(_ vs: [Point3], _ width: Int, _ height: Int) -> (Point2, Point2){ var mini = Point2(Scalar.infinity, Scalar.infinity) var maxi = Point2(-Scalar.infinity, -Scalar.infinity) let lim = Point2(Scalar(width-1), Scalar(height-1)) for v in vs { let v2 = Point2(v.x, v.y) mini = min(mini, v2) maxi = max(maxi, v2) } let finalMin = clamp(min(mini,maxi), min: Point2(0.0), max: lim) let finalMax = clamp(max(mini,maxi), min: Point2(0.0), max: lim) return (finalMin, finalMax) }
4e5ff1c0f535c0ab12d46ea8bf4521c2
20.384615
100
0.625899
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Internals/AudioKit.swift
mit
1
// // AudioKit.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // #if !os(tvOS) import CoreAudioKit #endif #if !os(macOS) import UIKit #endif import Dispatch public typealias AKCallback = () -> Void /// Top level AudioKit managing class @objc open class AudioKit: NSObject { // MARK: Global audio format (44.1K, Stereo) /// Format of AudioKit Nodes @objc open static var format = AKSettings.audioFormat // MARK: - Internal audio engine mechanics /// Reference to the AV Audio Engine @objc open static let engine = AVAudioEngine() @objc static var shouldBeRunning = false @objc static var finalMixer = AKMixer() /// An audio output operation that most applications will need to use last @objc open static var output: AKNode? { didSet { updateSessionCategoryAndOptions() output?.connect(to: finalMixer) engine.connect(finalMixer.avAudioNode, to: engine.outputNode) } } // MARK: - Device Management /// Enumerate the list of available input devices. @objc open static var inputDevices: [AKDevice]? { #if os(macOS) EZAudioUtilities.setShouldExitOnCheckResultFail(false) return EZAudioDevice.inputDevices().map { AKDevice(name: ($0 as AnyObject).name, deviceID: ($0 as AnyObject).deviceID) } #else var returnDevices = [AKDevice]() if let devices = AVAudioSession.sharedInstance().availableInputs { for device in devices { if device.dataSources == nil || device.dataSources!.isEmpty { returnDevices.append(AKDevice(name: device.portName, deviceID: device.uid)) } else { for dataSource in device.dataSources! { returnDevices.append(AKDevice(name: device.portName, deviceID: "\(device.uid) \(dataSource.dataSourceName)")) } } } return returnDevices } return nil #endif } /// Enumerate the list of available output devices. @objc open static var outputDevices: [AKDevice]? { #if os(macOS) EZAudioUtilities.setShouldExitOnCheckResultFail(false) return EZAudioDevice.outputDevices().map { AKDevice(name: ($0 as AnyObject).name, deviceID: ($0 as AnyObject).deviceID) } #else let devs = AVAudioSession.sharedInstance().currentRoute.outputs if devs.isNotEmpty { var outs = [AKDevice]() for dev in devs { outs.append(AKDevice(name: dev.portName, deviceID: dev.uid)) } return outs } return nil #endif } /// The name of the current input device, if available. @objc open static var inputDevice: AKDevice? { #if os(macOS) if let dev = EZAudioDevice.currentInput() { return AKDevice(name: dev.name, deviceID: dev.deviceID) } #else if let dev = AVAudioSession.sharedInstance().preferredInput { return AKDevice(name: dev.portName, deviceID: dev.uid) } else { let inputDevices = AVAudioSession.sharedInstance().currentRoute.inputs if inputDevices.isNotEmpty { for device in inputDevices { let dataSourceString = device.selectedDataSource?.description ?? "" let id = "\(device.uid) \(dataSourceString)".trimmingCharacters(in: [" "]) return AKDevice(name: device.portName, deviceID: id) } } } #endif return nil } /// The name of the current output device, if available. @objc open static var outputDevice: AKDevice? { #if os(macOS) if let dev = EZAudioDevice.currentOutput() { return AKDevice(name: dev.name, deviceID: dev.deviceID) } #else let devs = AVAudioSession.sharedInstance().currentRoute.outputs if devs.isNotEmpty { return AKDevice(name: devs[0].portName, deviceID: devs[0].uid) } #endif return nil } /// Change the preferred input device, giving it one of the names from the list of available inputs. @objc open static func setInputDevice(_ input: AKDevice) throws { #if os(macOS) var address = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyDefaultInputDevice, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMaster) var devid = input.deviceID AudioObjectSetPropertyData( AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, UInt32(MemoryLayout<AudioDeviceID>.size), &devid) #else if let devices = AVAudioSession.sharedInstance().availableInputs { for device in devices { if device.dataSources == nil || device.dataSources!.isEmpty { if device.uid == input.deviceID { do { try AVAudioSession.sharedInstance().setPreferredInput(device) } catch { AKLog("Could not set the preferred input to \(input)") } } } else { for dataSource in device.dataSources! { if input.deviceID == "\(device.uid) \(dataSource.dataSourceName)" { do { try AVAudioSession.sharedInstance().setInputDataSource(dataSource) } catch { AKLog("Could not set the preferred input to \(input)") } } } } } } if let devices = AVAudioSession.sharedInstance().availableInputs { for dev in devices { if dev.uid == input.deviceID { do { try AVAudioSession.sharedInstance().setPreferredInput(dev) } catch { AKLog("Could not set the preferred input to \(input)") } } } } #endif } /// Change the preferred output device, giving it one of the names from the list of available output. @objc open static func setOutputDevice(_ output: AKDevice) throws { #if os(macOS) var id = output.deviceID if let audioUnit = AudioKit.engine.outputNode.audioUnit { AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &id, UInt32(MemoryLayout<DeviceID>.size)) } #else //not available on ios #endif } // MARK: - Start/Stop /// Start up the audio engine with periodic functions open static func start(withPeriodicFunctions functions: AKPeriodicFunction...) { for function in functions { function.connect(to: finalMixer) } start() } /// Start up the audio engine @objc open static func start() { if output == nil { AKLog("AudioKit: No output node has been set yet, no processing will happen.") } // Start the engine. do { engine.prepare() #if os(iOS) if AKSettings.enableRouteChangeHandling { NotificationCenter.default.addObserver( self, selector: #selector(AudioKit.restartEngineAfterRouteChange), name: .AVAudioSessionRouteChange, object: nil) } if AKSettings.enableCategoryChangeHandling { NotificationCenter.default.addObserver( self, selector: #selector(AudioKit.restartEngineAfterConfigurationChange), name: .AVAudioEngineConfigurationChange, object: engine) } updateSessionCategoryAndOptions() try AVAudioSession.sharedInstance().setActive(true) #endif try engine.start() shouldBeRunning = true } catch { fatalError("AudioKit: Could not start engine. error: \(error).") } } @objc fileprivate static func updateSessionCategoryAndOptions() { #if !os(macOS) do { let sessionCategory = AKSettings.computedSessionCategory() let sessionOptions = AKSettings.computedSessionOptions() #if os(iOS) try AKSettings.setSession(category: sessionCategory, with: sessionOptions) #elseif os(tvOS) try AKSettings.setSession(category: sessionCategory) #endif } catch { fatalError("AudioKit: Could not update AVAudioSession category and options. error: \(error).") } #endif } /// Stop the audio engine @objc open static func stop() { // Stop the engine. engine.stop() shouldBeRunning = false #if os(iOS) do { try AVAudioSession.sharedInstance().setActive(false) } catch { AKLog("couldn't stop session \(error)") } #endif } // MARK: - Testing /// Testing AKNode @objc open static var tester: AKTester? /// Test the output of a given node /// /// - Parameters: /// - node: AKNode to test /// - duration: Number of seconds to test (accurate to the sample) /// @objc open static func test(node: AKNode, duration: Double, afterStart: () -> Void = {}) { #if swift(>=3.2) if #available(iOS 11, macOS 10.13, tvOS 11, *) { let samples = Int(duration * AKSettings.sampleRate) tester = AKTester(node, samples: samples) output = tester do { // maximum number of frames the engine will be asked to render in any single render call let maxNumberOfFrames: AVAudioFrameCount = 4_096 engine.reset() try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: maxNumberOfFrames) try engine.start() } catch { fatalError("could not enable manual rendering mode, \(error)") } afterStart() tester?.play() let buffer: AVAudioPCMBuffer = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat, frameCapacity: engine.manualRenderingMaximumFrameCount)! while engine.manualRenderingSampleTime < samples { do { let framesToRender = buffer.frameCapacity let status = try engine.renderOffline(framesToRender, to: buffer) switch status { case .success: // data rendered successfully break case .insufficientDataFromInputNode: // applicable only if using the input node as one of the sources break case .cannotDoInCurrentContext: // engine could not render in the current render call, retry in next iteration break case .error: // error occurred while rendering fatalError("render failed") } } catch { fatalError("render failed, \(error)") } } tester?.stop() } #endif } /// Audition the test to hear what it sounds like /// /// - Parameters: /// - node: AKNode to test /// - duration: Number of seconds to test (accurate to the sample) /// @objc open static func auditionTest(node: AKNode, duration: Double) { output = node start() if let playableNode = node as? AKToggleable { playableNode.play() } usleep(UInt32(duration * 1_000_000)) stop() start() } // MARK: - Configuration Change Response // Listen to changes in audio configuration // and restart the audio engine if it stops and should be playing @objc fileprivate static func restartEngineAfterConfigurationChange(_ notification: Notification) { DispatchQueue.main.async { if shouldBeRunning && !engine.isRunning { do { #if !os(macOS) let appIsNotActive = UIApplication.shared.applicationState != .active let appDoesNotSupportBackgroundAudio = !AKSettings.appSupportsBackgroundAudio if appIsNotActive && appDoesNotSupportBackgroundAudio { AKLog("engine not restarted after configuration change since app was not active and does not support background audio") return } #endif try engine.start() // Sends notification after restarting the engine, so it is safe to resume AudioKit functions. if AKSettings.notificationsEnabled { NotificationCenter.default.post( name: .AKEngineRestartedAfterConfigurationChange, object: nil, userInfo: notification.userInfo) } } catch { AKLog("couldn't start engine after configuration change \(error)") } } } } // Restarts the engine after audio output has been changed, like headphones plugged in. @objc fileprivate static func restartEngineAfterRouteChange(_ notification: Notification) { DispatchQueue.main.async { if shouldBeRunning && !engine.isRunning { do { #if !os(macOS) let appIsNotActive = UIApplication.shared.applicationState != .active let appDoesNotSupportBackgroundAudio = !AKSettings.appSupportsBackgroundAudio if appIsNotActive && appDoesNotSupportBackgroundAudio { AKLog("engine not restarted after route change since app was not active and does not support background audio") return } #endif try engine.start() // Sends notification after restarting the engine, so it is safe to resume AudioKit functions. if AKSettings.notificationsEnabled { NotificationCenter.default.post( name: .AKEngineRestartedAfterRouteChange, object: nil, userInfo: notification.userInfo) } } catch { AKLog("error restarting engine after route change") } } } } // MARK: - Disconnect node inputs /// Disconnect all inputs @objc open static func disconnectAllInputs() { engine.disconnectNodeInput(finalMixer.avAudioNode) } // MARK: - Deinitialization deinit { #if os(iOS) NotificationCenter.default.removeObserver( self, name: .AKEngineRestartedAfterRouteChange, object: nil) #endif } } //This extension makes connect calls shorter, and safer by attaching nodes if not already attached. extension AudioKit { // Attaches nodes if node.engine == nil private static func safeAttach(_ nodes: [AVAudioNode]) { _ = nodes.filter { $0.engine == nil }.map { engine.attach($0) } } // AVAudioMixer will crash if engine is started and connection is made to a bus exceeding mixer's // numberOfInputs. The crash only happens when using the AVAudioEngine function that connects a node to an array // of AVAudioConnectionPoints and the mixer is one of those points. When AVAudioEngine uses a different function // that connects a node's output to a single AVAudioMixerNode, the mixer's inputs are incremented to accommodate // the new connection. So the workaround is to create dummy nodes, make a connections to the mixer using the // function that makes the mixer create new inputs, then remove the dummy nodes so that there is an available // bus to connect to. // private static func checkMixerInputs(_ connectionPoints: [AVAudioConnectionPoint]) { if !engine.isRunning { return } for connection in connectionPoints { if let mixer = connection.node as? AVAudioMixerNode, connection.bus >= mixer.numberOfInputs { var dummyNodes = [AVAudioNode]() while connection.bus >= mixer.numberOfInputs { let dummyNode = AVAudioUnitSampler() dummyNode.setOutput(to: mixer) dummyNodes.append(dummyNode) } for dummyNode in dummyNodes { dummyNode.disconnectOutput() } } } } // If an AVAudioMixerNode's output connection is made while engine is running, and there are no input connections // on the mixer, subsequent connections made to the mixer will silently fail. A workaround is to connect a dummy // node to the mixer prior to making a connection, then removing the dummy node after the connection has been made. // private static func addDummyOnEmptyMixer(_ node: AVAudioNode) -> AVAudioNode? { func mixerHasInputs(_ mixer: AVAudioMixerNode) -> Bool { for i in 0..<mixer.numberOfInputs { if engine.inputConnectionPoint(for: mixer, inputBus: i) != nil { return true } } return false } // Only an issue if engine is running, node is a mixer, and mixer has no inputs guard let mixer = node as? AVAudioMixerNode, engine.isRunning, !mixerHasInputs(mixer) else { return nil } let dummy = AVAudioUnitSampler() engine.attach(dummy) engine.connect(dummy, to: mixer, format: AudioKit.format) return dummy } @objc open static func connect(_ sourceNode: AVAudioNode, to destNodes: [AVAudioConnectionPoint], fromBus sourceBus: AVAudioNodeBus, format: AVAudioFormat?) { let connectionsWithNodes = destNodes.filter { $0.node != nil } safeAttach([sourceNode] + connectionsWithNodes.map { $0.node! }) // See addDummyOnEmptyMixer for dummyNode explanation. let dummyNode = addDummyOnEmptyMixer(sourceNode) checkMixerInputs(connectionsWithNodes) engine.connect(sourceNode, to: connectionsWithNodes, fromBus: sourceBus, format: format) dummyNode?.disconnectOutput() } @objc open static func connect(_ node1: AVAudioNode, to node2: AVAudioNode, fromBus bus1: AVAudioNodeBus, toBus bus2: AVAudioNodeBus, format: AVAudioFormat?) { safeAttach([node1, node2]) // See addDummyOnEmptyMixer for dummyNode explanation. let dummyNode = addDummyOnEmptyMixer(node1) engine.connect(node1, to: node2, fromBus: bus1, toBus: bus2, format: format) dummyNode?.disconnectOutput() } @objc open static func connect(_ node1: AVAudioNode, to node2: AVAudioNode, format: AVAudioFormat?) { connect(node1, to: node2, fromBus: 0, toBus: 0, format: format) } //Convenience @objc open static func detach(nodes: [AVAudioNode]) { for node in nodes { engine.detach(node) } } /// Render output to an AVAudioFile for a duration. /// - Parameters /// - audioFile: An file initialized for writing /// - seconds: Duration to render /// - prerender: A closure called before rendering starts, use this to start players, set initial parameters, etc... /// @available(iOS 11, macOS 10.13, tvOS 11, *) @objc open static func renderToFile(_ audioFile: AVAudioFile, seconds: Double, prerender: (() -> Void)? = nil) throws { try engine.renderToFile(audioFile, seconds: seconds, prerender: prerender) } } extension AVAudioEngine { /// Adding connection between nodes with default format open func connect(_ node1: AVAudioNode, to node2: AVAudioNode) { connect(node1, to: node2, format: AudioKit.format) } /// Render output to an AVAudioFile for a duration. /// - Parameters /// - audioFile: An file initialized for writing /// - seconds: Duration to render /// - prerender: A closure called before rendering starts, use this to start players, set initial parameters, etc... /// @available(iOS 11.0, macOS 10.13, tvOS 11.0, *) public func renderToFile(_ audioFile: AVAudioFile, seconds: Double, prerender: (() -> Void)? = nil) throws { guard seconds >= 0 else { throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"Seconds needs to be a positive value"]) } // Engine can't be running when switching to offline render mode. if isRunning { stop() } try enableManualRenderingMode(.offline, format: audioFile.processingFormat, maximumFrameCount: 4096) // This resets the sampleTime of offline rendering to 0. reset() try start() guard let buffer = AVAudioPCMBuffer(pcmFormat: manualRenderingFormat, frameCapacity: manualRenderingMaximumFrameCount) else { throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"Couldn't creat buffer in renderToFile"]) } // This is for users to prepare the nodes for playing, i.e player.play() prerender?() // Render until file contains >= target samples let targetSamples = AVAudioFramePosition(seconds * manualRenderingFormat.sampleRate) while audioFile.framePosition < targetSamples { let framesToRender = min(buffer.frameCapacity, AVAudioFrameCount( targetSamples - audioFile.framePosition)) let status = try renderOffline(framesToRender, to: buffer) switch status { case .success: try audioFile.write(from: buffer) case .cannotDoInCurrentContext: print("renderToFile cannotDoInCurrentContext") continue case .error, .insufficientDataFromInputNode: throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"renderToFile render error"]) } } stop() disableManualRenderingMode() } }
16cf066cead6679a3499716f621347a7
38.3021
147
0.559191
false
false
false
false
PureSwift/Cacao
refs/heads/develop
Sources/Cacao/UIViewContentMode.swift
mit
1
// // UIViewContentMode.swift // Cacao // // Created by Alsey Coleman Miller on 5/31/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(macOS) import Darwin.C.math #elseif os(Linux) import Glibc #endif import Foundation import Silica public enum UIViewContentMode: Int { public init() { self = .scaleToFill } case scaleToFill case scaleAspectFit case scaleAspectFill case redraw case center case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight } // MARK: - Internal Cacao Extension internal extension UIViewContentMode { func rect(for bounds: CGRect, size: CGSize) -> CGRect { switch self { case .redraw: fallthrough case .scaleToFill: return CGRect(origin: .zero, size: bounds.size) case .scaleAspectFit: let widthRatio = bounds.width / size.width let heightRatio = bounds.height / size.height var newSize = bounds.size if (widthRatio < heightRatio) { newSize.height = bounds.size.width / size.width * size.height } else if (heightRatio < widthRatio) { newSize.width = bounds.size.height / size.height * size.width } newSize = CGSize(width: ceil(newSize.width), height: ceil(newSize.height)) var origin = bounds.origin origin.x += (bounds.size.width - newSize.width) / 2.0 origin.y += (bounds.size.height - newSize.height) / 2.0 return CGRect(origin: origin, size: newSize) case .scaleAspectFill: let widthRatio = (bounds.size.width / size.width) let heightRatio = (bounds.size.height / size.height) var newSize = bounds.size if (widthRatio > heightRatio) { newSize.height = bounds.size.width / size.width * size.height } else if (heightRatio > widthRatio) { newSize.width = bounds.size.height / size.height * size.width } newSize = CGSize(width: ceil(newSize.width), height: ceil(newSize.height)) var origin = CGPoint() origin.x = (bounds.size.width - newSize.width) / 2.0 origin.y = (bounds.size.height - newSize.height) / 2.0 return CGRect(origin: origin, size: newSize) case .center: var rect = CGRect(origin: .zero, size: size) rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .top: var rect = CGRect(origin: .zero, size: size) rect.origin.y = 0.0 rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 return rect case .bottom: var rect = CGRect(origin: .zero, size: size) rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = bounds.size.height - rect.size.height return rect case .left: var rect = CGRect(origin: .zero, size: size) rect.origin.x = 0.0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .right: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .topLeft: return CGRect(origin: .zero, size: size) case .topRight: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = 0.0 return rect case .bottomLeft: var rect = CGRect(origin: .zero, size: size) rect.origin.x = 0.0 rect.origin.y = bounds.size.height - rect.size.height return rect case .bottomRight: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = bounds.size.height - rect.size.height return rect } } }
f6029cd3fe6efa33c30e922269d39a8f
27.772727
86
0.484795
false
false
false
false
gluecode/ImagePickerSheetStoryBoard
refs/heads/master
photoSheetTest/ViewController.swift
mit
1
// // ViewController.swift // photoSheetTest // // Created by Sunil Karkera on 5/22/15. // import UIKit import Photos import ImagePickerSheet class ViewController: UIViewController, ImagePickerSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var photoButton: UIButton! 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. } @IBAction func onPhotoButton(sender: AnyObject) { let sheet = ImagePickerSheet() sheet.numberOfButtons = 3 sheet.delegate = self sheet.showInView(view) } func imagePickerSheet(imagePickerSheet: ImagePickerSheet, titleForButtonAtIndex buttonIndex: Int) -> String { let photosSelected = (imagePickerSheet.selectedPhotos.count > 0) if (buttonIndex == 0) { if photosSelected { return NSLocalizedString("Add comment", comment: "Add comment") } else { return NSLocalizedString("Take Photo Or Video", comment: "Take Photo Or Video") } } else { if photosSelected { return NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "The secondary title of the image picker sheet to send the photos"), imagePickerSheet.selectedPhotos.count) } else { return NSLocalizedString("Photo Library", comment: "Photo Library") } } } func imagePickerSheet(imagePickerSheet: ImagePickerSheet, willDismissWithButtonIndex buttonIndex: Int) { if buttonIndex != imagePickerSheet.cancelButtonIndex { if imagePickerSheet.selectedPhotos.count > 0 { println(imagePickerSheet.selectedPhotos) } else { let controller = UIImagePickerController() controller.delegate = self controller.sourceType = (buttonIndex == 2) ? .PhotoLibrary : .Camera presentViewController(controller, animated: true, completion: nil) } } } }
174dbe77f545e2794e725f08a9d17cb5
34
235
0.636134
false
false
false
false
MinMao-Hub/MMActionSheet
refs/heads/master
Sources/MMActionSheet/MMActionSheet.swift
mit
1
// // MMActionSheet.swift // swiftui // // Created by 郭永红 on 2017/10/9. // Copyright © 2017年 keeponrunning. All rights reserved. // import UIKit public class MMActionSheet: UIView { /// MMSelectionClosure public typealias MMSelectionClosure = (_ item: MMButtonItem?) -> Void /// SelectionClosure public var selectionClosure: MMSelectionClosure? /// top cornerRadius public var topCornerRadius: CGFloat = 0 /// Parmeters private var title: MMTitleItem? private var buttons: [MMButtonItem] = [] private var duration: Double? private var cancelButton: MMButtonItem? /// Constants private struct Constants { /// 按钮与按钮之间的分割线高度 static let mmdivideLineHeight: CGFloat = 1 /// 屏幕Bounds static let mmscreenBounds = UIScreen.main.bounds /// 屏幕大小 static let mmscreenSize = UIScreen.main.bounds.size /// 屏幕宽度 static let mmscreenWidth = mmscreenBounds.width /// 屏幕高度 static let mmscreenHeight = mmscreenBounds.height /// button高度 static let mmbuttonHeight: CGFloat = 48.0 * mmscreenBounds.width / 375 /// 标题的高度 static let mmtitleHeight: CGFloat = 40.0 * mmscreenBounds.width / 375 /// 取消按钮与其他按钮之间的间距 static let mmbtnPadding: CGFloat = 5 * mmscreenBounds.width / 375 /// mmdefaultDuration static let mmdefaultDuration = 0.25 /// sheet的最大高度 static let mmmaxHeight = mmscreenHeight * 0.62 /// 适配iphoneX static let paddng_bottom: CGFloat = MMTools.isIphoneX ? 34.0 : 0.0 } /// ActionSheet private var actionSheetView: UIView = UIView() private var actionSheetHeight: CGFloat = 0 public var actionSheetViewBackgroundColor: UIColor? = MMTools.DefaultColor.backgroundColor /// scrollView private var scrollView: UIScrollView = UIScrollView() public var buttonBackgroundColor: UIColor? /// Init override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 初始化 /// /// - Parameters: /// - title: 标题 /// - buttons: 按钮数组 /// - duration: 动画时长 /// - cancel: 是否需要取消按钮 public convenience init( title: MMTitleItem?, buttons: [MMButtonItem], duration: Double?, cancelButton: MMButtonItem? ) { /// 半透明背景 self.init(frame: Constants.mmscreenBounds) self.title = title self.buttons = buttons self.duration = duration ?? Constants.mmdefaultDuration self.cancelButton = cancelButton /// 添加单击事件,隐藏sheet let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapDismiss)) singleTap.delegate = self addGestureRecognizer(singleTap) /// actionSheet initActionSheet() /// 初始化UI initUI() } func initActionSheet() { let btnCount = buttons.count var tHeight: CGFloat = 0.0 if title != nil { tHeight = Constants.mmtitleHeight } var cancelHeight: CGFloat = 0.0 if cancelButton != nil { cancelHeight = Constants.mmbuttonHeight + Constants.mmbtnPadding } let contentHeight = CGFloat(btnCount) * Constants.mmbuttonHeight + CGFloat(btnCount) * Constants.mmdivideLineHeight let height = min(contentHeight, Constants.mmmaxHeight - tHeight - cancelHeight) scrollView.frame = CGRect(x: 0, y: tHeight, width: Constants.mmscreenWidth, height: height) actionSheetView.addSubview(scrollView) actionSheetHeight = tHeight + height + cancelHeight + Constants.paddng_bottom let aFrame: CGRect = CGRect(x: 0, y: Constants.mmscreenHeight, width: Constants.mmscreenWidth, height: actionSheetHeight) actionSheetView.frame = aFrame addSubview(actionSheetView) /// 根据内容高度计算动画时长 duration = duration ?? (Constants.mmdefaultDuration * Double(actionSheetHeight / 216)) } func initUI() { /// setTitleView setTitleView() /// setButtons setButtons() /// Cancel Button setCancelButton() /// setExtraView setExtraView() } /// Title private func setTitleView() { /// 标题不为空,则添加标题 if title != nil { let titleFrame = CGRect(x: 0, y: 0, width: Constants.mmscreenWidth, height: Constants.mmtitleHeight) let titlelabel = UILabel(frame: titleFrame) titlelabel.text = title!.text titlelabel.textAlignment = title!.textAlignment! titlelabel.textColor = title!.textColor titlelabel.font = title!.textFont titlelabel.backgroundColor = title!.backgroundColor?.rawValue actionSheetView.addSubview(titlelabel) } } /// Buttons private func setButtons() { let contentHeight = CGFloat(buttons.count) * Constants.mmbuttonHeight + CGFloat(buttons.count) * Constants.mmdivideLineHeight let view = UIView(frame: CGRect(x: 0, y: 0, width: Constants.mmscreenWidth, height: contentHeight)) view.clipsToBounds = true scrollView.addSubview(view) scrollView.contentSize = CGSize(width: Constants.mmscreenWidth, height: contentHeight) let buttonsCount = buttons.count for index in 0 ..< buttonsCount { let item = buttons[index] let origin_y = Constants.mmbuttonHeight * CGFloat(index) + Constants.mmdivideLineHeight * CGFloat(index) let button = MMButton(type: .custom) button.frame = CGRect(x: 0.0, y: origin_y, width: Constants.mmscreenWidth, height: Constants.mmbuttonHeight) /// Button Item button.item = item button.addTarget(self, action: #selector(actionClick), for: .touchUpInside) view.addSubview(button) } } /// ExtraView private func setExtraView() { guard MMTools.isIphoneX else { return } let frame = CGRect(x: 0, y: self.actionSheetView.bounds.size.height - Constants.paddng_bottom, width: Constants.mmscreenWidth, height: Constants.paddng_bottom) let extraView = UIView() extraView.frame = frame if cancelButton != nil { extraView.backgroundColor = cancelButton?.backgroudImageColorNormal?.rawValue } else { let bgColor = buttons.first?.backgroudImageColorNormal?.rawValue extraView.backgroundColor = bgColor } self.actionSheetView.addSubview(extraView) } /// Cancel Button private func setCancelButton() { /// 如果取消为ture则添加取消按钮 if cancelButton != nil { let button = MMButton(type: .custom) button.frame = CGRect(x: 0, y: actionSheetView.bounds.size.height - Constants.mmbuttonHeight - Constants.paddng_bottom, width: Constants.mmscreenWidth, height: Constants.mmbuttonHeight) button.item = cancelButton button.addTarget(self, action: #selector(actionClick), for: .touchUpInside) actionSheetView.addSubview(button) } } private func updateTopCornerMask() { guard topCornerRadius > 0 else { return } let shape = CAShapeLayer() let path = UIBezierPath(roundedRect: actionSheetView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: topCornerRadius, height: topCornerRadius)) shape.path = path.cgPath shape.frame = actionSheetView.bounds actionSheetView.layer.mask = shape } /// 修改样式 override public func layoutSubviews() { super.layoutSubviews() /// 顶部圆角 updateTopCornerMask() } } //MARK: Event extension MMActionSheet { /// items action @objc func actionClick(button: MMButton) { dismiss() guard let item = button.item else { return } /// Callback selectionClosure?(item) } //tap action @objc func singleTapDismiss() { dismiss() /// Callback selectionClosure?(nil) } } //MARK: present, dismiss extension MMActionSheet { /// 显示 public func present() { if #available(iOS 13.0, *) { if let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first { keyWindow.addSubview(self) } } else { UIApplication.shared.keyWindow?.addSubview(self) } UIView.animate(withDuration: 0.1, animations: { [self] in /// backgroundColor self.actionSheetView.backgroundColor = actionSheetViewBackgroundColor }) { (_: Bool) in UIView.animate(withDuration: self.duration!) { self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3) self.actionSheetView.transform = CGAffineTransform(translationX: 0, y: -self.actionSheetView.frame.size.height) } } } /// 隐藏 func dismiss() { UIView.animate(withDuration: duration!, animations: { self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) self.actionSheetView.transform = .identity }) { (_: Bool) in self.removeFromSuperview() } } } // MARK: - UIGestureRecognizerDelegate extension MMActionSheet: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard touch.view == actionSheetView else { return true } return false } }
d6d39f108841ffd3006e9aebfaaea68c
33.179577
197
0.629855
false
false
false
false
CoderJChen/SWWB
refs/heads/master
CJWB/CJWB/Classes/Profile/Tools/category/UITextView-Extension.swift
apache-2.0
1
// // UITextView-Extension.swift // CJWB // // Created by 星驿ios on 2017/9/14. // Copyright © 2017年 CJ. All rights reserved. // import UIKit extension UITextView{ /// 获取textView属性字符串,对应的表情字符串 func getEmotionString() -> String{ // 1、获取属性字符串 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 2、遍历属性字符串 let range = NSRange(location: 0, length: attrMStr.length) attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in if let attachment = dict["NSAttachment"] as? CJEmotionAttachment{ attrMStr.replaceCharacters(in: range, with: attachment.chs!) } } // 3、获取字符串 return attrMStr.string } // 给textView插入表情 func insertEmotion(emotion : CJEmotionModel){ // 1、空白表情 if emotion.isEmpty { return } // 2、删除按钮 if emotion.isRemove { return } // 3、emoji表情 if emotion.emojiCode != nil { // 3.1 获取光标所在位置:UITextView let textRange = selectedTextRange // 3.2 替换emoji表情 replace(textRange!, withText: emotion.emojiCode!) return } // 4、普通表情:图文混排 // 4.1根据图片路径创建属性字符串 let attachment = CJEmotionAttachment() attachment.chs = emotion.chs attachment.image = UIImage(contentsOfFile: emotion.pngPath!) let font = self.font! attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) let attrImageStr = NSAttributedString(attachment: attachment) // 4.2 创建可变的属性字符串你 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 4.3 将图片属性字符串,替换到可变属性字符串的某一个位置 // 4.3.1 获取光标所在位置 let range = selectedRange // 4.3.2 替换属性字符串 attrMStr.replaceCharacters(in: range, with: attrImageStr) // 显示属性字符串 attributedText = attrMStr // 将文字的大小重置 self.font = font // 将光标设置回原来的位置+1 selectedRange = NSRange(location: range.location + 1, length: 0) } }
8de8b79008721b0539d050d17643c251
29.166667
96
0.587477
false
false
false
false
dawsonbotsford/MobileAppsFall2015
refs/heads/master
iOS/lab7/lab7/ViewController.swift
mit
1
// // ViewController.swift // lab7 // // Created by Dawson Botsford on 10/15/15. // Copyright © 2015 Dawson Botsford. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate{ var audioPlayer: AVAudioPlayer? var audioRecorder: AVAudioRecorder? let fileName = "audio.caf" @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBAction func recordAction(sender: AnyObject) { if audioRecorder?.recording == false { playButton.enabled = false stopButton.enabled = true audioRecorder?.record() } } @IBAction func playAction(sender: AnyObject) { if audioRecorder?.recording == false{ stopButton.enabled = true recordButton.enabled = false do { audioPlayer = try AVAudioPlayer(contentsOfURL: (audioRecorder?.url)!) audioPlayer?.delegate = self audioPlayer?.play() } catch let error { print("AVAudioPlayer error: \(error)") } } } @IBAction func stopAction(sender: AnyObject) { stopButton.enabled = false playButton.enabled = true recordButton.enabled = true if audioRecorder?.recording == true { audioRecorder?.stop() } else { audioPlayer?.stop() } } override func viewDidLoad() { playButton.enabled = false stopButton.enabled = false let dirPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let docDir = dirPath[0] let audioFilePath = docDir.stringByAppendingString(fileName) let audioFileURL = NSURL(fileURLWithPath: audioFilePath) let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, AVEncoderBitRateKey: 16, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0] let error: NSError! //audioRecorder = AVAudioRecorder(URL: <#T##NSURL#>, settings: <#T##[String : AnyObject]#>), do { audioRecorder=try AVAudioRecorder(URL: audioFileURL, settings: recordSettings as! [String : AnyObject]) audioRecorder?.delegate = self audioRecorder?.meteringEnabled = true audioRecorder?.prepareToRecord() } catch let error { audioRecorder = nil print(error) } //audioRecorder = AVAudioRecorder(URL: audioFileURL, settings: recordSettings as! [String: AnyObject], error: &error) /* if let err = error { print("AVAudioRecorder error: \(err.localizedDescription)") } else { audioRecorder?.delegate = self audioRecorder?.prepareToRecord() }*/ 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. } }
3f5e22a210e080a54b40e26c52e503f3
30.266055
161
0.598005
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/toplevel.swift
apache-2.0
4
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func markUsed<T>(_ t: T) {} func trap() -> Never { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): // -- initialize x // CHECK: alloc_global @_T08toplevel1xSiv // CHECK: [[X:%[0-9]+]] = global_addr @_T08toplevel1xSiv : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [trivial] [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_T08toplevel7print_xyyF : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_T08toplevel5countSiv // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_T08toplevel5countSiv : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [trivial] [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_T08toplevel1ySiv // CHECK: [[Y1:%[0-9]+]] = global_addr @_T08toplevel1ySiv : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_T08toplevel7print_yyyF y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A // CHECK-NOT: destroy_value // CHECK: [[SINK:%.+]] = function_ref @_T08toplevel8markUsedyxlF // CHECK-NOT: destroy_value // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_T08toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_T08toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_T08toplevel7print_xyyF // CHECK-LABEL: sil hidden @_T08toplevel7print_yyyF // CHECK: sil hidden @_T08toplevel13testGlobalCSESiyF // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_T08toplevel1xSiv : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
135b0b659ad91c018f41bfb8a2b92032
25.766129
119
0.639349
false
false
false
false
apple/swift-experimental-string-processing
refs/heads/main
Sources/_StringProcessing/Engine/MEBuiltins.swift
apache-2.0
1
@_implementationOnly import _RegexParser // For AssertionKind extension Character { var _isHorizontalWhitespace: Bool { self.unicodeScalars.first?.isHorizontalWhitespace == true } var _isNewline: Bool { self.unicodeScalars.first?.isNewline == true } } extension Processor { mutating func matchBuiltin( _ cc: _CharacterClassModel.Representation, _ isInverted: Bool, _ isStrictASCII: Bool, _ isScalarSemantics: Bool ) -> Bool { guard let next = _doMatchBuiltin( cc, isInverted, isStrictASCII, isScalarSemantics ) else { signalFailure() return false } currentPosition = next return true } func _doMatchBuiltin( _ cc: _CharacterClassModel.Representation, _ isInverted: Bool, _ isStrictASCII: Bool, _ isScalarSemantics: Bool ) -> Input.Index? { guard let char = load(), let scalar = loadScalar() else { return nil } let asciiCheck = (char.isASCII && !isScalarSemantics) || (scalar.isASCII && isScalarSemantics) || !isStrictASCII var matched: Bool var next: Input.Index switch (isScalarSemantics, cc) { case (_, .anyGrapheme): next = input.index(after: currentPosition) case (_, .anyScalar): next = input.unicodeScalars.index(after: currentPosition) case (true, _): next = input.unicodeScalars.index(after: currentPosition) case (false, _): next = input.index(after: currentPosition) } switch cc { case .any, .anyGrapheme: matched = true case .anyScalar: if isScalarSemantics { matched = true } else { matched = input.isOnGraphemeClusterBoundary(next) } case .digit: if isScalarSemantics { matched = scalar.properties.numericType != nil && asciiCheck } else { matched = char.isNumber && asciiCheck } case .horizontalWhitespace: if isScalarSemantics { matched = scalar.isHorizontalWhitespace && asciiCheck } else { matched = char._isHorizontalWhitespace && asciiCheck } case .verticalWhitespace: if isScalarSemantics { matched = scalar.isNewline && asciiCheck } else { matched = char._isNewline && asciiCheck } case .newlineSequence: if isScalarSemantics { matched = scalar.isNewline && asciiCheck if matched && scalar == "\r" && next != input.endIndex && input.unicodeScalars[next] == "\n" { // Match a full CR-LF sequence even in scalar semantics input.unicodeScalars.formIndex(after: &next) } } else { matched = char._isNewline && asciiCheck } case .whitespace: if isScalarSemantics { matched = scalar.properties.isWhitespace && asciiCheck } else { matched = char.isWhitespace && asciiCheck } case .word: if isScalarSemantics { matched = scalar.properties.isAlphabetic && asciiCheck } else { matched = char.isWordCharacter && asciiCheck } } if isInverted { matched.toggle() } guard matched else { return nil } return next } func isAtStartOfLine(_ payload: AssertionPayload) -> Bool { if currentPosition == subjectBounds.lowerBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input[input.index(before: currentPosition)].isNewline case .unicodeScalar: return input.unicodeScalars[input.unicodeScalars.index(before: currentPosition)].isNewline } } func isAtEndOfLine(_ payload: AssertionPayload) -> Bool { if currentPosition == subjectBounds.upperBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input[currentPosition].isNewline case .unicodeScalar: return input.unicodeScalars[currentPosition].isNewline } } mutating func builtinAssert(by payload: AssertionPayload) throws -> Bool { // Future work: Optimize layout and dispatch switch payload.kind { case .startOfSubject: return currentPosition == subjectBounds.lowerBound case .endOfSubjectBeforeNewline: if currentPosition == subjectBounds.upperBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input.index(after: currentPosition) == subjectBounds.upperBound && input[currentPosition].isNewline case .unicodeScalar: return input.unicodeScalars.index(after: currentPosition) == subjectBounds.upperBound && input.unicodeScalars[currentPosition].isNewline } case .endOfSubject: return currentPosition == subjectBounds.upperBound case .resetStartOfMatch: fatalError("Unreachable, we should have thrown an error during compilation") case .firstMatchingPositionInSubject: return currentPosition == searchBounds.lowerBound case .textSegment: return input.isOnGraphemeClusterBoundary(currentPosition) case .notTextSegment: return !input.isOnGraphemeClusterBoundary(currentPosition) case .startOfLine: return isAtStartOfLine(payload) case .endOfLine: return isAtEndOfLine(payload) case .caretAnchor: if payload.anchorsMatchNewlines { return isAtStartOfLine(payload) } else { return currentPosition == subjectBounds.lowerBound } case .dollarAnchor: if payload.anchorsMatchNewlines { return isAtEndOfLine(payload) } else { return currentPosition == subjectBounds.upperBound } case .wordBoundary: if payload.usesSimpleUnicodeBoundaries { // TODO: How should we handle bounds? return atSimpleBoundary(payload.usesASCIIWord, payload.semanticLevel) } else { return input.isOnWordBoundary(at: currentPosition, using: &wordIndexCache, &wordIndexMaxIndex) } case .notWordBoundary: if payload.usesSimpleUnicodeBoundaries { // TODO: How should we handle bounds? return !atSimpleBoundary(payload.usesASCIIWord, payload.semanticLevel) } else { return !input.isOnWordBoundary(at: currentPosition, using: &wordIndexCache, &wordIndexMaxIndex) } } } }
129418879857af965b071324356a57c5
29.642157
103
0.664694
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
169. Camera/Camera/GLPreviewViewController.swift
mit
1
// // GLPreviewViewController.swift // Camera // // Created by Matteo Caldari on 28/01/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import GLKit import CoreImage import OpenGLES class GLPreviewViewController: UIViewController, CameraPreviewViewController, CameraFramesDelegate { var cameraController:CameraController? { didSet { cameraController?.framesDelegate = self } } private var glContext:EAGLContext? private var ciContext:CIContext? private var renderBuffer:GLuint = GLuint() private var filter = CIFilter(name:"CIPhotoEffectMono") private var glView:GLKView { get { return view as! GLKView } } override func loadView() { self.view = GLKView() } override func viewDidLoad() { super.viewDidLoad() glContext = EAGLContext(API: .OpenGLES2) glView.context = glContext! glView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) if let window = glView.window { glView.frame = window.bounds } ciContext = CIContext(EAGLContext: glContext!) } // MARK: CameraControllerDelegate func cameraController(cameraController: CameraController, didOutputImage image: CIImage) { if glContext != EAGLContext.currentContext() { EAGLContext.setCurrentContext(glContext) } glView.bindDrawable() filter!.setValue(image, forKey: "inputImage") let outputImage = filter!.outputImage ciContext?.drawImage(outputImage!, inRect:image.extent, fromRect: image.extent) glView.display() } }
d237288df9989992c3fd9a7d1546e2e9
20.323944
100
0.73646
false
false
false
false
techgrains/TGFramework-iOS
refs/heads/master
TGFrameworkExample/TGFrameworkExample/Classes/Controller/ServiceViewController.swift
apache-2.0
1
import UIKit import TGFramework class ServiceViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var serviceListTableView:UITableView! var serviceList = [Any]() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = false // self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 125/255, green: 194/255, blue: 66/255, alpha: 1) // self.navigationController?.navigationBar.tintColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) // self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1)] self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] /** * Add service name in list */ serviceList.append(["Service Name": "Create Employee"]) serviceList.append(["Service Name": "Employee List"]) serviceList.append(["Service Name": "Employee List with Name"]) serviceListTableView.reloadData() serviceListTableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.title = "Service List" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table Delegate /** * Render List of Service Name */ func numberOfSections(in aTableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return serviceList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell?.selectionStyle = UITableViewCellSelectionStyle.none let servicaNameDic = serviceList[indexPath.row] as! Dictionary<String, Any> cell?.textLabel?.text = servicaNameDic["Service Name"] as! String? cell?.textLabel?.textColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if(TGSession.isInternetAvailable()) { self.navigationItem.title = "Back" if (indexPath.row == 0) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "CreateEmployeeServiceVC") as! CreateEmployeeServiceViewController self.navigationController?.pushViewController(viewController, animated: true) } else if(indexPath.row == 1) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "EmployeeListVC") as! EmployeeListViewController self.navigationController?.pushViewController(viewController, animated: true) } else if(indexPath.row == 2) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "FilterEmployeeListVC") as! FilterEmployeeListViewController self.navigationController?.pushViewController(viewController, animated: true) } } else { TGUtil.showAlertView("Sorry", message: "Internet is not reachable.") } } }
b36c953dc736a1c8af90dcd16d4f52c4
46.158537
180
0.682441
false
false
false
false
chen392356785/DouyuLive
refs/heads/master
DouyuLive/DouyuLive/Classes/Tools/Extension/AnchorModel.swift
mit
1
// // AnchorModel.swift // DouyuLive // // Created by chenxiaolei on 2016/9/30. // Copyright © 2016年 chenxiaolei. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播 1 : 手机直播 var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
a8bb8a90b203867b1914f649a5973cc6
19.361111
72
0.557981
false
false
false
false
omise/omise-ios
refs/heads/master
OmiseSDK/PaymentOptionTableViewCell.swift
mit
1
import UIKit class PaymentOptionTableViewCell: UITableViewCell { let separatorView = UIView() @IBInspectable var separatorHeight: CGFloat = 1 override init(style: TableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initializeInstance() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeInstance() } private func initializeInstance() { addSubview(separatorView) let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = UIColor.selectedCellBackgroundColor self.selectedBackgroundView = selectedBackgroundView } override func layoutSubviews() { super.layoutSubviews() contentView.frame.size.height = bounds.height - separatorHeight var separatorFrame = bounds if let textLabel = self.textLabel { let textLabelFrame = self.convert(textLabel.frame, from: contentView) (_, separatorFrame) = separatorFrame.divided(atDistance: textLabelFrame.minX, from: .minXEdge) } else { (_, separatorFrame) = separatorFrame.divided(atDistance: layoutMargins.left, from: .minXEdge) } separatorFrame.origin.y = bounds.height - separatorHeight separatorFrame.size.height = separatorHeight separatorView.frame = separatorFrame } }
e148ce19cffdf54e82764674c3f9e1dd
33.97619
106
0.675289
false
false
false
false