repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
manuelbl/WirekiteMac | Examples/Servo/Servo/ViewController.swift | 1 | 1464 | //
// Wirekite for MacOS
//
// Copyright (c) 2017 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
import Cocoa
import AVFoundation
import WirekiteMac
class ViewController: NSViewController, WirekiteServiceDelegate {
var service: WirekiteService? = nil
var device: WirekiteDevice? = nil
var servo: Servo?
var timer: Timer?
var angle = 0.0
var angleInc = 30.0
override func viewDidLoad() {
super.viewDidLoad()
service = WirekiteService()
service?.delegate = self
service?.start()
}
func connectedDevice(_ device: WirekiteDevice!) {
self.device = device
device.configurePWMTimer(0, frequency: 100, attributes: [])
servo = Servo(device: device, pin: 10)
servo!.turnOn(initialAngle: 0)
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
timer in self.moveServo()
}
}
func disconnectedDevice(_ device: WirekiteDevice!) {
if self.device == device {
self.device = nil
timer?.invalidate()
timer = nil
}
}
func moveServo() {
angle += angleInc
if angle > 180.9 {
angleInc = -30.0
angle = 150.0
}
if angle < 0 {
angleInc = 30.0
angle = 30.0
}
servo!.move(toAngle: angle)
}
}
| mit | 8b0fb1b3732e220da880d83c33a360f5 | 22.238095 | 74 | 0.564891 | 4.344214 | false | false | false | false |
Swamii/adventofcode2016 | Sources/day1.swift | 1 | 2814 | import Foundation
struct Day1 {
struct Position: Hashable {
var vertical: Int
var horizontal: Int
var fromStart: Int {
return abs(horizontal) + abs(vertical)
}
var hashValue: Int {
return (31 &* vertical.hashValue) &+ vertical.hashValue
}
}
class Actor {
var position = Position(vertical: 0, horizontal: 0)
var facing = CompassPoint.north
var history: Set<Position> = Set()
var firstVisitedTwice: Position?
func move(path: String) {
let index = path.index(path.startIndex, offsetBy: 1)
guard let side = Side(rawValue: path.substring(to: index)) else {
print("Direction not found in path: \(path)")
return
}
guard let steps = Int(path.substring(from: index)) else {
print("Number of steps not found in path: \(path)")
return
}
// print("New instructions: \(side) \(steps)" )
setDirection(side: side)
// print("Now facing \(facing)")
setPosition(steps: steps)
// print("New position \(position)")
}
func setDirection(side: Side) {
switch side {
case .left:
facing = CompassPoint(rawValue: facing.rawValue - 1) ?? CompassPoint.last
case .right:
facing = CompassPoint(rawValue: facing.rawValue + 1) ?? CompassPoint.first
}
}
func setPosition(steps: Int) {
for _ in 1...steps {
history.insert(position)
switch facing {
case .north:
position.vertical += 1
case .east:
position.horizontal += 1
case .south:
position.vertical -= 1
case .west:
position.horizontal -= 1
}
if firstVisitedTwice == nil && history.contains(position) {
firstVisitedTwice = position
}
}
}
}
public static func run(input: String) {
let actor = Actor()
for movement in input.components(separatedBy: ", ") {
actor.move(path: movement)
}
print("Done. Moved \(actor.position.fromStart) blocks away from startpoint")
if let visitedTwice = actor.firstVisitedTwice {
print(
"First position visited twice was \(visitedTwice).",
"\(visitedTwice.fromStart) blocks away"
)
}
}
}
func == (lhs: Day1.Position, rhs: Day1.Position) -> Bool {
return lhs.vertical == rhs.vertical && lhs.horizontal == rhs.horizontal
}
| mit | bbe9cc87e62b40e2bf6a235a98cd6538 | 28.621053 | 90 | 0.507463 | 4.954225 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/FalconTextView.swift | 1 | 1190 | //
// FalconTextView.swift
// Pigeon-project
//
// Created by Roman Mizin on 12/11/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
class FalconTextView: UITextView {
convenience init() {
self.init(frame: .zero)
font = MessageFontsAppearance.defaultMessageTextFont
backgroundColor = .clear
isEditable = false
isScrollEnabled = false
dataDetectorTypes = .all
linkTextAttributes = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let pos = closestPosition(to: point) else { return false }
guard let range = tokenizer.rangeEnclosingPosition(pos, with: .character, inDirection: .layout(.left)) else { return false }
let startIndex = offset(from: beginningOfDocument, to: range.start)
return attributedText.attribute(NSAttributedString.Key.link, at: startIndex, effectiveRange: nil) != nil
}
}
| gpl-3.0 | bda8d6e45ca4b9b7232a290207fcbc3d | 28.725 | 126 | 0.718251 | 4.355311 | false | false | false | false |
wftllc/hahastream | Haha Stream/Features/Sport/DateListViewController.swift | 1 | 2911 | import UIKit
protocol DateListDelegate: class {
func dateListDidSelect(date: Date);
}
class DateListViewController: UITableViewController {
var sport: Sport!
weak var delegate: DateListDelegate?;
var dates:[Date]!;
let daysToShow = 1000;
var dateFormatter: DateFormatter = {
let df = DateFormatter();
df.locale = Locale.current;
df.dateStyle = .medium;
return df;
}()
var dateFormatterDayOfWeek: DateFormatter = {
let df = DateFormatter();
df.locale = Locale.current;
df.dateFormat = "EEE";
return df;
}()
func refreshData() {
setupDates();
tableView.reloadData();
tableView.remembersLastFocusedIndexPath = true;
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = sport.name
refreshData()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.tableView.selectRow(at: IndexPath(row: 1, section: 0), animated: false, scrollPosition: .none);
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshData()
}
override func indexPathForPreferredFocusedView(in tableView: UITableView) -> IndexPath? {
return IndexPath(item: 1, section: 0);
}
func setupDates() {
dates = [];
let calendar = Calendar.current;
let today = Date();
let tomorrow = calendar.date(byAdding: .day, value: 1, to: today);
dates.append(tomorrow!);
dates.append(today);
for i in 1 ... daysToShow {
dates.append(calendar.date(byAdding: .day, value: -i, to: today)!);
}
}
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 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dates.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "dateRightDetailCell", for: indexPath);
let date = self.dates[indexPath.row];
let calendar = Calendar.current;
let title: String;
if( calendar.isDateInToday(date)) {
let weekday = dateFormatterDayOfWeek.string(from: date);
title = "Today (\(weekday))"
}
else if( calendar.isDateInYesterday(date)) {
let weekday = dateFormatterDayOfWeek.string(from: date);
title = "Yesterday (\(weekday))"
}
else if( calendar.isDateInTomorrow(date)) {
let weekday = dateFormatterDayOfWeek.string(from: date);
title = "Tomorrow (\(weekday))";
}
else {
title = self.dateFormatter.string(from: date);
}
cell.textLabel?.text = title;
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let date = self.dates[indexPath.row];
self.delegate?.dateListDidSelect(date: date);
}
}
| mit | 9b0078e9a3e150a33c0844bc3d920917 | 24.761062 | 106 | 0.704569 | 3.736842 | false | false | false | false |
DAloG/BlueCap | BlueCap/Peripheral/PeripheralManagerAdvertisedServicesViewController.swift | 1 | 4413 | //
// PeripheralManagerAdvertisedServicesViewController.swift
// BlueCap
//
// Created by Troy Stribling on 10/2/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class PeripheralManagerAdvertisedServicesViewController: UITableViewController {
struct MainStoryboard {
static let peripheralManagerAddAdvertisedServiceSegue = "PeripheralManagerAddAdvertisedService"
static let peripheralManagerAdvertisedServiceCell = "PeripheralManagerAdvertisedServiceCell"
}
var peripheral : String?
var peripheralManagerViewController : PeripheralManagerViewController?
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Advertised Services"
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
self.tableView.reloadData()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == MainStoryboard.peripheralManagerAddAdvertisedServiceSegue {
let viewController = segue.destinationViewController as! PeripheralManagerAddAdvertisedServiceViewController
viewController.peripheral = self.peripheral
if let peripheralManagerViewController = self.peripheralManagerViewController {
viewController.peripheralManagerViewController = peripheralManagerViewController
}
}
}
func didResignActive() {
Logger.debug()
if let peripheralManagerViewController = self.peripheralManagerViewController {
self.navigationController?.popToViewController(peripheralManagerViewController, animated:false)
}
}
func didBecomeActive() {
Logger.debug()
}
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
if let peripheral = self.peripheral {
return PeripheralStore.getAdvertisedPeripheralServicesForPeripheral(peripheral).count
} else {
return 0
}
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerAdvertisedServiceCell, forIndexPath: indexPath) as! NameUUIDCell
if let peripheral = self.peripheral {
let serviceUUID = PeripheralStore.getAdvertisedPeripheralServicesForPeripheral(peripheral)[indexPath.row]
cell.uuidLabel.text = serviceUUID.UUIDString
if let service = PeripheralManager.sharedInstance.service(serviceUUID) {
cell.nameLabel.text = service.name
} else {
cell.nameLabel.text = "Unknown"
}
} else {
cell.uuidLabel.text = "Unknown"
cell.nameLabel.text = "Unknown"
}
return cell
}
override func tableView(tableView:UITableView, canEditRowAtIndexPath indexPath:NSIndexPath) -> Bool {
return true
}
override func tableView(tableView:UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) {
if editingStyle == .Delete {
if let peripheral = self.peripheral {
let serviceUUIDs = PeripheralStore.getAdvertisedPeripheralServicesForPeripheral(peripheral)
PeripheralStore.removeAdvertisedPeripheralService(peripheral, service:serviceUUIDs[indexPath.row])
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Fade)
}
}
}
}
| mit | 4030b3068140f6eaf5c4e6b163c790fb | 39.861111 | 159 | 0.70383 | 6.120666 | false | false | false | false |
XLsn0w/XLsn0wKit_swift | XLsn0wKit/XLsn0wToast/ToastWindow.swift | 1 | 5315 | /*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
import UIKit
open class ToastWindow: UIWindow {
open static let shared = ToastWindow(frame: UIScreen.main.bounds)
/// Will not return `rootViewController` while this value is `true`. Or the rotation will be fucked in iOS 9.
var isStatusBarOrientationChanging = false
/// Don't rotate manually if the application:
///
/// - is running on iPad
/// - is running on iOS 9
/// - supports all orientations
/// - doesn't require full screen
/// - has launch storyboard
///
var shouldRotateManually: Bool {
let iPad = UIDevice.current.userInterfaceIdiom == .pad
let application = UIApplication.shared
let window = application.delegate?.window ?? nil
let supportsAllOrientations = application.supportedInterfaceOrientations(for: window) == .all
let info = Bundle.main.infoDictionary
let requiresFullScreen = (info?["UIRequiresFullScreen"] as? NSNumber)?.boolValue == true
let hasLaunchStoryboard = info?["UILaunchStoryboardName"] != nil
if #available(iOS 9, *), iPad && supportsAllOrientations && !requiresFullScreen && hasLaunchStoryboard {
return false
}
return true
}
override open var rootViewController: UIViewController? {
get {
guard !self.isStatusBarOrientationChanging else { return nil }
guard let firstWindow = UIApplication.shared.windows.first else { return nil }
return firstWindow is ToastWindow ? nil : firstWindow.rootViewController
}
set { /* Do nothing */ }
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.isUserInteractionEnabled = false
self.windowLevel = CGFloat.greatestFiniteMagnitude
self.backgroundColor = .clear
self.isHidden = false
self.handleRotate(UIApplication.shared.statusBarOrientation)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.bringWindowToTop),
name: .UIWindowDidBecomeVisible,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.statusBarOrientationWillChange),
name: .UIApplicationWillChangeStatusBarOrientation,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.statusBarOrientationDidChange),
name: .UIApplicationDidChangeStatusBarOrientation,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.applicationDidBecomeActive),
name: .UIApplicationDidBecomeActive,
object: nil
)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Bring ToastWindow to top when another window is being shown.
func bringWindowToTop(_ notification: Notification) {
if !(notification.object is ToastWindow) {
ToastWindow.shared.isHidden = true
ToastWindow.shared.isHidden = false
}
}
dynamic func statusBarOrientationWillChange() {
self.isStatusBarOrientationChanging = true
}
dynamic func statusBarOrientationDidChange() {
let orientation = UIApplication.shared.statusBarOrientation
self.handleRotate(orientation)
self.isStatusBarOrientationChanging = false
}
func applicationDidBecomeActive() {
let orientation = UIApplication.shared.statusBarOrientation
self.handleRotate(orientation)
}
func handleRotate(_ orientation: UIInterfaceOrientation) {
let angle = self.angleForOrientation(orientation)
if self.shouldRotateManually {
self.transform = CGAffineTransform(rotationAngle: CGFloat(angle))
}
if let window = UIApplication.shared.windows.first {
if orientation.isPortrait || !self.shouldRotateManually {
self.frame.size.width = window.bounds.size.width
self.frame.size.height = window.bounds.size.height
} else {
self.frame.size.width = window.bounds.size.height
self.frame.size.height = window.bounds.size.width
}
}
self.frame.origin = .zero
DispatchQueue.main.async {
ToastCenter.default.currentToast?.view.setNeedsLayout()
}
}
func angleForOrientation(_ orientation: UIInterfaceOrientation) -> Double {
switch orientation {
case .landscapeLeft: return -.pi / 2
case .landscapeRight: return .pi / 2
case .portraitUpsideDown: return .pi
default: return 0
}
}
}
| mit | 69d8471a132059ef1d8abc674fe6d50a | 35.40411 | 111 | 0.584196 | 4.562232 | false | false | false | false |
theJenix/swifter | src/Swifter/StringExt.swift | 1 | 1821 | //
// StringExt.swift
// COTFDemo
//
// Created by Jesse Rosalia on 7/23/14.
// Copyright (c) 2014 Jesse Rosalia. All rights reserved.
//
import Foundation
extension String {
func length() -> Int {
return self.characters.count
}
//copied from http://stackoverflow.com/a/24045523/1050693
subscript (r: Range<Int>) -> String {
get {
let subStart = self.startIndex.advancedBy(r.startIndex, limit: self.endIndex)
let subEnd = subStart.advancedBy(r.endIndex - r.startIndex, limit: self.endIndex)
return self.substringWithRange(subStart..<subEnd)
}
}
func substring(from: Int) -> String {
let end = self.length()
return self[from..<end]
}
func substring(from: Int, length: Int) -> String {
let end = from + length
return self[from..<end]
}
func grouped(n: Int) -> Array<String> {
let length = self.length()
let groupCount = Int(ceil(Double(length) / Double(n)))
var groups = Array<String>()
for i in 0..<groupCount {
// advance()
// let rng:Range<String.Index> = Range(start: n * i, end: min(n * (i + 1), length - 1))
let rng = (n * i)..<min(n * (i + 1), length)
groups.append(self[rng])
}
return groups
}
/**
* Map a function over the string. This function is useful for applying tests/changing values in the middle of a method chain
*/
func map(f: (String -> String?)) -> String? {
return f(self)
}
/**
* Generic trim function assumes we want to trim white space and new line characters
*/
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
} | mit | 10a329143f91519d0dcd769193296fe3 | 29.366667 | 130 | 0.583196 | 3.993421 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Video/VideoEditorViewController+Request.swift | 1 | 8224 | //
// VideoEditorViewController+Request.swift
// HXPHPicker
//
// Created by Slience on 2021/8/6.
//
import UIKit
import AVKit
import Photos
// MARK: PhotoAsset Request AVAsset
extension VideoEditorViewController {
#if HXPICKER_ENABLE_PICKER
func requestAVAsset() {
if photoAsset.isNetworkAsset {
pNetworkVideoURL = photoAsset.networkVideoAsset?.videoURL
downloadNetworkVideo()
return
}
let loadingView = ProgressHUD.showLoading(addedTo: view, text: nil, animated: true)
view.bringSubviewToFront(topView)
assetRequestID = photoAsset.requestAVAsset(
filterEditor: true,
deliveryMode: .highQualityFormat
) { [weak self] (photoAsset, requestID) in
self?.assetRequestID = requestID
loadingView?.mode = .circleProgress
loadingView?.text = "正在同步iCloud".localized + "..."
} progressHandler: { (photoAsset, progress) in
if progress > 0 {
loadingView?.progress = CGFloat(progress)
}
} success: { [weak self] (photoAsset, avAsset, info) in
ProgressHUD.hide(forView: self?.view, animated: false)
self?.pAVAsset = avAsset
self?.avassetLoadValuesAsynchronously()
// self?.reqeustAssetCompletion = true
// self?.assetRequestComplete()
} failure: { [weak self] (photoAsset, info, error) in
if let info = info, !info.isCancel {
ProgressHUD.hide(forView: self?.view, animated: false)
if info.inICloud {
self?.assetRequestFailure(message: "iCloud同步失败".localized)
}else {
self?.assetRequestFailure()
}
}
}
}
#endif
func assetRequestFailure(message: String = "视频获取失败!".localized) {
PhotoTools.showConfirm(
viewController: self,
title: "提示".localized,
message: message,
actionTitle: "确定".localized
) { (alertAction) in
self.backAction()
}
}
func assetRequestComplete() {
let image = PhotoTools.getVideoThumbnailImage(avAsset: avAsset, atTime: 0.1)
filterImageHandler(image: image)
videoSize = image?.size ?? view.size
coverImage = image
videoView.setAVAsset(avAsset, coverImage: image ?? .init())
cropView.avAsset = avAsset
if orientationDidChange {
setCropViewFrame()
}
if !videoInitializeCompletion {
setEditedSizeData()
videoInitializeCompletion = true
}
if transitionCompletion {
setAsset()
}
}
func setEditedSizeData() {
if let sizeData = editResult?.sizeData {
videoView.setVideoEditedData(editedData: sizeData)
brushColorView.canUndo = videoView.canUndoDraw
if let stickerData = sizeData.stickerData {
musicView.showLyricButton.isSelected = stickerData.showLyric
if stickerData.showLyric {
otherMusic = stickerData.items[stickerData.LyricIndex].item.music
}
}
}
}
func setAsset() {
if setAssetCompletion {
return
}
videoView.playerView.configAsset()
if let editResult = editResult {
hasOriginalSound = editResult.hasOriginalSound
if hasOriginalSound {
videoVolume = editResult.videoSoundVolume
}else {
videoView.playerView.player.volume = 0
}
volumeView.originalVolume = videoVolume
musicView.originalSoundButton.isSelected = hasOriginalSound
if let audioURL = editResult.backgroundMusicURL {
backgroundMusicPath = audioURL.path
musicView.backgroundButton.isSelected = true
PhotoManager.shared.playMusic(filePath: audioURL.path) {
}
videoView.imageResizerView.imageView.stickerView.audioView?.contentView.startTimer()
backgroundMusicVolume = editResult.backgroundMusicVolume
volumeView.musicVolume = backgroundMusicVolume
}
if !orientationDidChange && editResult.cropData != nil {
videoView.playerView.resetPlay()
startPlayTimer()
}
if let videoFilter = editResult.sizeData?.filter,
config.filter.isLoadLastFilter,
videoFilter.index < config.filter.infos.count {
let filterInfo = config.filter.infos[videoFilter.index]
videoView.playerView.setFilter(filterInfo, value: videoFilter.value)
}
videoView.imageResizerView.videoFilter = editResult.sizeData?.filter
}
setAssetCompletion = true
}
func filterImageHandler(image: UIImage?) {
guard let image = image else {
return
}
var hasFilter = false
var thumbnailImage: UIImage?
for option in config.toolView.toolOptions where option.type == .filter {
hasFilter = true
}
if hasFilter {
DispatchQueue.global().async {
thumbnailImage = image.scaleToFillSize(
size: CGSize(width: 80, height: 80),
equalRatio: true
)
if thumbnailImage == nil {
thumbnailImage = image
}
DispatchQueue.main.async {
self.filterView.image = thumbnailImage
}
}
}
}
}
// MARK: DownloadNetworkVideo
extension VideoEditorViewController {
func downloadNetworkVideo() {
if let videoURL = networkVideoURL {
let key = videoURL.absoluteString
if PhotoTools.isCached(forVideo: key) {
let localURL = PhotoTools.getVideoCacheURL(for: key)
pAVAsset = AVAsset.init(url: localURL)
avassetLoadValuesAsynchronously()
return
}
loadingView = ProgressHUD.showLoading(addedTo: view, text: "视频下载中".localized, animated: true)
view.bringSubviewToFront(topView)
PhotoManager.shared.downloadTask(
with: videoURL
) { [weak self] (progress, task) in
if progress > 0 {
self?.loadingView?.mode = .circleProgress
self?.loadingView?.progress = CGFloat(progress)
}
} completionHandler: { [weak self] (url, error, _) in
if let url = url {
#if HXPICKER_ENABLE_PICKER
if let photoAsset = self?.photoAsset {
photoAsset.networkVideoAsset?.fileSize = url.fileSize
}
#endif
self?.loadingView = nil
ProgressHUD.hide(forView: self?.view, animated: false)
self?.pAVAsset = AVAsset(url: url)
self?.avassetLoadValuesAsynchronously()
}else {
if let error = error as NSError?, error.code == NSURLErrorCancelled {
return
}
self?.loadingView = nil
ProgressHUD.hide(forView: self?.view, animated: false)
self?.assetRequestFailure()
}
}
}
}
func avassetLoadValuesAsynchronously() {
avAsset.loadValuesAsynchronously(
forKeys: ["duration"]
) { [weak self] in
guard let self = self else { return }
DispatchQueue.main.async {
if self.avAsset.statusOfValue(forKey: "duration", error: nil) != .loaded {
self.assetRequestFailure()
return
}
self.reqeustAssetCompletion = true
self.assetRequestComplete()
}
}
}
}
| mit | 2f33843e4ae84d99fa8becaaaa5f4b02 | 36.513761 | 105 | 0.553558 | 5.376726 | false | false | false | false |
n8armstrong/CalendarView | CalendarView/CalendarView/Classes/ContentView.swift | 1 | 3891 | //
// CalendarContentView.swift
// Calendar
//
// Created by Nate Armstrong on 3/29/15.
// Copyright (c) 2015 Nate Armstrong. All rights reserved.
// Updated to Swift 4 by A&D Progress aka verebes (c) 2018
//
import UIKit
import SwiftMoment
class ContentView: UIScrollView {
let numMonthsLoaded = 3
let currentPage = 1
var months: [MonthView] = []
var selectedDate: Moment?
var paged = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
isPagingEnabled = true
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
for month in months {
month.setdown()
month.removeFromSuperview()
}
months = []
let date = selectedDate ?? moment()
selectedDate = date
var currentDate = date.subtract(1, .Months)
for _ in 1...numMonthsLoaded {
let month = MonthView(frame: CGRect.zero)
month.date = currentDate
addSubview(month)
months.append(month)
currentDate = currentDate.add(1, .Months)
}
}
override func layoutSubviews() {
super.layoutSubviews()
var x: CGFloat = 0
for month in months {
month.frame = CGRect(x: x, y: 0, width: bounds.size.width, height: bounds.size.height)
x = month.frame.maxX
}
contentSize = CGSize(width: bounds.size.width * numMonthsLoaded, height: bounds.size.height)
}
func selectPage(page: Int) {
var page1FrameMatched = false
var page2FrameMatched = false
var page3FrameMatched = false
var frameCurrentMatched = false
let pageWidth = frame.size.width
let pageHeight = frame.size.height
let frameCurrent = CGRect(x: page * pageWidth, y: 0, width: pageWidth, height: pageHeight)
let frameLeft = CGRect(x: (page-1) * pageWidth, y: 0, width: pageWidth, height: pageHeight)
let frameRight = CGRect(x: (page+1) * pageWidth, y: 0, width: pageWidth, height: pageHeight)
let page1 = months.first!
let page2 = months[1]
let page3 = months.last!
if frameCurrent.origin.x == page1.frame.origin.x {
page1FrameMatched = true
frameCurrentMatched = true
}
else if frameCurrent.origin.x == page2.frame.origin.x {
page2FrameMatched = true
frameCurrentMatched = true
}
else if frameCurrent.origin.x == page3.frame.origin.x {
page3FrameMatched = true
frameCurrentMatched = true
}
if frameCurrentMatched {
if page2FrameMatched {
print("something weird happened")
}
else if page1FrameMatched {
page3.date = page1.date.subtract(1, .Months)
page1.frame = frameCurrent
page2.frame = frameRight
page3.frame = frameLeft
months = [page3, page1, page2]
}
else if page3FrameMatched {
page1.date = page3.date.add(1, .Months)
page1.frame = frameRight
page2.frame = frameLeft
page3.frame = frameCurrent
months = [page2, page3, page1]
}
contentOffset.x = frame.width
selectedDate = nil
paged = true
}
}
func selectDate(date: Moment) {
selectedDate = date
setup()
selectVisibleDate(date: date.day)
setNeedsLayout()
}
func selectVisibleDate(date: Int) -> DayView? {
let month = currentMonth()
for week in month.weeks {
for day in week.days {
if day.date != nil && day.date.month == month.date.month && day.date.day == date {
day.selected = true
return day
}
}
}
return nil
}
func removeObservers() {
for month in months {
for week in month.weeks {
for day in week.days {
NotificationCenter.default.removeObserver(day)
}
}
}
}
func currentMonth() -> MonthView {
return months[1]
}
}
| mit | a364b4d5ebbd1dd7931ee29449467300 | 24.598684 | 96 | 0.632999 | 3.910553 | false | false | false | false |
maxsokolov/Leeloo | Sources/NetworkClientResponseHandler.swift | 1 | 2857 | //
// Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov
//
// 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 Alamofire
private enum DataRequestError: Error {
case missingResponseData
}
extension DataRequest {
@discardableResult
func responseObject<R: NetworkRequest, T>(
networkRequest: R,
requestBehaviors: [NetworkRequestBehavior],
completionHandler: @escaping (DataResponse<T>) -> Void)
-> Self
where R.Response == T
{
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else {
return .failure(NetworkRequestError.connectionError(error: error!))
}
guard let response = response, let data = data else {
return .failure(DataRequestError.missingResponseData)
}
do {
try requestBehaviors.forEach({ try $0.didReceive(httpResponse: response, data: data) })
} catch let error {
return .failure(NetworkRequestError.userError(error: error))
}
do {
let result: T = try networkRequest.responseConverter.convert(
httpResponse: response,
data: data,
keyPath: networkRequest.responseKeyPath
)
return .success(result)
} catch let error {
return .failure(NetworkRequestError.responseConverterError(error: error))
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
| mit | d00915f7d7a8a22b5cde6e903a461db8 | 39.239437 | 103 | 0.627231 | 5.290741 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/LoginInputCell.swift | 1 | 2364 | //
// LoginInputCell.swift
// HiChongSwift
//
// Created by eagle on 14/12/18.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
enum LoginInputCellType {
case PhoneNumber
case Password
}
class LoginInputCell: UITableViewCell {
@IBOutlet private weak var icyImageView: UIImageView!
@IBOutlet weak var icyTextField: UITextField!
weak var delegate: LoginInputCellDelegate?
var icyCellType: LoginInputCellType = .PhoneNumber {
didSet {
switch icyCellType {
case .PhoneNumber:
icyImageView.image = UIImage(named: "LoginPhone")
self.icyTextField.keyboardType = UIKeyboardType.NumberPad
self.icyTextField.secureTextEntry = false
self.icyTextField.placeholder = "请输入您的手机号"
case .Password:
icyImageView.image = UIImage(named: "LoginPassword")
self.icyTextField.keyboardType = UIKeyboardType.ASCIICapable
self.icyTextField.secureTextEntry = true
self.icyTextField.placeholder = "请输入6到18位的密码"
}
icyTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
}
}
class func identifier() -> String {
return "LoginInputCellIdentifier"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.LCYThemeColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension LoginInputCell: UITextFieldDelegate {
func textFieldDidEndEditing(textField: UITextField) {
delegate?.loginInputDidEndEditing(icyCellType, text: textField.text)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
delegate?.loginInputDidEndEditing(icyCellType, text: newText)
return true
}
}
protocol LoginInputCellDelegate: class {
func loginInputDidEndEditing(cellType: LoginInputCellType, text: String)
}
| apache-2.0 | e0835d669baa0778dc4e467a86c7a316 | 30.378378 | 132 | 0.672696 | 5.069869 | false | false | false | false |
devpunk/velvet_room | Source/Model/Connecting/Models/MConnectingPin.swift | 1 | 764 | import Foundation
final class MConnectingPin
{
let length:Int
private let pinString:String
init()
{
pinString = MConnectingPin.generatePin()
length = pinString.count
}
//MARK: internal
func digitAtIndex(index:Int) -> String
{
let startIndex:String.Index = pinString.startIndex
let digitIndex:String.Index = pinString.index(
startIndex,
offsetBy:index)
let digitCharacter:Character = pinString[digitIndex]
let digitString:String = String(digitCharacter)
return digitString
}
func validatePin(pinString:String) -> Bool
{
let equal:Bool = self.pinString == pinString
return equal
}
}
| mit | d7956fe7bcfd434f864ccba7622955d4 | 21.470588 | 60 | 0.604712 | 4.60241 | false | false | false | false |
liuwin7/meizi_app_ios | Pods/ElasticTransition/ElasticTransition/EdgePanTransition.swift | 1 | 8718 | /*
The MIT License (MIT)
Copyright (c) 2015 Luke Zhao <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
@available(iOS 8.0, *)
public class EdgePanTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerInteractiveTransitioning, UIViewControllerTransitioningDelegate, UINavigationControllerDelegate{
public var panThreshold:CGFloat = 0.2
public var edge:Edge = .Right
// private
var transitioning = false
var presenting = true
var interactive = false
var navigation = false
var transitionContext:UIViewControllerContextTransitioning!
var container:UIView!
var size:CGSize{
return container.bounds.size
}
var frontView:UIView{
return frontViewController.view
}
var backView:UIView{
return backViewController.view
}
var frontViewController: UIViewController{
return presenting ? toViewController : fromViewController
}
var backViewController: UIViewController{
return !presenting ? toViewController : fromViewController
}
var toView:UIView{
return toViewController.view
}
var fromView:UIView{
return fromViewController.view
}
var toViewController:UIViewController{
return transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
}
var fromViewController:UIViewController{
return transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
}
var currentPanGR: UIPanGestureRecognizer?
var translation:CGPoint = CGPointZero
var dragPoint:CGPoint = CGPointZero
func update(){}
func setup(){
transitioning = true
container.addSubview(backView)
container.addSubview(frontView)
}
func clean(finished: Bool){
if !navigation {
// bug: http://openradar.appspot.com/radar?id=5320103646199808
UIApplication.sharedApplication().keyWindow!.addSubview(finished ? toView : fromView)
}
if(!presenting && finished || presenting && !finished){
frontView.removeFromSuperview()
backView.layer.transform = CATransform3DIdentity
}
currentPanGR = nil
interactive = false
transitioning = false
navigation = false
transitionContext.completeTransition(finished)
}
func startInteractivePresent(fromViewController fromVC:UIViewController, toViewController toVC:UIViewController?, identifier:String?, pan:UIPanGestureRecognizer, presenting:Bool, completion:(() -> Void)? = nil){
interactive = true
currentPanGR = pan
if presenting{
if let identifier = identifier{
fromVC.performSegueWithIdentifier(identifier, sender: self)
}else if let toVC = toVC{
fromVC.presentViewController(toVC, animated: true, completion: nil)
}
}else{
if navigation{
fromVC.navigationController?.popViewControllerAnimated(true)
}else{
fromVC.dismissViewControllerAnimated(true, completion: completion)
}
}
translation = pan.translationInView(pan.view!)
dragPoint = pan.locationInView(pan.view!)
}
public func updateInteractiveTransition(gestureRecognizer pan:UIPanGestureRecognizer) -> Bool?{
if !transitioning{
return nil
}
if pan.state == .Changed{
translation = pan.translationInView(pan.view!)
dragPoint = pan.locationInView(pan.view!)
update()
return nil
}else{
return endInteractiveTransition()
}
}
public func startInteractiveTransition(fromViewController:UIViewController, segueIdentifier identifier:String, gestureRecognizer pan:UIPanGestureRecognizer){
self.startInteractivePresent(fromViewController:fromViewController, toViewController:nil, identifier:identifier, pan: pan, presenting: true)
}
public func startInteractiveTransition(fromViewController:UIViewController, toViewController:UIViewController, gestureRecognizer pan:UIPanGestureRecognizer){
self.startInteractivePresent(fromViewController:fromViewController, toViewController:toViewController, identifier:nil, pan: pan, presenting: true)
}
public func dissmissInteractiveTransition(viewController:UIViewController, gestureRecognizer pan:UIPanGestureRecognizer, completion:(() -> Void)?){
self.startInteractivePresent(fromViewController:viewController, toViewController:nil, identifier:nil, pan: pan, presenting: false, completion: completion)
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
self.container = transitionContext.containerView()
setup()
}
public func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning){
animateTransition(transitionContext)
}
func cancelInteractiveTransition(){
self.transitionContext.cancelInteractiveTransition()
}
func finishInteractiveTransition(){
self.transitionContext.finishInteractiveTransition()
}
func endInteractiveTransition() -> Bool{
let finished:Bool
if let pan = currentPanGR{
let translation = pan.translationInView(pan.view!)
var progress:CGFloat
switch edge{
case .Left:
progress = translation.x / pan.view!.frame.width
case .Right:
progress = translation.x / pan.view!.frame.width * -1
case .Bottom:
progress = translation.y / pan.view!.frame.height * -1
case .Top:
progress = translation.y / pan.view!.frame.height
}
progress = presenting ? progress : -progress
if(progress > panThreshold){
finished = true
} else {
finished = false
}
}else{
finished = true
}
if finished{
finishInteractiveTransition()
}else{
cancelInteractiveTransition()
}
return finished
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if transitioning{
return nil
}
self.presenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if transitioning{
return nil
}
self.presenting = false
return self
}
public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if transitioning{
return nil
}
self.presenting = true
return self.interactive ? self : nil
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if transitioning{
return nil
}
self.presenting = false
return self.interactive ? self : nil
}
public func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if transitioning{
return nil
}
return self.interactive ? self : nil
}
public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if transitioning{
return nil
}
navigation = true
presenting = operation == .Push
return self
}
}
| mit | a26a2d0c62d289b31a4ee0adf3686219 | 33.872 | 286 | 0.750631 | 5.731755 | false | false | false | false |
satyasuman/SwiftSkeleton | SwiftSkeleton/AppDelegate.swift | 1 | 7604 | //
// AppDelegate.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 8/21/14.
// Copyright (c) 2014 Wilson Zhao. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController
let controller = masterNavigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController!, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "WZ.SwiftSkeleton" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SwiftSkeleton", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftSkeleton.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 988c66c392fb6bd4ea2196b851eb62f8 | 56.606061 | 290 | 0.725145 | 6.187144 | false | false | false | false |
Bruno-Furtado/holt_winters | HoltWinters/Classes/Model/ItemModel.swift | 1 | 990 | //
// ItemModel.swift
// HoltWinters
//
// Created by Bruno Tortato Furtado on 03/05/16.
// Copyright © 2016 Bruno Tortato Furtado. All rights reserved.
//
import Foundation
final class ItemModel: CustomStringConvertible {
var t: Int = 0
var d: Double = 0
var L: Double = 0
var b: Double = 0
var S: Double = 0
var F: Double = 0
var e: Double = 0
var ep: Double = 0
// MARK: CustomStringConvertible
var description: String {
var line = "\(self.t)"
line += (self.d == 0.0) ? ";" : ";\(d.toString(2))"
line += (self.L == 0.0) ? ";" : ";\(L.toString(4))"
line += (self.b == 0.0) ? ";" : ";\(b.toString(6))"
line += (self.S == 0.0) ? ";" : ";\(S.toString(6))"
line += (self.F == 0.0) ? ";" : ";\(F.toString(4))"
line += (self.e == 0.0) ? ";" : ";\(e.toString(3))"
line += (self.ep == 0.0) ? ";" : ";\(ep.toString(1))%"
return line
}
} | mit | 9d55808979c7e241dd74895077f95598 | 25.052632 | 64 | 0.47725 | 3.159744 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/FormattableContent/FormattableRangesFactory.swift | 2 | 1016 |
protocol FormattableRangesFactory {
static func contentRange(from dictionary: [String: AnyObject]) -> FormattableContentRange?
}
extension FormattableRangesFactory {
static func rangeFrom(_ dictionary: [String: AnyObject]) -> NSRange? {
guard let indices = dictionary[RangeKeys.indices] as? [Int],
let start = indices.first,
let end = indices.last else {
return nil
}
return NSMakeRange(start, end - start)
}
static func kindString(from dictionary: [String: AnyObject]) -> String? {
if let section = dictionary[RangeKeys.section] as? String {
return section
}
return dictionary[RangeKeys.rawType] as? String
}
}
private enum RangeKeys {
static let rawType = "type"
static let section = "section"
static let url = "url"
static let indices = "indices"
static let id = "id"
static let value = "value"
static let siteId = "site_id"
static let postId = "post_id"
}
| gpl-2.0 | 25cfbf9edb0c2dd070ce7de35ceb2344 | 29.787879 | 94 | 0.634843 | 4.34188 | false | false | false | false |
NicolasKim/Roy | Example/Pods/GRDB.swift/GRDB/Record/RowConvertible+Decodable.swift | 1 | 13595 | private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let decoder: RowDecoder
init(decoder: RowDecoder) {
self.decoder = decoder
}
var codingPath: [CodingKey] { return decoder.codingPath }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] {
let row = decoder.row
let columnNames = Set(row.columnNames)
let scopeNames = row.scopeNames
return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) }
}
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
func decodeNil(forKey key: Key) throws -> Bool {
let row = decoder.row
return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns nil if the container does not have a value
/// associated with key, or if the value is null. The difference between
/// these states can be distinguished with a contains(_:) call.
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T?
} else if dbValue.isNull {
return nil
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
return nil
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue) {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".")
fatalError("No such column or scope: \(path)")
}
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("not implemented")
}
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
public func superDecoder() throws -> Decoder {
return decoder
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return decoder
}
}
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
let row: Row
var codingPath: [CodingKey]
let column: CodingKey
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return row[column.stringValue] == nil
}
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool { return row[column.stringValue] }
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(row[column.stringValue]) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: [column]))
}
}
}
private struct RowDecoder: Decoder {
let row: Row
init(row: Row, codingPath: [CodingKey]) {
self.row = row
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
// Asked for a value type: column name required
guard let codingKey = codingPath.last else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
}
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
}
}
extension RowConvertible where Self: Decodable {
/// Initializes a record from `row`.
public init(row: Row) {
try! self.init(from: RowDecoder(row: row, codingPath: []))
}
}
| mit | 168a75e4dd015f39ad98066846b64415 | 51.898833 | 262 | 0.660316 | 4.52714 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Branding/Button/CircularImageButton.swift | 1 | 1808 | import UIKit
/// Use this UIButton subclass to set a custom background for the button image, different from tintColor and backgroundColor.
/// If there's not image, it has no effect. Supports only circular images.
class CircularImageButton: UIButton {
private lazy var imageBackgroundView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
/// Sets a custom circular background color below the imageView, different from the button background or tint color
/// - Parameters:
/// - color: the custom background color
/// - ratio: the extent of the background view that lays below the button image view (default: 0.75 of the image view)
func setImageBackgroundColor(_ color: UIColor, ratio: CGFloat = 0.75) {
guard let imageView = imageView else {
return
}
imageBackgroundView.backgroundColor = color
insertSubview(imageBackgroundView, belowSubview: imageView)
imageBackgroundView.clipsToBounds = true
imageBackgroundView.isUserInteractionEnabled = false
NSLayoutConstraint.activate([
imageBackgroundView.centerXAnchor.constraint(equalTo: imageView.centerXAnchor),
imageBackgroundView.centerYAnchor.constraint(equalTo: imageView.centerYAnchor),
imageBackgroundView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: ratio),
imageBackgroundView.widthAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: ratio),
])
}
override func layoutSubviews() {
super.layoutSubviews()
guard imageView != nil else {
return
}
imageBackgroundView.layer.cornerRadius = imageBackgroundView.frame.height / 2
}
}
| gpl-2.0 | b436efd53987400b04cd03a91a609f18 | 43.097561 | 125 | 0.702987 | 5.832258 | false | false | false | false |
mentalfaculty/impeller | Sources/JSONForestSerializer.swift | 1 | 11873 | //
// JSONRepository.swift
// Impeller
//
// Created by Drew McCormack on 26/01/2017.
// Copyright © 2017 Drew McCormack. All rights reserved.
//
import Foundation
public enum JSONSerializationError: Error {
case invalidMetadata
case invalidFormat(reason: String)
case invalidProperty(reason: String)
}
protocol JSONRepresentable {
init(withJSONRepresentation json: Any) throws
func JSONRepresentation() -> Any
}
public class JSONForestSerializer: ForestSerializer {
public init() {}
public func load(from url:URL) throws -> Forest {
let data = try Data(contentsOf: url)
guard let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] else {
throw JSONSerializationError.invalidFormat(reason: "JSON root was not a dictionary")
}
let trees = try dict.map { (_, json) in try ValueTree(withJSONRepresentation: json) }
return Forest(valueTrees: trees)
}
public func save(_ forest:Forest, to url:URL) throws {
var json = [String:Any]()
for tree in forest {
let key = tree.valueTreeReference.asString
json[key] = tree.JSONRepresentation()
}
let data = try JSONSerialization.data(withJSONObject: json, options: [])
try data.write(to: url)
}
}
extension ValueTree: JSONRepresentable {
public enum JSONKey: String {
case metadata, repositedType, uniqueIdentifier, timestamp, isDeleted, version, propertiesByName
}
public init(withJSONRepresentation json: Any) throws {
guard let json = json as? [String:Any] else {
throw JSONSerializationError.invalidFormat(reason: "No root dictionary in JSON")
}
guard
let metadataDict = json[JSONKey.metadata.rawValue] as? [String:Any],
let id = metadataDict[JSONKey.uniqueIdentifier.rawValue] as? String,
let repositedType = metadataDict[JSONKey.repositedType.rawValue] as? RepositedType,
let timestamp = metadataDict[JSONKey.timestamp.rawValue] as? TimeInterval,
let isDeleted = metadataDict[JSONKey.isDeleted.rawValue] as? Bool,
let version = metadataDict[JSONKey.version.rawValue] as? RepositedVersion else {
throw JSONSerializationError.invalidMetadata
}
var metadata = Metadata(uniqueIdentifier: id)
metadata.timestamp = timestamp
metadata.isDeleted = isDeleted
metadata.version = version
self.repositedType = repositedType
self.metadata = metadata
guard let propertiesByName = json[JSONKey.propertiesByName.rawValue] as? [String:Any] else {
throw JSONSerializationError.invalidFormat(reason: "No properties dictionary found for object")
}
self.propertiesByName = try propertiesByName.mapValues {
try Property(withJSONRepresentation: $1 as AnyObject)
}
}
public func JSONRepresentation() -> Any {
var json = [String:Any]()
let metadataDict: [String:Any] = [
JSONKey.repositedType.rawValue : repositedType,
JSONKey.uniqueIdentifier.rawValue : metadata.uniqueIdentifier,
JSONKey.timestamp.rawValue : metadata.timestamp,
JSONKey.isDeleted.rawValue : metadata.isDeleted,
JSONKey.version.rawValue : metadata.version
]
json[JSONKey.metadata.rawValue] = metadataDict
json[JSONKey.propertiesByName.rawValue] = propertiesByName.mapValues { _, property in
return property.JSONRepresentation()
}
return json
}
}
extension Property: JSONRepresentable {
public enum JSONKey: String {
case propertyType, primitiveType, value, referencedType, referencedIdentifier, referencedIdentifiers
}
public init(withJSONRepresentation json: Any) throws {
guard
let json = json as? [String:Any],
let propertyTypeInt = json[JSONKey.propertyType.rawValue] as? Int,
let propertyType = PropertyType(rawValue: propertyTypeInt) else {
throw JSONSerializationError.invalidProperty(reason: "No valid property type")
}
let primitiveTypeInt = json[JSONKey.primitiveType.rawValue] as? Int
let primitiveType = primitiveTypeInt != nil ? PrimitiveType(rawValue: primitiveTypeInt!) : nil
switch propertyType {
case .primitive:
guard
let primitiveType = primitiveType,
let value = json[JSONKey.value.rawValue] else {
throw JSONSerializationError.invalidProperty(reason: "No primitive type or value found")
}
self = try Property(withPrimitiveType: primitiveType, value: value)
case .optionalPrimitive:
let isNull = primitiveTypeInt == 0
if isNull {
self = .optionalPrimitive(nil)
}
else {
guard
let primitiveType = primitiveType,
let value = json[JSONKey.value.rawValue] else {
throw JSONSerializationError.invalidProperty(reason: "No primitive type or value found")
}
self = try Property(withPrimitiveType: primitiveType, value: value)
}
case .primitives:
let isEmpty = primitiveTypeInt == 0
if isEmpty {
self = .primitives([])
}
else {
guard
let primitiveType = primitiveType,
let value = json[JSONKey.value.rawValue] as? [Any] else {
throw JSONSerializationError.invalidProperty(reason: "No primitive type or value found")
}
switch primitiveType {
case .string:
guard let v = value as? [String] else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitives(v.map { .string($0) })
case .int:
guard let v = value as? [Int] else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitives(v.map { .int($0) })
case .float:
guard let v = value as? [Float] else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitives(v.map { .float($0) })
case .bool:
guard let v = value as? [Bool] else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitives(v.map { .bool($0) })
case .data:
guard let v = value as? [Data] else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitives(v.map { .data($0) })
}
}
case .valueTreeReference:
self = try Property(withReferenceDictionary: json)
case .optionalValueTreeReference:
if let referencedType = json[JSONKey.referencedType.rawValue] as? Int, referencedType == 0 {
self = .optionalValueTreeReference(nil)
}
else {
self = try Property(withReferenceDictionary: json)
}
case .valueTreeReferences:
if let referencedType = json[JSONKey.referencedType.rawValue] as? Int, referencedType == 0 {
self = .valueTreeReferences([])
}
else {
guard
let referencedType = json[JSONKey.referencedType.rawValue] as? String,
let referencedIdentifiers = json[JSONKey.referencedIdentifiers.rawValue] as? [String] else {
throw JSONSerializationError.invalidProperty(reason: "No primitive type or value found")
}
let refs = referencedIdentifiers.map { ValueTreeReference(uniqueIdentifier: $0, repositedType: referencedType) }
self = .valueTreeReferences(refs)
}
}
}
private init(withPrimitiveType primitiveType: PrimitiveType, value: Any) throws {
switch primitiveType {
case .string:
guard let v = value as? String else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitive(.string(v))
case .int:
guard let v = value as? Int else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitive(.int(v))
case .float:
guard let v = value as? Float else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitive(.float(v))
case .bool:
guard let v = value as? Bool else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitive(.bool(v))
case .data:
guard let v = value as? Data else { throw JSONSerializationError.invalidProperty(reason: "Wrong type found") }
self = .primitive(.data(v))
}
}
private init(withReferenceDictionary dict: [String:Any]) throws {
guard
let referencedType = dict[JSONKey.referencedType.rawValue] as? String,
let referencedIdentifier = dict[JSONKey.referencedIdentifier.rawValue] as? String else {
throw JSONSerializationError.invalidProperty(reason: "No primitive type or value found")
}
let ref = ValueTreeReference(uniqueIdentifier: referencedIdentifier, repositedType: referencedType)
self = .valueTreeReference(ref)
}
public func JSONRepresentation() -> Any {
var result = [String:Any]()
result[JSONKey.propertyType.rawValue] = propertyType.rawValue
switch self {
case .primitive(let primitive):
result[JSONKey.primitiveType.rawValue] = primitive.type.rawValue
result[JSONKey.value.rawValue] = primitive.value
case .optionalPrimitive(let primitive):
if let primitive = primitive {
result[JSONKey.primitiveType.rawValue] = primitive.type.rawValue
result[JSONKey.value.rawValue] = primitive.value
}
else {
result[JSONKey.primitiveType.rawValue] = 0
}
case .primitives(let primitives):
if primitives.count > 0 {
result[JSONKey.primitiveType.rawValue] = primitives.first!.type.rawValue
result[JSONKey.value.rawValue] = primitives.map { $0.value }
}
else {
result[JSONKey.primitiveType.rawValue] = 0
}
case .valueTreeReference(let ref):
result[JSONKey.referencedType.rawValue] = ref.repositedType
result[JSONKey.referencedIdentifier.rawValue] = ref.uniqueIdentifier
case .optionalValueTreeReference(let ref):
if let ref = ref {
result[JSONKey.referencedType.rawValue] = ref.repositedType
result[JSONKey.referencedIdentifier.rawValue] = ref.uniqueIdentifier
}
else {
result[JSONKey.referencedType.rawValue] = 0
}
case .valueTreeReferences(let refs):
if refs.count > 0 {
result[JSONKey.referencedType.rawValue] = refs.first!.repositedType
result[JSONKey.referencedIdentifiers.rawValue] = refs.map { $0.uniqueIdentifier }
}
else {
result[JSONKey.referencedType.rawValue] = 0
}
}
return result as AnyObject
}
}
| mit | 3ee4389055891d9772c6bf0807fe36f9 | 41.859206 | 134 | 0.606301 | 5.049766 | false | false | false | false |
omochi/numsw | Playgrounds/ChartRenderer.swift | 1 | 1141 | //
// ChartRenderer.swift
// sandbox
//
// Created by omochimetaru on 2017/03/06.
// Copyright © 2017年 sonson. All rights reserved.
//
import CoreGraphics
public class ChartRenderer: Renderer {
public init(chart: Chart) {
self.chart = chart
update()
}
public let chart: Chart
public func render(context: CGContext, windowSize: CGSize) {
compositer?.render(context: context, windowSize: windowSize)
}
private func update() {
var renderers: [Renderer] = []
renderers.append(AxisRenderer(chart: chart))
for element in chart.elements {
switch element {
case .line(let line):
renderers.append(LineGraphRenderer(viewport: chart.viewport, line: line))
case .scatter(let scatter):
renderers.append(ScatterGraphRenderer(viewport: chart.viewport, scatter: scatter))
}
}
let r = CompositeRenderer()
self.compositer = r
r.renderers = renderers
}
private var compositer: CompositeRenderer?
}
| mit | 2a5bedfc2a8af608fca77f0f869e89e6 | 24.288889 | 98 | 0.589631 | 4.552 | false | false | false | false |
Crisfole/SwiftWeather | SwiftWeather/ForecastView.swift | 2 | 2734 | //
// ForecastView.swift
// SwiftWeather
//
// Created by Jake Lin on 8/22/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import UIKit
@IBDesignable class ForecastView: UIView {
// Our custom view from the XIB file
var view: UIView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var iconLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
// MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
view = loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
view = loadViewFromNib()
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName(), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(view);
return view
}
// MARK: - ViewModel
var viewModel: ForecastViewModel? {
didSet {
viewModel?.time.observe {
[unowned self] in
self.timeLabel.text = $0
}
viewModel?.iconText.observe {
[unowned self] in
self.iconLabel.text = $0
}
viewModel?.temperature.observe {
[unowned self] in
self.temperatureLabel.text = $0
}
}
}
func loadViewModel(viewModel: ForecastViewModel) {
self.viewModel = viewModel
}
// MARK: - IBInspectable
@IBInspectable var time: String? {
get {
return timeLabel.text
}
set {
timeLabel.text = newValue
}
}
@IBInspectable var icon: String? {
get {
return iconLabel.text
}
set {
iconLabel.text = newValue
}
}
@IBInspectable var temperature: String? {
get {
return temperatureLabel.text
}
set {
temperatureLabel.text = newValue
}
}
@IBInspectable var timeColor: UIColor {
get {
return timeLabel.textColor
}
set {
timeLabel.textColor = newValue
}
}
@IBInspectable var iconColor: UIColor {
get {
return iconLabel.textColor
}
set {
iconLabel.textColor = newValue
}
}
@IBInspectable var temperatureColor: UIColor {
get {
return temperatureLabel.textColor
}
set {
temperatureLabel.textColor = newValue
}
}
@IBInspectable var bgColor: UIColor {
get {
return view.backgroundColor!
}
set {
view.backgroundColor = newValue
}
}
// MARK: - Private
private func nibName() -> String {
return self.dynamicType.description().componentsSeparatedByString(".").last!
}
}
| mit | a7f391a4d71b735e8e67b1b6e57eeb27 | 18.521429 | 80 | 0.611416 | 4.480328 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/server/TKRealTimeFetcher.swift | 1 | 7414 | //
// TKRealTimeFetcher.swift
// TripKit
//
// Created by Adrian Schönig on 6/8/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
#if canImport(CoreData)
import Foundation
import CoreData
public class TKRealTimeFetcher {
private init() {}
public static func update(_ entries: Set<DLSEntry>, in region: TKRegion, completion: @escaping (Result<Set<DLSEntry>, Error>) -> Void) {
var serviceParas: [[String: Any]] = []
var keysToUpdateables: [String: Updateable] = [:]
var context: NSManagedObjectContext? = nil
for entry in entries {
guard let service = entry.service, !service.wantsRealTimeUpdates, let startTime = entry.originalTime else { continue }
context = context ?? service.managedObjectContext
assert(context == service.managedObjectContext)
serviceParas.append([
"serviceTripID": service.code,
"operatorID": service.operatorID ?? "",
"operator": service.operatorName ?? "",
"startStopCode": entry.stop.stopCode,
"startTime": startTime.timeIntervalSince1970,
"endStopCode": entry.endStop.stopCode,
])
keysToUpdateables[service.code] = .service(service)
}
fetchAndUpdate(serviceParas: serviceParas, keysToUpdateables: keysToUpdateables, region: region, context: context) { result in
completion(result.map { _ in entries })
}
}
public static func update(_ visits: Set<StopVisits>, in region: TKRegion, completion: @escaping (Result<Set<StopVisits>, Error>) -> Void) {
var serviceParas: [[String: Any]] = []
var keysToUpdateables: [String: Updateable] = [:]
var context: NSManagedObjectContext? = nil
for visit in visits {
guard let service = visit.service, !service.wantsRealTimeUpdates, let startTime = visit.originalTime else { continue }
context = context ?? service.managedObjectContext
assert(context == service.managedObjectContext)
serviceParas.append([
"serviceTripID": service.code,
"operatorID": service.operatorID ?? "",
"operator": service.operatorName ?? "",
"startStopCode": visit.stop.stopCode,
"startTime": startTime.timeIntervalSince1970,
])
keysToUpdateables[service.code] = .service(service)
}
fetchAndUpdate(serviceParas: serviceParas, keysToUpdateables: keysToUpdateables, region: region, context: context) { result in
completion(result.map { _ in visits })
}
}
public static func update(_ services: Set<Service>, in region: TKRegion, completion: @escaping (Result<Set<Service>, Error>) -> Void) {
var serviceParas: [[String: Any]] = []
var keysToUpdateables: [String: Updateable] = [:]
var context: NSManagedObjectContext? = nil
for service in services {
guard service.wantsRealTimeUpdates else { continue }
context = context ?? service.managedObjectContext
assert(context == service.managedObjectContext)
serviceParas.append([
"serviceTripID": service.code,
"operatorID": service.operatorID ?? "",
"operator": service.operatorName ?? "",
])
keysToUpdateables[service.code] = .service(service)
}
fetchAndUpdate(serviceParas: serviceParas, keysToUpdateables: keysToUpdateables, region: region, context: context) { result in
completion(result.map { _ in services })
}
}
private static func fetchAndUpdate(
serviceParas: [[String: Any]],
keysToUpdateables: [String: Updateable],
region: TKRegion,
context: NSManagedObjectContext?,
completion: @escaping (Result<Void, Error>) -> Void
) {
guard !serviceParas.isEmpty, let context = context else {
return completion(.success(()))
}
let paras: [String: Any] = [
"region": region.code,
"block": false,
"services": serviceParas
]
TKServer.shared.hit(TKAPI.LatestResponse.self, .POST, path: "latest.json", parameters: paras, region: region, callbackOnMain: false) { _, _, result in
switch result {
case .success(let response):
context.perform {
update(keysToUpdateables: keysToUpdateables, from: response)
completion(.success(()))
}
case .failure(let error):
completion(.failure(error))
}
}
}
private enum Updateable {
case visit(StopVisits)
case service(Service)
}
private static func update(keysToUpdateables: [String: Updateable], from response: TKAPI.LatestResponse) {
for apiService in response.services {
guard let updatable = keysToUpdateables[apiService.code] else {
continue
}
let service: Service
let visit: StopVisits?
switch updatable {
case .visit(let updateable):
service = updateable.service
visit = updateable
case .service(let updateable):
service = updateable
visit = nil
}
service.addVehicles(primary: apiService.primaryVehicle, alternatives: apiService.alternativeVehicles)
if let visit = visit {
// we have supplied a start stop code, so we only want to update that
guard let startTime = apiService.startTime else { continue }
if let dls = visit as? DLSEntry {
if let endTime = apiService.endTime {
dls.departure = startTime
dls.arrival = endTime
service.isRealTime = true
} else if let arrival = dls.arrival, let departure = dls.departure {
let previousDuration = arrival.timeIntervalSince(departure)
dls.departure = startTime
dls.arrival = startTime.addingTimeInterval(previousDuration)
service.isRealTime = true
}
} else {
visit.departure = startTime
visit.triggerRealTimeKVO()
service.isRealTime = true
}
} else if !apiService.stops.isEmpty {
// we want to update all the stops in the service
service.isRealTime = true
let arrivals = apiService.stops.reduce(into: [String: Date]()) { acc, next in
acc[next.stopCode] = next.arrival
}
let departures = apiService.stops.reduce(into: [String: Date]()) { acc, next in
acc[next.stopCode] = next.departure
}
var delay: TimeInterval = 0
for visit in service.sortedVisits {
if let newArrival = arrivals[visit.stop.stopCode] {
if let arrival = visit.arrival {
delay = newArrival.timeIntervalSince(arrival)
}
visit.arrival = newArrival
}
if let newDeparture = departures[visit.stop.stopCode] {
if let departure = visit.departure {
delay = newDeparture.timeIntervalSince(departure)
}
// use time for KVO
visit.departure = newDeparture
visit.triggerRealTimeKVO()
}
if arrivals[visit.stop.stopCode] == nil, let arrival = visit.arrival, abs(delay) > 1 {
visit.arrival = arrival.addingTimeInterval(delay)
}
if departures[visit.stop.stopCode] == nil, let departure = visit.departure, abs(delay) > 1 {
// use time for KVO
visit.departure = departure.addingTimeInterval(delay)
visit.triggerRealTimeKVO()
}
}
}
}
}
}
#endif
| apache-2.0 | ca6f6502401c471be5cf010a0e0d4f70 | 34.980583 | 154 | 0.633567 | 4.519512 | false | false | false | false |
AECC-UPRRP/GallitoBooks | GallitoBooks/AppDelegate.swift | 1 | 6124 | //
// AppDelegate.swift
// GallitoBooks
//
// Created by Xiomara on 5/9/15.
// Copyright (c) 2015 UPRRP. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.uprrp.GallitoBooks" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("GallitoBooks", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("GallitoBooks.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 2b48c396bf29c8e0936866bc5f3af605 | 54.672727 | 290 | 0.715872 | 5.718021 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/AppConfigLoader.swift | 1 | 3507 | //
// AppConfigLoader.swift
// Outlander
//
// Created by Joseph McBride on 3/19/17.
// Copyright © 2017 Joe McBride. All rights reserved.
//
import Foundation
@objc
class AppConfigLoader : NSObject {
class func newInstance(context:GameContext, fileSystem:FileSystem) -> AppConfigLoader {
return AppConfigLoader(context: context, fileSystem: fileSystem)
}
var context:GameContext
var fileSystem:FileSystem
let defaultDateFormat = "yyyy-MM-dd"
let defaultTimeFormat = "hh:mm:ss a"
let defaultDateTimeFormat = "yyyy-MM-dd hh:mm:ss a"
init(context:GameContext, fileSystem:FileSystem) {
self.context = context
self.fileSystem = fileSystem
}
func load() {
let configFile = self.context.pathProvider.configFolder().stringByAppendingPathComponent("app.cfg")
if !self.fileSystem.fileExists(configFile) {
context.settings.profile = "Default"
context.settings.checkForApplicationUpdates = true
context.settings.downloadPreReleaseVersions = false
context.settings.variableDateFormat = defaultDateFormat
context.settings.variableTimeFormat = defaultTimeFormat
context.settings.variableDatetimeFormat = defaultDateTimeFormat
return
}
var data:String?
do {
data = try self.fileSystem.stringWithContentsOfFile(configFile, encoding: NSUTF8StringEncoding)
} catch {
return
}
if data == nil {
return
}
do {
let dict = try JSONSerializer.toDictionary(data!)
self.context.settings.defaultProfile = dict.stringValue("defaultProfile", defaultVal: "Default")
self.context.settings.checkForApplicationUpdates = dict.boolValue("checkForApplicationUpdates", defaultVal: true)
self.context.settings.downloadPreReleaseVersions = dict.boolValue("downloadPreReleaseVersions", defaultVal: false)
self.context.settings.variableDateFormat = dict.stringValue("variableDateFormat", defaultVal: defaultDateFormat)
self.context.settings.variableTimeFormat = dict.stringValue("variableTimeFormat", defaultVal: defaultTimeFormat)
self.context.settings.variableDatetimeFormat = dict.stringValue("variableDatetimeFormat", defaultVal: defaultDateTimeFormat)
}
catch {
}
}
func save() {
let configFile = self.context.pathProvider.configFolder().stringByAppendingPathComponent("app.cfg")
let settings = BasicSettings(
defaultProfile: self.context.settings.defaultProfile,
checkForApplicationUpdates: self.context.settings.checkForApplicationUpdates ? "yes" : "no",
downloadPreReleaseVersions: self.context.settings.downloadPreReleaseVersions ? "yes" : "no",
variableDateFormat: self.context.settings.variableDateFormat,
variableTimeFormat: self.context.settings.variableTimeFormat,
variableDatetimeFormat: self.context.settings.variableDatetimeFormat)
let json = JSONSerializer.toJson(settings, prettify: true)
self.fileSystem.write(json, toFile: configFile)
}
struct BasicSettings {
var defaultProfile:String
var checkForApplicationUpdates:String
var downloadPreReleaseVersions:String
var variableDateFormat:String
var variableTimeFormat:String
var variableDatetimeFormat:String
}
}
| mit | 95261220517aabd02454c177f2051044 | 36.698925 | 136 | 0.692812 | 4.987198 | false | true | false | false |
hachinobu/SwiftQiitaClient | SwiftQiitaClient/Model/QiitaAPI/Endpoint/PostItemEndpoint.swift | 1 | 1778 | //
// PostItemEndpoint.swift
// SwiftQiitaClient
//
// Created by Takahiro Nishinobu on 2015/11/29.
// Copyright © 2015年 hachinobu. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
extension QiitaAPI {
class AllPostItemList: RequestProtocol {
typealias ResponseType = AllPostItemListModel
var path: String = "/api/v2/items"
var parameters: [String: AnyObject]?
init(parameters: [String: AnyObject]?) {
self.parameters = parameters
}
var responseSerializer: ResponseSerializer<ResponseType, NSError> {
return ResponseSerializer<ResponseType, NSError> { request, response, data, error -> Result<ResponseType, NSError> in
let resultJson = Alamofire.Request.JSONResponseSerializer().serializeResponse(request, response, data, error)
if let error = resultJson.error {
return .Failure(error)
}
guard let object = Mapper<PostItemModel>().mapArray(resultJson.value) else {
return .Failure(NSError(domain: "com.hachinobu.qiitaclient", code: -1000, userInfo: [NSLocalizedFailureReasonErrorKey: "Mapping Error"]))
}
let postItemList = AllPostItemListModel(postItems: object)
return .Success(postItemList)
}
}
}
class PostItemDetail: RequestProtocol {
typealias ResponseType = PostItemModel
var path: String = "/api/v2/items/"
init(itemId: String) {
path += itemId
}
}
} | mit | 3cfa72bbdce560a160d7ce1cb830c50f | 29.101695 | 157 | 0.567324 | 5.378788 | false | false | false | false |
Athlee/ATHKit | Examples/ATHImagePickerController/Storyboard/TestPicker/Pods/Material/Sources/iOS/NavigationController.swift | 2 | 6413 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UINavigationController {
/// Device status bar style.
open var statusBarStyle: UIStatusBarStyle {
get {
return Application.statusBarStyle
}
set(value) {
Application.statusBarStyle = value
}
}
}
open class NavigationController: UINavigationController {
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with an Optional nib and bundle.
- Parameter nibNameOrNil: An Optional String for the nib.
- Parameter bundle: An Optional NSBundle where the nib is located.
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
An initializer that initializes the object with a rootViewController.
- Parameter rootViewController: A UIViewController for the rootViewController.
*/
public override init(rootViewController: UIViewController) {
super.init(navigationBarClass: NavigationBar.self, toolbarClass: nil)
setViewControllers([rootViewController], animated: false)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let v = interactivePopGestureRecognizer else {
return
}
guard let x = navigationDrawerController else {
return
}
if let l = x.leftPanGesture {
l.require(toFail: v)
}
if let r = x.rightPanGesture {
r.require(toFail: v)
}
}
open override func viewDidLoad() {
super.viewDidLoad()
prepare()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let v = navigationBar as? NavigationBar else {
return
}
guard let item = v.topItem else {
return
}
v.layoutNavigationItem(item: item)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
navigationBar.width = view.width
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
navigationBar.heightPreset = .normal
navigationBar.width = view.width
view.clipsToBounds = true
view.backgroundColor = .white
view.contentScaleFactor = Screen.scale
// This ensures the panning gesture is available when going back between views.
if let v = interactivePopGestureRecognizer {
v.isEnabled = true
v.delegate = self
}
}
}
extension NavigationController: UINavigationBarDelegate {
/**
Delegation method that is called when a new UINavigationItem is about to be pushed.
This is used to prepare the transitions between UIViewControllers on the stack.
- Parameter navigationBar: A UINavigationBar that is used in the NavigationController.
- Parameter item: The UINavigationItem that will be pushed on the stack.
- Returns: A Boolean value that indicates whether to push the item on to the stack or not.
True is yes, false is no.
*/
public func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool {
if let v = navigationBar as? NavigationBar {
item.backButton.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside)
item.backButton.image = v.backButtonImage
item.leftViews.insert(item.backButton, at: 0)
v.layoutNavigationItem(item: item)
}
return true
}
/// Handler for the back button.
@objc
internal func handleBackButton() {
popViewController(animated: true)
}
}
extension NavigationController: UIGestureRecognizerDelegate {
/**
Detects the gesture recognizer being used. This is necessary when using
NavigationDrawerController. It eliminates the conflict in panning.
- Parameter gestureRecognizer: A UIGestureRecognizer to detect.
- Parameter touch: The UITouch event.
- Returns: A Boolean of whether to continue the gesture or not, true yes, false no.
*/
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return interactivePopGestureRecognizer == gestureRecognizer && nil != navigationBar.backItem
}
}
| mit | bbd15a668eeb79d6d6aa7a7f06f1fb7b | 35.856322 | 115 | 0.701388 | 5.025862 | false | false | false | false |
rabbitinspace/Tosoka | Tests/TosokaTests/JSON/Jay/Formatter.swift | 2 | 4239 | //
// Formatter.swift
// Jay
//
// Created by Honza Dvorsky on 2/19/16.
// Copyright © 2016 Honza Dvorsky. All rights reserved.
//
protocol JsonFormattable {
func format(to stream: JsonOutputStream, with formatter: Formatter) throws
}
extension JSON: JsonFormattable {
func format(to stream: JsonOutputStream, with formatter: Formatter) throws {
switch self {
//null
case .null:
stream <<< Const.Null
//number
case .number(let num):
switch num {
case .integer(let i):
stream <<< String(i).chars()
case .unsignedInteger(let ui):
stream <<< String(ui).chars()
case .double(let d):
stream <<< String(d).chars()
}
//boolean
case .boolean(let bool):
stream <<< (bool ? Const.True : Const.False)
//string
case .string(let str):
try self.format(to: stream, string: str)
//array
case .array(let arr):
try self.format(to: stream, array: arr, with: formatter)
//object
case .object(let obj):
return try self.format(to: stream, object: obj, with: formatter)
}
}
func format(to stream: JsonOutputStream, string: String) throws {
var contents: [JChar] = []
for c in string.utf8 {
//if this is an escapable character, escape it
//first check for specific rules
if let replacement = Const.EscapingRulesInv[c] {
contents.append(contentsOf: [Const.Escape, replacement])
continue
}
//simple escape, just prepend with the escape char
if Const.SimpleEscaped.contains(c) {
contents.append(contentsOf: [Const.Escape, c])
continue
}
//control character that wasn't escaped above, just convert to
//an escaped unicode sequence, i.e. "\u0006" for "ACK"
if Const.ControlCharacters.contains(c) {
contents.append(contentsOf: c.controlCharacterHexString())
continue
}
//nothing to escape, just append byte
contents.append(c)
}
//now we have the contents of the string, we need to add
//quotes before and after
stream <<< Const.QuotationMark
stream <<< contents
stream <<< Const.QuotationMark
}
func format(to stream: JsonOutputStream, array: [JSON], with formatter: Formatter) throws {
guard array.count > 0 else {
stream <<< Const.BeginArray <<< Const.EndArray
return
}
let nested = formatter.nextLevel()
stream <<< Const.BeginArray <<< formatter.newline()
for (idx, item) in array.enumerated() {
if idx > 0 { stream <<< Const.ValueSeparator <<< nested.newline() }
stream <<< nested.indent()
try item.format(to: stream, with: nested)
}
stream <<< formatter.newlineAndIndent() <<< Const.EndArray
}
func format(to stream: JsonOutputStream, object: [String: JSON], with formatter: Formatter) throws {
if object.count == 0 {
stream <<< Const.BeginObject <<< Const.EndObject
return
}
//sort first however, to be good citizens
let pairs = object.sorted { (a, b) -> Bool in a.0 <= b.0 }
let nested = formatter.nextLevel()
stream <<< Const.BeginObject <<< formatter.newline()
for (idx, pair) in pairs.enumerated() {
if idx > 0 { stream <<< Const.ValueSeparator <<< nested.newline() }
stream <<< nested.indent()
try self.format(to: stream, string: pair.0)
stream <<< Const.NameSeparator <<< nested.separator()
try pair.1.format(to: stream, with: nested)
}
stream <<< formatter.newlineAndIndent() <<< Const.EndObject
}
}
| mit | 49bfbd12b1536ea4a9f2cadd5d06bdc6 | 32.109375 | 104 | 0.526899 | 4.821388 | false | false | false | false |
insidegui/PlayAlways | PlayAways/StatusItemController.swift | 1 | 3962 | //
// StatusItemController.swift
// PlayAways
//
// Created by Guilherme Rambo on 08/12/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Cocoa
enum MenuOptions: Int {
case iOS
case macOS
case tvOS
case iOSWithPanel
case macOSWithPanel
case tvOSWithPanel
}
final class StatusItemController {
private let menu: NSMenu = {
let newMenu = NSMenu(title: "PlayAlways")
// New iOS Playground
let newEmbeddedItem = NSMenuItem(title: NSLocalizedString("New iOS Playground", comment: "New iOS Playgroud menu item"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "1")
newEmbeddedItem.tag = MenuOptions.iOS.rawValue
newMenu.addItem(newEmbeddedItem)
// New iOS Playground (with path selection)
let newEmbeddedItemAlternate = NSMenuItem(title: NSLocalizedString("New iOS Playground…", comment: "New iOS Playgroud menu item (alternate, with ellipsis)"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "1")
newEmbeddedItemAlternate.tag = MenuOptions.iOSWithPanel.rawValue
newEmbeddedItemAlternate.isAlternate = true
newEmbeddedItemAlternate.keyEquivalentModifierMask = [.command, .option]
newMenu.addItem(newEmbeddedItemAlternate)
// New macOS Playground
let newMacItem = NSMenuItem(title: NSLocalizedString("New macOS Playground", comment: "New macOS Playgroud menu item"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "2")
newMacItem.tag = MenuOptions.macOS.rawValue
newMenu.addItem(newMacItem)
// New macOS Playground (with path selection)
let newMacItemAlternate = NSMenuItem(title: NSLocalizedString("New macOS Playground…", comment: "New macOS Playgroud menu item (alternate, with ellipsis)"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "2")
newMacItemAlternate.tag = MenuOptions.macOSWithPanel.rawValue
newMacItemAlternate.isAlternate = true
newMacItemAlternate.keyEquivalentModifierMask = [.command, .option]
newMenu.addItem(newMacItemAlternate)
// New tvOS Playground
let newTVItem = NSMenuItem(title: NSLocalizedString("New tvOS Playground", comment: "New tvOS Playgroud menu item"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "3")
newTVItem.tag = MenuOptions.tvOS.rawValue
newMenu.addItem(newTVItem)
// New tvOS Playground (with path selection)
let newTVItemAlternate = NSMenuItem(title: NSLocalizedString("New tvOS Playground…", comment: "New tvOS Playgroud menu item (alternate, with ellipsis)"), action: #selector(AppDelegate.createNewPlayground(sender:)), keyEquivalent: "3")
newTVItemAlternate.tag = MenuOptions.tvOSWithPanel.rawValue
newTVItemAlternate.isAlternate = true
newTVItemAlternate.keyEquivalentModifierMask = [.command, .option]
newMenu.addItem(newTVItemAlternate)
// Separator
newMenu.addItem(NSMenuItem.separator())
// Set Path
let pathItem = NSMenuItem(title: NSLocalizedString("Set Path…", comment: "Set Path…"), action: #selector(AppDelegate.setPath(_:)), keyEquivalent: "p")
newMenu.addItem(pathItem)
// Quit
let quitItem = NSMenuItem(title: NSLocalizedString("Quit", comment: "Quit"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
newMenu.addItem(quitItem)
return newMenu
}()
private let statusItem: NSStatusItem
init() {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.menu = menu
statusItem.image = #imageLiteral(resourceName: "PlayAlways")
statusItem.highlightMode = true
}
}
| bsd-2-clause | cd73ab0d0e5293778ebdc7a2e98146a1 | 46.035714 | 246 | 0.697545 | 4.800729 | false | false | false | false |
irealme/MapManager | Maptest/Maptest/ViewController.swift | 1 | 11414 | //
// ViewController.swift
// Maptest
//
// Created by Jimmy Jose on 18/08/14.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import MapKit
class ViewController: UIViewController,UITextFieldDelegate,MKMapViewDelegate,UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate{
@IBOutlet var mapView:MKMapView? = MKMapView()
@IBOutlet var textfieldTo:UITextField? = UITextField()
@IBOutlet var textfieldFrom:UITextField? = UITextField()
@IBOutlet var textfieldToCurrentLocation:UITextField? = UITextField()
@IBOutlet var textView:UITextView? = UITextView()
@IBOutlet var tableView:UITableView? = UITableView()
var tableData = NSArray()
var mapManager = MapManager()
var locationManager: CLLocationManager!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
//[CLLocationManager requestWhenInUseAuthorization];
//[CLLocationManager requestAlwaysAuthorization]
let address = "1 Infinite Loop, CA, USA"
textfieldTo?.delegate = self
textfieldFrom?.delegate = self
self.mapView?.delegate = self
}
func mapViewWillStartLocatingUser(mapView: MKMapView!) {
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
println("done")
return polylineRenderer
}
return nil
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "direction")
var idx:Int = indexPath.row
var dictTable:NSDictionary = tableData[idx] as NSDictionary
var instruction = dictTable["instructions"] as NSString
var distance = dictTable["distance"] as NSString
var duration = dictTable["duration"] as NSString
var detail = "distance:\(distance) duration:\(duration)"
cell.textLabel.text = instruction
cell.backgroundColor = UIColor.clearColor()
cell.textLabel.font = UIFont(name: "Helvetica Neue Light", size: 15.0)
cell.selectionStyle = UITableViewCellSelectionStyle.None
//cell.textLabel.font= [UIFont fontWithName:"Helvetica Neue-Light" size:15];
cell.detailTextLabel!.text = detail
return cell
}
@IBAction func usingGoogleButtonPressed(sender:UIButton){
var origin = textfieldFrom?.text
var destination = textfieldTo?.text
origin = origin?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
destination = destination?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if(origin == nil || (countElements(origin!) == 0) || destination == nil || countElements(destination!) == 0)
{
println("enter to and from")
return
}
self.view.endEditing(true)
mapManager.directionsUsingGoogle(from: origin!, to: destination!) { (route,directionInformation, boundingRegion, error) -> () in
if(error != nil){
println(error)
}else{
var pointOfOrigin = MKPointAnnotation()
pointOfOrigin.coordinate = route!.coordinate
pointOfOrigin.title = directionInformation?.objectForKey("start_address") as NSString
pointOfOrigin.subtitle = directionInformation?.objectForKey("duration") as NSString
var pointOfDestination = MKPointAnnotation()
pointOfDestination.coordinate = route!.coordinate
pointOfDestination.title = directionInformation?.objectForKey("end_address") as NSString
pointOfDestination.subtitle = directionInformation?.objectForKey("distance") as NSString
var start_location = directionInformation?.objectForKey("start_location") as NSDictionary
var originLat = start_location.objectForKey("lat")?.doubleValue
var originLng = start_location.objectForKey("lng")?.doubleValue
var end_location = directionInformation?.objectForKey("end_location") as NSDictionary
var destLat = end_location.objectForKey("lat")?.doubleValue
var destLng = end_location.objectForKey("lng")?.doubleValue
var coordOrigin = CLLocationCoordinate2D(latitude: originLat!, longitude: originLng!)
var coordDesitination = CLLocationCoordinate2D(latitude: destLat!, longitude: destLng!)
pointOfOrigin.coordinate = coordOrigin
pointOfDestination.coordinate = coordDesitination
if let web = self.mapView?{
dispatch_async(dispatch_get_main_queue()) {
self.removeAllPlacemarkFromMap(shouldRemoveUserLocation: true)
web.addOverlay(route!)
web.addAnnotation(pointOfOrigin)
web.addAnnotation(pointOfDestination)
web.setVisibleMapRect(boundingRegion!, animated: true)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableData = directionInformation?.objectForKey("steps") as NSArray
self.tableView?.reloadData()
}
}
}
}
}
@IBAction func usingAppleButtonPressed(sender:UIButton){
var destination = textfieldToCurrentLocation?.text
if(destination == nil || countElements(destination!) == 0)
{
println("enter to and from")
return
}
self.view.endEditing(true)
locationManager = CLLocationManager()
locationManager.delegate = self
// locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
//locationManager.requestAlwaysAuthorization() // add in plist NSLocationAlwaysUsageDescription
locationManager.requestWhenInUseAuthorization() // add in plist NSLocationWhenInUseUsageDescription
}
//var location = self.mapView?.userLocation
//var from = location?.coordinate
}
func getDirectionsUsingApple() {
var destination = textfieldToCurrentLocation?.text
mapManager.directionsFromCurrentLocation(to: destination!) { (route, directionInformation, boundingRegion, error) -> () in
if (error? != nil) {
println(error!)
}else{
if let web = self.mapView?{
dispatch_async(dispatch_get_main_queue()) {
self.removeAllPlacemarkFromMap(shouldRemoveUserLocation: true)
web.addOverlay(route!)
web.setVisibleMapRect(boundingRegion!, animated: true)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableData = directionInformation?.objectForKey("steps") as NSArray
self.tableView?.reloadData()
}
}
}
}
}
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var hasAuthorised = false
var locationStatus:NSString = ""
var verboseKey = status
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access"
case CLAuthorizationStatus.Denied:
locationStatus = "Denied access"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Not determined"
default:
locationStatus = "Allowed access"
hasAuthorised = true
}
if(hasAuthorised == true){
getDirectionsUsingApple()
}else {
println("locationStatus \(locationStatus)")
}
}
func removeAllPlacemarkFromMap(#shouldRemoveUserLocation:Bool){
if let mapView = self.mapView {
for annotation in mapView.annotations{
if shouldRemoveUserLocation {
if annotation as? MKUserLocation != mapView.userLocation {
mapView.removeAnnotation(annotation as MKAnnotation)
}
}
}
}
}
}
| mit | f7d8a4135a0c5928645915723cf34015 | 35.006309 | 145 | 0.580953 | 6.376536 | false | false | false | false |
vtourraine/AcknowList | Sources/AcknowList/AcknowListViewController.swift | 1 | 17215 | //
// AcknowListViewController.swift
//
// Copyright (c) 2015-2022 Vincent Tourraine (https://www.vtourraine.net)
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#endif
#if os(iOS)
import SafariServices
#endif
#if os(iOS) || os(tvOS)
/// Subclass of `UITableViewController` that displays a list of acknowledgements.
@available(iOS 9.0.0, tvOS 9.0.0, *)
@available(iOSApplicationExtension, unavailable)
open class AcknowListViewController: UITableViewController {
/// The represented array of `Acknow`.
open var acknowledgements: [Acknow] = []
/**
Header text to be displayed above the list of the acknowledgements.
It needs to get set before `viewDidLoad` gets called.
Its value can be defined in the header of the plist file.
*/
@IBInspectable open var headerText: String?
/**
Footer text to be displayed below the list of the acknowledgements.
It needs to get set before `viewDidLoad` gets called.
Its value can be defined in the header of the plist file.
*/
@IBInspectable open var footerText: String?
/**
Acknowledgements plist file name whose contents to be loaded.
It expects to get set by "User Defined Runtime Attributes" in Interface Builder.
*/
@IBInspectable var acknowledgementsPlistName: String?
// MARK: - Initialization
/**
Initializes the `AcknowListViewController` instance based on default configuration.
- Returns: The new `AcknowListViewController` instance.
*/
public init() {
super.init(style: .grouped)
title = AcknowLocalization.localizedTitle()
if let acknowList = AcknowParser.defaultAcknowList() {
configure(with: acknowList)
}
}
/**
Initializes the `AcknowListViewController` instance with the content of a plist file based on its name.
- Parameters fileName: Name of the acknowledgements plist file
- Returns: The new `AcknowListViewController` instance.
*/
public convenience init(fileNamed fileName: String) {
if let url = Bundle.main.url(forResource: fileName, withExtension: AcknowParser.K.DefaultPods.fileExtension) {
self.init(plistFileURL: url)
}
else {
self.init()
}
}
/**
Initializes the `AcknowListViewController` instance with the content of a plist file based on its path.
- Parameters:
- plistFileURL: The URL to the acknowledgements plist file.
- style: `UITableView.Style` to apply to the table view. **Default:** `.grouped`
- Returns: The new `AcknowListViewController` instance.
*/
public init(plistFileURL: URL, style: UITableView.Style = .grouped) {
super.init(style: style)
title = AcknowLocalization.localizedTitle()
if let data = try? Data(contentsOf: plistFileURL),
let acknowList = try? AcknowPodDecoder().decode(from: data) {
configure(with: acknowList)
}
}
/**
Initializes the `AcknowListViewController` instance with an array of `Acknow`.
- Parameters:
- acknowledgements: The array of `Acknow`.
- style: `UITableView.Style` to apply to the table view. **Default:** `.grouped`
- Returns: The new `AcknowListViewController` instance.
*/
public init(acknowledgements: [Acknow], style: UITableView.Style = .grouped) {
super.init(style: style)
title = AcknowLocalization.localizedTitle()
self.acknowledgements = acknowledgements
}
/**
Initializes the `AcknowListViewController` instance with a coder.
- Parameter coder: The archive coder.
- Returns: The new `AcknowListViewController` instance.
*/
public required init?(coder: NSCoder) {
super.init(coder: coder)
title = AcknowLocalization.localizedTitle()
}
// MARK: - View life cycle
/// Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
override open func awakeFromNib() {
super.awakeFromNib()
if let plistName = acknowledgementsPlistName,
let url = Bundle.main.url(forResource: plistName, withExtension: AcknowParser.K.DefaultPods.fileExtension),
let data = try? Data(contentsOf: url),
let acknowList = try? AcknowPodDecoder().decode(from: data) {
configure(with: acknowList)
}
else if let defaultAcknowList = AcknowParser.defaultAcknowList() {
configure(with: defaultAcknowList)
}
}
/// Called after the controller's view is loaded into memory.
open override func viewDidLoad() {
super.viewDidLoad()
// Register the cell before use it
let identifier = String(describing: UITableViewCell.self)
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier)
tableView.cellLayoutMarginsFollowReadableWidth = true
if let navigationController = navigationController {
if presentingViewController != nil && navigationController.viewControllers.first == self {
let item = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(AcknowListViewController.dismissViewController(_:)))
navigationItem.leftBarButtonItem = item
}
}
}
/**
Notifies the view controller that its view is about to be added to a view hierarchy.
- Parameter animated: If `YES`, the view is being added to the window using an animation.
*/
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureHeaderView()
configureFooterView()
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: animated)
}
}
/**
Notifies the view controller that its view was added to a view hierarchy.
- Parameter animated: If `YES`, the view is being added to the window using an animation.
*/
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if acknowledgements.isEmpty {
print(
"** AcknowList Warning **\n" +
"No acknowledgements found.\n" +
"This probably means that you didn’t import the `Pods-###-acknowledgements.plist` to your main target.\n" +
"Please take a look at https://github.com/vtourraine/AcknowList for instructions.", terminator: "\n")
}
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { _ in
self.configureHeaderView()
self.configureFooterView()
}
}
// MARK: - Actions
/**
Opens a link with Safari.
- Parameter sender: The event sender, a gesture recognizer attached to the label containing the link URL.
*/
@IBAction open func openLink(_ sender: UIGestureRecognizer) {
guard let label = sender.view as? UILabel,
let text = label.text,
let url = AcknowParser.firstLink(in: text) else {
return
}
if #available(iOS 10.0, tvOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
/**
Dismisses the view controller.
- Parameter sender: The event sender.
*/
@IBAction open func dismissViewController(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
// MARK: - Configuration
let LabelMargin: CGFloat = 20
let FooterBottomMargin: CGFloat = 20
func configure(with acknowList: AcknowList) {
acknowledgements = AcknowLocalization.sorted(acknowList.acknowledgements)
if let header = acknowList.headerText, header != AcknowPodDecoder.K.DefaultHeaderText, !header.isEmpty {
headerText = header
}
if acknowList.footerText == AcknowPodDecoder.K.DefaultFooterText, footerText == nil {
footerText = AcknowLocalization.localizedCocoaPodsFooterText()
}
else if let footer = acknowList.footerText, !footer.isEmpty, footerText == nil {
footerText = footer
}
}
func headerFooterLabel(frame: CGRect, font: UIFont, text: String?) -> UILabel {
let label = UILabel(frame: frame)
label.text = text
label.font = font
if #available(iOS 13.0, tvOS 13.0, *) {
label.textColor = .secondaryLabel
}
else {
label.textColor = .gray
}
label.numberOfLines = 0
label.textAlignment = .center
label.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
if #available(iOS 10.0, tvOS 10.0, *) {
label.adjustsFontForContentSizeCategory = true
}
if let text = text, AcknowParser.firstLink(in: text) != nil {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AcknowListViewController.openLink(_:)))
label.addGestureRecognizer(tapGestureRecognizer)
label.isUserInteractionEnabled = true
}
return label
}
func configureHeaderView() {
let font = UIFont.preferredFont(forTextStyle: .footnote)
let labelWidth = view.frame.width - 2 * LabelMargin
guard let text = headerText else {
return
}
let labelHeight = heightForLabel(text: text as NSString, width: labelWidth)
let labelFrame = CGRect(x: LabelMargin, y: LabelMargin, width: labelWidth, height: labelHeight)
let label = headerFooterLabel(frame: labelFrame, font: font, text: text)
let headerFrame = CGRect(x: 0, y: 0, width: view.frame.width, height: label.frame.height + 2 * LabelMargin)
let headerView = UIView(frame: headerFrame)
headerView.isUserInteractionEnabled = label.isUserInteractionEnabled
headerView.addSubview(label)
tableView.tableHeaderView = headerView
}
func configureFooterView() {
let font = UIFont.preferredFont(forTextStyle: .footnote)
let labelWidth = view.frame.width - 2 * LabelMargin
guard let text = footerText else {
return
}
let labelHeight = heightForLabel(text: text as NSString, width: labelWidth)
let labelFrame = CGRect(x: LabelMargin, y: 0, width: labelWidth, height: labelHeight);
let label = headerFooterLabel(frame: labelFrame, font: font, text: text)
let footerHeight: CGFloat
let labelOriginY: CGFloat
if tableView.style == .plain {
// “Plain” table views need additional margin between the bottom of the last row and the top of the footer label.
labelOriginY = FooterBottomMargin
footerHeight = label.frame.height + FooterBottomMargin * 2
}
else {
labelOriginY = 0
footerHeight = label.frame.height + FooterBottomMargin
}
let footerFrame = CGRect(x: 0, y: 0, width: label.frame.width, height: footerHeight)
let footerView = UIView(frame: footerFrame)
footerView.isUserInteractionEnabled = label.isUserInteractionEnabled
footerView.addSubview(label)
label.frame = CGRect(x: 0, y: labelOriginY, width: label.frame.width, height: label.frame.height);
tableView.tableFooterView = footerView
}
func heightForLabel(text labelText: NSString, width labelWidth: CGFloat) -> CGFloat {
let font = UIFont.preferredFont(forTextStyle: .footnote)
let options: NSStringDrawingOptions = NSStringDrawingOptions.usesLineFragmentOrigin
// should be (NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin)?
let labelBounds: CGRect = labelText.boundingRect(with: CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude), options: options, attributes: [NSAttributedString.Key.font: font], context: nil)
let labelHeight = labelBounds.height
return CGFloat(ceilf(Float(labelHeight)))
}
// MARK: - Table view data source
/**
Asks the data source to return the number of sections in the table view.
- Parameter tableView: An object representing the table view requesting this information.
- Returns: The number of sections in `tableView`. The default value is 1.
*/
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return acknowledgements.count
}
/**
Asks the data source for a cell to insert in a particular location of the table view.
- Parameters:
- tableView: The table-view object requesting the cell.
- indexPath: An index path that locates a row in `tableView`.
- Returns: An object inheriting from `UITableViewCell` that the table view can use for the specified row. An assertion is raised if you return `nil`.
*/
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = String(describing: UITableViewCell.self)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
if let acknowledgement = acknowledgements[(indexPath as NSIndexPath).row] as Acknow?,
let textLabel = cell.textLabel as UILabel? {
textLabel.text = acknowledgement.title
if canOpen(acknowledgement) {
cell.accessoryType = .disclosureIndicator
cell.selectionStyle = .default
}
else {
cell.accessoryType = .none
cell.selectionStyle = .none
}
}
return cell
}
// MARK: Table view delegate
/**
Tells the delegate that the specified row is now selected.
- Parameters:
- tableView: A table-view object informing the delegate about the new row selection.
- indexPath: An index path locating the new selected row in `tableView`.
*/
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let acknowledgement = acknowledgements[(indexPath as NSIndexPath).row] as Acknow?,
let navigationController = navigationController {
if acknowledgement.text != nil {
let viewController = AcknowViewController(acknowledgement: acknowledgement)
navigationController.pushViewController(viewController, animated: true)
}
else if canOpenRepository(for: acknowledgement),
let repository = acknowledgement.repository {
#if !os(tvOS)
let safariViewController = SFSafariViewController(url: repository)
present(safariViewController, animated: true)
#endif
}
}
}
/**
Asks the delegate for the estimated height of a row in a specified location.
- Parameters:
- tableView: The table-view object requesting this information.
- indexPath: An index path that locates a row in `tableView`.
- Returns: A nonnegative floating-point value that estimates the height (in points) that `row` should be. Return `UITableViewAutomaticDimension` if you have no estimate.
*/
open override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
// MARK: - Navigation
private func canOpen(_ acknowledgement: Acknow) -> Bool {
return acknowledgement.text != nil || canOpenRepository(for: acknowledgement)
}
private func canOpenRepository(for acknowledgement: Acknow) -> Bool {
guard let scheme = acknowledgement.repository?.scheme else {
return false
}
return scheme == "http" || scheme == "https"
}
}
#endif
| mit | efc1524834b4dfe991cc7ad1ebebe84e | 39.02093 | 211 | 0.666279 | 4.975137 | false | false | false | false |
359north/swift-quiet-uisplitviewcontroller | SplitViewWithContainer/DetailViewController.swift | 1 | 1496 | //
// DetailViewController.swift
// SplitViewWithContainer
//
// Created by Steve Mykytyn on 8/14/15.
// Copyright (c) 2015 359 North Inc. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
static var instanceCounter:Int = 0
var instanceID:Int = -1
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
if ( instanceID == -1) { // capture the ID and update the counter once for each instance
DetailViewController.instanceCounter++
instanceID = DetailViewController.instanceCounter
}
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = String(format:"DetailViewController\nhash = %lx\nitem = %@\ninstance %ld",self.hash,detailItem!.description, instanceID)
}
}
}
// note the following method is essential: you can just rely on the super method being in place
// the first set of detailItem occurs
// before DetailViewController.instanceCounter is available
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
let someString = String(format: "DetailViewController deinit instanceID = %ld",instanceID)
println(someString);
}
}
| mit | 26e70abd04093943eb2543f31ce0539f | 20.070423 | 137 | 0.707888 | 4.087432 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/AccountPicker/RIB/AccountPickerInteractor.swift | 1 | 9468 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import Combine
import DIKit
import Errors
import MoneyKit
import PlatformKit
import RIBs
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
public protocol AccountPickerRouting: ViewableRouting {
// Declare methods the interactor can invoke to manage sub-tree via the router.
}
public final class AccountPickerInteractor: PresentableInteractor<AccountPickerPresentable>, AccountPickerInteractable {
// MARK: - Properties
weak var router: AccountPickerRouting?
// MARK: - Private Properties
private let searchRelay: PublishRelay<String?> = .init()
private let accountProvider: AccountPickerAccountProviding
private let didSelect: AccountPickerDidSelect?
private let disposeBag = DisposeBag()
private weak var listener: AccountPickerListener?
private let app: AppProtocol
private let priceRepository: PriceRepositoryAPI
// MARK: - Init
init(
presenter: AccountPickerPresentable,
accountProvider: AccountPickerAccountProviding,
listener: AccountPickerListenerBridge,
app: AppProtocol = resolve(),
priceRepository: PriceRepositoryAPI = resolve(tag: DIKitPriceContext.volume)
) {
self.app = app
self.priceRepository = priceRepository
self.accountProvider = accountProvider
switch listener {
case .simple(let didSelect):
self.didSelect = didSelect
self.listener = nil
case .listener(let listener):
didSelect = nil
self.listener = listener
}
super.init(presenter: presenter)
}
// MARK: - Methods
override public func didBecomeActive() {
super.didBecomeActive()
let button = presenter.button
if let button = button {
button.tapRelay
.bind { [weak self] in
guard let self = self else { return }
self.handle(effects: .button)
}
.disposeOnDeactivate(interactor: self)
}
let searchObservable = searchRelay.asObservable()
.startWith(nil)
.distinctUntilChanged()
.debounce(.milliseconds(350), scheduler: MainScheduler.asyncInstance)
let interactorState: Driver<State> = Observable
.combineLatest(
accountProvider.accounts.flatMap { [app, priceRepository] accounts in
accounts.snapshot(app: app, priceRepository: priceRepository).asObservable()
},
searchObservable
)
.map { [button] accounts, searchString -> State in
let isFiltering = searchString
.flatMap { !$0.isEmpty } ?? false
var interactors = accounts
.filter { snapshot in
snapshot.account.currencyType.matchSearch(searchString)
}
.sorted(by: >)
.map(\.account)
.map(\.accountPickerCellItemInteractor)
if interactors.isEmpty {
interactors.append(.emptyState)
}
if let button = button {
interactors.append(.button(button))
}
return State(
isFiltering: isFiltering,
interactors: interactors
)
}
.asDriver(onErrorJustReturn: .empty)
presenter
.connect(state: interactorState)
.drive(onNext: handle(effects:))
.disposeOnDeactivate(interactor: self)
}
// MARK: - Private methods
private func handle(effects: Effects) {
switch effects {
case .select(let account):
didSelect?(account)
listener?.didSelect(blockchainAccount: account)
case .back:
listener?.didTapBack()
case .closed:
listener?.didTapClose()
case .filter(let string):
searchRelay.accept(string)
case .button:
listener?.didSelectActionButton()
case .ux(let ux):
listener?.didSelect(ux: ux)
case .none:
break
}
}
}
extension AccountPickerInteractor {
public struct State {
static let empty = State(isFiltering: false, interactors: [])
let isFiltering: Bool
let interactors: [AccountPickerCellItem.Interactor]
}
public enum Effects {
case select(BlockchainAccount)
case back
case closed
case ux(UX.Dialog)
case filter(String?)
case button
case none
}
}
extension BlockchainAccount {
fileprivate var accountPickerCellItemInteractor: AccountPickerCellItem.Interactor {
switch self {
case is PaymentMethodAccount:
return .paymentMethodAccount(self as! PaymentMethodAccount)
case is LinkedBankAccount:
let account = self as! LinkedBankAccount
return .linkedBankAccount(account)
case is SingleAccount:
let singleAccount = self as! SingleAccount
return .singleAccount(singleAccount, AccountAssetBalanceViewInteractor(account: singleAccount))
case is AccountGroup:
let accountGroup = self as! AccountGroup
return .accountGroup(
accountGroup,
AccountGroupBalanceCellInteractor(
balanceViewInteractor: WalletBalanceViewInteractor(account: accountGroup)
)
)
default:
impossible()
}
}
}
struct BlockchainAccountSnapshot: Comparable {
let account: BlockchainAccount
let balance: FiatValue
let count: Int
let isSelectedAsset: Bool
let volume24h: BigInt
static func == (lhs: BlockchainAccountSnapshot, rhs: BlockchainAccountSnapshot) -> Bool {
lhs.account.identifier == rhs.account.identifier
&& lhs.balance == rhs.balance
&& lhs.count == rhs.count
&& lhs.volume24h == rhs.volume24h
&& lhs.isSelectedAsset == rhs.isSelectedAsset
}
static func < (lhs: BlockchainAccountSnapshot, rhs: BlockchainAccountSnapshot) -> Bool {
(
lhs.isSelectedAsset ? 1 : 0,
lhs.count,
lhs.balance.amount,
lhs.account.currencyType == .bitcoin ? 1 : 0,
lhs.volume24h
) < (
rhs.isSelectedAsset ? 1 : 0,
rhs.count,
rhs.balance.amount,
rhs.account.currencyType == .bitcoin ? 1 : 0,
rhs.volume24h
)
}
}
extension BlockchainAccount {
var empty: (snapshot: BlockchainAccountSnapshot, Void) {
(
snapshot: BlockchainAccountSnapshot(
account: self,
balance: .zero(currency: .USD),
count: 0,
isSelectedAsset: false,
volume24h: 0
), ()
)
}
}
private enum BlockchainAccountSnapshotError: Error {
case isNotEnabled
case noTradingCurrency
}
extension Collection where Element == BlockchainAccount {
func snapshot(
app: AppProtocol,
priceRepository: PriceRepositoryAPI
) -> AnyPublisher<[BlockchainAccountSnapshot], Never> {
Task<[BlockchainAccountSnapshot], Error>.Publisher {
guard try await app.get(blockchain.ux.transaction.smart.sort.order.is.enabled) else {
throw BlockchainAccountSnapshotError.isNotEnabled
}
guard let currency: FiatCurrency = try await app.get(
blockchain.user.currency.preferred.fiat.display.currency
) else {
throw BlockchainAccountSnapshotError.noTradingCurrency
}
let prices = try await priceRepository.prices(
of: map(\.currencyType),
in: FiatCurrency.USD,
at: .oneDay
)
.stream()
.next()
var accounts = [BlockchainAccountSnapshot]()
for account in self {
let count: Int? = try? await app.get(
blockchain.ux.transaction.source.target[account.currencyType.code].count.of.completed
)
let currentId: String? = try? await app.get(
blockchain.ux.transaction.source.target.id
)
let balance = try? await account.fiatBalance(fiatCurrency: currency)
.stream()
.next()
accounts.append(
BlockchainAccountSnapshot(
account: account,
balance: balance?.fiatValue ?? .zero(currency: currency),
count: count ?? 0,
isSelectedAsset: currentId?.lowercased() == account.currencyType.code.lowercased(),
volume24h: prices["\(account.currencyType.code)-USD"].flatMap { quote in
quote.moneyValue.amount * BigInt(quote.volume24h.or(.zero))
} ?? .zero
)
)
}
return accounts
}
.replaceError(with: map(\.empty.snapshot))
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | ec052ef7beae479feba5aa5487984ad4 | 31.421233 | 120 | 0.577268 | 5.394302 | false | false | false | false |
keyeMyria/DeckRocket | Source/Shared/Slide.swift | 1 | 2434 | //
// Slide.swift
// DeckRocket
//
// Created by JP Simard on 4/8/15.
// Copyright (c) 2015 JP Simard. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
typealias Image = UIImage
#else
import AppKit
typealias Image = NSImage
extension NSImage {
func imageByScalingWithFactor(factor: CGFloat) -> NSImage {
let targetSize = CGSize(width: size.width * factor, height: size.height * factor)
let targetRect = NSRect(origin: NSZeroPoint, size: targetSize)
let newImage = NSImage(size: targetSize)
newImage.lockFocus()
drawInRect(targetRect, fromRect: NSZeroRect, operation: .CompositeSourceOver, fraction: 1)
newImage.unlockFocus()
return newImage
}
}
#endif
struct Slide {
let image: Image
let notes: String?
init(image: Image, notes: String?) {
self.image = image
self.notes = notes
}
init?(dictionary: NSDictionary) {
let image = flatMap(dictionary["image"] as? NSData) { Image(data: $0) }
let notes = dictionary["notes"] as? String
if let image = image {
self.init(image: image, notes: notes)
return
}
return nil
}
static func slidesfromData(data: NSData) -> [Slide?]? {
return flatMap(NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [NSDictionary]) { data in
map(data) {
if let imageData = $0["image"] as? NSData, image = Image(data: imageData) {
let notes = $0["notes"] as? String
return Slide(image: image, notes: notes)
}
return nil
}
}
}
#if !os(iOS)
init?(pdfData: NSData, notes: String?) {
if let pdfImageRep = NSPDFImageRep(data: pdfData) {
let image = NSImage()
image.addRepresentation(pdfImageRep)
self.init(image: image.imageByScalingWithFactor(0.5), notes: notes)
return
}
return nil
}
var dictionaryRepresentation: NSDictionary? {
return flatMap(flatMap(image.TIFFRepresentation) {
return NSBitmapImageRep(data: $0)?
.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: 0.5])
}) {
return ["image": $0, "notes": notes ?? ""]
}
}
#endif
}
| mit | 4f851d312f5dd78cd324ab5723e6d9b1 | 28.682927 | 102 | 0.576007 | 4.449726 | false | false | false | false |
ludoded/ReceiptBot | ReceiptBot/Scene/Expenses/ExpensesRouter.swift | 1 | 2112 | //
// ExpensesRouter.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/5/17.
// Copyright (c) 2017 receiptbot. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol ExpensesRouterInput {
func navigateToSomewhere()
}
class ExpensesRouter: ExpensesRouterInput {
weak var viewController: ExpensesViewController!
// MARK: - Navigation
func navigateToSomewhere() {
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: - Communication
func passDataToNextScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue: segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| lgpl-3.0 | 3e75baa1e1e4609aa0902bb7956b9381 | 36.052632 | 114 | 0.722538 | 5.557895 | false | false | false | false |
cactis/SwiftEasyKit | Source/Classes/GroupView.swift | 1 | 1350 | // GruposView.swift
//
import UIKit
import Neon
import Facade
open class GroupsView: DefaultView {
public var body: UIView!
public var groupMargins: [UIView]! = []
public var groups: [UIView]! = []
public var count: Int! = 2
public var padding: CGFloat! = 0
public var group: Neon.Group! = .horizontal
public var margin: UIEdgeInsets!
public var label: UILabel!
public init(count: Int? = 2, padding: CGFloat? = 0, group: Neon.Group? = .horizontal, margin: UIEdgeInsets? = .zero) {
self.count = count
self.padding = padding
self.group = group!
self.margin = margin!
super.init(frame: .zero)
body = addView()
for _ in 0...count! - 1 {
let v = body.addView()
groupMargins.append(v)
let g = v.addView()
groups.append(g)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override open func layoutSubviews() {
super.layoutSubviews()
body.fillSuperview()
body.groupAndFill(group: group, views: groupMargins.map({$0 as UIView}) , padding: padding!)
groups.forEach({ (v) -> () in
v.fillSuperview(withLeftPadding: margin.left, rightPadding: margin.right, topPadding: margin.top, bottomPadding: margin.bottom)
})
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
| mit | 084aa747575857efa12fc0a0a24b86a1 | 24.471698 | 133 | 0.657037 | 3.75 | false | false | false | false |
johndatserakis/RibbonReminder | Ribbon Reminder/ViewController.swift | 1 | 22801 | //
// ViewController.swift
// Ribbon Reminder
//
// Created by John Datserakis on 11/7/14.
// Copyright (c) 2014 John Datserakis. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var indexPathHolder = 0
var overlayView: UIView!
var alertView: UIView!
var animator: UIDynamicAnimator!
var attachmentBehavior : UIAttachmentBehavior!
var snapBehavior : UISnapBehavior!
@IBOutlet weak var tableMain: UITableView!
@IBOutlet var textFieldAdd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Initialize the animator
animator = UIDynamicAnimator(referenceView: view)
textFieldAdd?.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "itemChanged:", name: "reloadTableViewData", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
tableMain.reloadData()
}
func itemChanged(sender: AnyObject) {
tableMain.reloadData()
}
//Delegate method
func textFieldDidBeginEditing(textField: UITextField!) {
println("began editing")
}
//Delegate method
func textFieldShouldEndEditing(textField: UITextField!) -> Bool {
return false
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
textFieldAdd?.endEditing(true)
}
@IBAction func ribbon_button(sender: UIButton) {
println("ribbon pressed")
}
@IBAction func question_button(sender: UIButton) {
println("question pressed")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func detailTapped(sender: UIButton) {
var cell = sender.superview as UITableViewCell
var indexPath = tableMain.indexPathForCell(cell)
if indexPath?.row == 0 {
println("Row 1 was clicked")
indexPathHolder = 0
// Create the dark background view and the alert view
createOverlay()
createAlert()
showAlert()
textFieldAdd.becomeFirstResponder()
}
if indexPath?.row == 1 {
println("Row 2 was clicked")
indexPathHolder = 1
createOverlay()
createAlert()
showAlert()
textFieldAdd.becomeFirstResponder()
}
if indexPath?.row == 2 {
println("Row 3 was clicked")
indexPathHolder = 2
createOverlay()
createAlert()
showAlert()
textFieldAdd.becomeFirstResponder()
}
if indexPath?.row == 3 {
println("Row 4 was clicked")
indexPathHolder = 3
createOverlay()
createAlert()
showAlert()
textFieldAdd.becomeFirstResponder()
}
if indexPath?.row == 4 {
println("Row 5 was clicked")
indexPathHolder = 4
createOverlay()
createAlert()
showAlert()
textFieldAdd.becomeFirstResponder()
}
}
func removeTapped(sender: UIButton) {
var cell = sender.superview as UITableViewCell
var indexPath = tableMain.indexPathForCell(cell)
if indexPath?.row == 0 {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey("textfield0")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.removeObjectForKey("ribbon0")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible0")
sharedDefaults?.synchronize()
}
if indexPath?.row == 1 {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey("textfield1")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible1")
sharedDefaults?.removeObjectForKey("ribbon1")
sharedDefaults?.synchronize()
}
if indexPath?.row == 2 {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey("textfield2")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible2")
sharedDefaults?.removeObjectForKey("ribbon2")
sharedDefaults?.synchronize()
}
if indexPath?.row == 3 {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey("textfield3")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible3")
sharedDefaults?.removeObjectForKey("ribbon3")
sharedDefaults?.synchronize()
}
if indexPath?.row == 4 {
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.removeObjectForKey("textfield4")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible4")
sharedDefaults?.removeObjectForKey("ribbon4")
sharedDefaults?.synchronize()
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell
if (cell == nil) {
//creating cell
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
}
//Label Work
var label_title : UILabel? = self.view.viewWithTag(1) as? UILabel;
var newFont = UIFont(name: "Wawati TC", size: 20)
label_title?.font = newFont
var userDefaults = NSUserDefaults.standardUserDefaults()
if indexPath.row == 0 {
if userDefaults.stringForKey("textfield0") != nil {
label_title?.text = userDefaults.stringForKey("textfield0")
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "remove_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "removeTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
} else {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "add_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "detailTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
label_title?.text = "Thumb"
}
}
if indexPath.row == 1 {
if userDefaults.stringForKey("textfield1") != nil {
label_title?.text = userDefaults.stringForKey("textfield1")
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "remove_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "removeTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
} else {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "add_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "detailTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
label_title?.text = "Index"
}
}
if indexPath.row == 2 {
if userDefaults.stringForKey("textfield2") != nil {
label_title?.text = userDefaults.stringForKey("textfield2")
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "remove_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "removeTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
} else {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "add_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "detailTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
label_title?.text = "Middle"
}
}
if indexPath.row == 3 {
if userDefaults.stringForKey("textfield3") != nil {
label_title?.text = userDefaults.stringForKey("textfield3")
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "remove_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "removeTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
} else {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "add_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "detailTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
label_title?.text = "Ring"
}
}
if indexPath.row == 4 {
if userDefaults.stringForKey("textfield4") != nil {
label_title?.text = userDefaults.stringForKey("textfield4")
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "remove_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "removeTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
} else {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "add_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "detailTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
label_title?.text = "Pinky"
}
}
return cell!
}
func createOverlay() {
overlayView = UIView(frame: view.bounds)
overlayView.backgroundColor = UIColor(red: 255/255, green: 239/255, blue: 229/255, alpha: 1.0)
overlayView.alpha = 0.0
view.addSubview(overlayView)
}
func createAlert() {
var alertWidth: CGFloat = 250
var alertHeight: CGFloat = 200
if self.view.frame.width == 414.0 {
println("iPhone 6")
alertWidth = 350
}
if self.view.frame.width == 375.0 {
println("iPhone 6")
alertWidth = 300
}
if self.view.frame.width == 320.0 {
println("iPhone 5/4s")
}
var alertViewFrame: CGRect = CGRectMake(0, 0, alertWidth, alertHeight)
alertView = UIView(frame: alertViewFrame)
alertView.backgroundColor = UIColor.whiteColor()
alertView.alpha = 0.0
alertView.layer.cornerRadius = 10;
alertView.layer.shadowColor = UIColor.blackColor().CGColor;
alertView.layer.shadowOffset = CGSizeMake(0, 5);
alertView.layer.shadowOpacity = 0.3;
alertView.layer.shadowRadius = 10.0;
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.setTitle("Dismiss", forState: UIControlState.Normal)
button.backgroundColor = UIColor.redColor()
button.frame = CGRectMake(0, 0, alertWidth, 40.0)
button.tintColor = UIColor.whiteColor()
button.layer.cornerRadius = 10
button.addTarget(self, action: Selector("dismissAlert"), forControlEvents: UIControlEvents.TouchUpInside)
alertView.addSubview(button)
view.addSubview(alertView)
var label = UILabel(frame: CGRectMake(0, 0, alertWidth, 125))
label.textColor = UIColor.blackColor()
label.textAlignment = .Center
label.font = UIFont(name: "Wawati TC", size: 15.0)
if indexPathHolder == 0 {
label.text = "Add a ribbon to your thumb"
}
if indexPathHolder == 1 {
label.text = "Add a ribbon to your index finger"
}
if indexPathHolder == 2 {
label.text = "Add a ribbon to your middle finger"
}
if indexPathHolder == 3 {
label.text = "Add a ribbon to your ring finger"
}
if indexPathHolder == 4 {
label.text = "Add a ribbon to your pinky"
}
alertView.addSubview(label)
textFieldAdd = UITextField(frame: CGRectMake(10, 90, alertWidth - 20, 40))
textFieldAdd.borderStyle = UITextBorderStyle.RoundedRect
alertView.addSubview(textFieldAdd)
var buttonGo = UIButton.buttonWithType(UIButtonType.System) as UIButton
buttonGo.setTitle("Save", forState: UIControlState.Normal)
buttonGo.titleLabel?.font = UIFont(name: "Wawati TC", size: 18.0)
buttonGo.tintColor = UIColor.whiteColor()
buttonGo.backgroundColor = UIColor.greenColor()
buttonGo.frame = CGRectMake(100, 145, alertWidth - 200, 40)
buttonGo.addTarget(self, action: Selector("saveGo"), forControlEvents: UIControlEvents.TouchUpInside)
buttonGo.layer.cornerRadius = 10.0
alertView.addSubview(buttonGo)
if UIScreen.mainScreen().bounds.size.height == 480 {
println("iPhone 4/4s")
alertView.frame = CGRectMake(0, 0, alertWidth, 140)
textFieldAdd.frame = CGRectMake(10, 75, alertWidth - 20, 25)
label.frame = CGRectMake(0, -5, alertWidth, 125)
buttonGo.frame = CGRectMake(100, 110, alertWidth - 200, 25)
}
}
func saveGo() {
if textFieldAdd.text == "" {
} else {
var userDefaults = NSUserDefaults.standardUserDefaults()
if indexPathHolder == 0 {
userDefaults.setObject(textFieldAdd.text, forKey: "textfield0")
userDefaults.setBool(true, forKey: "notificationIsVisible0")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setObject(userDefaults.objectForKey("textfield0"), forKey: "ribbon0")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible0")
sharedDefaults?.synchronize()
}
if indexPathHolder == 1 {
userDefaults.setObject(textFieldAdd.text, forKey: "textfield1")
userDefaults.setBool(true, forKey: "notificationIsVisible1")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setObject(userDefaults.objectForKey("textfield1"), forKey: "ribbon1")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible1")
sharedDefaults?.synchronize()
}
if indexPathHolder == 2 {
userDefaults.setObject(textFieldAdd.text, forKey: "textfield2")
userDefaults.setBool(true, forKey: "notificationIsVisible2")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setObject(userDefaults.objectForKey("textfield2"), forKey: "ribbon2")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible2")
sharedDefaults?.synchronize()
}
if indexPathHolder == 3 {
userDefaults.setObject(textFieldAdd.text, forKey: "textfield3")
userDefaults.setBool(true, forKey: "notificationIsVisible3")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setObject(userDefaults.objectForKey("textfield3"), forKey: "ribbon3")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible3")
sharedDefaults?.synchronize()
}
if indexPathHolder == 4 {
userDefaults.setObject(textFieldAdd.text, forKey: "textfield4")
userDefaults.setBool(true, forKey: "notificationIsVisible4")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setObject(userDefaults.objectForKey("textfield4"), forKey: "ribbon4")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible4")
sharedDefaults?.synchronize()
}
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
textFieldAdd.endEditing(true)
dismissAlert()
}
}
func showAlert() {
if (alertView == nil) {
createAlert()
}
createGestureRecognizer()
animator.removeAllBehaviors()
UIView.animateWithDuration(0.4) {
self.overlayView.alpha = 1.0
}
alertView.alpha = 1.0
var snapBehaviour: UISnapBehavior = UISnapBehavior(item: alertView, snapToPoint: CGPointMake(view.center.x, view.center.y - 200))
animator.addBehavior(snapBehaviour)
}
func dismissAlert() {
animator.removeAllBehaviors()
var gravityBehaviour: UIGravityBehavior = UIGravityBehavior(items: [alertView])
gravityBehaviour.gravityDirection = CGVectorMake(0.0, 10.0);
animator.addBehavior(gravityBehaviour)
var itemBehaviour: UIDynamicItemBehavior = UIDynamicItemBehavior(items: [alertView])
itemBehaviour.addAngularVelocity(CGFloat(-M_PI_2), forItem: alertView)
animator.addBehavior(itemBehaviour)
UIView.animateWithDuration(0.4, animations: {
self.overlayView.alpha = 0.0
}, completion: {
(value: Bool) in
self.alertView.removeFromSuperview()
self.alertView = nil
})
}
@IBAction func showAlertView(sender: UIButton) {
showAlert()
}
func createGestureRecognizer() {
let panGestureRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:"))
view.addGestureRecognizer(panGestureRecognizer)
}
func handlePan(sender: UIPanGestureRecognizer) {
if (alertView != nil) {
let panLocationInView = sender.locationInView(view)
let panLocationInAlertView = sender.locationInView(alertView)
if sender.state == UIGestureRecognizerState.Began {
animator.removeAllBehaviors()
let offset = UIOffsetMake(panLocationInAlertView.x - CGRectGetMidX(alertView.bounds), panLocationInAlertView.y - CGRectGetMidY(alertView.bounds));
attachmentBehavior = UIAttachmentBehavior(item: alertView, offsetFromCenter: offset, attachedToAnchor: panLocationInView)
animator.addBehavior(attachmentBehavior)
}
else if sender.state == UIGestureRecognizerState.Changed {
attachmentBehavior.anchorPoint = panLocationInView
}
else if sender.state == UIGestureRecognizerState.Ended {
animator.removeAllBehaviors()
snapBehavior = UISnapBehavior(item: alertView, snapToPoint: CGPointMake(view.center.x, view.center.y - 200))
animator.addBehavior(snapBehavior)
if sender.translationInView(view).y > 100 {
dismissAlert()
}
}
}
}
}
| mit | 303a487580e4910e6215f3e04f658f6a | 38.585069 | 162 | 0.608131 | 5.528855 | false | false | false | false |
Antondomashnev/Sourcery | SourceryTests/Stub/Performance-Code/Kiosk/App/Views/Text Fields/CursorView.swift | 4 | 1234 | import UIKit
class CursorView: UIView {
let cursorLayer: CALayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func awakeFromNib() {
setupCursorLayer()
startAnimating()
}
func setup() {
layer.addSublayer(cursorLayer)
setupCursorLayer()
}
func setupCursorLayer() {
cursorLayer.frame = CGRect(x: layer.frame.width/2 - 1, y: 0, width: 2, height: layer.frame.height)
cursorLayer.backgroundColor = UIColor.black.cgColor
cursorLayer.opacity = 0.0
}
func startAnimating() {
animate(Float.infinity)
}
fileprivate func animate(_ times: Float) {
let fade = CABasicAnimation()
fade.duration = 0.5
fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
fade.repeatCount = times
fade.autoreverses = true
fade.fromValue = 0.0
fade.toValue = 1.0
cursorLayer.add(fade, forKey: "opacity")
}
func stopAnimating() {
cursorLayer.removeAllAnimations()
}
}
| mit | c062d7203121c8e53f42b631bec5ee16 | 23.196078 | 106 | 0.614263 | 4.487273 | false | false | false | false |
teaxus/TSAppEninge | Source/Tools/InformationManage/StringManage.swift | 1 | 13264 | //
// StringManage.swift
// TSAppEngine
//
// Created by teaxus on 15/11/19.
// Copyright © 2015年 teaxus. All rights reserved.
//
import Foundation
public class StringManage: NSObject {
class var textview_test_size:UITextView?{
struct simgle{
static var textview:UITextView?
}
if simgle.textview == nil{
simgle.textview = UITextView()
}
return simgle.textview
}
public static func textViewHeightForAttributedText(text:NSAttributedString,width:CGFloat) -> CGFloat{
if text.string.isEmpty{
return 0
}
StringManage.textview_test_size?.attributedText = text
let size = StringManage.textview_test_size?.sizeThatFits(CGSize(width:width,height:CGFloat.greatestFiniteMagnitude))
return (size?.height)!
}
public static func textViewHeightForText(text:String,width:CGFloat,font:UIFont?) -> CGFloat{
if text.isEmpty{
return 0
}
StringManage.textview_test_size?.text = text
StringManage.textview_test_size?.font = font
let size = StringManage.textview_test_size?.sizeThatFits(CGSize(width:width,height:CGFloat.greatestFiniteMagnitude))
return (size?.height)!
}
public func makeStringArray(r:Range<Int>) -> Array<String>{
var arr_return = Array<String>()
for i in r.lowerBound...r.upperBound{
arr_return.append("\(i)")
}
return arr_return
}
}
extension String{
public var length:Int{
set{}
get{
return (self as NSString).length
}
}
public var url:URL?{
var urlSet = CharacterSet()
// urlSet.formUnionWithCharacterSet(.URLFragmentAllowedCharacterSet())
urlSet.formUnion(CharacterSet.urlFragmentAllowed)
urlSet.formUnion(CharacterSet.urlHostAllowed)
urlSet.formUnion(CharacterSet.urlPasswordAllowed)
urlSet.formUnion(CharacterSet.urlQueryAllowed)
urlSet.formUnion(CharacterSet.urlUserAllowed)
guard let encodevalue = self.addingPercentEncoding(withAllowedCharacters:urlSet) else{
return nil
}
return URL(string: encodevalue)
}
public subscript (r: Range<Int>) -> String? { //Optional String as return value
get {
let stringCount = self.characters.count as Int
//Check for out of boundary condition
if (stringCount < r.upperBound) || (stringCount < r.lowerBound){
return nil
}
let startIndex = self.startIndex//.advancedBy(r.lowerBound)
let endIndex = self.startIndex//.advancedBy(r.upperBound)
// return self[Range(start: startIndex, end: endIndex)]
LogWarn("如果这个地方出现问题使用回原来代码")
return self[startIndex..<endIndex]
}
}
public subscript (r: Int) -> String? {
get {
var i = 0
for ch in self.characters{
if i == r{
return "\(ch)"
}
i += 1
}
return ""
}
}
//MARK:字符串处理
public var md5:String{
return AESCrypt.md5(self)
}
public var toBase64:String{
return AESCrypt.base64String(fromText: self)
}
public var fromBase64:String{
return AESCrypt.text(fromBase64String: self)
}
public var toInteger:Int{
return (self as NSString).integerValue
}
public var toInt:Int32{
return (self as NSString).intValue
}
public var HexToInt:Int32{//16进制转换成为10进制
let dict_hex_to_int = [
"0":0,"1":1,"2":2,
"3":3,"4":4,"5":5,
"6":6,"7":7,"8":8,
"9":9,"a":10,"b":11,
"c":12,"d":13,"e":14,
"f":15
]
if self.isEmpty{
return 0
}
var result = Int32(0)
for i in 1...self.length{
let char = self[self.length-i]!.lowercased()
let int = dict_hex_to_int[char]!
let weight = powf(16, Float(i-1))
result = result + Int32(weight)*Int32(int)
}
return result
}
public var IntToHex:String{
return String(format: "%0X", self.toInt)
}
public var toFloat:Float{
return (self as NSString).floatValue
}
public var toDouble:Double{
return (self as NSString).doubleValue
}
public var toCGfloat:CGFloat{
return CGFloat((self as NSString).doubleValue)
}
public var toBool:Bool{
return (self as NSString).boolValue
}
public var toHex:NSData?{
let str = self as NSString
let hexData = NSMutableData(capacity: 8)
var range = NSRange()
if str.length % 2 == 0{
range = NSMakeRange(0, 2)
}
else{
range = NSMakeRange(0, 1)
}
var i = range.location
while i < str.length {
i = i + 2
var anInt = UInt32(0)
let hexChartStr = str.substring(with: range)
let scanner = Scanner(string: hexChartStr)
scanner.scanHexInt32(&anInt)
let entity = Data(bytes: &anInt, count: 1)
hexData?.append(entity)
range.location = range.location + range.length
range.length = 2
}
return hexData
}
public var toChineseString:String{
let string_deal = self
let zh = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
let unit = ["", "十", "百", "千", "万", "十", "百", "千", "亿", "十"]
var string_return = ""
var r = 0
var l = 0
for j in 0..<string_deal.length{
/**
* 当前数字
*/
r = string_deal[string_deal.length-1-j]!.toInteger
if j != 0{
/**
* 上一个数字
*/
l = string_deal[string_deal.length-1-(j-1)]!.toInteger
}
if j == 0{
if r != 0 || string_deal.length == 1{
string_return = zh[r]
continue
}
}
if j==1 || j==2 || j==3 || j==5 || j==6 || j==7 || j==9 {
if r != 0{
string_return = zh[r] + unit[j] + string_return
}
else if l != 0{
string_return = zh[r] + string_return
continue
}
}
if j == 4 || j == 8 {
string_return = unit[j] + string_return
if (l != 0 && r == 0) || r != 0{
string_return = zh[r] + string_return
continue
}
}
}
return string_return
}
//MARK:字符串判断
public var isPhoneNumber:Bool{
let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
let CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
let CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
if ((regextestmobile.evaluate(with: self) == true)
|| (regextestcm.evaluate(with: self) == true)
|| (regextestct.evaluate(with: self) == true)
|| (regextestcu.evaluate(with: self) == true))
{
return true
}
else
{
return false
}
}
//判断是否身份证号码
public var isIDCardNumber:Bool{
let value = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let length = value.length
if length != 15 && length != 18{
return false
}
//省份代码
let areasArray = ["11","12", "13","14", "15","21", "22","23", "31","32", "33","34", "35","36", "37","41", "42","43", "44","45", "46","50", "51","52", "53","54", "61","62", "63","64", "65","71", "81","82", "91"]
//valueStart2 = [value substringToIndex:2];
let valueStart2 = (value as NSString).substring(to: 2)
var areaFlag = false
for areaCode in areasArray{
if areaCode == valueStart2{
areaFlag = true
break
}
}
if !areaFlag{
return false
}
var regularExpression:NSRegularExpression?
var numberofMatch:Int?
var year = 0
switch length{
case 15:
year = Int((value as NSString).substring(with: NSMakeRange(6,2)))! + 1900
if year%4==0 || (year%100==0 && year%4==0){
do{
regularExpression = try NSRegularExpression(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$", options: NSRegularExpression.Options.caseInsensitive)
}
catch _{
return false
}
}
else{
do{
regularExpression = try NSRegularExpression(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$", options: NSRegularExpression.Options.caseInsensitive)
}
catch _{
return false
}
}
numberofMatch = regularExpression?.numberOfMatches(in: value, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, value.length))
if numberofMatch! > 0{
return true
}
else{
return false
}
case 18:
year = Int((value as NSString).substring(with: NSMakeRange(6,4)))!
if year%4==0 || (year%100==0 && year%4==0){
do{
regularExpression = try NSRegularExpression(pattern: "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$", options: NSRegularExpression.Options.caseInsensitive)
}
catch _{
return false
}
}
else{
do{
regularExpression = try NSRegularExpression(pattern: "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$", options: NSRegularExpression.Options.caseInsensitive)
}
catch _{
return false
}
}
numberofMatch = regularExpression?.numberOfMatches(in: value, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, value.length))
return numberofMatch! > 0
default:
return false
}
}
//MARK:通过字符串生成某些实例
//生成二维码
public var makeQR:UIImage?{
return MakeQRImageWithString(string_qr: self)
}
public var imageWithName:UIImage?{
return UIImage(named: self)
}
//MARK:世界化字符串
/*
字典要命名成这样子
let dict_Localized = [
"ZH":["":""
]
]
*/
public var locMode:String{
guard let string_return = dict_Localized[STDSystemConfigure.share.string_localized_mode]?[self] else{
return self
}
return string_return
}
}
extension NSAttributedString{
public convenience init(image:UIImage?) {
let textAttachment = NSTextAttachment()
textAttachment.image = image
self.init(attachment:textAttachment)
}
public convenience init(string:String,color:UIColor,font:UIFont){
self.init(string: string, attributes: [NSForegroundColorAttributeName:color,
NSFontAttributeName:font])
}
public convenience init(string:String,color:UIColor,underStyle:NSUnderlineStyle){
self.init(string: string, attributes: [NSForegroundColorAttributeName:color,
NSUnderlineStyleAttributeName:NSNumber(value: underStyle.hashValue)])
}
}
public func - (left:String,right:String)->String {
return left.replacingOccurrences(of: right, with: "")
}
public func +(left:NSAttributedString,right:NSAttributedString) -> NSAttributedString{
let attr_string_return = NSMutableAttributedString(attributedString: left)
attr_string_return.append(right)
return NSAttributedString(attributedString: attr_string_return)
}
| mit | b1a0a2c56053ff26f3d9319f82d82d1c | 31.86398 | 281 | 0.520579 | 4.00092 | false | false | false | false |
kesun421/firefox-ios | Shared/Extensions/HexExtensions.swift | 3 | 2398 | /* 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 Foundation
extension String {
public var hexDecodedData: Data {
// Convert to a CString and make sure it has an even number of characters (terminating 0 is included, so we
// check for uneven!)
guard let cString = self.cString(using: String.Encoding.ascii), (cString.count % 2) == 1 else {
return Data()
}
var result = Data(capacity: (cString.count - 1) / 2)
for i in stride(from: 0, to: (cString.count - 1), by: 2) {
guard let l = hexCharToByte(cString[i]), let r = hexCharToByte(cString[i+1]) else {
return Data()
}
var value: UInt8 = (l << 4) | r
result.append(&value, count: MemoryLayout.size(ofValue: value))
}
return result
}
private func hexCharToByte(_ c: CChar) -> UInt8? {
if c >= 48 && c <= 57 { // 0 - 9
return UInt8(c - 48)
}
if c >= 97 && c <= 102 { // a - f
return UInt8(10) + UInt8(c - 97)
}
if c >= 65 && c <= 70 { // A - F
return UInt8(10) + UInt8(c - 65)
}
return nil
}
}
private let HexDigits: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
extension Data {
public var hexEncodedString: String {
var result = String()
result.reserveCapacity(count * 2)
withUnsafeBytes { (p: UnsafePointer<UInt8>) in
for i in 0..<count {
result.append(HexDigits[Int((p[i] & 0xf0) >> 4)])
result.append(HexDigits[Int(p[i] & 0x0f)])
}
}
return String(result)
}
public static func randomOfLength(_ length: UInt) -> Data? {
let length = Int(length)
var data = Data(count: length)
var result: Int32 = 0
data.withUnsafeMutableBytes { (p: UnsafeMutablePointer<UInt8>) in
result = SecRandomCopyBytes(kSecRandomDefault, length, p)
}
return result == 0 ? data : nil
}
}
extension Data {
public var base64EncodedString: String {
return self.base64EncodedString(options: NSData.Base64EncodingOptions())
}
}
| mpl-2.0 | a20a6058bc563f09c7f7b2239c5fdd10 | 33.257143 | 115 | 0.547123 | 3.758621 | false | false | false | false |
Shaquu/SwiftProjectsPub | PassedData/PassedData/AppDelegate.swift | 1 | 4614 | //
// AppDelegate.swift
// PassedData
//
// Created by Tadeusz Wyrzykowski on 11.11.2016.
// Copyright © 2016 Tadeusz Wyrzykowski. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "PassedData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| gpl-3.0 | ee593d09c263e7b83492a6fbe9027023 | 48.602151 | 285 | 0.687188 | 5.883929 | false | false | false | false |
barabashd/WeatherApp | WeatherApp/Stopwatch.swift | 1 | 1268 | //
// Stopwatch.swift
// WeatherApp
//
// Created by Dmytro Barabash on 2/17/18.
// Copyright © 2018 Dmytro. All rights reserved.
//
import Foundation
public class Stopwatch {
public init() { }
private var start_: TimeInterval = 0.0
private var end_: TimeInterval = 0.0
private var timer = Timer()
private var closureSaver: (() -> ())!
public func start(_ completion: @escaping () -> ()) {
start_ = NSDate().timeIntervalSince1970
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
closureSaver = completion
completion()
}
public func stop() {
end_ = NSDate().timeIntervalSince1970
}
public func durationSeconds() -> TimeInterval {
return end_ - start_
}
@objc private func updateCounting() {
stop()
let time = abs(durationSeconds())
if time > 1 {
timer.invalidate()
start_ = 0
stop()
closureSaver()
} else {
start({})
start_ -= time
}
}
public func callBack(completion: @escaping () -> ()) {
}
}
| mit | 35068903d0577384d3a7fbb380884f05 | 22.462963 | 141 | 0.541436 | 4.641026 | false | false | false | false |
GlobusLTD/components-ios | Demo/Sources/ViewControllers/TextField/TextFieldViewController.swift | 1 | 1397 | //
// Globus
//
import Globus
class TextFieldViewController: GLBViewController {
// MARK - Outlet property
@IBOutlet fileprivate weak var textField: GLBTextField!
// MARK - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let textStyle = GLBTextStyle()
textStyle.font = UIFont.boldSystemFont(ofSize: 16)
textStyle.color = UIColor.darkGray
self.textField.textStyle = textStyle
let placeholderStyle = GLBTextStyle()
placeholderStyle.font = UIFont.boldSystemFont(ofSize: 16)
placeholderStyle.color = UIColor.lightGray
self.textField.placeholderStyle = placeholderStyle
self.textField.placeholder = "Placeholder"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.textField.becomeFirstResponder()
}
// MARK - Action
@IBAction internal func pressedMenu(_ sender: Any) {
self.glb_slideViewController?.showLeftViewController(animated: true, complete: nil)
}
@IBAction internal func changedText(_ sender: Any) {
print("ChangedText: \(self.textField.text)")
}
// MARK: - GLBNibExtension
public override static func nibName() -> String {
return "TextFieldViewController-Swift"
}
}
| mit | 55fc9a986d89c78e7ad7e8184695957b | 25.358491 | 91 | 0.635648 | 5.117216 | false | false | false | false |
willpowell8/LocalizationKit_iOS | Examples/iOS_Swift_Cocoapods/LocalizationKit/ViewController.swift | 1 | 2523 | //
// ViewController.swift
// LocalizationKit
//
// Created by Will Powell on 11/08/2016.
// Copyright (c) 2016 Will Powell. All rights reserved.
//
import UIKit
import LocalizationKit
import MBProgressHUD
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func reset(_ sender:AnyObject){
Localization.resetToDeviceLanguage()
}
@IBAction func changeLanguage(_ sender:AnyObject){
let localizedString = "Select Language".localize
let alertController = UIAlertController(title: localizedString!, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
print("\(localizedString!)");
Localization.availableLanguages { (languages) in
let d = DateFormatter()
d.dateFormat = "dd MMM yyyy"
d.LocalizeKey = "General.DateFormatter"
let dStr = d.string(from: Date())
print(dStr)
for language in languages {
let action = UIAlertAction(title: language.localizedName, style: .default, handler: {(alert: UIAlertAction!) in
DispatchQueue.main.async(execute: {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "Loading ..."
hud.mode = .indeterminate
Localization.setLanguage(language.key, {
print("Language loaded");
DispatchQueue.main.async(execute: {
hud.hide(animated: true);
});
})
})
})
alertController.addAction(action)
}
if UIDevice.current.userInterfaceIdiom == .pad
{
if let currentPopoverpresentioncontroller = alertController.popoverPresentationController{
let btn = sender as! UIBarButtonItem
currentPopoverpresentioncontroller.barButtonItem = btn
currentPopoverpresentioncontroller.permittedArrowDirections = .up;
}
}
DispatchQueue.main.async(execute: {
self.present(alertController, animated: true, completion:{})
});
}
}
}
| mit | 2ce845199768f25775006443b449120b | 34.535211 | 139 | 0.557273 | 5.840278 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftDemo/SwiftDemo/AppDelegate.swift | 1 | 2438 | //
// AppDelegate.swift
// SwiftDemo
//
// Created by apple on 17/5/4.
// Copyright © 2017年 UgoMedia. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds);
let rootTabVC = JWBasicTabBarViewController();
// rootTabVC.selectedIndex = 2;
rootTabVC.selectedIndex = (rootTabVC.viewControllers?.count)! - 1;
window?.rootViewController = rootTabVC;
window?.makeKeyAndVisible();
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 33a7faa4085ae00f61a4ebcc4a7f3c09 | 44.092593 | 285 | 0.733881 | 5.484234 | false | false | false | false |
avito-tech/Marshroute | Marshroute/Sources/Routers/BaseImpls/BaseMasterDetailRouter/MasterDetailRouterSeed.swift | 1 | 1542 | import Foundation
/// Параметры для создания роутеров, управляющих двумя экранами (двумя UINavigationController'ами)
public struct MasterDetailRouterSeed {
public let masterTransitionsHandlerBox: RouterTransitionsHandlerBox
public let detailTransitionsHandlerBox: RouterTransitionsHandlerBox
public let transitionId: TransitionId
public let presentingTransitionsHandler: TransitionsHandler?
public let transitionsHandlersProvider: TransitionsHandlersProvider
public let transitionIdGenerator: TransitionIdGenerator
public let controllersProvider: RouterControllersProvider
public init(
masterTransitionsHandlerBox: RouterTransitionsHandlerBox,
detailTransitionsHandlerBox: RouterTransitionsHandlerBox,
transitionId: TransitionId,
presentingTransitionsHandler: TransitionsHandler?,
transitionsHandlersProvider: TransitionsHandlersProvider,
transitionIdGenerator: TransitionIdGenerator,
controllersProvider: RouterControllersProvider)
{
self.masterTransitionsHandlerBox = masterTransitionsHandlerBox
self.detailTransitionsHandlerBox = detailTransitionsHandlerBox
self.transitionId = transitionId
self.presentingTransitionsHandler = presentingTransitionsHandler
self.transitionsHandlersProvider = transitionsHandlersProvider
self.transitionIdGenerator = transitionIdGenerator
self.controllersProvider = controllersProvider
}
}
| mit | 988f2d0bc43baa49f6edb2e181b41b76 | 48.4 | 98 | 0.803644 | 7.264706 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsValues.swift | 1 | 6077 | //
// ProfileSettingsValues.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileSettings {
// MARK: -
// MARK: Get
func value(forSubkey subkey: PayloadSubkey, payloadIndex: Int) -> Any? {
if let value = self.value(forValueKeyPath: subkey.valueKeyPath, subkey: subkey, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex) {
do {
if subkey.valueProcessor != nil || subkey.typeInput != subkey.type {
if let valueProcessed = try PayloadValueProcessors.shared.process(savedValue: value, forSubkey: subkey) {
return valueProcessed
}
}
} catch {
Log.shared.error(message: "Failed to process value: \(value)", category: String(describing: self))
}
return value
}
return nil
}
func value(forValueKeyPath valueKeyPath: String, subkey: PayloadSubkey? = nil, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) -> Any? {
if domainIdentifier == kManifestDomainConfiguration {
return self.profileValue(forKey: valueKeyPath)
} else {
if
let domainIdentifierSettings = self.settings(forDomainIdentifier: domainIdentifier, type: type, payloadIndex: payloadIndex),
let value = domainIdentifierSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey)] ?? domainIdentifierSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey, reversed: false)] {
return value
} else if
subkey?.payload?.subdomain != nil,
let domain = subkey?.domain,
let domainSettings = self.settings(forDomainIdentifier: domain, type: type, payloadIndex: payloadIndex),
let value = domainSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey)] ?? domainSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey, reversed: false)] {
return value
}
}
return nil
}
private func profileValue(forKey key: String) -> Any? {
self.settingsProfile[key]
}
// MARK: -
// MARK: Set
func setValue(_ value: Any, forSubkey subkey: PayloadSubkey, payloadIndex: Int) {
Log.shared.debug(message: "Subkey: \(subkey.keyPath) valueKeyPath: \(subkey.valueKeyPath)", category: String(describing: self))
do {
if subkey.valueProcessor != nil || subkey.typeInput != subkey.type {
if let valueProcessed = try PayloadValueProcessors.shared.process(inputValue: value, forSubkey: subkey) {
self.setPayloadValue(valueProcessed, forValueKeyPath: subkey.valueKeyPath, subkey: subkey, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
return
}
}
} catch {
Log.shared.error(message: "Failed to process value: \(value)", category: String(describing: self))
}
self.setPayloadValue(value, forValueKeyPath: subkey.valueKeyPath, subkey: subkey, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func setValue(_ value: Any, forValueKeyPath valueKeyPath: String, subkey payloadSubkey: PayloadSubkey? = nil, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) {
if let subkey = payloadSubkey {
do {
if subkey.valueProcessor != nil || subkey.typeInput != subkey.type {
if let valueProcessed = try PayloadValueProcessors.shared.process(inputValue: value, forSubkey: subkey) {
self.setPayloadValue(valueProcessed, forValueKeyPath: valueKeyPath, subkey: subkey, domainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex)
return
}
}
} catch {
Log.shared.error(message: "Failed to process value: \(value)", category: String(describing: self))
}
}
self.setPayloadValue(value, forValueKeyPath: valueKeyPath, subkey: payloadSubkey, domainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex)
}
private func setPayloadValue(_ value: Any, forValueKeyPath valueKeyPath: String, subkey: PayloadSubkey? = nil, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) {
Log.shared.debug(message: "KeyPath: \(valueKeyPath) SET value: \(value)", category: String(describing: self))
if domainIdentifier == kManifestDomainConfiguration {
self.setProfileValue(value, forKey: valueKeyPath)
} else {
var domainSettings = self.settings(forDomainIdentifier: domainIdentifier, type: type, payloadIndex: payloadIndex) ?? [String: Any]()
if let sKey = subkey, sKey.type == .dictionary, let newValue = value as? [String: Any] {
domainSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey)] = newValue
} else {
domainSettings[keyPath: KeyPath(valueKeyPath, subkey: subkey)] = value
}
self.setSettings(domainSettings, forDomainIdentifier: domainIdentifier, type: type, payloadIndex: payloadIndex)
}
}
private func setProfileValue(_ value: Any, forKey key: String) {
// This is an ugly hack, that results in setting the payloadDisplayName twice to activate KVO on the self.title variable that is actually computed.
// This should be able
if key == PayloadKey.payloadDisplayName, let title = value as? String, title != self.title {
self.settingsProfile[key] = value
self.setValue(title, forKey: self.titleSelector)
} else {
self.settingsProfile[key] = value
}
}
}
| mit | 16a7dadd9276301f128be87ad145f7b1 | 51.834783 | 214 | 0.64763 | 4.710078 | false | false | false | false |
SlimGinz/HomeworkHelper | Homework Helper/Menu.swift | 1 | 5403 | //
// Menu.swift
// Homework Helper
//
// Created by Cory Ginsberg on 2/8/15.
// Copyright (c) 2015 Boiling Point Development. All rights reserved.
//
import UIKit
@objc protocol MenuDelegate {
optional func getCurrentViewController() -> UIViewController
optional func pathMenu(menu: PathMenu, didSelectIndex idx: Int)
}
class Menu: NSObject, PathMenuDelegate, MenuDelegate {
var delegate: MenuDelegate?
var indx:Int?
func createPathMenu() {
let view = delegate?.getCurrentViewController!().view
// Define the Images to be used in the menu
let menuItemBackground = [
UIImage(named: "bg-icon-blue"),
UIImage(named: "bg-icon-yellow"),
UIImage(named: "bg-icon-green"),
UIImage(named: "bg-icon-purple")]
let menuItemBackgroundPressed = [
UIImage(named: "bg-icon-blue-pressed"),
UIImage(named: "bg-icon-yellow-pressed"),
UIImage(named: "bg-icon-green-pressed"),
UIImage(named: "bg-icon-purple-pressed")]
let menuItemIcon = [
UIImage(named: "bg-icon-blue-icon"),
UIImage(named: "bg-icon-yellow-icon"),
UIImage(named: "bg-icon-green-icon"),
UIImage(named: "bg-icon-purple-icon")]
// Define the Menu Items
let starMenuItem1 = PathMenuItem(image: menuItemBackground[0], highlightedImage: menuItemBackgroundPressed[0], contentImage: menuItemIcon[0], highlightedContentImage: menuItemIcon[0])
let starMenuItem2 = PathMenuItem(image: menuItemBackground[1], highlightedImage: menuItemBackgroundPressed[1], contentImage: menuItemIcon[1], highlightedContentImage: menuItemIcon[1])
let starMenuItem3 = PathMenuItem(image: menuItemBackground[2], highlightedImage: menuItemBackgroundPressed[2], contentImage: menuItemIcon[2], highlightedContentImage: menuItemIcon[2])
let starMenuItem4 = PathMenuItem(image: menuItemBackground[3], highlightedImage: menuItemBackgroundPressed[3], contentImage: menuItemIcon[3], highlightedContentImage: menuItemIcon[3])
var menus: [PathMenuItem] = [starMenuItem1, starMenuItem2, starMenuItem3, starMenuItem4]
let startItem: PathMenuItem = PathMenuItem(image: UIImage(named: "bg-menu-button"), highlightedImage: UIImage(named: "bg-menu-button-pressed"), contentImage: UIImage(), highlightedContentImage: UIImage())
var menu: PathMenu = PathMenu(frame: view?.bounds, startItem: startItem, optionMenus: menus)
menu.startPoint = CGPoint(x: view!.frame.size.width - 55.0, y: view!.frame.size.height - 120.0)
menu.menuWholeAngle = CGFloat(M_PI / 180 * 95)
menu.rotateAngle = CGFloat(M_PI / 180 * -95)
menu.farRadius = 120.0
menu.nearRadius = 95.0
menu.endRadius = 100.0
menu.timeOffset = 0.025
menu.delegate = self
view?.addSubview(menu)
view?.bringSubviewToFront(menu)
}
func pathMenu(menu: PathMenu, didSelectIndex idx: Int) {
// Delays showing the next view to allow the animation to finish first
let delayInSeconds = 0.2
let startTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(startTime, dispatch_get_main_queue()) { () -> Void in
switch idx {
case 0: // Assignments
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("InitialController") as! UIViewController
controller.modalTransitionStyle = .CrossDissolve
self.delegate?.getCurrentViewController!().presentViewController(controller, animated: true, completion: nil)
break
case 1: // Grades
var storyboard = UIStoryboard(name: "Grades", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("InitialController") as! UIViewController
controller.modalTransitionStyle = .CrossDissolve
self.delegate?.getCurrentViewController!().presentViewController(controller, animated: true, completion: nil)
break
case 2: // Classes
var storyboard = UIStoryboard(name: "Classes", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("InitialController") as! UIViewController
controller.modalTransitionStyle = .CrossDissolve
self.delegate?.getCurrentViewController!().presentViewController(controller, animated: true, completion: nil)
break
case 3: // Teachers
var storyboard = UIStoryboard(name: "Teachers", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("InitialController") as! UIViewController
controller.modalTransitionStyle = .CrossDissolve
self.delegate?.getCurrentViewController!().presentViewController(controller, animated: true, completion: nil)
break
default: // Default
break
}
}
}
}
| gpl-2.0 | 2baffa3cc3eabe791c60aabbe7feae49 | 47.675676 | 212 | 0.638534 | 5.021375 | false | false | false | false |
plutoless/fgo-pluto | FgoPluto/FgoPluto/views/plan/PlanEditor.swift | 1 | 9076 | //
// TargetEditor.swift
// FgoPluto
//
// Created by Zhang, Qianze on 29/09/2017.
// Copyright © 2017 Plutoless Studio. All rights reserved.
//
import Foundation
import UIKit
import RangeSeekSlider
typealias PlanRange = (Int, Int)
protocol PlanEditDelegate : class{
func didFinishEdit(servant:Servant, values:[PlanRange])
}
class PlanEditorItem : BaseView
{
lazy var titleLabel:UILabel = {
let label = UILabel()
label.font = .font(size:14)
label.textColor = UIColor(hex: "#4A4A4A")
return label
}()
lazy var stepper : RangeSeekSlider = {
let stepper = RangeSeekSlider()
stepper.lineHeight = 10
stepper.tintColor = UIColor(hex: "#E6E6E6")
stepper.colorBetweenHandles = UIColor(hex: "#3C91E6")
stepper.handleImage = UIImage(named: "slider_handler")
stepper.labelPadding = 0.0
stepper.minLabelColor = UIColor(hex: "#AAAAAA")
stepper.maxLabelColor = UIColor(hex: "#AAAAAA")
stepper.selectedHandleDiameterMultiplier = 1.2
stepper.step = 1
// stepper
// stepper.labelFont = .font(size:12)
return stepper
}()
override func create_contents() {
super.create_contents()
self.addSubview(self.titleLabel)
self.addSubview(self.stepper)
}
override func set_constraints() {
super.set_constraints()
self.titleLabel.snp.makeConstraints { maker in
maker.left.equalToSuperview().inset(20)
maker.bottom.equalToSuperview()
maker.top.equalToSuperview()
}
self.stepper.snp.makeConstraints { maker in
maker.right.equalToSuperview().inset(20)
maker.width.equalToSuperview().dividedBy(2)
maker.top.equalToSuperview()
maker.bottom.equalToSuperview()
}
}
}
class PlanEditor : BaseView
{
lazy var bottom_line:UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: "#DCDCDC")
return view
}()
lazy var title_label:UILabel = {
let label = UILabel()
label.font = .font(size:14)
label.textColor = UIColor(hex: "#4A4A4A")
label.textAlignment = .center
return label
}()
lazy var close_btn:UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("完成", for: .normal)
btn.titleLabel?.font = .font(size:14)
btn.backgroundColor = UIColor(hex: "#4A90E2")
btn.addTarget(self, action: #selector(save), for: .touchUpInside)
return btn
}()
var items:[PlanEditorItem] = []
func setValues(values:[PlanRange]){
for i in 0..<values.count{
let value:PlanRange = values[i]
let item = self.items[i]
item.stepper.selectedMinValue = CGFloat(value.0)
item.stepper.selectedMaxValue = CGFloat(value.1)
}
}
var servant:Servant?
weak var delegate:PlanEditDelegate?
convenience init(servant:Servant) {
self.init(frame: .zero)
self.servant = servant
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func create_contents() {
super.create_contents()
self.backgroundColor = UIColor(hex: "#ffffff")
self.addSubview(self.bottom_line)
self.addSubview(self.title_label)
self.addSubview(self.close_btn)
let ad_item = PlanEditorItem(frame: .zero)
ad_item.titleLabel.text = "灵基再临"
ad_item.stepper.minValue = 0
ad_item.stepper.maxValue = 4
self.addSubview(ad_item)
let skill1_item = PlanEditorItem(frame: .zero)
skill1_item.titleLabel.text = "技能1"
skill1_item.stepper.minValue = 1
skill1_item.stepper.maxValue = 10
self.addSubview(skill1_item)
let skill2_item = PlanEditorItem(frame: .zero)
skill2_item.titleLabel.text = "技能2"
skill2_item.stepper.minValue = 1
skill2_item.stepper.maxValue = 10
self.addSubview(skill2_item)
let skill3_item = PlanEditorItem(frame: .zero)
skill3_item.titleLabel.text = "技能3"
skill3_item.stepper.minValue = 1
skill3_item.stepper.maxValue = 10
self.addSubview(skill3_item)
self.items = [ad_item, skill1_item, skill2_item, skill3_item]
}
override func set_constraints() {
super.set_constraints()
self.bottom_line.snp.makeConstraints { maker in
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.height.equalTo(0.5)
maker.top.equalToSuperview().inset(54)
}
self.title_label.snp.makeConstraints {[weak self] maker in
guard let weakself = self else {return}
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.top.equalToSuperview()
maker.bottom.equalTo(weakself.bottom_line.snp.top)
}
for i in 0..<4{
let item = self.items[i]
item.snp.makeConstraints({[weak self] maker in
guard let weakself = self else {return}
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.height.equalTo(44)
if( i == 0){
maker.top.equalTo(weakself.bottom_line.snp.bottom).offset(10)
} else {
maker.top.equalTo(weakself.items[i - 1].snp.bottom).offset(10)
}
})
}
self.close_btn.snp.makeConstraints {maker in
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.bottom.equalToSuperview()
maker.height.equalTo(44)
}
}
static func defaultRanges(servant:Servant) -> [PlanRange]{
return [
(servant.ad_level, servant.ad_level),
(servant.skill1_level+1, servant.skill1_level+1),
(servant.skill2_level+1, servant.skill2_level+1),
(servant.skill3_level+1, servant.skill3_level+1)
]
}
static func showFrom(parent:UIView, plan: PlanItem) -> PlanEditor{
let editor = PlanEditor(frame: .zero)
editor.servant = plan.0
let ranges:[PlanRange] = plan.1
editor.setValues(values: ranges)
let mask = UIView()
let tap = UITapGestureRecognizer(target: editor, action: #selector(onTapMask(_:)))
mask.tag = 1000
mask.backgroundColor = UIColor(hex: "#000000")
mask.addGestureRecognizer(tap)
mask.alpha = 0
parent.addSubview(mask)
mask.snp.makeConstraints { maker in
maker.top.equalToSuperview()
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.bottom.equalToSuperview()
}
let panel_height:CGFloat = 330
parent.addSubview(editor)
editor.tag = 1001
editor.frame = CGRect(x: 0, y: parent.bounds.height, width: parent.bounds.width, height: panel_height)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
mask.alpha = 0.4
editor.frame.origin.y = parent.bounds.height - panel_height
}, completion: nil)
return editor
}
func onTapMask(_ tap:UITapGestureRecognizer){
self.cancel()
}
func save(){
self.close(true)
}
func cancel(){
self.close(false)
}
func values() -> [PlanRange]{
var results:[PlanRange] = []
for i in 0..<self.items.count{
let item = self.items[i]
results.append((lround(Double(item.stepper.selectedMinValue)), lround(Double(item.stepper.selectedMaxValue))))
}
return results
}
func close(_ result:Bool){
guard let parentView = self.superview, let maskView = parentView.viewWithTag(1000) else {return}
if(result){
let results:[PlanRange] = self.values()
if let servant:Servant = self.servant {
self.delegate?.didFinishEdit(servant: servant, values: results)
}
}
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: .curveEaseInOut, animations: { [weak self] in
maskView.alpha = 0
self?.frame.origin.y = parentView.bounds.height
}) {[weak self] finished in
if(finished){
maskView.removeFromSuperview()
self?.removeFromSuperview()
}
}
}
}
| apache-2.0 | b1161e2ae5fd9f339b92ca1b4571b0e3 | 30.757895 | 159 | 0.5785 | 4.299762 | false | false | false | false |
HongliYu/firefox-ios | Storage/Rust/RustLogins.swift | 1 | 15721 | /* 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 Foundation
import Shared
import Deferred
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public extension LoginRecord {
public convenience init(credentials: URLCredential, protectionSpace: URLProtectionSpace) {
let hostname: String
if let _ = protectionSpace.`protocol` {
hostname = protectionSpace.urlString()
} else {
hostname = protectionSpace.host
}
let httpRealm = protectionSpace.realm
let username = credentials.user
let password = credentials.password
self.init(fromJSONDict: [
"hostname": hostname,
"httpRealm": httpRealm as Any,
"username": username ?? "",
"password": password ?? ""
])
}
public var credentials: URLCredential {
return URLCredential(user: username ?? "", password: password, persistence: .none)
}
public var protectionSpace: URLProtectionSpace {
return URLProtectionSpace.fromOrigin(hostname)
}
public var hasMalformedHostname: Bool {
let hostnameURL = hostname.asURL
guard let _ = hostnameURL?.host else {
return true
}
return false
}
public var isValid: Maybe<()> {
// Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271
// Logins with empty hostnames are not valid.
if hostname.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty hostname."))
}
// Logins with empty passwords are not valid.
if password.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty password."))
}
// Logins with both a formSubmitURL and httpRealm are not valid.
if let _ = formSubmitURL, let _ = httpRealm {
return Maybe(failure: LoginRecordError(description: "Can't add a login with both a httpRealm and formSubmitURL."))
}
// Login must have at least a formSubmitURL or httpRealm.
if (formSubmitURL == nil) && (httpRealm == nil) {
return Maybe(failure: LoginRecordError(description: "Can't add a login without a httpRealm or formSubmitURL."))
}
// All good.
return Maybe(success: ())
}
}
public class LoginRecordError: MaybeErrorType {
public let description: String
public init(description: String) {
self.description = description
}
}
public class RustLogins {
let databasePath: String
let encryptionKey: String
let queue: DispatchQueue
let storage: LoginsStorage
public fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String, encryptionKey: String) {
self.databasePath = databasePath
self.encryptionKey = encryptionKey
self.queue = DispatchQueue(label: "RustLogins queue: \(databasePath)", attributes: [])
self.storage = LoginsStorage(databasePath: databasePath)
}
private func moveDatabaseFileToBackupLocation() {
let databaseURL = URL(fileURLWithPath: databasePath)
let databaseContainingDirURL = databaseURL.deletingLastPathComponent()
let baseFilename = databaseURL.lastPathComponent
// Attempt to make a backup as long as the database file still exists.
guard FileManager.default.fileExists(atPath: databasePath) else {
// No backup was attempted since the database file did not exist.
Sentry.shared.sendWithStacktrace(message: "The Logins database was deleted while in use", tag: SentryTag.rustLogins)
return
}
Sentry.shared.sendWithStacktrace(message: "Unable to open Logins database", tag: SentryTag.rustLogins, severity: .warning, description: "Attempting to move '\(baseFilename)'")
// Note that a backup file might already exist! We append a counter to avoid this.
var bakCounter = 0
var bakBaseFilename: String
var bakDatabasePath: String
repeat {
bakCounter += 1
bakBaseFilename = "\(baseFilename).bak.\(bakCounter)"
bakDatabasePath = databaseContainingDirURL.appendingPathComponent(bakBaseFilename).path
} while FileManager.default.fileExists(atPath: bakDatabasePath)
do {
try FileManager.default.moveItem(atPath: bakDatabasePath, toPath: bakDatabasePath)
let shmBaseFilename = baseFilename + "-shm"
let walBaseFilename = baseFilename + "-wal"
log.debug("Moving \(shmBaseFilename) and \(walBaseFilename)…")
let shmDatabasePath = databaseContainingDirURL.appendingPathComponent(shmBaseFilename).path
if FileManager.default.fileExists(atPath: shmDatabasePath) {
log.debug("\(shmBaseFilename) exists.")
try FileManager.default.moveItem(atPath: shmDatabasePath, toPath: "\(bakDatabasePath)-shm")
}
let walDatabasePath = databaseContainingDirURL.appendingPathComponent(walBaseFilename).path
if FileManager.default.fileExists(atPath: walDatabasePath) {
log.debug("\(walBaseFilename) exists.")
try FileManager.default.moveItem(atPath: shmDatabasePath, toPath: "\(bakDatabasePath)-wal")
}
log.debug("Finished moving Logins database successfully.")
} catch let error as NSError {
Sentry.shared.sendWithStacktrace(message: "Unable to move Logins database to backup location", tag: SentryTag.rustLogins, severity: .error, description: "Attempted to move to '\(bakBaseFilename)'. \(error.localizedDescription)")
}
}
private func open() -> NSError? {
do {
try self.storage.unlock(withEncryptionKey: encryptionKey)
isOpen = true
return nil
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
// The encryption key is incorrect, or the `databasePath`
// specified is not a valid database. This is an unrecoverable
// state unless we can move the existing file to a backup
// location and start over.
case .InvalidKey(let message):
log.error(message)
if !didAttemptToMoveToBackup {
moveDatabaseFileToBackupLocation()
didAttemptToMoveToBackup = true
return open()
}
case .Panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when opening Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
} else {
Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
do {
try self.storage.lock()
isOpen = false
return nil
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Unknown error when closing Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
return err
}
}
public func reopenIfClosed() {
if !isOpen {
_ = open()
}
}
public func forceClose() {
if isOpen {
_ = close()
}
}
public func sync(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
try self.storage.sync(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
case .Panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func get(id: String) -> Deferred<Maybe<LoginRecord?>> {
let deferred = Deferred<Maybe<LoginRecord?>>()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
let record = try self.storage.get(id: id)
deferred.fill(Maybe(success: record))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
guard let query = query?.lowercased(), !query.isEmpty else {
return deferMaybe(ArrayCursor(data: records))
}
let filteredRecords = records.filter({
$0.hostname.lowercased().contains(query) ||
($0.username?.lowercased() ?? "").contains(query)
})
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String? = nil) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
let filteredRecords: [LoginRecord]
if let username = username {
filteredRecords = records.filter({
$0.username == username && (
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
)
})
} else {
filteredRecords = records.filter({
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
})
}
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
return deferMaybe((result.successValue?.count ?? 0) > 0)
})
}
public func list() -> Deferred<Maybe<[LoginRecord]>> {
let deferred = Deferred<Maybe<[LoginRecord]>>()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
let records = try self.storage.list()
deferred.fill(Maybe(success: records))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func add(login: LoginRecord) -> Deferred<Maybe<String>> {
let deferred = Deferred<Maybe<String>>()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
let id = try self.storage.add(login: login)
deferred.fill(Maybe(success: id))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func use(login: LoginRecord) -> Success {
login.timesUsed += 1
login.timeLastUsed = Int64(Date.nowMicroseconds())
return self.update(login: login)
}
public func update(login: LoginRecord) -> Success {
let deferred = Success()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
try self.storage.update(login: login)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func delete(ids: [String]) -> Deferred<[Maybe<Bool>]> {
return all(ids.map({ delete(id: $0) }))
}
public func delete(id: String) -> Deferred<Maybe<Bool>> {
let deferred = Deferred<Maybe<Bool>>()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
let existed = try self.storage.delete(id: id)
deferred.fill(Maybe(success: existed))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func reset() -> Success {
let deferred = Success()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
try self.storage.reset()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func wipe() -> Success {
let deferred = Success()
queue.async {
if !self.isOpen, let error = self.open() {
deferred.fill(Maybe(failure: error))
return
}
do {
try self.storage.wipe()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
}
| mpl-2.0 | 9a9f1cf2785fc911e8b90282df07089d | 34.008909 | 240 | 0.57421 | 5.167324 | false | false | false | false |
remirobert/Dotzu-Objective-c | Pods/Dotzu/Dotzu/LoggerNetwork.swift | 1 | 5071 | //
// LoggerNetwork.swift
// exampleWindow
//
// Created by Remi Robert on 24/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import Foundation
fileprivate var bodyValues = [String:Data]()
extension NSMutableURLRequest {
@objc class func httpBodyHackSwizzle() {
let setHttpBody = class_getInstanceMethod(self, #selector(setter: NSMutableURLRequest.httpBody))
let httpBodyHackSetHttpBody = class_getInstanceMethod(self, #selector(self.httpBodyHackSetHttpBody(body:)))
method_exchangeImplementations(setHttpBody, httpBodyHackSetHttpBody)
}
@objc func httpBodyHackSetHttpBody(body: NSData?) {
let keyRequest = "\(hashValue)"
guard let body = body, bodyValues[keyRequest] == nil else { return }
bodyValues[keyRequest] = body as Data
httpBodyHackSetHttpBody(body: body)
}
}
class LoggerNetwork: URLProtocol {
var connection: NSURLConnection?
var sessionTask: URLSessionTask?
var responseData: NSMutableData?
var response: URLResponse?
var newRequest: NSMutableURLRequest?
var currentLog: LogRequest?
let store = StoreManager<LogRequest>(store: .network)
static let shared = LoggerNetwork()
lazy var queue: OperationQueue = {
var queue = OperationQueue()
queue.name = "request.logger.queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
var session: URLSession?
open class func register() {
NSMutableURLRequest.httpBodyHackSwizzle()
URLProtocol.registerClass(self)
}
open class func unregister() {
URLProtocol.unregisterClass(self)
}
open override class func canInit(with request: URLRequest) -> Bool {
if !LogsSettings.shared.network && self.property(forKey: "MyURLProtocolHandledKey", in: request) != nil {
return false
}
return true
}
open override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
open override class func requestIsCacheEquivalent(_ reqA: URLRequest, to reqB: URLRequest) -> Bool {
return super.requestIsCacheEquivalent(reqA, to: reqB)
}
open override func startLoading() {
guard let req = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest,
newRequest == nil else { return }
LoggerNetwork.setProperty(true, forKey: "MyURLProtocolHandledKey", in: req)
LoggerNetwork.setProperty(Date(), forKey: "MyURLProtocolDateKey", in: req)
self.newRequest = req
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: queue)
sessionTask = session?.dataTask(with: req as URLRequest)
sessionTask?.resume()
responseData = NSMutableData()
currentLog = LogRequest(request: req)
LogNotificationApp.newRequest.post(Void())
}
open override func stopLoading() {
sessionTask?.cancel()
guard let log = currentLog else {return}
let keyRequest = "\(newRequest?.hashValue ?? 0)"
log.httpBody = bodyValues["\(keyRequest)"]
bodyValues.removeValue(forKey: keyRequest)
if let startDate = LoggerNetwork.property(forKey: "MyURLProtocolDateKey",
in: newRequest! as URLRequest) as? Date {
let difference = fabs(startDate.timeIntervalSinceNow)
log.duration = difference
}
store.add(log: log)
LogNotificationApp.stopRequest.post(Void())
}
}
extension LoggerNetwork: URLSessionDataDelegate, URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
client?.urlProtocol(self, didFailWithError: error)
let reason = (error as NSError).localizedDescription
currentLog?.errorClientDescription = reason
return
}
client?.urlProtocolDidFinishLoading(self)
}
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
if let error = error {
let error = (error as NSError).localizedDescription
currentLog?.errorClientDescription = error
return
}
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
completionHandler(.allow)
currentLog?.initResponse(response: response)
if let data = responseData {
currentLog?.dataResponse = data as NSData
}
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
responseData?.append(data)
}
}
| mit | ff79788427f118e9eda09f7d9e9202d3 | 34.454545 | 115 | 0.664103 | 5.121212 | false | false | false | false |
OscarSwanros/swift | test/Interpreter/SDK/objc_swift_getObjectType.swift | 16 | 1389 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
protocol P: class { }
class AbstractP: P { }
class DelegatedP<D: P>: AbstractP {
init(_ d: D) { }
}
class AnyP: DelegatedP<AbstractP> {
init<D: P>(_ d: D) {
super.init(DelegatedP<D>(d))
}
}
extension P {
var anyP: AnyP {
return AnyP(self)
}
}
// SR-4363
// Test several paths through swift_getObjectType()
// instance of a Swift class that conforms to P
class O: NSObject, P { }
var o = O()
let obase: NSObject = o
print(String(cString: object_getClassName(o)))
_ = (o as P).anyP
_ = (obase as! P).anyP
// CHECK: main.O
// ... and KVO's artificial subclass thereof
o.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil)
print(String(cString: object_getClassName(o)))
_ = (o as P).anyP
_ = (obase as! P).anyP
// CHECK-NEXT: NSKVONotifying_main.O
// instance of an ObjC class that conforms to P
extension NSLock: P { }
var l = NSLock()
let lbase: NSObject = l
print(String(cString: object_getClassName(l)))
_ = (l as P).anyP
_ = (lbase as! P).anyP
// CHECK-NEXT: NSLock
// ... and KVO's artificial subclass thereof
l.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil)
print(String(cString: object_getClassName(l)))
_ = (l as P).anyP
_ = (lbase as! P).anyP
// CHECK-NEXT: NSKVONotifying_NSLock
| apache-2.0 | cdb449a738a3ecf151187c5e8c6f4b1e | 22.15 | 75 | 0.663787 | 3.013015 | false | false | false | false |
5lucky2xiaobin0/PandaTV | PandaTV/PandaTV/Classes/Home/Controller/HomeVC.swift | 1 | 2263 | //
// HomeVC.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/24.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
class HomeVC: UIViewController {
lazy var titleView : IndexTitleView = {
let titles = ["订阅","推荐","全部"]
let titleView = IndexTitleView(frame: CGRect(x: 0, y: 0, width: screenW, height: titleViewH), titles: titles)
titleView.backgroundColor = UIColor.white
titleView.delegate = self
return titleView
}()
lazy var liveContentView : ContentView = {
//创建子控制器----订阅.推荐.全部
let takeVC = UIStoryboard(name: "TakeVC", bundle: nil).instantiateInitialViewController()
let commendVC = CommendVC()
let allGameVC = AllGameVC()
let childs = [takeVC,commendVC,allGameVC]
let liveVC = ContentView(frame: CGRect(x: 0, y: titleViewH, width: screenW, height: screenH - titleViewH - tabBarH), views: childs as! [UIViewController])
liveVC.backgroundColor = UIColor.white
liveVC.delegate = self
return liveVC
}()
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
setUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
}
// MARK: - 界面设置
extension HomeVC {
fileprivate func setUI(){
view.addSubview(liveContentView)
view.addSubview(titleView)
}
}
// MARK: - ContentViewDelegate
extension HomeVC : ContentViewDelegate, IndexTitleViewDetegate {
func contentViewScrollTo(index: Int) {
titleView.scrollToTitle(index: index)
}
func indexTitleView(index: Int) {
liveContentView.scrollToView(index: index)
}
func indexTitleViewToSearch() {
let url = URL(string: "App-Prefs:root=WIFI")
UIApplication.shared.openURL(url!)
}
}
| mit | e8934cdadae33592b8394a057cdb1de4 | 26.65 | 162 | 0.636528 | 4.468687 | false | false | false | false |
5604Pocusset/PlaySwift | GuidedTour.playground/section-58.swift | 1 | 662 | class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
| apache-2.0 | 6d021b2ae845ddbbe493deaa7b9d834d | 24.461538 | 76 | 0.60423 | 4.534247 | false | false | false | false |
frootloops/swift | test/SILGen/generic_witness.swift | 1 | 2499 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method: Runcible) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible }
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr immutable_access [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumA2aEP4drawy6StrokeQyd__5paint_qd__6penciltAA6PencilRd__7Texture_5PaintQZAIRSlFTW : $@convention(witness_method: Medium) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4drawy5PaintQz5paint_qd__6penciltAA6PencilRd__6StrokeQyd__AFRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| apache-2.0 | 66814fa399ad90a7d4819db218356e52 | 43.017857 | 360 | 0.63002 | 2.794785 | false | false | false | false |
VoIPGRID/vialer-ios | Vialer/Helpers/VialerGAITracker.swift | 1 | 11778 | //
// GAITracker.swift
// Copyright © 2016 VoIPGRID. All rights reserved.
//
import Foundation
/// Wrapper class that makes tracking within the app easy.
class VialerGAITracker: NSObject {
/**
Constants for this class.
*/
struct GAIConstants {
static let inbound: String = "Inbound"
static let outbound: String = "Outbound"
/**
Custom Dimensions that will be used for Google Analytics.
VIALI-3274: index of the dimension should be read from Config.plist.
*/
struct CustomDimensions {
static let clientID: UInt = GAConfiguration.shared.clientIndex()
static let build: UInt = GAConfiguration.shared.buildIndex()
}
/**
Categories used for Google Analytics.
*/
struct Categories {
static let call: String = "Call"
static let middleware: String = "Middleware"
static let metrics: String = "Metrics"
}
/**
Actions used for Google Analytics.
*/
struct Actions {
static let callMetrics: String = "CallMetrics"
}
/**
Names use for tracking webviews.
*/
struct TrackingNames {
static let statisticsWebView: String = "StatisticsWebView"
static let informationWebView: String = "InformationWebView"
static let dialplanWebview: String = "DialplanWebview"
static let userProfileWebView: String = "UserProfileWebView"
static let addFixedDestinationWebView: String = "AddFixedDestinationWebView"
}
}
// These constants should be turned into a Struct when the whole project is rewritten in Swift: VIALI-3255
@objc class func GAStatisticsWebViewTrackingName() -> String {
return VialerGAITracker.GAIConstants.TrackingNames.statisticsWebView
}
@objc class func GAInformationWebViewTrackingName() -> String {
return VialerGAITracker.GAIConstants.TrackingNames.informationWebView
}
@objc class func GADialplanWebViewTrackingName() -> String {
return VialerGAITracker.GAIConstants.TrackingNames.dialplanWebview
}
@objc class func GAUserProfileWebViewTrackingName() -> String {
return VialerGAITracker.GAIConstants.TrackingNames.userProfileWebView
}
@objc class func GAAddFixedDestinationWebViewTrackingName() -> String {
return VialerGAITracker.GAIConstants.TrackingNames.addFixedDestinationWebView
}
/// The default Google Analytics Tracker.
static var tracker: GAITracker {
return GAI.sharedInstance().defaultTracker
}
// MARK: - Setup
/**
Configures the shared GA Tracker instance with the default info log level
and sets dry run according to DEBUG being set or not.
*/
@objc static func setupGAITracker() {
#if DEBUG
let dryRun = false
let logLevel = GAILogLevel.warning
#else
let dryRun = false
let logLevel = GAILogLevel.warning
#endif
_ = setupGAITracker(logLevel:logLevel, isDryRun:dryRun)
}
/**
Configures the shared GA Tracker instance with the parameters provided.
- parameter logLevel: The GA log level you want to configure the shared instance with.
- parameter isDryRun: Boolean indicating GA to run in dry run mode or not.
*/
@objc static func setupGAITracker(logLevel: GAILogLevel, isDryRun: Bool) -> Bool {
guard let gai = GAI.sharedInstance() else {
assert(false, "Google Analytics not configured correctly")
return false
}
gai.tracker(withTrackingId: GAConfiguration.shared.trackingId());
gai.trackUncaughtExceptions = true
gai.logger.logLevel = logLevel
gai.dryRun = isDryRun
tracker.set(GAIFields.customDimension(for: GAIConstants.CustomDimensions.build), value: AppInfo.currentAppVersion()!)
return true
}
/**
Set the client ID as a custom dimension.
- parameter clientID: The client ID to set as custom dimension.
*/
static func setCustomDimension(withClientID clientID:String) {
tracker.set(GAIFields.customDimension(for: GAIConstants.CustomDimensions.clientID), value: clientID)
}
/**
Tracks a screen with the given name.
If the name contains "ViewController" this is removed.
- parameter name: The name of the screen name to track.
*/
@objc static func trackScreenForController(name:String) {
tracker.set(kGAIScreenName, value: name.replacingOccurrences(of: "ViewController", with: ""))
tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject])
}
// MARK: - Events
/**
Create an Event and send it to Google Analytics.
- parameter category: The Category of the Event
- parameter action: The Action of the Event
- parameter label: The Label of the Event
- parameter value: The value of the Event
*/
static func sendEvent(withCategory category: String, action: String, label: String, value: NSNumber!) {
let event = GAIDictionaryBuilder.createEvent(withCategory: category, action: action, label: label, value: value).build() as [NSObject : AnyObject]
tracker.send(event)
}
/**
Indication a call event is received from the SIP Proxy and the app is ringing.
*/
@objc static func incomingCallRingingEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Ringing", value: 0)
}
/**
The incoming call is accepted.
*/
@objc static func acceptIncomingCallEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Accepted", value: 0)
}
/**
The incoming call is rejected.
*/
@objc static func declineIncomingCallEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Declined", value: 0)
}
static func missedIncomingCallCompletedElsewhereEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Missed - Call completed elsewhere", value: 0)
}
static func missedIncomingCallOriginatorCancelledEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Missed - Originator cancel", value: 0)
}
/**
The incoming call is rejected because there is another call in progress.
*/
static func declineIncomingCallBecauseAnotherCallInProgressEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Declined - Another call in progress", value: nil)
}
/**
The incoming call is rejected because of insufficient internet connection.
*/
@objc static func declineIncomingCallBecauseOfInsufficientInternetConnectionEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.inbound, label: "Declined - Insufficient internet connection", value: nil)
}
/**
Event to track an outbound SIP call.
*/
@objc static func setupOutgoingSIPCallEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.outbound, label: "SIP", value: nil)
}
/**
Event to track an outbound ConnectAB (aka two step) call.
*/
@objc static func setupOutgoingConnectABCallEvent() {
sendEvent(withCategory: GAIConstants.Categories.call, action: GAIConstants.outbound, label: "ConnectAB", value: nil)
}
/**
Incoming VoIPPush notification was responded with available to middleware.
- parameter connectionType: A string indicating the current connection type, as described in the "Google Analytics events for all Mobile apps" document.
- parameter isAccepted: Boolean indicating if we can accept the incoming VoIP call.
*/
@objc static func pushNotification(isAccepted: Bool, connectionType: String ) {
let action = isAccepted ? "Accepted" : "Rejected"
sendEvent(withCategory: GAIConstants.Categories.middleware, action: action, label: connectionType, value: nil)
}
/**
Event to be sent when a call tranfer was successfull.
*/
static func callTranferEvent(withSuccess success:Bool) {
let labelString = success ? "Success" : "Fail";
sendEvent(withCategory: GAIConstants.Categories.call, action: "Transfer", label: labelString, value: nil)
}
// MARK: - Exceptions
/**
Exception when the registration failed on the middleware.
*/
@objc static func registrationFailedWithMiddleWareException() {
let exception = GAIDictionaryBuilder.createException(withDescription: "Failed middleware registration", withFatal: false).build() as [NSObject : AnyObject]
tracker.send(exception)
}
// MARK: - Timings
/**
This method will log the time it took to respond to the incoming push notification and respond to the middleware.
- parameter responseTime: NSTimeInterval with the time it took to respond.
*/
@objc static func respondedToIncomingPushNotification(withResponseTime responseTime: TimeInterval) {
let timing = GAIDictionaryBuilder.createTiming(withCategory: GAIConstants.Categories.metrics,
interval: Int(round(responseTime * 1000)) as NSInteger as NSNumber,
name: GAIConstants.Categories.middleware,
label: "Response Time")
.build() as [NSObject : AnyObject]
tracker.send(timing)
}
// MARK: - After call Metrics
/**
After a call is finished, sent call metrics to GA.
- parameter call: the call that was finished
*/
@objc static func callMetrics(finishedCall call: VSLCall) {
// Only sent call statistics when the call duration was longer than 10 seconds
// to prevent large rounding errors.
guard call.connectDuration > 10 else {
VialerLogInfo("Not sending metrics")
return
}
VialerLogInfo("Sending metrics")
let audioCodec = "AudioCodec:\(call.activeCodec)"
sendMOSValue(call: call, forCodec: audioCodec)
sendBandwidth(call: call, forCodec: audioCodec)
}
/**
Helper function for sending the MOS value for a call.
- parameter call: The call
- parameter codec: The Codec used for the call
*/
private static func sendMOSValue(call: VSLCall, forCodec codec:String) {
// Get the current connection type for the call.
let reachability = ReachabilityHelper.instance.reachability!
let labelString = "MOS for \(codec) on Networktype: \(reachability.status)"
let value = Int(call.mos * 100.0) as NSNumber
sendEvent(withCategory: GAIConstants.Categories.metrics, action: GAIConstants.Actions.callMetrics, label: labelString, value: value)
}
/**
Helper function for sending the Bandwidth used for a call.
- parameter call: The call
- parameter codec: The Codec used for the call
*/
private static func sendBandwidth(call: VSLCall, forCodec codec:String) {
let mbPerMinute = call.totalMBsUsed / (Float)(call.connectDuration / 60)
let value = Int(mbPerMinute * 1024.0) as NSNumber
let labelString = "Bandwidth for \(codec)"
sendEvent(withCategory: GAIConstants.Categories.metrics, action: GAIConstants.Actions.callMetrics, label: labelString, value: value)
}
}
| gpl-3.0 | 95ab8e9af69e05ae4c74cdaf65d2280c | 37.996689 | 163 | 0.671478 | 4.86251 | false | false | false | false |
jalehman/tips | tips/Settings.swift | 1 | 1099 | //
// Settings.swift
// tips
//
// Created by Josh Lehman on 1/14/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import Foundation
class Settings: NSObject, NSCoding {
var percentages: [TipPercent]!
var splitBetween: Int = 1
var billAmount: Double = 0
override init() {}
init(percentages: [TipPercent]) {
self.percentages = percentages
}
required convenience init(coder decoder: NSCoder) {
self.init()
self.percentages = decoder.decodeObjectForKey("percentages") as [TipPercent]
self.splitBetween = decoder.decodeIntegerForKey("splitBetween") as Int
self.billAmount = decoder.decodeDoubleForKey("billAmount") as Double
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.percentages, forKey: "percentages")
aCoder.encodeInteger(self.splitBetween, forKey: "splitBetween")
aCoder.encodeDouble(self.billAmount, forKey: "billAmount")
}
func resetTemporalSettings() {
self.splitBetween = 1
self.billAmount = 0
}
} | gpl-2.0 | 46dadee250cd7774ea852186e8efdcff | 27.205128 | 84 | 0.658781 | 4.292969 | false | false | false | false |
xwu/swift | stdlib/public/Concurrency/AsyncDropWhileSequence.swift | 1 | 4646 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Omits elements from the base asynchronous sequence until a given closure
/// returns false, after which it passes through all remaining elements.
///
/// Use `drop(while:)` to omit elements from an asynchronous sequence until
/// the element received meets a condition you specify.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `drop(while:)` method causes the modified
/// sequence to ignore received values until it encounters one that is
/// divisible by `3`:
///
/// let stream = Counter(howHigh: 10)
/// .drop { $0 % 3 != 0 }
/// for await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "3 4 5 6 7 8 9 10"
///
/// After the predicate returns `false`, the sequence never executes it again,
/// and from then on the sequence passes through elements from its underlying
/// sequence as-is.
///
/// - Parameter predicate: A closure that takes an element as a parameter and
/// returns a Boolean value indicating whether to drop the element from the
/// modified sequence.
/// - Returns: An asynchronous sequence that skips over values from the
/// base sequence until the provided closure returns `false`.
@inlinable
public __consuming func drop(
while predicate: @escaping (Element) async -> Bool
) -> AsyncDropWhileSequence<Self> {
AsyncDropWhileSequence(self, predicate: predicate)
}
}
/// An asynchronous sequence which omits elements from the base sequence until a
/// given closure returns false, after which it passes through all remaining
/// elements.
@available(SwiftStdlib 5.5, *)
public struct AsyncDropWhileSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let predicate: (Base.Element) async -> Bool
@usableFromInline
init(
_ base: Base,
predicate: @escaping (Base.Element) async -> Bool
) {
self.base = base
self.predicate = predicate
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropWhileSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The drop-while sequence produces whatever type of element its base
/// sequence produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the drop-while sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var predicate: ((Base.Element) async -> Bool)?
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
predicate: @escaping (Base.Element) async -> Bool
) {
self.baseIterator = baseIterator
self.predicate = predicate
}
/// Produces the next element in the drop-while sequence.
///
/// This iterator calls `next()` on its base iterator and evaluates the
/// result with the `predicate` closure. As long as the predicate returns
/// `true`, this method returns `nil`. After the predicate returns `false`,
/// for a value received from the base iterator, this method returns that
/// value. After that, the iterator returns values received from its
/// base iterator as-is, and never executes the predicate closure again.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
while let predicate = self.predicate {
guard let element = try await baseIterator.next() else {
return nil
}
if await predicate(element) == false {
self.predicate = nil
return element
}
}
return try await baseIterator.next()
}
}
/// Creates an instance of the drop-while sequence iterator.
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), predicate: predicate)
}
}
| apache-2.0 | 2c98dc3d0da4577672d049813d788ae7 | 35.015504 | 80 | 0.66229 | 4.819502 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLVUserFollowProductsView.swift | 1 | 4062 | //
// SLVUserFollowProductsView.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 2..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
import TagListView
class SLVUserFollowProductsView: UICollectionViewCell {
@IBOutlet weak var photosView: UICollectionView! //"SLVPhotoSelectionCell"
var type: ProductPhotoType = .sellerItem
var items: [FollowerProductSimpleInfo]?
var photos: [[String]] = []
var viewerBlock: ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ())?
override public func awakeFromNib() {
super.awakeFromNib()
self.setupCollectionView()
}
func setupData(type: ProductPhotoType, items: [FollowerProductSimpleInfo] ) {
self.type = type
self.items = items
for (_, v) in (self.items?.enumerated())! {
let item = v as FollowerProductSimpleInfo
if let photos = item.photos {
if photos.count > 0 {
let photo = photos.first! as String
let productId = (item.id ?? "").copy()
let value = [photo , productId]
self.photos.append(value as! [String])
}
}
}
// log.debug("[PhotoCell] type : \(self.type) --> \(self.photos!)")
self.photosView.reloadData()
}
func setupCollectionView() {
self.photosView.register(UINib(nibName: "SLVProductPhoteHorizontalCell", bundle: nil), forCellWithReuseIdentifier: "SLVProductPhoteHorizontalCell")
self.photosView.delegate = self
self.photosView.dataSource = self
}
func setupViewer(block: @escaping ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ()) ) {
self.viewerBlock = block
}
func move(path: IndexPath, image: UIImage, productId: String) {
if self.viewerBlock != nil {
self.viewerBlock!(path, image, productId)
}
}
func imageDomain() -> String {
var domain = dnProduct
switch self.type {
case .style :
domain = dnStyle
break
case .damage :
domain = dnDamage
break
case .accessory :
domain = dnAccessory
break
default:
break
}
return domain
}
}
extension SLVUserFollowProductsView: UICollectionViewDataSource, UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let index = indexPath.row
let cell = collectionView.cellForItem(at: indexPath) as? SLVProductPhoteHorizontalCell
if let cell = cell {
let image = cell.thumnail.image
let info = self.photos[index]
let productId = info.last
self.move(path: indexPath, image: image!, productId: productId! )
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// log.debug("PhotoType : \(self.type) - count : \( self.photos!.count)")
return self.photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVProductPhoteHorizontalCell", for: indexPath) as! SLVProductPhoteHorizontalCell
cell.isViewer = true
if self.photos.count >= indexPath.row + 1 {
let info = self.photos[indexPath.row] as! [String]
let name = info.first!
if name != "" {
let domain = self.imageDomain()
let from = URL(string: "\(domain)\(name)")
let dnModel = SLVDnImageModel.shared
DispatchQueue.global(qos: .default).async {
dnModel.setupImageView(view: (cell.thumnail)!, from: from!)
}
}
}
return cell
}
}
| mit | d8e39a00098f4da7070605ddf4f57fa8 | 33.939655 | 157 | 0.592401 | 4.842294 | false | false | false | false |
eduarenas80/MarvelClient | Source/Entities/Comic.swift | 2 | 4459 | //
// Comic.swift
// MarvelClient
//
// Copyright (c) 2016 Eduardo Arenas <[email protected]>
//
// 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
import SwiftyJSON
public struct Comic: Entity {
public let id: Int
public let digitalId: Int
public let title: String
public let issueNumber: Int
public let variantDescription: String
public let modified: NSDate?
public let isbn: String
public let upc: String
public let diamondCode: String
public let ean: String
public let issn: String
public let format: String
public let pageCount: Int
public let textObjects: [TextObject]
public let resourceURI: String
public let urls: [Url]
public let series: SeriesSummary
public let variants: [ComicSummary]
public let collections: [ComicSummary]
public let collectedIssues: [ComicSummary]
public let dates: [ComicDate]
public let prices: [ComicPrice]
public let thumbnail: Image
public let images: [Image]
public let creators: ResourceList<CreatorSummary>
public let characters: ResourceList<CharacterSummary>
public let stories: ResourceList<StorySummary>
public let events: ResourceList<EventSummary>
public init(json: JSON) {
self.id = json["id"].int!
self.digitalId = json["digitalId"].int!
self.title = json["title"].string!
self.issueNumber = json["issueNumber"].int!
self.variantDescription = json["variantDescription"].string!
self.modified = json["modified"].dateTime
self.isbn = json["isbn"].string!
self.upc = json["upc"].string!
self.diamondCode = json["diamondCode"].string!
self.ean = json["ean"].string!
self.issn = json["issn"].string!
self.format = json["format"].string!
self.pageCount = json["pageCount"].int!
self.textObjects = json["textObjects"].array!.map { TextObject(json: $0) }
self.resourceURI = json["resourceURI"].string!
self.urls = json["urls"].array!.map { Url(json: $0) }
self.series = SeriesSummary(json: json["series"])
self.variants = json["variants"].array!.map { ComicSummary(json: $0) }
self.collections = json["collections"].array!.map { ComicSummary(json: $0) }
self.collectedIssues = json["collectedIssues"].array!.map { ComicSummary(json: $0) }
self.dates = json["dates"].array!.map { ComicDate(json: $0) }
self.prices = json["prices"].array!.map { ComicPrice(json: $0) }
self.thumbnail = Image(json: json["thumbnail"])
self.images = json["images"].array!.map { Image(json: $0) }
self.creators = ResourceList<CreatorSummary>(json: json["creators"])
self.characters = ResourceList<CharacterSummary>(json: json["characters"])
self.stories = ResourceList<StorySummary>(json: json["stories"])
self.events = ResourceList<EventSummary>(json: json["events"])
}
}
public struct ComicSummary: EntitySummary {
public let resourceURI: String
public let name: String
public init(json: JSON) {
self.resourceURI = json["resourceURI"].string!
self.name = json["name"].string!
}
}
public struct ComicDate: JSONSerializable {
let type: String
let date: NSDate?
public init(json: JSON) {
self.type = json["type"].string!
self.date = json["date"].dateTime
}
}
public struct ComicPrice: JSONSerializable {
let type: String
let price: Double
public init(json: JSON) {
self.type = json["type"].string!
self.price = json["price"].double!
}
}
| mit | 15343f91c9434e77ecd1699509079f9e | 35.252033 | 88 | 0.708679 | 3.98125 | false | false | false | false |
xiangwangfeng/M80AttributedLabel | SwiftDemo/Classes/Util/Util.swift | 1 | 690 | //
// Util.swift
// SwiftDemo
//
// Created by amao on 2016/10/12.
// Copyright © 2016年 amao. All rights reserved.
//
import Foundation
func RGB(_ value : Int) -> UIColor {
let r = CGFloat((value & 0xFF0000) >> 16) / 255.0
let g = CGFloat((value & 0x00FF00) >> 8 ) / 255.0
let b = CGFloat((value & 0x0000FF) ) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
func ClassByName(name : String) -> AnyClass? {
var result : AnyClass? = nil
if let bundle = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String {
let className = bundle + "." + name
result = NSClassFromString(className)
}
return result
}
| mit | e8ddc49d2de475617160a9f7c16732da | 24.444444 | 89 | 0.614265 | 3.255924 | false | false | false | false |
esttorhe/RxSwift | RxSwift/RxSwift/Observables/Implementations/Sink.swift | 1 | 1581 | //
// Sink.swift
// Rx
//
// Created by Krunoslav Zaher on 2/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Sink<O : ObserverType> : Disposable {
private typealias Element = O.Element
typealias State = (
observer: O?,
cancel: Disposable,
disposed: Bool
)
private var lock = Lock()
private var _state: State
var observer: O? {
get {
return lock.calculateLocked { _state.observer }
}
}
var cancel: Disposable {
get {
return lock.calculateLocked { _state.cancel }
}
}
var state: State {
get {
return lock.calculateLocked { _state }
}
}
init(observer: O, cancel: Disposable) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
_state = (
observer: observer,
cancel: cancel,
disposed: false
)
}
func dispose() {
let cancel: Disposable? = lock.calculateLocked {
if _state.disposed {
return nil
}
let cancel = _state.cancel
_state.disposed = true
_state.observer = nil
_state.cancel = NopDisposable.instance
return cancel
}
if let cancel = cancel {
cancel.dispose()
}
}
deinit {
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
} | mit | 811675e0883e0c956bd0f616d5a5ce4c | 19.545455 | 60 | 0.504744 | 4.834862 | false | false | false | false |
r-mckay/montreal-iqa | montrealIqa/Carthage/Checkouts/Reusable/Example/ReusableDemo iOS/CollectionViewCells/MyColorSquareCell.swift | 3 | 962 | //
// MyColorSquareCell.swift
// ReusableDemo
//
// Created by Olivier Halligon on 19/01/2016.
// Copyright © 2016 AliSoftware. All rights reserved.
//
import UIKit
import Reusable
/**
* This view is reusable and has a `reuseIdentifier` (as it's a CollectionViewCell
* and it uses the Collectioniew recycling mechanism).
*
* That's why it's annotated with the `Reusable` protocol.
*
* This view is NOT loaded from a NIB (but defined entierly by code),
* that's why it's not annotated as `NibLoadable` but only `Reusable`
*/
final class MyColorSquareCell: UICollectionViewCell, Reusable {
private lazy var colorView: UIView = {
let colorView = UIView()
colorView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
colorView.frame = self.contentView.bounds.insetBy(dx: 10, dy: 10)
self.contentView.addSubview(colorView)
return colorView
}()
func fill(_ color: UIColor) {
self.colorView.backgroundColor = color
}
}
| mit | 6ef3a658f4adbbdaf3b3279380338cb4 | 28.121212 | 82 | 0.720083 | 4.037815 | false | false | false | false |
easyui/Alamofire | Tests/ParameterEncoderTests.swift | 2 | 33072 | //
// ParameterEncoderTests.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import XCTest
final class JSONParameterEncoderTests: BaseTestCase {
func testThatDataIsProperlyEncodedAndProperContentTypeIsSet() throws {
// Given
let encoder = JSONParameterEncoder()
let request = Endpoint().urlRequest
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "application/json")
XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}")
}
func testThatDataIsProperlyEncodedButContentTypeIsNotSetIfRequestAlreadyHasAContentType() throws {
// Given
let encoder = JSONParameterEncoder()
var request = Endpoint().urlRequest
request.headers.update(.contentType("type"))
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "type")
XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}")
}
func testThatJSONEncoderCanBeCustomized() throws {
// Given
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
let encoder = JSONParameterEncoder(encoder: jsonEncoder)
let request = Endpoint().urlRequest
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
let expected = """
{
"property" : "property"
}
"""
XCTAssertEqual(newRequest.httpBody?.asString, expected)
}
func testThatJSONEncoderDefaultWorks() throws {
// Given
let encoder = JSONParameterEncoder.default
let request = Endpoint().urlRequest
// When
let encoded = try encoder.encode(TestParameters.default, into: request)
// Then
let expected = """
{"property":"property"}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
func testThatJSONEncoderPrettyPrintedPrintsPretty() throws {
// Given
let encoder = JSONParameterEncoder.prettyPrinted
let request = Endpoint().urlRequest
// When
let encoded = try encoder.encode(TestParameters.default, into: request)
// Then
let expected = """
{
"property" : "property"
}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
}
final class SortedKeysJSONParameterEncoderTests: BaseTestCase {
func testTestJSONEncoderSortedKeysHasSortedKeys() throws {
guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) else { return }
// Given
let encoder = JSONParameterEncoder.sortedKeys
let request = Endpoint().urlRequest
// When
let encoded = try encoder.encode(["z": "z", "a": "a", "p": "p"], into: request)
// Then
let expected = """
{"a":"a","p":"p","z":"z"}
"""
XCTAssertEqual(encoded.httpBody?.asString, expected)
}
}
final class URLEncodedFormParameterEncoderTests: BaseTestCase {
func testThatQueryIsBodyEncodedAndProperContentTypeIsSetForPOSTRequest() throws {
// Given
let encoder = URLEncodedFormParameterEncoder()
let request = Endpoint(method: .post).urlRequest
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "application/x-www-form-urlencoded; charset=utf-8")
XCTAssertEqual(newRequest.httpBody?.asString, "property=property")
}
func testThatQueryIsBodyEncodedButContentTypeIsNotSetWhenRequestAlreadyHasContentType() throws {
// Given
let encoder = URLEncodedFormParameterEncoder()
var request = Endpoint(method: .post).urlRequest
request.headers.update(.contentType("type"))
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
XCTAssertEqual(newRequest.headers["Content-Type"], "type")
XCTAssertEqual(newRequest.httpBody?.asString, "property=property")
}
func testThatEncoderCanBeCustomized() throws {
// Given
let urlEncoder = URLEncodedFormEncoder(boolEncoding: .literal)
let encoder = URLEncodedFormParameterEncoder(encoder: urlEncoder)
let request = Endpoint().urlRequest
// When
let newRequest = try encoder.encode(["bool": true], into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertEqual(components?.percentEncodedQuery, "bool=true")
}
func testThatQueryIsInURLWhenDestinationIsURLAndMethodIsPOST() throws {
// Given
let encoder = URLEncodedFormParameterEncoder(destination: .queryString)
let request = Endpoint(method: .post).urlRequest
// When
let newRequest = try encoder.encode(TestParameters.default, into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertEqual(components?.percentEncodedQuery, "property=property")
}
func testThatQueryIsNilWhenEncodableResultsInAnEmptyString() throws {
// Given
let encoder = URLEncodedFormParameterEncoder(destination: .queryString)
let request = Endpoint().urlRequest
// When
let newRequest = try encoder.encode([String: String](), into: request)
// Then
let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false)
XCTAssertNil(components?.percentEncodedQuery)
}
}
final class URLEncodedFormEncoderTests: BaseTestCase {
func testEncoderThrowsErrorWhenAttemptingToEncodeNilInKeyedContainer() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = FailingOptionalStruct(testedContainer: .keyed)
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
}
func testEncoderThrowsErrorWhenAttemptingToEncodeNilInUnkeyedContainer() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = FailingOptionalStruct(testedContainer: .unkeyed)
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
}
func testEncoderCanEncodeDictionary() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": "a"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=a")
}
func testEncoderCanEncodeDecimal() {
// Given
let encoder = URLEncodedFormEncoder()
let decimal: Decimal = 1.0
let parameters = ["a": decimal]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeDecimalWithHighPrecision() {
// Given
let encoder = URLEncodedFormEncoder()
let decimal: Decimal = 1.123456
let parameters = ["a": decimal]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.123456")
}
func testEncoderCanEncodeDouble() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": 1.0]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.0")
}
func testEncoderCanEncodeFloat() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Float] = ["a": 1.0]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1.0")
}
func testEncoderCanEncodeInt8() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int8] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt16() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int16] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt32() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int32] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeInt64() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: Int64] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt8() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt8] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt16() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt16] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt32() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt32] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testEncoderCanEncodeUInt64() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: UInt64] = ["a": 1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a=1")
}
func testThatNestedDictionariesHaveBracketedKeys() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["a": ["b": "b"]]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "a%5Bb%5D=b")
}
func testThatEncodableStructCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&seven%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&three=1&two=2"
XCTAssertEqual(result.success, expected)
}
func testThatManuallyEncodableStructCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ManuallyEncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "root%5B%5D%5B%5D%5B%5D=1&root%5B%5D%5B%5D%5B%5D=2&root%5B%5D%5B%5D%5B%5D=3&root%5B%5D%5B%5D=1&root%5B%5D%5B%5D=2&root%5B%5D%5B%5D=3&root%5B%5D%5Ba%5D%5Bstring%5D=string"
XCTAssertEqual(result.success, expected)
}
func testThatEncodableClassWithNoInheritanceCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableSuperclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one=one&three=1&two=2")
}
func testThatEncodableSubclassCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = EncodableSubclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&three=1&two=2"
XCTAssertEqual(result.success, expected)
}
func testThatEncodableSubclassCanBeEncodedInImplementationOrderWhenAlphabetizeKeysIsFalse() {
// Given
let encoder = URLEncodedFormEncoder(alphabetizeKeyValuePairs: false)
let parameters = EncodableStruct()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "one=one&two=2&three=1&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&five%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&seven%5Ba%5D=a"
XCTAssertEqual(result.success, expected)
}
func testThatManuallyEncodableSubclassCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ManuallyEncodableSubclass()
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfive%5D=2&four%5Bfour%5D=one"
XCTAssertEqual(result.success, expected)
}
func testThatARootArrayCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = [1]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatARootValueCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = "string"
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatOptionalValuesCannotBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters: [String: String?] = ["string": nil]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertFalse(result.isSuccess)
}
func testThatArraysCanBeEncodedWithoutBrackets() {
// Given
let encoder = URLEncodedFormEncoder(arrayEncoding: .noBrackets)
let parameters = ["array": [1, 2]]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "array=1&array=2")
}
func testThatBoolsCanBeLiteralEncoded() {
// Given
let encoder = URLEncodedFormEncoder(boolEncoding: .literal)
let parameters = ["bool": true]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "bool=true")
}
func testThatDataCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["data": Data("data".utf8)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "data=ZGF0YQ%3D%3D")
}
func testThatCustomDataEncodingFailsWhenErrorIsThrown() {
// Given
struct DataEncodingError: Error {}
let encoder = URLEncodedFormEncoder(dataEncoding: .custom { _ in throw DataEncodingError() })
let parameters = ["data": Data("data".utf8)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
XCTAssertTrue(result.failure is DataEncodingError)
}
func testThatDatesCanBeEncoded() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .deferredToDate)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=123.456")
}
func testThatDatesCanBeEncodedAsSecondsSince1970() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .secondsSince1970)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=978307323.456")
}
func testThatDatesCanBeEncodedAsMillisecondsSince1970() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .millisecondsSince1970)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=978307323456.0")
}
func testThatDatesCanBeEncodedAsISO8601Formatted() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .iso8601)
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=2001-01-01T00%3A02%3A03Z")
}
func testThatDatesCanBeEncodedAsFormatted() {
// Given
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let encoder = URLEncodedFormEncoder(dateEncoding: .formatted(dateFormatter))
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=2001-01-01%2000%3A02%3A03.4560")
}
func testThatDatesCanBeEncodedAsCustomFormatted() {
// Given
let encoder = URLEncodedFormEncoder(dateEncoding: .custom { "\($0.timeIntervalSinceReferenceDate)" })
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "date=123.456")
}
func testEncoderThrowsErrorWhenCustomDateEncodingFails() {
// Given
struct DateEncodingError: Error {}
let encoder = URLEncodedFormEncoder(dateEncoding: .custom { _ in throw DateEncodingError() })
let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertTrue(result.isFailure)
XCTAssertTrue(result.failure is DateEncodingError)
}
func testThatKeysCanBeEncodedIntoSnakeCase() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .convertToSnakeCase)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one_two_three=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoKebabCase() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .convertToKebabCase)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "one-two-three=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoACapitalizedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .capitalized)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "OneTwoThree=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoALowercasedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .lowercased)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "onetwothree=oneTwoThree")
}
func testThatKeysCanBeEncodedIntoAnUppercasedString() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .uppercased)
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "ONETWOTHREE=oneTwoThree")
}
func testThatKeysCanBeCustomEncoded() {
// Given
let encoder = URLEncodedFormEncoder(keyEncoding: .custom { _ in "A" })
let parameters = ["oneTwoThree": "oneTwoThree"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "A=oneTwoThree")
}
func testThatSpacesCanBeEncodedAsPluses() {
// Given
let encoder = URLEncodedFormEncoder(spaceEncoding: .plusReplaced)
let parameters = ["spaces": "replace with spaces"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "spaces=replace+with+spaces")
}
func testThatEscapedCharactersCanBeCustomized() {
// Given
var allowed = CharacterSet.afURLQueryAllowed
allowed.remove(charactersIn: "?/")
let encoder = URLEncodedFormEncoder(allowedCharacters: allowed)
let parameters = ["allowed": "?/"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "allowed=%3F%2F")
}
func testThatUnreservedCharactersAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz",
"numbers": "0123456789",
"uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expected = "lowercase=abcdefghijklmnopqrstuvwxyz&numbers=0123456789&uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
XCTAssertEqual(result.success, expected)
}
func testThatReservedCharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let generalDelimiters = ":#[]@"
let subDelimiters = "!$&'()*+,;="
let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D")
}
func testThatIllegalASCIICharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["illegal": " \"#%<>[]\\^`{}|"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C")
}
func testThatAmpersandsInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "foo%26bar=baz%26qux&foobar=bazqux")
}
func testThatQuestionMarksInKeysAndValuesAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["?foo?": "?bar?"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "?foo?=?bar?")
}
func testThatSlashesInKeysAndValuesAreNotPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["foo": "/bar/baz/qux"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "foo=/bar/baz/qux")
}
func testThatSpacesInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = [" foo ": " bar "]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "%20foo%20=%20bar%20")
}
func testThatPlusesInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["+foo+": "+bar+"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "%2Bfoo%2B=%2Bbar%2B")
}
func testThatPercentsInKeysAndValuesArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["percent%": "%25"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
XCTAssertEqual(result.success, "percent%25=%2525")
}
func testThatNonLatinCharactersArePercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let parameters = ["french": "français",
"japanese": "日本語",
"arabic": "العربية",
"emoji": "😃"]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let expectedParameterValues = ["arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9",
"emoji=%F0%9F%98%83",
"french=fran%C3%A7ais",
"japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E"].joined(separator: "&")
XCTAssertEqual(result.success, expectedParameterValues)
}
func testStringWithThousandsOfChineseCharactersIsPercentEscaped() {
// Given
let encoder = URLEncodedFormEncoder()
let repeatedCount = 2000
let parameters = ["chinese": String(repeating: "一二三四五六七八九十", count: repeatedCount)]
// When
let result = Result<String, Error> { try encoder.encode(parameters) }
// Then
let escaped = String(repeating: "%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%E5%8D%81",
count: repeatedCount)
let expected = "chinese=\(escaped)"
XCTAssertEqual(result.success, expected)
}
}
private struct EncodableStruct: Encodable {
let one = "one"
let two = 2
let three = true
let four = [1, 2, 3]
let five = ["a": "a"]
let six = ["a": ["b": "b"]]
let seven = NestedEncodableStruct()
}
private struct NestedEncodableStruct: Encodable {
let a = "a"
}
private class EncodableSuperclass: Encodable {
let one = "one"
let two = 2
let three = true
}
private final class EncodableSubclass: EncodableSuperclass {
let four = [1, 2, 3]
let five = ["a": "a", "b": "b"]
private enum CodingKeys: String, CodingKey {
case four, five
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(four, forKey: .four)
try container.encode(five, forKey: .five)
}
}
private final class ManuallyEncodableSubclass: EncodableSuperclass {
let four = [1, 2, 3]
let five = ["a": "a", "b": "b"]
private enum CodingKeys: String, CodingKey {
case four, five
}
override func encode(to encoder: Encoder) throws {
var keyedContainer = encoder.container(keyedBy: CodingKeys.self)
try keyedContainer.encode(four, forKey: .four)
try keyedContainer.encode(five, forKey: .five)
let superEncoder = keyedContainer.superEncoder()
var superContainer = superEncoder.container(keyedBy: CodingKeys.self)
try superContainer.encode(one, forKey: .four)
let keyedSuperEncoder = keyedContainer.superEncoder(forKey: .four)
var superKeyedContainer = keyedSuperEncoder.container(keyedBy: CodingKeys.self)
try superKeyedContainer.encode(two, forKey: .five)
var unkeyedContainer = keyedContainer.nestedUnkeyedContainer(forKey: .four)
let unkeyedSuperEncoder = unkeyedContainer.superEncoder()
var keyedUnkeyedSuperContainer = unkeyedSuperEncoder.container(keyedBy: CodingKeys.self)
try keyedUnkeyedSuperContainer.encode(one, forKey: .four)
}
}
private struct ManuallyEncodableStruct: Encodable {
let a = ["string": "string"]
let b = [1, 2, 3]
private enum RootKey: String, CodingKey {
case root
}
private enum TypeKeys: String, CodingKey {
case a, b
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RootKey.self)
var nestedKeyedContainer = container.nestedContainer(keyedBy: TypeKeys.self, forKey: .root)
try nestedKeyedContainer.encode(a, forKey: .a)
var nestedUnkeyedContainer = container.nestedUnkeyedContainer(forKey: .root)
try nestedUnkeyedContainer.encode(b)
var nestedUnkeyedKeyedContainer = nestedUnkeyedContainer.nestedContainer(keyedBy: TypeKeys.self)
try nestedUnkeyedKeyedContainer.encode(a, forKey: .a)
var nestedUnkeyedUnkeyedContainer = nestedUnkeyedContainer.nestedUnkeyedContainer()
try nestedUnkeyedUnkeyedContainer.encode(b)
}
}
private struct FailingOptionalStruct: Encodable {
enum TestedContainer {
case keyed, unkeyed
}
enum CodingKeys: String, CodingKey { case a }
let testedContainer: TestedContainer
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch testedContainer {
case .keyed:
var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .a)
try nested.encodeNil(forKey: .a)
case .unkeyed:
var nested = container.nestedUnkeyedContainer(forKey: .a)
try nested.encodeNil()
}
}
}
| mit | 322507a11c47ca669ae60cb4431dc630 | 31.387255 | 193 | 0.631391 | 4.503135 | false | true | false | false |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/player/AudioPlayerMode.swift | 3 | 1204 | //
// AudioPlayerMode.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 19/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
/// Represents the mode in which the player should play. Modes can be used as masks so that you can play in `.shuffle`
/// mode and still `.repeatAll`.
public struct AudioPlayerMode: OptionSet {
/// The raw value describing the mode.
public let rawValue: UInt
/// Initializes an `AudioPlayerMode` from a `rawValue`.
///
/// - Parameter rawValue: The raw value describing the mode.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// In this mode, player's queue will be played as given.
public static let normal = AudioPlayerMode(rawValue: 0)
/// In this mode, player's queue is shuffled randomly.
public static let shuffle = AudioPlayerMode(rawValue: 0b001)
/// In this mode, the player will continuously play the same item over and over.
public static let `repeat` = AudioPlayerMode(rawValue: 0b010)
/// In this mode, the player will continuously play the same queue over and over.
public static let repeatAll = AudioPlayerMode(rawValue: 0b100)
}
| mit | 31fbe6347865aa3acac5ee43a71ec154 | 33.371429 | 118 | 0.700748 | 4.296429 | false | false | false | false |
a736220388/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/foodCourse/model/FoodCourseModel.swift | 1 | 3955 | //
// FoodCourseModel.swift
// TestKitchen
//
// Created by qianfeng on 16/8/25.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
import SwiftyJSON
class FoodCourseModel: NSObject {
var code:String?
var msg:String?
var version:String?
var timestamp:NSNumber?
var data:FoodCourseDataModel?
class func parseModelWithData(data:NSData)->FoodCourseModel{
let model = FoodCourseModel()
let jsonData = JSON(data:data)
model.code = jsonData["code"].string
model.msg = jsonData["msg"].string
model.version = jsonData["version"].string
model.timestamp = jsonData["timestamp"].number
let subJSON = jsonData["data"]
model.data = FoodCourseDataModel.praseModel(subJSON)
return model
}
}
class FoodCourseDataModel:NSObject{
var series_id:String?
var series_name:String?
var series_title:String?
var create_time:String?
var last_update:String?
var order_no:String?
var tag:String?
var episode:NSNumber?
var series_image:String?
var share_title:String?
var share_description:String?
var share_image:String?
var album:String?
var album_logo:String?
var relate_activity:String?
var data:Array<FoodCourseSerialModel>?
var play:NSNumber?
var share_url:String?
class func praseModel(jsonData:JSON)->FoodCourseDataModel{
let model = FoodCourseDataModel()
model.series_id = jsonData["series_id"].string
model.series_name = jsonData["series_name"].string
model.series_title = jsonData["series_title"].string
model.create_time = jsonData["create_time"].string
model.last_update = jsonData["last_update"].string
model.order_no = jsonData["order_no"].string
model.tag = jsonData["tag"].string
model.episode = jsonData["episode"].number
model.series_image = jsonData["series_image"].string
model.share_title = jsonData["share_title"].string
model.share_description = jsonData["share_description"].string
model.share_image = jsonData["share_image"].string
model.album = jsonData["album"].string
model.album_logo = jsonData["album_logo"].string
model.relate_activity = jsonData["relate_activity"].string
model.play = jsonData["play"].number
model.share_url = jsonData["share_url"].string
let array = jsonData["data"]
var dataArray = Array<FoodCourseSerialModel>()
for (_,subJOSN) in array{
let dataModel = FoodCourseSerialModel.praseModel(subJOSN)
dataArray.append(dataModel)
}
model.data = dataArray
return model
}
}
class FoodCourseSerialModel:NSObject{
var course_id:NSNumber?
var course_video:String?
var episode:NSNumber?
var course_name:String?
var course_subject:String?
var course_image:String?
var ischarge:String?
var price:String?
var video_watchcount:NSNumber?
var course_introduce:String?
var is_collect:NSNumber?
var is_like:NSNumber?
class func praseModel(jsonData:JSON)->FoodCourseSerialModel{
let model = FoodCourseSerialModel()
model.course_id = jsonData["course_id"].number
model.course_video = jsonData["course_video"].string
model.episode = jsonData["episode"].number
model.course_name = jsonData["course_name"].string
model.course_subject = jsonData["course_subject"].string
model.course_image = jsonData["course_image"].string
model.ischarge = jsonData["ischarge"].string
model.price = jsonData["price"].string
model.video_watchcount = jsonData["video_watchcount"].number
model.course_introduce = jsonData["course_introduce"].string
model.is_collect = jsonData["is_collect"].number
model.is_like = jsonData["is_like"].number
return model
}
}
| mit | f06483702cf0a2045f0c9ccffb7c2902 | 33.365217 | 70 | 0.662702 | 4.204255 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/2079-swift-module-lookupvalue.swift | 13 | 367 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let f = true }
struct D : NSObject {
print() -> {
}
protocol P {
typealias d : d == b> Int = [B
case A, y: Any, x = ")) -> : NSObject {
func c
self.B<D
| apache-2.0 | 6651ee431ef618cf72058fb467532307 | 23.466667 | 87 | 0.66485 | 3.306306 | false | true | false | false |
mightydeveloper/swift | test/SILPasses/Inputs/BaseProblem.swift | 14 | 404 | public class BaseProblem
{
func run() -> Int
{
return 0
}
}
class Evaluator
{
var map: [Int: () -> Int] = [:]
init()
{
map[1] = { Problem1().run() }
map[2] = { Problem2().run() }
}
func evaluate(n: Int)
{
if let problemBlock = map[n]
{
let foo = problemBlock()
print("foo = \(foo)")
}
}
}
| apache-2.0 | ab090c4dd3609f22e862c3b6ca0f9563 | 13.962963 | 37 | 0.408416 | 3.452991 | false | false | false | false |
morpheby/aTarantula | Xcode Templates/aTarantula Plug-in.xctemplate/main/SettingsViewController.swift | 1 | 5238 | //___FILEHEADER___
import Cocoa
import TarantulaPluginCore
class SettingsViewController: NSViewController {
var plugin: ___PACKAGENAMEASIDENTIFIER___CrawlerPlugin!
@objc dynamic var filterDrugName: String? = UserDefaults.standard.filterDrugName {
didSet {
UserDefaults.standard.filterDrugName = filterDrugName
}
}
var filterSetting: FilterSetting = (UserDefaults.standard.filterSetting.flatMap { x in FilterSetting(rawValue: x) }) ?? .noFilter {
didSet {
UserDefaults.standard.filterSetting = filterSetting.rawValue
}
}
@IBOutlet var noFilterButton: NSButton!
@IBOutlet var filterByNameButton: NSButton!
enum FilterSetting: Int {
case noFilter = 0
case drugNameFilter = 1
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch (segue.identifier) {
case .some(.initialObject):
guard let viewController = segue.destinationController as? InitialObjectViewController else {
fatalError("Invalid segue")
}
viewController.plugin = plugin
break
default:
break
}
}
@IBAction func selectFilter(_ sender: NSButton!) {
switch sender {
case noFilterButton:
filterSetting = .noFilter
case filterByNameButton:
filterSetting = .drugNameFilter
default:
fatalError("Choice not implemented")
}
}
@IBAction func eraseDatabase(_ sender: Any?) {
guard let repository = plugin.repository else {
fatalError("Repository uninitialized")
}
var objectCount = 0
repository.performAndWait {
for type in self.plugin.allObjectTypes {
objectCount += repository.countAllObjects(type)
}
}
let alert = NSAlert()
alert.addButton(withTitle: "Yes, delete \(objectCount) objects")
alert.addButton(withTitle: "Cancel")
alert.messageText = "Delete all \(objectCount) objects from the database?"
alert.informativeText = "Deleted objects cannot be restored."
alert.alertStyle = .warning;
guard alert.runModal() == .alertFirstButtonReturn else {
return
}
repository.performAndWait {
for type in self.plugin.allObjectTypes {
let allObjects = repository.readAllObjects(type)
for object in allObjects {
repository.delete(object: object)
}
}
}
}
@IBAction func unfilterAll(_ sender: Any?) {
guard let repository = plugin.repository else {
fatalError("Repository uninitialized")
}
repository.performAndWait {
for type in self.plugin.crawlableObjectTypes {
let allObjects = repository.readAllObjects(type, withSelection: .unselectedObjects) as! [CrawlableObject]
for object in allObjects {
object.objectIsSelected = true
}
}
}
}
@IBAction func assignFilter(_ sender: Any?) {
switch filterSetting {
case .noFilter:
self.plugin.filterMethod = .none
case .drugNameFilter:
guard let drugName = filterDrugName else {
let alert = NSAlert()
alert.addButton(withTitle: "OK")
alert.messageText = "Enter drug name"
alert.alertStyle = .warning
alert.runModal()
return
}
self.plugin.filterMethod = .closure({ object in
switch object {
// TODO: Input filter methods here
default:
return false
}
})
}
}
@IBAction func invokeFilter(_ sender: Any?) {
guard let repository = plugin.repository else {
fatalError("Repository uninitialized")
}
repository.performAndWait {
for type in self.plugin.crawlableObjectTypes {
let allObjects = repository.readAllObjects(type, withSelection: .all) as! [CrawlableObject]
for object in allObjects {
object.objectIsSelected = needsToBeSelected(object: object, filterMethod: self.plugin.filterMethod)
}
}
}
}
@IBAction func specialButton(_ sender: Any?) {
// A special place to implement any temporary function :)
Configuration.specialButton(self.plugin)
}
}
extension UserDefaults {
var filterDrugName: String? {
get {
return self.string(forKey: "\(Configuration.pluginName)_filterDrugName")
}
set {
self.set(newValue, forKey: "\(Configuration.pluginName)_filterDrugName")
}
}
var filterSetting: Int? {
get {
return self.integer(forKey: "\(Configuration.pluginName)_filterSetting")
}
set {
self.set(newValue, forKey: "\(Configuration.pluginName)_filterSetting")
}
}
}
| gpl-3.0 | 6dbd7a25c46d42a43928148a2cccc0a6 | 31.333333 | 135 | 0.580565 | 5.243243 | false | false | false | false |
mmadjer/RxStateFlow | Tests/TestMocks.swift | 1 | 1340 | //
// TestMocks.swift
// RxStateFlow
//
// Created by Miroslav Valkovic-Madjer on 27/10/16.
// Copyright © 2016 Miroslav Madjer. All rights reserved.
//
@testable import RxStateFlow
class TestState: StateObject {
open fileprivate(set) dynamic var value: String = ""
override func react(to event: Event) {
switch event {
case let event as TestStringEvent:
value = event.value
default:
break
}
}
}
struct TestStringEvent: Event {
let value: String
}
struct TestCommand: Command {
typealias StateType = TestState
func execute(state: StateType, store: Store<StateType>) {
store.dispatch(event: TestStringEvent(value: "OK"))
}
}
struct TestConditionalCommand: Command {
typealias StateType = TestState
func execute(state: StateType, store: Store<StateType>) {
if state.value == "INIT" {
store.dispatch(event: TestStringEvent(value: "OK"))
} else {
store.dispatch(event: TestStringEvent(value: "NOT OK"))
}
}
}
struct TestAsyncCommand: Command {
typealias StateType = TestState
func execute(state: StateType, store: Store<StateType>) {
DispatchQueue.global(qos: .default).async {
store.dispatch(event: TestStringEvent(value: "OK"))
}
}
}
| mit | f7a022acac2e02fe2d487454df0720bf | 22.491228 | 67 | 0.635549 | 3.997015 | false | true | false | false |
Sajjon/Zeus | Zeus/ModelManager.swift | 1 | 6666 | //
// ModelManager.swift
// Zeus
//
// Created by Alexander Georgii-Hemming Cyon on 20/08/16.
// Copyright © 2016 com.cyon. All rights reserved.
//
import Foundation
import CoreData
import Alamofire
import SwiftyBeaver
public protocol ModelManagerProtocol {
static var sharedInstance: ModelManagerProtocol! { get set }
var managedObjectStore: DataStoreProtocol { get }
var httpClient: Alamofire.SessionManager { get }
func map(_ a: MappingProtocol, closure: (MappingProxy) -> Void)
func map(_ a: MappingProtocol, _ b: MappingProtocol, closure: (MappingProxy, MappingProxy) -> Void)
func map(_ a: MappingProtocol, _ b: MappingProtocol, _ c: MappingProtocol, closure: (MappingProxy, MappingProxy, MappingProxy) -> Void)
func map(_ a: MappingProtocol, _ b: MappingProtocol, _ c: MappingProtocol, _ d: MappingProtocol, closure: (MappingProxy, MappingProxy, MappingProxy, MappingProxy) -> Void)
func map(_ a: MappingProtocol, _ b: MappingProtocol, _ c: MappingProtocol, _ d: MappingProtocol, _ e: MappingProtocol, closure: (MappingProxy, MappingProxy, MappingProxy, MappingProxy, MappingProxy) -> Void)
func get(atPath path: APIPathProtocol, queryParameters params: QueryParameters?, options: Options?, done: Done?)
func post(model: AnyObject?, toPath path: APIPathProtocol, queryParameters params: QueryParameters?, done: Done?)
}
open class ModelManager: ModelManagerProtocol {
open static var sharedInstance: ModelManagerProtocol!
open let managedObjectStore: DataStoreProtocol
open let httpClient: Alamofire.SessionManager
fileprivate let modelMappingManager: ModelMappingManagerProtocol
fileprivate let baseUrl: String
public init(baseUrl: String, store: DataStoreProtocol) {
self.baseUrl = baseUrl
self.managedObjectStore = store
self.httpClient = Alamofire.SessionManager()
self.modelMappingManager = ModelMappingManager()
}
open func get(atPath path: APIPathProtocol, queryParameters params: QueryParameters?, options: Options?, done: Done?) {
let pathFull = path.request(baseUrl: baseUrl)
let options = options ?? Options(.persistEntitiesDuringMapping)
httpClient.request(pathFull, withMethod: Alamofire.HTTPMethod.get, parameters: params)
.validate()
.responseJSON {
response in
self.handle(jsonResponse: response, fromPath: path, options: options, done: done)
}
}
open func post(model: AnyObject?, toPath path: APIPathProtocol, queryParameters params: QueryParameters?, done: Done?) {
log.error("post")
}
open func map(
_ a: MappingProtocol,
closure: (MappingProxy) -> Void
) {
let context = MappingContext()
closure(
MappingProxy(context: context, mapping: a)
)
modelMappingManager.addResponseDescriptors(fromContext: context)
}
open func map(
_ a: MappingProtocol,
_ b: MappingProtocol,
closure: (MappingProxy, MappingProxy) -> Void
) {
let context = MappingContext()
closure(
MappingProxy(context: context, mapping: a),
MappingProxy(context: context, mapping: b)
)
modelMappingManager.addResponseDescriptors(fromContext: context)
}
open func map(
_ a: MappingProtocol,
_ b: MappingProtocol,
_ c: MappingProtocol,
closure: (MappingProxy, MappingProxy, MappingProxy) -> Void
) {
let context = MappingContext()
closure(
MappingProxy(context: context, mapping: a),
MappingProxy(context: context, mapping: b),
MappingProxy(context: context, mapping: c)
)
modelMappingManager.addResponseDescriptors(fromContext: context)
}
open func map(
_ a: MappingProtocol,
_ b: MappingProtocol,
_ c: MappingProtocol,
_ d: MappingProtocol,
closure: (MappingProxy, MappingProxy, MappingProxy, MappingProxy) -> Void
) {
let context = MappingContext()
closure(
MappingProxy(context: context, mapping: a),
MappingProxy(context: context, mapping: b),
MappingProxy(context: context, mapping: c),
MappingProxy(context: context, mapping: d)
)
modelMappingManager.addResponseDescriptors(fromContext: context)
}
open func map(
_ a: MappingProtocol,
_ b: MappingProtocol,
_ c: MappingProtocol,
_ d: MappingProtocol,
_ e: MappingProtocol,
closure: (MappingProxy, MappingProxy, MappingProxy, MappingProxy, MappingProxy) -> Void
) {
let context = MappingContext()
closure(
MappingProxy(context: context, mapping: a),
MappingProxy(context: context, mapping: b),
MappingProxy(context: context, mapping: c),
MappingProxy(context: context, mapping: d),
MappingProxy(context: context, mapping: e)
)
modelMappingManager.addResponseDescriptors(fromContext: context)
}
}
//MARK: Private Methods
private extension ModelManager {
func fullPath(withPath path: String) -> String {
let fullPath = baseUrl + path
return fullPath
}
func handle(jsonResponse response: Response<Any, NSError>, fromPath path: APIPathProtocol, options: Options, done: Done?) {
switch response.result {
case .success(let data):
var result: Result!
if let arrayOrRawJson = data as? [RawJSON] {
let jsonArray: [JSON] = arrayOrRawJson.map { return JSON($0) }
result = modelMappingManager.mapping(withJsonArray: jsonArray, fromPath: path, options: options)
} else if let json = data as? RawJSON {
result = modelMappingManager.mapping(withJsonOrArray: JSON(json), fromPath: path, options: options)
}
if let mappingResult = result {
if mappingResult.isManagedObject && options.persistEntities {
managedObjectStore.mainThreadManagedObjectContext.saveToPersistentStore()
}
done?(mappingResult)
} else {
done?(Result(.parsingJSON))
}
case .failure(let error):
log.error("failed, error: \(error)")
done?(Result(.parsingJSON))
}
}
func addResponseDescriptors(fromContext context: MappingContext) {
modelMappingManager.addResponseDescriptors(fromContext: context)
}
}
| apache-2.0 | 5574f81b133ae2de026343dacb77154b | 37.976608 | 211 | 0.643661 | 4.716914 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/AppAPI/MarketAPI/MarketSocketAPI.swift | 1 | 7440 | //
// MarketSocketAPI.swift
// iOSStar
//
// Created by J-bb on 17/5/13.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
class MarketSocketAPI: BaseSocketAPI,MarketAPI {
//请求行情分类
func requestTypeList(complete: CompleteBlock?, error: ErrorBlock?) {
let paramters:[String:Any] = [SocketConst.Key.phone : "123"]
let packet = SocketDataPacket(opcode: .marketType, parameters: paramters)
startModelsRequest(packet, listName: "list", modelClass: MarketClassifyModel.self, complete: complete, error: error)
}
//搜索
func searchstar(requestModel:MarketSearhModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .searchStar, model: requestModel, type:.search)
startModelsRequest(packet, listName: "starsinfo", modelClass: SearchResultModel.self, complete: complete, error: error)
}
//单个分类明星列表
func requestStarList(requestModel:StarListRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .starList, model: requestModel)
startModelsRequest(packet, listName: "symbol_info", modelClass: MarketListModel.self, complete: complete, error: error)
}
//自选明星
func requestOptionalStarList(startnum:Int, endnum:Int,complete: CompleteBlock?, error: ErrorBlock?) {
guard UserDefaults.standard.string(forKey: SocketConst.Key.phone) != nil else {
return
}
let paramters:[String:Any] = [SocketConst.Key.startnum : startnum,
SocketConst.Key.endnum : endnum,
SocketConst.Key.phone : UserDefaults.standard.string(forKey: SocketConst.Key.phone)!]
let packet = SocketDataPacket(opcode: .marketStar, parameters: paramters)
startModelsRequest(packet, listName: "list", modelClass: MarketListModel.self, complete: complete, error: error)
}
//添加自选明星
func addOptinal(starcode:String,complete: CompleteBlock?, error: ErrorBlock?) {
guard UserDefaults.standard.string(forKey: SocketConst.Key.phone) != nil else {
return
}
let parameters:[String:Any] = [SocketConst.Key.starcode:starcode,
SocketConst.Key.phone:UserDefaults.standard.string(forKey: SocketConst.Key.phone)!]
let packet = SocketDataPacket(opcode: .addOptinal, parameters: parameters)
startResultIntRequest(packet, complete: complete, error: error)
}
//获取明星经历
func requestStarExperience(code:String,complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.starCode : code]
let packet = SocketDataPacket(opcode: .starExperience, parameters: parameters)
startModelsRequest(packet, listName: "list", modelClass: ExperienceModel.self, complete: complete, error: error)
}
func requestStarArachive(code:String,complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.starCode : code]
let packet = SocketDataPacket(opcode: .starAchive, parameters: parameters)
startModelsRequest(packet, listName: "list", modelClass: AchiveModel.self, complete: complete, error: error)
}
//获取实时报价
func requestRealTime(requestModel:RealTimeRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .realTime, model: requestModel)
startModelsRequest(packet, listName: "priceinfo", modelClass: RealTimeModel.self, complete: complete, error: error)
}
//获取分时图
func requestTimeLine(requestModel:TimeLineRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .timeLine, model: requestModel)
startModelsRequest(packet, listName: "priceinfo", modelClass: TimeLineModel.self, complete: complete, error: error)
}
//发送评论
func sendComment(requestModel:SendCommentModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .sendComment, model: requestModel)
startRequest(packet, complete: complete, error: error)
}
//获取评论列表
func requestCommentList(requestModel:CommentListRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .commentList, model: requestModel)
startRequest(packet, complete: complete, error: error)
}
//获取拍卖时间
func requestAuctionStatus(requestModel:AuctionStatusRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .auctionStatus, model: requestModel)
startModelRequest(packet, modelClass: AuctionStatusModel.self, complete: complete, error: error)
}
// 获取明星服务类型
func requestStarServiceType(starcode: String, complete: CompleteBlock?, error: ErrorBlock?) {
let parameters:[String:Any] = [SocketConst.Key.starcode : starcode]
let packet = SocketDataPacket(opcode: .starServiceType, parameters: parameters)
startModelsRequest(packet, listName: "list", modelClass: ServiceTypeModel.self, complete: complete, error: error)
}
// 订购明星服务
func requestBuyStarService(requestModel: ServiceTypeRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .buyStarService, model: requestModel)
startRequest(packet, complete: complete, error: error)
}
//委托粉丝榜
func requestEntrustFansList(requestModel:FanListRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .fansList, model: requestModel)
startModelsRequest(packet, listName: "positionsList", modelClass: FansListModel.self, complete: complete, error: error)
}
//订单粉丝榜
func requestOrderFansList(requestModel:FanListRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .orderFansList, model: requestModel)
startModelsRequest(packet, listName: "ordersList", modelClass: OrderFansListModel.self, complete: complete, error: error)
}
//持有某个明星时间数量
func requestPositionCount(requestModel:PositionCountRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .positionCount, model: requestModel)
startModelRequest(packet, modelClass: PositionCountModel.self, complete: complete, error: error)
}
//买卖占比
func requstBuySellPercent(requestModel:BuySellPercentRequest,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .buySellPercent, model: requestModel)
startModelRequest(packet, modelClass: BuySellCountModel.self, complete: complete, error: error)
}
//请求明星发行时间
func requestTotalCount(starCode:String,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode:.starTotalTime, parameters: ["starcode":starCode])
startModelRequest(packet, modelClass: StarTotalCountModel.self, complete: complete, error: error)
}
}
| gpl-3.0 | 43d20ad472412485f2b2ba539d7cdcff | 48.5 | 129 | 0.708178 | 4.387978 | false | false | false | false |
nuudles/NavigationMeshGraph | Example/NavigationMeshGraphExample/GameScene.swift | 1 | 5223 | //
// GameScene.swift
// NavigationMeshGraphExample
//
// Created by Christopher Luu on 7/2/15.
// Copyright (c) 2015 Nuudles. All rights reserved.
//
import SpriteKit
import GameplayKit
import NavigationMeshGraph
import SwiftyJSON
// Extend `CGPoint` to add an initializer from a `float2` representation of a point.
extension CGPoint {
// MARK: Initializers
/// Initialize with a `float2` type.
init(_ point: float2) {
x = CGFloat(point.x)
y = CGFloat(point.y)
}
}
// Extend `float2` to add an initializer from a `CGPoint`.
extension float2 {
// MARK: Initialization
/// Initialize with a `CGPoint` type.
init(_ point: CGPoint) {
self.init(x: Float(point.x), y: Float(point.y))
}
}
class GameScene: SKScene
{
let shipSprite = SKSpriteNode(imageNamed: "Spaceship")
lazy var graph: NavigationMeshGraph =
{
let json = JSON(data: NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("Testing", ofType: "json")!)!)
var polygons: [NavigationMeshPolygon] = []
for polygon in json["rigidBodies"][0]["polygons"].arrayValue
{
var points: [float2] = []
for point in polygon.arrayValue
{
points.append(float2(point["x"].floatValue * Float(self.size.width) + 50, point["y"].floatValue * Float(self.size.height) + 300))
}
polygons.append(NavigationMeshPolygon(points: points))
}
let graph = NavigationMeshGraph(polygons: polygons)
return graph
}()
var lastTime: NSTimeInterval = 0
var path: [GKGraphNode2D]?
var nextPosition: float2?
let pathNode = SKShapeNode()
override func didMoveToView(view: SKView)
{
super.didMoveToView(view)
let polygonPath = CGPathCreateMutable()
for polygon in graph.polygons
{
let points = polygon.points
CGPathMoveToPoint(polygonPath, nil, CGFloat(points[0].x), CGFloat(points[0].y))
for point in points
{
CGPathAddLineToPoint(polygonPath, nil, CGFloat(point.x), CGFloat(point.y))
}
}
let polygonNode = SKShapeNode()
polygonNode.path = polygonPath
polygonNode.fillColor = .blueColor()
polygonNode.strokeColor = .greenColor()
addChild(polygonNode)
/*
// Uncomment this to draw the graph connections
for node in graph.nodes as! [GKGraphNode2D]
{
let path = CGPathCreateMutable()
for connectedNode in node.connectedNodes as! [GKGraphNode2D]
{
CGPathMoveToPoint(path, nil, CGFloat(node.position.x), CGFloat(node.position.y))
CGPathAddLineToPoint(path, nil, CGFloat(connectedNode.position.x), CGFloat(connectedNode.position.y))
}
let shapeNode = SKShapeNode()
shapeNode.path = path
shapeNode.strokeColor = UIColor.yellowColor()
addChild(shapeNode)
}
*/
pathNode.strokeColor = UIColor.redColor()
pathNode.lineWidth = 10
addChild(pathNode)
shipSprite.position = CGPoint(x: 200, y: 400)
shipSprite.xScale = 0.1
shipSprite.yScale = 0.1
addChild(shipSprite)
}
override func didChangeSize(oldSize: CGSize)
{
super.didChangeSize(oldSize)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
guard let touch = touches.first else { return }
let startPosition = shipSprite.position
let endPosition = touch.locationInNode(self)
let startNode = NavigationMeshGraphNode(point: float2(startPosition))
let endNode = NavigationMeshGraphNode(point: float2(endPosition))
graph.connectNodeToClosestPointOnNavigationMesh(startNode)
graph.connectNodeToClosestPointOnNavigationMesh(endNode)
if let path = graph.findPathFromNode(startNode, toNode: endNode) as? [GKGraphNode2D]
{
nextPosition = nil
self.path = path.count > 0 ? path : nil
if path.count > 0
{
let linePath = CGPathCreateMutable()
CGPathMoveToPoint(linePath, nil, CGFloat(path[0].position.x), CGFloat(path[0].position.y))
for node in path
{
CGPathAddLineToPoint(linePath, nil, CGFloat(node.position.x), CGFloat(node.position.y))
}
pathNode.path = linePath
}
}
graph.removeNodes([startNode, endNode])
}
override func update(currentTime: CFTimeInterval)
{
let deltaTime = currentTime - lastTime
if path != nil && nextPosition == nil
{
nextPosition = path![0].position
path!.removeAtIndex(0)
if path!.count == 0
{
path = nil
}
}
if let nextPosition = self.nextPosition
{
let movementSpeed = CGFloat(300)
let displacement = nextPosition - float2(shipSprite.position)
let angle = CGFloat(atan2(displacement.y, displacement.x))
let maxPossibleDistanceToMove = movementSpeed * CGFloat(deltaTime)
let normalizedDisplacement: float2
if length(displacement) > 0.0
{
normalizedDisplacement = normalize(displacement)
}
else
{
normalizedDisplacement = displacement
}
let actualDistanceToMove = CGFloat(length(normalizedDisplacement)) * maxPossibleDistanceToMove
// Find the x and y components of the distance based on the angle.
let dx = actualDistanceToMove * cos(angle)
let dy = actualDistanceToMove * sin(angle)
shipSprite.position = CGPoint(x: shipSprite.position.x + dx, y: shipSprite.position.y + dy)
shipSprite.zRotation = atan2(-dx, dy)
if length(displacement) <= Float(maxPossibleDistanceToMove)
{
self.nextPosition = nil
}
}
lastTime = currentTime
}
}
| mit | 32ee6369ac021adc55bba00849860618 | 25.647959 | 133 | 0.713957 | 3.49131 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/RemoteNotifications/Sources/RemoteNotificationsKit/Network/PushNotificationAuthPayload.swift | 1 | 1542 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import NetworkKit
struct RemoteNotificationTokenQueryParametersBuilder {
enum BuildError: Error {
case guidIsEmpty
case sharedKeyIsEmpty
case tokenIsEmpty
}
private enum Keys: String {
case guid
case sharedKey
case token = "payload"
case tokenLength = "length"
case apiCode = "api_code"
}
var parameters: Data? {
let queryItems = [
URLQueryItem(name: Keys.guid.rawValue, value: guid),
URLQueryItem(name: Keys.sharedKey.rawValue, value: sharedKey),
URLQueryItem(name: Keys.token.rawValue, value: token),
URLQueryItem(name: Keys.tokenLength.rawValue, value: "\(token.count)"),
URLQueryItem(name: Keys.apiCode.rawValue, value: BlockchainAPI.Parameters.apiCode)
]
var components = URLComponents()
components.queryItems = queryItems
let query = components.query
return query?.data(using: .utf8)
}
private let guid: String
private let sharedKey: String
private let token: String
init(guid: String, sharedKey: String, token: String) throws {
guard !guid.isEmpty else { throw BuildError.guidIsEmpty }
guard !sharedKey.isEmpty else { throw BuildError.sharedKeyIsEmpty }
guard !token.isEmpty else { throw BuildError.tokenIsEmpty }
self.guid = guid
self.sharedKey = sharedKey
self.token = token
}
}
| lgpl-3.0 | 7da4b95675c788ac52db9d0588f0283b | 30.44898 | 94 | 0.648929 | 4.741538 | false | false | false | false |
matsuda/MuddlerKit | MuddlerKit/UIViewControllerExtensions.swift | 1 | 2621 | //
// UIViewControllerExtensions.swift
// MuddlerKit
//
// Created by Kosuke Matsuda on 2015/12/28.
// Copyright © 2015年 Kosuke Matsuda. All rights reserved.
//
import UIKit
extension UIViewController {
public func peelAllPresentedViewControllers() {
var presented = self.presentedViewController
while presented?.presentedViewController != nil {
presented = presented?.presentedViewController
}
presented?.peelViewController()
}
public func peelViewController() {
let presenting = self.presentingViewController
self.dismiss(animated: false) {
presenting?.peelViewController()
}
}
public func setExclusiveTouchToBarButtonItems() {
var c: UIViewController? = self
while c != nil && !(c is UINavigationController) {
c = c?.parent
}
c?.setExclusiveTouchToBarButtonItems()
}
}
// MARK: -
extension UIViewController {
/// Manually adjust its scroll view insets.
/// reference to `automaticallyAdjustsScrollViewInsets`.
/// `automaticallyAdjustsScrollViewInsets` is only invoked when the scrollView is first child view.
/// So for example, in case that the scrollVie is not first child view or
/// the view controller has two scrollView.
///
/// - paramter scrollView: The ScrollView to adjust
public func manuallyAdjustsScrollViewInsetsAndOffset(_ scrollView: UIScrollView) {
guard automaticallyAdjustsScrollViewInsets else {
return
}
let currentInsets = scrollView.contentInset
var insets = currentInsets
/*
var parent: UIViewController? = self.parent
while (parent != nil) {
parent = parent?.parent
}
if let parent = parent {
insets.top = parent.topLayoutGuide.length
insets.bottom = parent.bottomLayoutGuide.length
} else {
insets.top = topLayoutGuide.length
insets.bottom = bottomLayoutGuide.length
}
*/
insets.top = topLayoutGuide.length
insets.bottom = bottomLayoutGuide.length
if (!UIEdgeInsetsEqualToEdgeInsets(currentInsets, insets)) {
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
// iOS8でcontentOffsetが調整されないのを対処
if UIDevice.current.systemVersion.compare("8.0", options: .numeric) != .orderedAscending {
scrollView.setContentOffset(CGPoint(x: 0, y: -insets.top), animated: false)
}
}
}
}
| mit | 8b7358a29852cbd9a3f6f88413a9aed5 | 32.25641 | 103 | 0.643408 | 5.359504 | false | false | false | false |
WLChopSticks/weiboCopy | weiboCopy/weiboCopy/AppDelegate.swift | 2 | 2786 | //
// AppDelegate.swift
// weiboCopy
//
// Created by 王 on 15/12/12.
// Copyright © 2015年 王. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// create a new window and set one keyWindow
window = UIWindow(frame: UIScreen.mainScreen().bounds)
//keyWindow
let tabBarVC = CHSTabBarController()
window?.rootViewController = tabBarVC
window?.backgroundColor = UIColor.whiteColor()
window?.makeKeyAndVisible()
//load user account
// let account = CHSAccountInfo.loadUserData()
// print(account?.name)
CHSAccountInfo.loadUserData()
setThemeColor()
return true
}
//set the theme color
func setThemeColor() {
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 38fd3b4ddae3d1814fa24c02b8b4c9fa | 40.477612 | 285 | 0.717164 | 5.459725 | false | false | false | false |
uasys/swift | test/APINotes/versioned-multi.swift | 5 | 20518 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 3 | %FileCheck -check-prefix=CHECK-SWIFT-3 %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -swift-version 4 | %FileCheck -check-prefix=CHECK-SWIFT-4 %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -swift-version 5 | %FileCheck -check-prefix=CHECK-SWIFT-5 %s
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal4_4: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Notes_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Notes: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal4Notes_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Notes_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Notes_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Header_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Header: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal4Header_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Header_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Header_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Both_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Both: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal4Both_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Both_4")
// CHECK-SWIFT-3: var multiVersionedGlobal4Both_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal34_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal34_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34_4: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Notes: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal34Notes_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal34Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Notes_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Notes_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Header: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal34Header_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal34Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Header_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Header_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Both: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal34Both_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal34Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Both_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal34Both_NEW: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal45_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Notes_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Notes: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal45Notes_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Notes_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Notes_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Header_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Header: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal45Header_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Header_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Header_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Both_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Both: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal45Both_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Both_4")
// CHECK-SWIFT-3: var multiVersionedGlobal45Both_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal345_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal345_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Notes: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal345Notes_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal345Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Notes_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Notes_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Notes_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Header: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal345Header_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal345Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Header_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Header_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Header_5: Int32
// CHECK-SWIFT-3: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Both: Int32
// CHECK-SWIFT-3: var multiVersionedGlobal345Both_3: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 4, renamed: "multiVersionedGlobal345Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Both_4: Int32
// CHECK-SWIFT-3: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Both_3")
// CHECK-SWIFT-3: var multiVersionedGlobal345Both_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal4_4: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Notes: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal4Notes_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Notes_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Header: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal4Header_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Header_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Both: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal4Both_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal4Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal4Both_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal34_4: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Notes: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Notes_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal34Notes_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Notes_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Header: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Header_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal34Header_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Header_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Both: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Both_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal34Both_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal34Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal34Both_NEW: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal45_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Notes: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal45Notes_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Notes_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Header: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal45Header_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Header_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Both: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal45Both_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal45Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal45Both_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal345_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Notes: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Notes_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal345Notes_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Notes_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Notes_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Header: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Header_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal345Header_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Header_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Header_5: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Both: Int32
// CHECK-SWIFT-4: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Both_3: Int32
// CHECK-SWIFT-4: var multiVersionedGlobal345Both_4: Int32
// CHECK-SWIFT-4: @available(swift, introduced: 5, renamed: "multiVersionedGlobal345Both_4")
// CHECK-SWIFT-4: var multiVersionedGlobal345Both_5: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal4: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal4")
// CHECK-SWIFT-5: var multiVersionedGlobal4_4: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Notes_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Notes: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal4Notes_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Notes_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal4Notes_NEW: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Header_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Header: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal4Header_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Header_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal4Header_NEW: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal4Both_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Both: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal4Both_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal4Both_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal4Both_NEW: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal34: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34")
// CHECK-SWIFT-5: var multiVersionedGlobal34_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal34")
// CHECK-SWIFT-5: var multiVersionedGlobal34_4: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Notes_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Notes: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Notes_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Notes_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal34Notes_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Notes_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal34Notes_NEW: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Header_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Header: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Header_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Header_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal34Header_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Header_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal34Header_NEW: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal34Both_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Both: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal34Both_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Both_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal34Both_NEW")
// CHECK-SWIFT-5: var multiVersionedGlobal34Both_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal34Both_NEW: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal45_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal45_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Notes_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Notes: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal45Notes_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Notes_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal45Notes_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Header_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Header: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal45Header_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Header_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal45Header_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal45Both_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Both: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal45Both_5")
// CHECK-SWIFT-5: var multiVersionedGlobal45Both_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal45Both_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal345_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal345_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Notes_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Notes: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Notes_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Notes_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal345Notes_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Notes_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal345Notes_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Header_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Header: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Header_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Header_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal345Header_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Header_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal345Header_5: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "multiVersionedGlobal345Both_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Both: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 4, renamed: "multiVersionedGlobal345Both_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Both_3: Int32
// CHECK-SWIFT-5: @available(swift, obsoleted: 5, renamed: "multiVersionedGlobal345Both_5")
// CHECK-SWIFT-5: var multiVersionedGlobal345Both_4: Int32
// CHECK-SWIFT-5: var multiVersionedGlobal345Both_5: Int32
| apache-2.0 | 9248a5d3eb737b4da1ff6396432108d5 | 68.084175 | 247 | 0.776635 | 3.100801 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/ViewModels/ShotDetailsFormatter.swift | 1 | 9157 | //
// ShotDetailsFormatter.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 23/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import UIKit.NSAttributedString
final class ShotDetailsFormatter {
static let ShotDetailsFormatterSmallFontSize: CGFloat = 12
static let ShotDetailsFormatterBigFontSize: CGFloat = 14
static var shotDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.locale = Locale.current
return formatter
}()
static var commentDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.locale = Locale.current
formatter.timeStyle = .short
return formatter
}()
fileprivate static var colorMode: ColorModeType {
return Settings.Customization.CurrentColorMode == .dayMode ? DayMode() : NightMode()
}
class func attributedStringForHeaderWithLinkRangeFromShot(_ shot: ShotType)
-> (attributedString: NSAttributedString, userLinkRange: NSRange?, teamLinkRange: NSRange?) {
let mutableAttributedString = NSMutableAttributedString()
var userLinkRange: NSRange?
var teamLinkRange: NSRange?
if shot.title.characters.count > 0 {
appendTitleAttributedString(mutableAttributedString, shot: shot)
}
let author = (shot.user.name ?? shot.user.username)
if author.characters.count > 0 {
userLinkRange = appendAuthorAttributedString(mutableAttributedString, author: author)
}
if let team = shot.team?.name, team.characters.count > 0 {
teamLinkRange = appendTeamAttributedString(mutableAttributedString, team: team)
}
let dateSting = shotDateFormatter.string(from: shot.createdAt as Date)
if dateSting.characters.count > 0 {
appendDateAttributedString(mutableAttributedString, dateSting: dateSting)
}
return (NSAttributedString(attributedString: mutableAttributedString), userLinkRange, teamLinkRange)
}
class func attributedShotDescriptionFromShot(_ shot: ShotType) -> NSAttributedString? {
guard let body = shot.attributedDescription?.attributedStringByTrimingTrailingNewLine() else {
return nil
}
let mutableBody = NSMutableAttributedString(attributedString: body)
let style = NSMutableParagraphStyle()
style.lineSpacing = 0
style.maximumLineHeight = 20
style.minimumLineHeight = 20
mutableBody.addAttributes([
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsDescriptionViewColorTextColor,
NSFontAttributeName: UIFont.systemFont(ofSize: 15),
NSParagraphStyleAttributeName: style
], range: NSRange(location: 0, length: mutableBody.length))
return mutableBody.copy() as? NSAttributedString
}
class func attributedCommentBodyForComment(_ comment: CommentType) -> NSAttributedString? {
guard let body = comment.body, body.length > 0 else {
return nil
}
if let mutableBody = body.attributedStringByTrimingTrailingNewLine().mutableCopy() as? NSMutableAttributedString {
let range = NSRange(location: 0, length: (mutableBody as AnyObject).length)
(mutableBody as AnyObject).addAttributes([
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsCommentContentTextColor,
NSFontAttributeName: UIFont.systemFont(ofSize: ShotDetailsFormatterBigFontSize)
], range: range)
return mutableBody.copy() as? NSAttributedString
}
return nil
}
class func commentDateForComment(_ comment: CommentType) -> NSAttributedString {
return NSAttributedString(string: commentDateFormatter.string(from: comment.createdAt as Date), attributes: [
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsCommentDateTextColor,
NSFontAttributeName: UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular)
])
}
class func commentAuthorForComment(_ comment: CommentType) -> NSAttributedString {
return NSAttributedString(string: comment.user.name ?? comment.user.username, attributes: [
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsCommentAuthorTextColor,
NSFontAttributeName: UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium)
])
}
class func commentLikesCountForComment(_ comment: CommentType) -> NSAttributedString {
return NSAttributedString(string: "\(comment.likesCount)", attributes: [
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsCommentLikesCountTextColor,
NSFontAttributeName: UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular)
])
}
}
private extension ShotDetailsFormatter {
class func appendTitleAttributedString(_ mutableAttributedString: NSMutableAttributedString, shot: ShotType) {
let titleAttributedString = NSAttributedString(string: shot.title,
attributes: [NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewTitleLabelTextColor,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15)])
mutableAttributedString.append(titleAttributedString)
mutableAttributedString.append(NSAttributedString.newLineAttributedString())
}
class func appendAuthorAttributedString(_ mutableAttributedString: NSMutableAttributedString,
author: String) -> NSRange {
let prefixString = Localized("ShotDetailsFormatter.By",
comment: "Preposition describing author of shot.")
let bigFont = UIFont.systemFont(ofSize: ShotDetailsFormatterBigFontSize)
let smallFont = UIFont.systemFont(ofSize: ShotDetailsFormatterSmallFontSize)
let authorAttributedString = NSMutableAttributedString(
string: prefixString + " " + author, attributes: [NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewAuthorLinkColor,
NSFontAttributeName: bigFont])
authorAttributedString.setAttributes([NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewAuthorNotLinkColor,
NSFontAttributeName: smallFont],
range: NSRange(location: 0, length: prefixString.characters.count))
let userLinkRange = NSRange(location: mutableAttributedString.length + prefixString.characters.count,
length: author.characters.count + 1)
mutableAttributedString.append(authorAttributedString)
mutableAttributedString.append(NSAttributedString.newLineAttributedString())
return userLinkRange
}
class func appendTeamAttributedString(_ mutableAttributedString: NSMutableAttributedString, team: String) -> NSRange {
let prefixString = Localized("ShotDetailsFormatter.For",
comment: "Preposition describing for who shot was made.")
let font = UIFont.systemFont(ofSize: ShotDetailsFormatterBigFontSize)
let teamAttributedString = NSMutableAttributedString(
string: prefixString + " " + team, attributes: [NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewAuthorLinkColor,
NSFontAttributeName: font])
teamAttributedString.setAttributes([
NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewAuthorNotLinkColor,
NSFontAttributeName: UIFont.systemFont(ofSize: ShotDetailsFormatterSmallFontSize)
], range: NSRange(location: 0, length: prefixString.characters.count))
let teamLinkRange = NSRange(location: mutableAttributedString.length + prefixString.characters.count,
length: team.characters.count + 1)
mutableAttributedString.append(teamAttributedString)
mutableAttributedString.append(NSAttributedString.newLineAttributedString())
return teamLinkRange
}
class func appendDateAttributedString(_ mutableAttributedString: NSMutableAttributedString, dateSting: String) {
let prefixString = Localized("ShotDetailsFormatter.On",
comment: "Preposition describing when shot was made.")
let font = UIFont.systemFont(ofSize: ShotDetailsFormatterSmallFontSize)
let dateAttributedString = NSAttributedString(
string: prefixString + " " + dateSting, attributes: [NSForegroundColorAttributeName: ColorModeProvider.current().shotDetailsHeaderViewAuthorNotLinkColor,
NSFontAttributeName: font])
mutableAttributedString.append(dateAttributedString)
}
}
| gpl-3.0 | 5494fda44e5fff48a7f01369b6916982 | 48.76087 | 161 | 0.699214 | 6 | false | false | false | false |
netguru/inbbbox-ios | Unit Tests/ParametersSpec.swift | 1 | 5181 | //
// ParametersSpec.swift
// Inbbbox
//
// Created by Radoslaw Szeja on 15/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
@testable import Inbbbox
class ParametersSpec: QuickSpec {
override func spec() {
describe("when newly initialized") {
var sut = Parameters(encoding: .url)
context("with URL encoding") {
beforeEach {
sut = Parameters(encoding: .url)
}
it("should not be nil") {
expect(sut).notTo(beNil())
}
it("should have URL encoding") {
expect(sut.encoding).to(equal(Parameters.Encoding.url))
}
it("should have empty query items") {
expect(sut.queryItems).to(beEmpty())
}
it("should have nil body") {
expect(sut.body).to(beNil())
}
context("when storing values") {
beforeEach {
sut["fixture.key.1"] = "fixture.value.1" as AnyObject?
sut["fixture.key.2"] = 123 as AnyObject?
}
it("should return correct value") {
expect(sut["fixture.key.1"] as? String).to(equal("fixture.value.1"))
}
it("should return correct query items") {
expect(sut["fixture.key.2"] as? Int).to(equal(123))
}
context("reading query items") {
var queryItems: [NSURLQueryItem]!
let expectedQueryItems: [NSURLQueryItem]! = [
NSURLQueryItem(name: "fixture.key.1", value: "fixture.value.1"),
NSURLQueryItem(name: "fixture.key.2", value: "123")
]
beforeEach {
queryItems = sut.queryItems as [NSURLQueryItem]!
}
it("should have correct query items") {
expect(queryItems).to(contain(expectedQueryItems.first!))
expect(queryItems).to(contain(expectedQueryItems.last!))
}
}
context("then clearing them") {
it("should return nil instead of string") {
sut["fixture.key.1"] = nil
expect(sut["fixture.key.1"]).to(beNil())
expect(sut["fixture.key.2"] as? Int).to(equal(123))
}
it("should return nil instead of array") {
sut["fixture.key.2"] = nil
expect(sut["fixture.key.1"] as? String).to(equal("fixture.value.1"))
expect(sut["fixture.key.2"]).to(beNil())
}
}
}
}
context("with JSON encoding") {
beforeEach {
sut = Parameters(encoding: .json)
}
it("should not be nil") {
expect(sut).notTo(beNil())
}
it("should have JSON encoding") {
expect(sut.encoding).to(equal(Parameters.Encoding.json))
}
it("should have empty query items") {
expect(sut.queryItems).to(beEmpty())
}
it("should have body") {
expect(sut.body).notTo(beNil())
}
context("when storing values") {
beforeEach {
sut["fixture.key.1"] = "fixture.value.1" as AnyObject?
sut["fixture.key.2"] = 123 as AnyObject?
}
it("should have correct JSON by serializing body") {
let json = try! JSONSerialization.jsonObject(with: sut.body!, options: .allowFragments) as! [String: AnyObject]
let expectedJSON = [
"fixture.key.1": "fixture.value.1" as AnyObject,
"fixture.key.2": 123 as AnyObject
] as [String: AnyObject]
expect(json == expectedJSON).to(beTrue())
}
}
}
}
}
}
private func ==(lhs: [String: AnyObject], rhs: [String: AnyObject]) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
| gpl-3.0 | 1fc52b8a23c66d0d85b79997e1a0364b | 37.088235 | 135 | 0.392471 | 5.787709 | false | false | false | false |
swordfishyou/fieldstool | FieldTool/Sources/Extensions/String+WKTHelpers.swift | 1 | 2167 | //
// String+WKTHelpers.swift
// FieldTool
//
import Foundation
extension String {
func geometryName() -> String {
let charactersToTrim = CharacterSet.uppercaseLetters.inverted
return self.trimmingCharacters(in: charactersToTrim)
}
func trimmingGeometryName() -> String {
let uppercaseLetters = CharacterSet.uppercaseLetters
let charactersToTrim = uppercaseLetters.union(CharacterSet.whitespacesAndNewlines)
return self.trimmingCharacters(in: charactersToTrim)
}
func trimmingParentheses() -> String {
let charactersToTrim = CharacterSet(charactersIn: "()")
return self.trimmingCharacters(in: charactersToTrim)
}
func replacingGeometriesSeparator(with delimiter: String) -> String {
return self.replacingOccurrences(of: "\\)(\\s*,\\s*)\\(",
with: delimiter,
options: .regularExpression,
range: self.range(of: self))
}
func replacingCoordinatesSeparator(with delimiter: String) -> String {
return self.replacingOccurrences(of: "(\\s*,\\s*)",
with: delimiter,
options: .regularExpression,
range: self.range(of: self))
}
func coordinates(separatedBy delimiter: String) -> String {
let trimmedParanetesis = self.trimmingParentheses()
return trimmedParanetesis.replacingCoordinatesSeparator(with: delimiter)
}
func geometryComponents(separatedBy delimiter: String) -> [String] {
let trimmed = self.trimmingGeometryName()
let rawComponentsString = trimmed.replacingGeometriesSeparator(with: delimiter)
let rawComponents = rawComponentsString.components(separatedBy: delimiter)
var components = [String]()
for raw in rawComponents {
if !raw.isEmpty {
components.append(raw.coordinates(separatedBy: delimiter))
}
}
return components
}
}
| mit | 3375c42d84178dff62fc4e1b7bd1a90c | 36.362069 | 90 | 0.597139 | 5.570694 | false | false | false | false |
pascaljette/GearKit | Example/GearKit/Samples/SamplesHomeViewController.swift | 1 | 5397 | // The MIT License (MIT)
//
// Copyright (c) 2015 pascaljette
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import GearKit
/// Root table view controller for the application.
class SamplesHomeViewController: GKTableViewControllerBase {
//
// MARK: Nested types
//
/// Identifiers for table cells in this table view.
enum TableCellIdentifiers: String {
case BASIC_CELL = "SamplesHomeBasicCell"
}
//
// MARK: Initialisation
//
/// Empty initializer, picks the nib automatically.
init() {
super.init(nibName: "SamplesHomeViewController", bundle: nil)
navigationItem.title = "Home"
}
/// Required initialiser with a coder.
/// We generate a fatal error to underline the fact that we do not want to support storyboards.
///
/// - parameter coder: Coder used to serialize the object.
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported (no storyboard support)")
}
}
extension SamplesHomeViewController {
//
// MARK: UIViewController overrides
//
/// View did load.
override func viewDidLoad() {
super.viewDidLoad()
registerNibName(TableCellIdentifiers.BASIC_CELL.rawValue, fromBundle: NSBundle.mainBundle())
tableSections = [customTableCellSection, graphSection, manualLoginSection, keyboardSection]
}
}
extension SamplesHomeViewController {
//
// MARK: Computed Properties
//
/// Table section for table
var customTableCellSection: GKTableSectionTitle {
get {
// Graph section
let customTableCell: GKTableCellBasic = GKTableCellBasic(identifier: TableCellIdentifiers.BASIC_CELL.rawValue
, title: "GKTable"
, subTitle: "CustomCell"
, cellTouchedFunction: { [weak self] _ in
self?.showViewController(GKTableCustomCellViewController(), sender: self)
}
, deselectOnSelected: true)
return GKTableSectionTitle(cells: [customTableCell], headerTitle: "GKTable")
}
}
// Table section for graph
var graphSection: GKTableSectionTitle {
get {
// Graph section
let radarGraphCell: GKTableCellBasic = GKTableCellBasic(identifier: TableCellIdentifiers.BASIC_CELL.rawValue
, title: "GKGraphs"
, subTitle: "GKRadarGraph"
, cellTouchedFunction: { [weak self] _ in
self?.showViewController(GKRadarGraphViewController(model: GKRadarGraphModel()), sender: self)
}
, deselectOnSelected: true)
return GKTableSectionTitle(cells: [radarGraphCell], headerTitle: "GKGraph")
}
}
// Table section for login
var manualLoginSection: GKTableSectionTitle {
get {
// Manual login section
let manualLoginCell: GKTableCellBasic = GKTableCellBasic(identifier: TableCellIdentifiers.BASIC_CELL.rawValue
, title: "GKManualLogin"
, subTitle: "GKManualLoginViewController"
, cellTouchedFunction: { [weak self] _ in
self?.showViewController(GKManualLoginViewController(), sender: self)
}
, deselectOnSelected: true)
return GKTableSectionTitle(cells: [manualLoginCell], headerTitle: "GKLogin")
}
}
// Table section for keyboard and auto-scrolling
var keyboardSection: GKTableSectionTitle {
get {
// Manual login section
let manualLoginCell: GKTableCellBasic = GKTableCellBasic(identifier: TableCellIdentifiers.BASIC_CELL.rawValue
, title: "Keyboard"
, subTitle: "ScrollView"
, cellTouchedFunction: { [weak self] _ in
self?.showViewController(GKKeyboardScrollViewController(), sender: self)
}
, deselectOnSelected: true)
return GKTableSectionTitle(cells: [manualLoginCell], headerTitle: "Keyboard")
}
}
}
| mit | ac869d70db02140aa19a4bfd3177bd1b | 34.27451 | 121 | 0.625718 | 5.255112 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Post/PostSettingsViewController+FeaturedImageUpload.swift | 1 | 6268 | import Foundation
import Photos
import WordPressFlux
extension PostSettingsViewController {
@objc func setFeaturedImage(asset: PHAsset) {
guard let media = MediaCoordinator.shared.addMedia(from: asset, to: self.apost) else {
return
}
apost.featuredImage = media
setupObservingOf(media: media)
}
@objc func setFeaturedImage(media: Media) {
apost.featuredImage = media
if !media.hasRemote {
MediaCoordinator.shared.retryMedia(media)
setupObservingOf(media: media)
}
if let mediaIdentifier = apost.featuredImage?.mediaID {
featuredImageDelegate?.gutenbergDidRequestFeaturedImageId(mediaIdentifier)
}
}
@objc func removeMediaObserver() {
if let receipt = mediaObserverReceipt {
MediaCoordinator.shared.removeObserver(withUUID: receipt)
mediaObserverReceipt = nil
}
}
@objc func setupObservingOf(media: Media) {
removeMediaObserver()
isUploadingMedia = true
mediaObserverReceipt = MediaCoordinator.shared.addObserver({ [weak self](media, state) in
self?.mediaObserver(media: media, state: state)
})
let progress = MediaCoordinator.shared.progress(for: media)
if let url = media.absoluteThumbnailLocalURL, let data = try? Data(contentsOf: url) {
progress?.setUserInfoObject(UIImage(data: data), forKey: .WPProgressImageThumbnailKey)
}
featuredImageProgress = progress
}
func mediaObserver(media: Media, state: MediaCoordinator.MediaState) {
switch state {
case .processing:
featuredImageProgress?.localizedDescription = NSLocalizedString("Preparing...", comment: "Label to show while converting and/or resizing media to send to server")
case .thumbnailReady:
if let url = media.absoluteThumbnailLocalURL, let data = try? Data(contentsOf: url) {
featuredImageProgress?.setUserInfoObject(UIImage(data: data), forKey: .WPProgressImageThumbnailKey)
}
case .uploading(let progress):
featuredImageProgress = progress
featuredImageProgress?.kind = .file
featuredImageProgress?.setUserInfoObject(Progress.FileOperationKind.copying, forKey: ProgressUserInfoKey.fileOperationKindKey)
featuredImageProgress?.localizedDescription = NSLocalizedString("Uploading...", comment: "Label to show while uploading media to server")
progressCell?.setProgress(progress)
tableView.reloadData()
case .ended:
isUploadingMedia = false
tableView.reloadData()
case .failed(let error):
DDLogError("Couldn't upload the featured image: \(error.localizedDescription)")
isUploadingMedia = false
tableView.reloadData()
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
apost.featuredImage = nil
apost.removeMediaObject(media)
break
}
let errorTitle = NSLocalizedString("Couldn't upload the featured image", comment: "The title for an alert that says to the user that the featured image he selected couldn't be uploaded.")
let notice = Notice(title: errorTitle, message: error.localizedDescription)
ActionDispatcher.dispatch(NoticeAction.clearWithTag(MediaProgressCoordinatorNoticeViewModel.uploadErrorNoticeTag))
// The Media coordinator shows its own notice about a failed upload. We have a better, more explanatory message for users here
// so we want to supress the one coming from the coordinator and show ours.
ActionDispatcher.dispatch(NoticeAction.post(notice))
case .progress:
break
}
}
@objc func showFeaturedImageRemoveOrRetryAction(atIndexPath indexPath: IndexPath) {
guard let media = apost.featuredImage else {
return
}
let alertController = UIAlertController(title: FeaturedImageActionSheet.title, message: nil, preferredStyle: .actionSheet)
alertController.addActionWithTitle(FeaturedImageActionSheet.dismissActionTitle,
style: .cancel,
handler: nil)
alertController.addActionWithTitle(FeaturedImageActionSheet.retryUploadActionTitle,
style: .default,
handler: { (action) in
self.setFeaturedImage(media: media)
})
alertController.addActionWithTitle(FeaturedImageActionSheet.removeActionTitle,
style: .destructive,
handler: { (action) in
self.apost.featuredImage = nil
self.apost.removeMediaObject(media)
})
if let error = media.error {
alertController.message = error.localizedDescription
}
if let anchorView = self.tableView.cellForRow(at: indexPath) ?? self.view {
alertController.popoverPresentationController?.sourceView = anchorView
alertController.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: anchorView.bounds.midX, y: anchorView.bounds.midY), size: CGSize(width: 1, height: 1))
alertController.popoverPresentationController?.permittedArrowDirections = .any
}
present(alertController, animated: true)
}
struct FeaturedImageActionSheet {
static let title = NSLocalizedString("Featured Image Options", comment: "Title for action sheet with featured media options.")
static let dismissActionTitle = NSLocalizedString("Dismiss", comment: "User action to dismiss featured media options.")
static let retryUploadActionTitle = NSLocalizedString("Retry", comment: "User action to retry featured media upload.")
static let removeActionTitle = NSLocalizedString("Remove", comment: "User action to remove featured media.")
}
}
| gpl-2.0 | 7c2898d5ee67a393812b3c270e25a24e | 48.354331 | 199 | 0.644384 | 5.651939 | false | false | false | false |
XiaHaozheJose/WB | WB/WB/Classes/Discover/JS_DiscoverViewController.swift | 1 | 3155 | //
// JS_DiscoverViewController.swift
// WB
//
// Created by 浩哲 夏 on 2017/1/3.
// Copyright © 2017年 浩哲 夏. All rights reserved.
//
import UIKit
class JS_DiscoverViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "发现"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
| apache-2.0 | 365e9842c90f4bcd5dbe59816c8921d1 | 31.666667 | 136 | 0.666135 | 5.209302 | false | false | false | false |
dnevera/IMProcessing | IMPlatforms/IMProcessingOSX/IMProcessingOSX/IMPScrollView.swift | 1 | 3757 | //
// IMPScrollView.swift
//
// Created by denis svinarchuk on 16.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import Cocoa
import IMProcessing
class IMPScrollView:NSScrollView {
private var cv:IMPClipView!
private func configure(){
cv = IMPClipView(frame: self.bounds)
self.contentView = cv
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.configure()
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.configure()
}
override func magnifyToFitRect(rect: NSRect) {
super.magnifyToFitRect(rect)
self.cv.moveToCenter(true)
}
}
class IMPClipView:NSClipView {
private var viewPoint = NSPoint()
override func constrainBoundsRect(proposedBounds: NSRect) -> NSRect {
if let documentView = self.documentView{
let documentFrame:NSRect = documentView.frame
var clipFrame = self.bounds
let x = documentFrame.size.width - clipFrame.size.width
let y = documentFrame.size.height - clipFrame.size.height
clipFrame.origin = proposedBounds.origin
if clipFrame.size.width>documentFrame.size.width{
clipFrame.origin.x = CGFloat(roundf(Float(x) / 2.0))
}
else{
let m = Float(max(0, min(clipFrame.origin.x, x)))
clipFrame.origin.x = CGFloat(roundf(m))
}
if clipFrame.size.height>documentFrame.size.height{
clipFrame.origin.y = CGFloat(roundf(Float(y) / 2.0))
}
else{
let m = Float(max(0, min(clipFrame.origin.y, y)))
clipFrame.origin.y = CGFloat(roundf(m))
}
viewPoint.x = NSMidX(clipFrame) / documentFrame.size.width;
viewPoint.y = NSMidY(clipFrame) / documentFrame.size.height;
return clipFrame
}
else{
return super.constrainBoundsRect(proposedBounds)
}
}
func moveToCenter(always:Bool = false){
if let documentView = self.documentView{
let documentFrame:NSRect = documentView.frame
var clipFrame = self.bounds
if documentFrame.size.width < clipFrame.size.width || always {
clipFrame.origin.x = CGFloat(roundf(Float(documentFrame.size.width - clipFrame.size.width) / 2.0));
} else {
clipFrame.origin.x = CGFloat(roundf(Float(viewPoint.x * documentFrame.size.width - (clipFrame.size.width) / 2.0)));
}
if documentFrame.size.height < clipFrame.size.height || always {
clipFrame.origin.y = CGFloat(roundf(Float(documentFrame.size.height - clipFrame.size.height) / 2.0));
} else {
clipFrame.origin.y = CGFloat(roundf(Float(viewPoint.x * documentFrame.size.height - (clipFrame.size.height) / 2.0)));
}
let scrollView = self.superview
self.scrollToPoint(self.constrainBoundsRect(clipFrame).origin)
scrollView?.reflectScrolledClipView(self)
}
}
override func viewBoundsChanged(notification: NSNotification) {
super.viewBoundsChanged(notification)
}
override func viewFrameChanged(notification: NSNotification) {
super.viewBoundsChanged(notification)
self.moveToCenter()
}
override var documentView:AnyObject?{
didSet{
self.moveToCenter()
}
}
}
| mit | 08c2c718f1060b6ee7da29151bbf4f35 | 31.102564 | 133 | 0.572417 | 4.487455 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/SizableCell/SizableBaseRoomCell.swift | 1 | 7622 | /*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MatrixSDK
@objc protocol SizableBaseRoomCellType: BaseRoomCellProtocol {
static func sizingViewHeightHashValue(from bubbleCellData: MXKRoomBubbleCellData) -> Int
}
/// `SizableBaseRoomCell` allows a cell using Auto Layout that inherits from this class to automatically return the height of the cell and cache the result.
@objcMembers
class SizableBaseRoomCell: BaseRoomCell, SizableBaseRoomCellType {
// MARK: - Constants
private static let sizingViewHeightStore = SizingViewHeightStore()
private static var sizingViews: [String: SizableBaseRoomCell] = [:]
private static let sizingReactionsView = RoomReactionsView()
private static let reactionsViewSizer = RoomReactionsViewSizer()
private static let reactionsViewModelBuilder = RoomReactionsViewModelBuilder()
private static let urlPreviewViewSizer = URLPreviewViewSizer()
private class var sizingView: SizableBaseRoomCell {
let sizingView: SizableBaseRoomCell
let reuseIdentifier: String = self.defaultReuseIdentifier()
if let cachedSizingView = self.sizingViews[reuseIdentifier] {
sizingView = cachedSizingView
} else {
sizingView = self.createSizingView()
self.sizingViews[reuseIdentifier] = sizingView
}
return sizingView
}
// MARK: - Overrides
override class func height(for cellData: MXKCellData!, withMaximumWidth maxWidth: CGFloat) -> CGFloat {
guard let cellData = cellData else {
return 0
}
guard let roomBubbleCellData = cellData as? MXKRoomBubbleCellData else {
return 0
}
return self.height(for: roomBubbleCellData, fitting: maxWidth)
}
// MARK - SizableBaseRoomCellType
// Each sublcass should override this method, to indicate a unique identifier for a view height.
// This means that the value should change if there is some data that modify the cell height.
class func sizingViewHeightHashValue(from bubbleCellData: MXKRoomBubbleCellData) -> Int {
// TODO: Improve default hash value computation:
// - Implement RoomBubbleCellData hash
// - Handle reactions
return bubbleCellData.hashValue
}
// MARK: - Private
class func createSizingView() -> SizableBaseRoomCell {
return self.init(style: .default, reuseIdentifier: self.defaultReuseIdentifier())
}
private class func height(for roomBubbleCellData: MXKRoomBubbleCellData, fitting width: CGFloat) -> CGFloat {
// FIXME: Size cache is disabled for the moment waiting for a better default `sizingViewHeightHashValue` implementation.
// let height: CGFloat
//
// let sizingViewHeight = self.findOrCreateSizingViewHeight(from: roomBubbleCellData)
//
// if let cachedHeight = sizingViewHeight.heights[width] {
// height = cachedHeight
// } else {
// height = self.contentViewHeight(for: roomBubbleCellData, fitting: width)
// sizingViewHeight.heights[width] = height
// }
//
// return height
return self.contentViewHeight(for: roomBubbleCellData, fitting: width)
}
private static func findOrCreateSizingViewHeight(from bubbleData: MXKRoomBubbleCellData) -> SizingViewHeight {
let bubbleDataHashValue = self.sizingViewHeightHashValue(from: bubbleData)
return self.sizingViewHeightStore.findOrCreateSizingViewHeight(from: bubbleDataHashValue)
}
private static func contentViewHeight(for cellData: MXKCellData, fitting width: CGFloat) -> CGFloat {
let sizingView = self.sizingView
sizingView.didEndDisplay()
sizingView.render(cellData)
sizingView.setNeedsLayout()
sizingView.layoutIfNeeded()
let fittingSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)
var height = sizingView.systemLayoutSizeFitting(fittingSize).height
// Add read receipt height if needed
if let roomBubbleCellData = cellData as? RoomBubbleCellData, let readReceipts = roomBubbleCellData.readReceipts, readReceipts.count > 0, sizingView is RoomCellReadReceiptsDisplayable {
height+=PlainRoomCellLayoutConstants.readReceiptsViewHeight
}
// Add reactions view height if needed
if sizingView is RoomCellReactionsDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData,
let reactionsViewModel = self.reactionsViewModelBuilder.buildForFirstVisibleComponent(of: roomBubbleCellData) {
let reactionWidth = sizingView.roomCellContentView?.reactionsContentView.frame.width ?? roomBubbleCellData.maxTextViewWidth
let reactionsHeight = self.reactionsViewSizer.height(for: reactionsViewModel, fittingWidth: reactionWidth)
height+=reactionsHeight
}
// Add thread summary view height if needed
if sizingView is RoomCellThreadSummaryDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData,
roomBubbleCellData.hasThreadRoot {
let bottomMargin = sizingView.roomCellContentView?.threadSummaryContentViewBottomConstraint.constant ?? 0
height += PlainRoomCellLayoutConstants.threadSummaryViewHeight
height += bottomMargin
}
// Add URL preview view height if needed
if sizingView is RoomCellURLPreviewDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData, let firstBubbleComponent =
roomBubbleCellData.getFirstBubbleComponentWithDisplay(), firstBubbleComponent.showURLPreview, let urlPreviewData = firstBubbleComponent.urlPreviewData as? URLPreviewData {
let urlPreviewMaxWidth = sizingView.roomCellContentView?.urlPreviewContentView.frame.width ?? roomBubbleCellData.maxTextViewWidth
let urlPreviewHeight = self.urlPreviewViewSizer.height(for: urlPreviewData, fittingWidth: urlPreviewMaxWidth)
height+=urlPreviewHeight
}
// Add read marker view height if needed
// Note: We cannot check if readMarkerView property is set here. Extra non needed height can be added
if sizingView is RoomCellReadMarkerDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData, let firstBubbleComponent =
roomBubbleCellData.getFirstBubbleComponentWithDisplay(),
let eventId = firstBubbleComponent.event.eventId, let room = roomBubbleCellData.mxSession.room(withRoomId: roomBubbleCellData.roomId), let readMarkerEventId = room.accountData.readMarkerEventId, eventId == readMarkerEventId {
height+=PlainRoomCellLayoutConstants.readMarkerViewHeight
}
return height
}
}
| apache-2.0 | 49a10e1315685c83754b966d2f164dad | 43.573099 | 236 | 0.701916 | 5.263812 | false | false | false | false |
pksprojects/ElasticSwift | Sources/ElasticSwiftQueryDSL/Queries/Sort.swift | 1 | 3594 | //
// Sort.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 6/4/17.
//
//
import ElasticSwiftCore
import Foundation
public enum SortBuilders {
public static func scoreSort() -> ScoreSortBuilder {
return ScoreSortBuilder()
}
public static func fieldSort(_ field: String) -> FieldSortBuilder {
return FieldSortBuilder(field)
}
}
public class ScoreSortBuilder: SortBuilder {
private static let _SCORE = "_score"
var sortOrder: SortOrder?
var field = ScoreSortBuilder._SCORE
init() {}
public func set(order: SortOrder) -> ScoreSortBuilder {
sortOrder = order
return self
}
public func build() -> Sort {
return Sort(withBuilder: self)
}
}
public class FieldSortBuilder: SortBuilder {
var field: String?
var sortOrder: SortOrder?
var mode: SortMode?
public init(_ field: String) {
self.field = field
}
public func set(order: SortOrder) -> FieldSortBuilder {
sortOrder = order
return self
}
public func set(mode: SortMode) -> FieldSortBuilder {
self.mode = mode
return self
}
public func build() -> Sort {
return Sort(withBuilder: self)
}
}
protocol SortBuilder {
func build() -> Sort
}
public struct Sort {
public let field: String
public let sortOrder: SortOrder
public let mode: SortMode?
init(withBuilder builder: ScoreSortBuilder) {
field = builder.field
sortOrder = builder.sortOrder ?? .desc
mode = nil
}
init(withBuilder builder: FieldSortBuilder) {
field = builder.field!
mode = builder.mode
sortOrder = builder.sortOrder ?? .desc
}
}
extension Sort: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
guard container.allKeys.count == 1 else {
throw Swift.DecodingError.typeMismatch(Sort.self, .init(codingPath: container.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(container.allKeys.count)."))
}
field = container.allKeys.first!.stringValue
if let fieldContainer = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) {
sortOrder = try fieldContainer.decode(SortOrder.self, forKey: .order)
mode = try fieldContainer.decodeIfPresent(SortMode.self, forKey: .mode)
} else {
sortOrder = try container.decode(SortOrder.self, forKey: .key(named: field))
mode = nil
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicCodingKeys.self)
guard mode != nil else {
try container.encode(sortOrder, forKey: .key(named: field))
return
}
var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field))
try nested.encode(sortOrder, forKey: .order)
try nested.encode(mode, forKey: .mode)
}
enum CodingKeys: String, CodingKey {
case order
case mode
}
}
extension Sort: Equatable {
public static func == (lhs: Sort, rhs: Sort) -> Bool {
return lhs.field == rhs.field
&& lhs.sortOrder == rhs.sortOrder
&& lhs.mode == rhs.mode
}
}
public enum SortOrder: String, Codable {
case asc
case desc
}
public enum SortMode: String, Codable {
case max
case min
case avg
case sum
case median
}
| mit | f179378d8a02fbbd0a7cabdd8463e041 | 24.309859 | 208 | 0.63133 | 4.319712 | false | false | false | false |
veeman961/Flicks | Flicks/AppDelegate.swift | 1 | 5635 | //
// AppDelegate.swift
// Flicks
//
// Created by Kevin Rajan on 1/10/16.
// Copyright © 2016 veeman961. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//var checked: [[Bool]]!
var checkedKey:String = "CHECKED_CATEGORIES"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().statusBarStyle = .LightContent
let defaults = NSUserDefaults.standardUserDefaults()
let checked = defaults.objectForKey(checkedKey)
if checked == nil {
myVariables.checked = [[true, false, false, true], [true, false, false, true]]
}
else {
myVariables.checked = checked as! [[Bool]]
}
myVariables.categories = [["Now Playing Movies","Popular Movies","Top Rated Movies", "Upcoming Movies"],["On the Air TV Shows", "TV Shows Airing Today", "Top Rated TV Shows", "Popular TV Shows"]]
myVariables.endPoints = [["movie/now_playing", "movie/popular", "movie/top_rated", "movie/upcoming"], ["tv/on_the_air", "tv/airing_today", "tv/top_rated", "tv/popular"]]
myVariables.backgroundColor = UIColor.darkGrayColor()
//print("app started")
//print(myVariables.checked)
defaults.setObject(myVariables.checked, forKey: checkedKey)
/*
//window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("FlicksNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "popular")
nowPlayingNavigationController.navigationBar.barStyle = .BlackTranslucent
let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("FlicksNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "topRated")
topRatedNavigationController.navigationBar.barStyle = .BlackTranslucent
//window?.rootViewController = tabBarController
/*
let tabBarController = storyboard.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
tabBarController.tabBar.barStyle = .Black
tabBarController.tabBar.tintColor = UIColor.orangeColor()
*/
//let containerViewController = storyboard.instantiateViewControllerWithIdentifier("ContainerViewController") as! ContainerViewController
//let mainContainerView = containerViewController.mainContainerView
//window?.makeKeyAndVisible()
*/
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//NSNotificationCenter.defaultCenter().postNotificationName("appDidEnterBackground", object: nil)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(myVariables.checked, forKey: checkedKey)
defaults.synchronize()
//print("app closing")
//print(myVariables.checked)
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 644b869d679fc46138b0ddf8f83f8f81 | 49.303571 | 285 | 0.715655 | 5.832298 | false | false | false | false |
xipengyang/SwiftApp1 | we sale assistant/we sale assistant/UIColor.swift | 1 | 1621 | //
// UIColor.swift
// we sale assistant
//
// Created by xipeng yang on 17/05/15.
// Copyright (c) 2015 xipeng yang. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat((hex & 0xFF)) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
public struct MKColor {
public static let Red = UIColor(hex: 0xF44336)
public static let Pink = UIColor(hex: 0xE91E63)
public static let Purple = UIColor(hex: 0x9C27B0)
public static let DeepPurple = UIColor(hex: 0x67AB7)
public static let Indigo = UIColor(hex: 0x3F51B5)
public static let Blue = UIColor(hex: 0x2196F3)
public static let LightBlue = UIColor(hex: 0x03A9F4)
public static let Cyan = UIColor(hex: 0x00BCD4)
public static let Teal = UIColor(hex: 0x009688)
public static let Green = UIColor(hex: 0x4CAF50)
public static let LightGreen = UIColor(hex: 0x8BC34A)
public static let Lime = UIColor(hex: 0xCDDC39)
public static let Yellow = UIColor(hex: 0xFFEB3B)
public static let Amber = UIColor(hex: 0xFFC107)
public static let Orange = UIColor(hex: 0xFF9800)
public static let DeepOrange = UIColor(hex: 0xFF5722)
public static let Brown = UIColor(hex: 0x795548)
public static let Grey = UIColor(hex: 0x9E9E9E)
public static let BlueGrey = UIColor(hex: 0x607D8B)
}
}
| mit | 683a2876b957af3251a357d129080e50 | 37.595238 | 63 | 0.642196 | 3.377083 | false | false | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/JSON/JSONFeedAuthor.swift | 2 | 3003 | //
// JSONFeedAuthor.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// (optional, object) specifies the feed author. The author object has several
/// members. These are all optional - but if you provide an author object, then at
/// least one is required:
public struct JSONFeedAuthor {
/// (optional, string) is the author's name.
public var name: String?
/// (optional, string) is the URL of a site owned by the author. It could be a
/// blog, micro-blog, Twitter account, and so on. Ideally the linked-to page
/// provides a way to contact the author, but that's not required. The URL
/// could be a mailto: link, though we suspect that will be rare.
public var url: String?
/// (optional, string) is the URL for an image for the author. As with icon,
/// it should be square and relatively large - such as 512 x 512 - and should
/// use transparency where appropriate, since it may be rendered on a non-white
/// background.
public var avatar: String?
}
// MARK: - Equatable
extension JSONFeedAuthor: Equatable {}
// MARK: - Codable
extension JSONFeedAuthor: Codable {
enum CodingKeys: String, CodingKey {
case name
case url
case avatar
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(url, forKey: .url)
try container.encode(avatar, forKey: .avatar)
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
url = try values.decodeIfPresent(String.self, forKey: .url)
avatar = try values.decodeIfPresent(String.self, forKey: .avatar)
}
}
| mit | 6be4a662d5ffe4560b53e7ac1b21d47f | 38 | 84 | 0.694972 | 4.265625 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Browser/ViewControllers/HistoryViewController.swift | 1 | 3953 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
import StatefulViewController
protocol HistoryViewControllerDelegate: class {
func didSelect(history: History, in controller: HistoryViewController)
}
final class HistoryViewController: UIViewController {
let store: HistoryStore
let tableView = UITableView(frame: .zero, style: .plain)
lazy var viewModel: HistoriesViewModel = {
return HistoriesViewModel(store: store)
}()
weak var delegate: HistoryViewControllerDelegate?
init(store: HistoryStore) {
self.store = store
super.init(nibName: nil, bundle: nil)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .singleLine
tableView.rowHeight = 60
tableView.register(R.nib.bookmarkViewCell(), forCellReuseIdentifier: R.nib.bookmarkViewCell.name)
view.addSubview(tableView)
emptyView = EmptyView(title: NSLocalizedString("history.noHistory.label.title", value: "No history yet!", comment: ""))
NSLayoutConstraint.activate([
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupInitialViewState()
fetch()
}
func fetch() {
tableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension HistoryViewController: StatefulViewController {
func hasContent() -> Bool {
return viewModel.hasContent
}
}
extension HistoryViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows
}
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: R.nib.bookmarkViewCell.name, for: indexPath) as! BookmarkViewCell
cell.viewModel = HistoryViewModel(history: viewModel.item(for: indexPath))
return cell
}
}
extension HistoryViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let history = viewModel.item(for: indexPath)
delegate?.didSelect(history: history, in: self)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let history = viewModel.item(for: indexPath)
confirm(
title: NSLocalizedString("Are you sure you would like to delete?", value: "Are you sure you would like to delete?", comment: ""),
okTitle: R.string.localizable.delete(),
okStyle: .destructive
) { [weak self] result in
switch result {
case .success:
self?.store.delete(histories: [history])
self?.tableView.reloadData()
case .failure: break
}
}
}
}
}
| gpl-3.0 | d745832b82b8f20ce19b0e8833bc71b8 | 33.675439 | 145 | 0.663294 | 5.370924 | false | false | false | false |
Palleas/Synchronizable | SynchronizableTests/DiffReducerSpec.swift | 1 | 5595 | //
// DiffReducerSpec.swift
// DiffReducerSpec
//
// Created by Romain Pouclet on 2016-09-04.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Quick
import Nimble
@testable import Synchronizable
class DiffReducerSpec: QuickSpec {
override func spec() {
describe("The Diff Reducer") {
let synchronizables: [GithubRepository] = (0..<10)
.map { ("repository\($0)", $0 < 5 ? "updated" : "not-updated" ) }
.map(GithubRepository.init)
let persistables: [Repository] = (3..<12)
.map { ("repository\($0)", "not-updated") }
.map(Repository.init)
context("When the persistence store is empty") {
describe("the resulting diff array") {
let result = Diff<GithubRepository>.reducer([], remote: synchronizables)
it("should contain as much elements as the synchronizable input") {
expect(result.count).to(equal(synchronizables.count))
}
it("should contain only Insert diff") {
let freqs = frequencies(result) { $0.key }
expect(freqs.count).to(equal(1))
expect(freqs["Insert"]).to(equal(synchronizables.count))
}
it("should return Insert diffs that match the Synchronizables") {
let wrappedSynchronizables: [Identifiable] = result
.map {
guard case .insert(let synchronizable) = $0 else { return nil }
return synchronizable
}
.flatMap { $0 }
let matches = compare(wrappedSynchronizables, synchronizables.map { $0 as Identifiable })
expect(matches).to(beTrue())
}
}
}
context("When the persistence store contains Persistables") {
describe("the resulting diff array") {
let result = Diff<GithubRepository>.reducer(persistables, remote: synchronizables)
let freqs = frequencies(result) { $0.key }
let identifiers = Set(persistables.map { $0.identifier } + synchronizables.map { $0.identifier })
it("should contain as much elements as there are identifers") {
expect(result.count).to(equal(identifiers.count))
}
it("should return 3 Insert") {
expect(freqs["Insert"]).to(equal(3))
}
it("should return Insert diffs that match the new Synchronizables") {
let inserted = synchronizables[0..<3]
let filtered = result.filter { $0.isInsert }
let match: Bool = filtered.reduce(true) { acc, diff in
guard case .insert(let lhs) = diff else { return false }
let rhs = inserted.filter { $0.identifier == lhs.identifier }.first!
return acc && rhs.head == lhs.head
}
expect(match).to(beTrue())
expect(inserted.count).to(equal(filtered.count))
}
it("should return 2 Update") {
expect(freqs["Update"]).to(equal(2))
}
it("should return Update diffs that match the updated Synchronizables") {
let updated = synchronizables[3...4]
let filtered = result.filter { $0.isUpdate }
let match: Bool = filtered.reduce(true) { acc, diff in
guard case .update(let lhs) = diff else { return false }
let rhs = updated.filter { $0.identifier == lhs.identifier }.first!
return acc && rhs.head == lhs.head
}
expect(match).to(beTrue())
expect(updated.count).to(equal(filtered.count))
}
it("should return 5 None") {
expect(freqs["None"]).to(equal(5))
}
it("should return 2 Delete") {
expect(freqs["Delete"]).to(equal(2))
}
it("should return Delete diffs that wrap the identifiers of the deleted Persistables") {
let deleted = persistables[7...8].map { $0.identifier }
let filtered = result.filter { $0.isDelete }
let match: [String] = filtered.reduce([]) { acc, diff in
guard case .delete(let id) = diff else { return acc }
return acc + deleted.filter { $0 == id }
}
expect(match.sorted()).to(equal(deleted.sorted()))
}
}
}
}
}
}
extension Diff {
var isInsert: Bool {
guard case .insert(_) = self else { return false }
return true
}
var isUpdate: Bool {
guard case .update(_) = self else { return false }
return true
}
var isDelete: Bool {
guard case .delete(_) = self else { return false }
return true
}
}
| mit | 3b72c86baed5214f3b46647a7c519665 | 38.118881 | 117 | 0.471398 | 5.237828 | false | false | false | false |
slevin/swiftfiddle | slisp/slisp/Engine.swift | 1 | 1959 | //
// Engine.swift
// slisp
//
// Created by Sean Levin on 5/4/15.
// Copyright (c) 2015 Sean Levin. All rights reserved.
//
import Foundation
public enum Atom : Equatable, Printable {
case StringAtom(String)
case IntAtom(Int)
public var description : String {
switch self {
case .StringAtom(let s): return "StringAtom: \(s)"
case .IntAtom(let i): return "IntAtom: \(i)"
}
}
}
public func ==(a: Atom, b: Atom) -> Bool {
switch (a, b) {
case (.IntAtom(let a), .IntAtom(let b)) where a == b: return true
default: return false
}
}
public func runIt(code: String) -> Int {
return 3
}
public func readFun(code: String) -> [String] {
var res:[String] = [String]()
var current = ""
for c in code {
if (c == "(") {
res = [String]()
} else if (c == " ") {
res.append(current)
current = ""
} else if (c == ")") {
res.append(current)
break;
} else {
current.append(c)
}
}
return res
}
public func eval(sexp: [Atom]) -> Atom {
let f:Atom = first(sexp)!
let r = dropFirst(sexp)
switch (f) {
case .StringAtom(let s) :
switch (s) {
case "+" :
return reduce(r, Atom.IntAtom(0), { (a: Atom, b: Atom) -> Atom in
switch (a, b) {
case (.IntAtom(let a), .IntAtom(let b)) : return .IntAtom(a + b)
default: return Atom.IntAtom(0)
}
})
case "-" :
return reduce(dropFirst(r), first(r)!, { (a: Atom, b: Atom) -> Atom in
switch (a, b) {
case (.IntAtom(let a), .IntAtom(let b)) : return .IntAtom(a - b)
default: return Atom.IntAtom(0)
}
})
default :
return Atom.IntAtom(0)
}
default:
return Atom.IntAtom(0)
}
} | unlicense | 917dc8828d9ebe4dd635635cf1e315bd | 23.197531 | 82 | 0.480347 | 3.548913 | false | false | false | false |
kimsand/Jupiter80Librarian | Jupiter80Librarian/Model/SVDTone.swift | 1 | 3622 | //
// SVDTone.swift
// Jupiter80Librarian
//
// Created by Kim André Sand on 09/12/14.
// Copyright (c) 2014 Kim André Sand. All rights reserved.
//
import Cocoa
enum SVDOscType {
case unknown
case saw
case square
case pulse
case triangle
case sine
case noise
case superSaw
case pcm
}
class SVDTone: SVDType {
private let toneNameLength = 0x0C
private var partial1OscTypeBytes = SVDBytes(location: 0x1E, length: 0x1)
private var partial2OscTypeBytes = SVDBytes(location: 0x4C, length: 0x1)
private var partial3OscTypeBytes = SVDBytes(location: 0x7A, length: 0x1)
private var partial1PCMBytes = SVDBytes(location: 0x45, length: 0x2)
private var partial2PCMBytes = SVDBytes(location: 0x73, length: 0x2)
private var partial3PCMBytes = SVDBytes(location: 0xA1, length: 0x2)
var registrations: [SVDRegistration] = []
var liveSets: [SVDLiveSet] = []
var partialOscTypes: [SVDOscType] = []
var partialNames: [String] = []
@objc let toneName: String
@objc var partial1Name: String!
@objc var partial2Name: String!
@objc var partial3Name: String!
init(svdFile: SVDFile, toneBytes: SVDBytes, orderNr: Int) {
let toneNameBytes = SVDBytes(location: toneBytes.location, length: toneNameLength)
toneName = svdFile.stringFromShiftedBytes(toneNameBytes)
super.init(svdFile: svdFile, orderNr: orderNr)
partial1OscTypeBytes.location += toneBytes.location
partial2OscTypeBytes.location += toneBytes.location
partial3OscTypeBytes.location += toneBytes.location
partial1PCMBytes.location += toneBytes.location
partial2PCMBytes.location += toneBytes.location
partial3PCMBytes.location += toneBytes.location
findPartialsFromBytes(partial1OscTypeBytes, pcmBytes: partial1PCMBytes)
findPartialsFromBytes(partial2OscTypeBytes, pcmBytes: partial2PCMBytes)
findPartialsFromBytes(partial3OscTypeBytes, pcmBytes: partial3PCMBytes)
partial1Name = partialNames[0]
partial2Name = partialNames[1]
partial3Name = partialNames[2]
}
func addDependencyToRegistration(_ svdRegistration: SVDRegistration) {
// Ignore Registrations that are not initialized
if svdRegistration.regName != "INIT REGIST" {
registrations.append(svdRegistration)
}
}
func addDependencyToLiveSet(_ svdLiveSet: SVDLiveSet) {
// Ignore Live Sets that are not initialized
if svdLiveSet.liveName != "INIT LIVESET" {
liveSets.append(svdLiveSet)
}
}
func findPartialsFromBytes(_ byteStruct: SVDBytes, pcmBytes: SVDBytes) {
let oscType = oscTypeFromBytes(byteStruct)
partialOscTypes.append(oscType)
var partialName: String
if oscType == .pcm {
partialName = svdFile.pcmNameFromNibbleBytes(pcmBytes)
} else {
partialName = partialNameFromOscType(oscType)
}
partialNames.append(partialName)
}
func oscTypeFromBytes(_ byteStruct: SVDBytes) -> SVDOscType {
let number = svdFile.unshiftedNumberFromBytes(byteStruct, nrOfBits: 3)
var oscType: SVDOscType
switch number {
case 0: oscType = .saw
case 1: oscType = .square
case 2: oscType = .pulse
case 3: oscType = .triangle
case 4: oscType = .sine
case 5: oscType = .noise
case 6: oscType = .superSaw
case 7: oscType = .pcm
default: oscType = .unknown
}
return oscType
}
func partialNameFromOscType(_ oscType: SVDOscType) -> String {
var name: String
switch oscType {
case .saw: name = "Saw"
case .square: name = "Square"
case .pulse: name = "Pulse"
case .triangle: name = "Triangle"
case .sine: name = "Sine"
case .noise: name = "Noise"
case .superSaw: name = "SuperSaw"
case .pcm: name = "PCM"
default: name = "Unknown"
}
return name
}
}
| mit | 4520f6b69de75acfd8d7d9b2e21929ba | 26.846154 | 90 | 0.737569 | 3.094017 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Charts/RadarChartView.swift | 2 | 7594 | //
// RadarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Implementation of the RadarChart, a "spidernet"-like chart. It works best
/// when displaying 5-10 entries per DataSet.
public class RadarChartView: PieRadarChartViewBase
{
/// width of the web lines that come from the center.
public var webLineWidth = CGFloat(1.5)
/// width of the web lines that are in between the lines coming from the center
public var innerWebLineWidth = CGFloat(0.75)
/// color for the web lines that come from the center
public var webColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// color for the web lines in between the lines that come from the center.
public var innerWebColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// transparency the grid is drawn with (0.0 - 1.0)
public var webAlpha: CGFloat = 150.0 / 255.0
/// flag indicating if the web lines should be drawn or not
public var drawWeb = true
/// the object reprsenting the y-axis labels
private var _yAxis: ChartYAxis!
/// the object representing the x-axis labels
private var _xAxis: ChartXAxis!
internal var _yAxisRenderer: ChartYAxisRendererRadarChart!
internal var _xAxisRenderer: ChartXAxisRendererRadarChart!
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
internal override func initialize()
{
super.initialize();
_yAxis = ChartYAxis(position: .Left);
_xAxis = ChartXAxis();
_xAxis.spaceBetweenLabels = 0;
renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler);
_yAxisRenderer = ChartYAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self);
_xAxisRenderer = ChartXAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self);
}
internal override func calcMinMax()
{
super.calcMinMax();
var minLeft = _data.getYMin(.Left);
var maxLeft = _data.getYMax(.Left);
_chartXMax = Double(_data.xVals.count) - 1.0;
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
var leftRange = CGFloat(abs(maxLeft - (_yAxis.isStartAtZeroEnabled ? 0.0 : minLeft)));
var topSpaceLeft = leftRange * _yAxis.spaceTop;
var bottomSpaceLeft = leftRange * _yAxis.spaceBottom;
_chartXMax = Double(_data.xVals.count) - 1.0;
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
_yAxis.axisMaximum = !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : maxLeft + Double(topSpaceLeft);
_yAxis.axisMinimum = !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : minLeft - Double(bottomSpaceLeft);
// consider starting at zero (0)
if (_yAxis.isStartAtZeroEnabled)
{
_yAxis.axisMinimum = 0.0;
}
_yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum);
}
public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
var angle = self.sliceAngle * CGFloat(entry.xIndex) + self.rotationAngle;
var val = CGFloat(entry.value) * self.factor;
var c = self.centerOffsets;
var p = CGPoint(x: c.x + val * cos(angle * ChartUtils.Math.FDEG2RAD),
y: c.y + val * sin(angle * ChartUtils.Math.FDEG2RAD));
return p;
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
_yAxis?._defaultValueFormatter = _defaultValueFormatter;
_yAxisRenderer?.computeAxis(yMin: _yAxis.axisMinimum, yMax: _yAxis.axisMaximum);
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals);
if (_legend !== nil && !_legend.isLegendCustom)
{
_legendRenderer?.computeLegend(_data);
}
calculateOffsets();
setNeedsDisplay();
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect);
if (_dataNotSet)
{
return;
}
let context = UIGraphicsGetCurrentContext();
_xAxisRenderer?.renderAxisLabels(context: context);
if (drawWeb)
{
renderer!.drawExtras(context: context);
}
_yAxisRenderer.renderLimitLines(context: context);
renderer!.drawData(context: context);
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHightlight);
}
_yAxisRenderer.renderAxisLabels(context: context);
renderer!.drawValues(context: context);
_legendRenderer.renderLegend(context: context);
drawDescription(context: context);
drawMarkers(context: context);
}
/// Returns the factor that is needed to transform values into pixels.
public var factor: CGFloat
{
var content = _viewPortHandler.contentRect;
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange);
}
/// Returns the angle that each slice in the radar chart occupies.
public var sliceAngle: CGFloat
{
return 360.0 / CGFloat(_data.xValCount);
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
var a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle);
var sliceAngle = self.sliceAngle;
for (var i = 0; i < _data.xValCount; i++)
{
if (sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 > a)
{
return i;
}
}
return 0;
}
/// Returns the object that represents all y-labels of the RadarChart.
public var yAxis: ChartYAxis
{
return _yAxis;
}
/// Returns the object that represents all x-labels that are placed around the RadarChart.
public var xAxis: ChartXAxis
{
return _xAxis;
}
internal override var requiredBottomOffset: CGFloat
{
return _legend.font.pointSize * 4.0;
}
internal override var requiredBaseOffset: CGFloat
{
return _xAxis.isEnabled ? _xAxis.labelWidth : 10.0;
}
public override var radius: CGFloat
{
var content = _viewPortHandler.contentRect;
return min(content.width / 2.0, content.height / 2.0);
}
/// Returns the maximum value this chart can display on it's y-axis.
public override var chartYMax: Double { return _yAxis.axisMaximum; }
/// Returns the minimum value this chart can display on it's y-axis.
public override var chartYMin: Double { return _yAxis.axisMinimum; }
/// Returns the range of y-values this chart can display.
public var yRange: Double { return _yAxis.axisRange}
} | apache-2.0 | 2fde642be2e90032f39b74c83ceca1ec | 30 | 117 | 0.615618 | 4.728518 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Insurance | PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/EnterPinViewController.swift | 1 | 10822 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
This protocol is implemented by view controllers that embed this view controller
*/
protocol PinEntryDelegate: class {
func didEnterPin()
func pinSyncFinished(error: Bool, errorMessage: String?)
func fakePinSyncFinished()
}
/**
This view controller is embedded into the PinViewController and SettingsViewController. This view controller handles the UI and logic of the user
entering a pin and then subscribing to that pin.
*/
class EnterPinViewController: PerchViewController {
@IBOutlet weak var pinContainerView: UIView!
@IBOutlet weak var pinTextField: UITextField!
@IBOutlet weak var syncButton: UIButton!
@IBOutlet weak var pinContainerToSyncButtonVerticalSpace: NSLayoutConstraint!
@IBOutlet weak var needAPinButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var downArrow: UIButton!
@IBOutlet weak var upArrow: UIButton!
let screenHeight: CGFloat = UIScreen.mainScreen().bounds.height
weak var delegate: PinEntryDelegate?
var syncInProgress = false
var animationActive = false
var changingPin = false
override func viewDidLoad() {
super.viewDidLoad()
self.pinTextField.setPlaceholderTextColor(UIColor.perchOrange())
/** Apply kerning (spacing between letters) to buttons */
self.applyKerningToButtonText()
/** The button for showing a url to access a pin should be initially shown. The "close" button for that section should initially be hidden since they appear to be the same button. */
self.showNeedAPin()
/** Initially hide the error label */
self.errorLabel.hidden = true
}
/** Method for applying kerning to buttons specific to this view controller */
func applyKerningToButtonText() {
let syncString = NSAttributedString(string: syncButton.titleLabel!.text!, attributes: [NSKernAttributeName:5.0])
self.syncButton.titleLabel?.attributedText = syncString
let needAPinString = NSAttributedString(string: needAPinButton.titleLabel!.text!, attributes: [NSKernAttributeName:3.0])
self.needAPinButton.titleLabel?.attributedText = needAPinString
}
/** Method for deciding which view should be shown in the pin area.
Either the pin text field or the url for connecting with sensors. */
func revealPinOrLink() {
let animateSlidingViewTime = 0.25
if self.pinTextFieldVisible() {
self.showClose()
/** Don't want to allow clicking sync if user can't even see pin text field */
self.syncButton.enabled = false
/** Push the pin container view down below the sync button */
self.pinContainerToSyncButtonVerticalSpace.constant = -self.pinContainerView.height
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(animateSlidingViewTime, animations: { () -> Void in
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
})
} else {
self.showNeedAPin()
self.syncButton.enabled = true
/** Animate the pin container back up above sync button */
self.pinContainerToSyncButtonVerticalSpace.constant = 0
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(animateSlidingViewTime, animations: { () -> Void in
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
})
}
}
/** Helper method for showing an error message */
func shakeAndShowError(msg: String?) {
self.pinContainerView.shakeView()
self.errorLabel.text = msg
self.errorLabel.hidden = false
}
// MARK: Helper Methods
/** Helper method for showing the "Need A Pin?" button instead of the "Close" button.
These buttons appear to be the same button, but they actually are separate buttons
that are shown/hidden. Making them the same button while also including an image in the
button was not as straightforward as you'd think, so went for this solution. */
func showNeedAPin() {
self.downArrow.hidden = false
self.upArrow.hidden = true
}
/** Helper method for showing the "Close" button instead of the "Need A Pin?" button.
These buttons appear to be the same button, but they actually are separate buttons
that are shown/hidden. Making them the same button while also including an image in the
button was not as straightforward as you'd think, so went for this solution. */
func showClose() {
self.downArrow.hidden = true
self.upArrow.hidden = false
}
/** Helper method for determining if the pin text field is currently visible. Assumes the pin container view is normally show directly on top of sync button. */
func pinTextFieldVisible() -> Bool {
return self.pinContainerToSyncButtonVerticalSpace.constant == 0
}
/** Helper method for determining which direction the keyboard is animating */
func keyboardAnimatingDown(keyboardFrameEnd: CGRect) -> Bool {
return screenHeight == keyboardFrameEnd.origin.y
}
/** Helper method for enabling/disabling all buttons */
func buttonsEnabled(enabled: Bool) {
self.syncButton.enabled = enabled
self.needAPinButton.enabled = enabled
self.upArrow.enabled = enabled
self.downArrow.enabled = enabled
}
// MARK: IBActions
/** Attempt to sync with pin entered in text field */
@IBAction func syncButtonTapped(sender: AnyObject) {
/** If there was a previous error, go ahead and hide it when trying a new pin */
self.errorLabel.hidden = true
/** Prevent networking call with an invalid pin length or non-numeric pin */
if self.pinTextField.text!.length != PinViewController.requiredPinLength || Int(self.pinTextField.text!) == nil {
shakeAndShowError(NSLocalizedString("The pin must be \(PinViewController.requiredPinLength) digits", comment: ""))
return
}
// Prevent call if we are already subscribed to this pin
if self.pinTextField.text == CurrentUser.sharedInstance.userPin && self.pinTextField.text != "0000"{
shakeAndShowError(NSLocalizedString("You are already subscribed to that pin", comment: ""))
return
}
syncInProgress = true
pinTextField.resignFirstResponder()
/** Only actually try to subscribe to bluemix push if not on simulator because won't work otherwise */
if UIDevice.currentDevice().model != "iPhone Simulator" && pinTextField.text != "0000" {
self.delegate?.didEnterPin()
// If we are not changing the pin, then subscribe to the pin as normal
if !changingPin {
PushServiceManager.sharedInstance.subscribe(self.pinTextField.text!) { (error, errorMsg) -> Void in
var currentErrorMessage: String?
if error {
currentErrorMessage = errorMsg!
dispatch_async(dispatch_get_main_queue()) { self.delegate?.pinSyncFinished(true, errorMessage: currentErrorMessage) }
self.shakeAndShowError(currentErrorMessage)
} else {
dispatch_async(dispatch_get_main_queue()) { self.delegate?.pinSyncFinished(false, errorMessage: nil) }
}
}
} else {
// If we are changing the pin, we first want to try subscribing to the new pin before unsubscribing to all other pins
PushServiceManager.sharedInstance.subscribeWithoutUnsubscribing(self.pinTextField.text!) { (error, errorMsg) -> Void in
var currentErrorMessage: String?
if error {
currentErrorMessage = errorMsg!
dispatch_async(dispatch_get_main_queue()) { self.delegate?.pinSyncFinished(true, errorMessage: currentErrorMessage) }
self.shakeAndShowError(currentErrorMessage)
} else {
dispatch_async(dispatch_get_main_queue()) { self.delegate?.pinSyncFinished(false, errorMessage: nil) }
}
}
}
} else {
/** We are on simulator so just show loading and set appropriate variables to auto transition to next screen after showing loading */
self.fakePinSync()
}
}
/** Since the up/down arrows couldn't be easily added to the same button as the text, just have them as separate buttons that implement the same action */
@IBAction func arrowTapped(sender: AnyObject) {
self.revealPinOrLink()
}
/** Since the up/down arrows couldn't be easily added to the same button as the text, just have them as separate buttons that implement the same action */
@IBAction func needAPinTapped(sender: AnyObject) {
self.revealPinOrLink()
}
/**
Fakes a pin sync. Used when on the simulator
*/
func fakePinSync() {
CurrentUser.sharedInstance.userPin = self.pinTextField.text!
self.delegate?.fakePinSyncFinished()
}
}
// MARK: UITextFieldDelegate
extension EnterPinViewController: UITextFieldDelegate {
/** Limit the number of characters in the text field to requiredPinLength */
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = textField.text!.characters.count + string.characters.count - range.length
return newLength <= PinViewController.requiredPinLength
}
/** Don't allow keyboard to become activated during a loading animation or if text field hidden.
Text field can become hidden if user clicks the "Need A Pin? button to reveal the simulator url */
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if animationActive || !pinTextFieldVisible() {
return false
}
return true
}
}
| epl-1.0 | 06cd8384361069ebb83bfd35f38601af | 43.167347 | 190 | 0.649293 | 5.209918 | false | false | false | false |
Fidetro/SwiftFFDB | Sources/Columns.swift | 1 | 1257 | //
// Columns.swift
// Swift-FFDB
//
// Created by Fidetro on 2018/5/30.
// Copyright © 2018年 Fidetro. All rights reserved.
//
import Foundation
public struct Columns:STMT {
let stmt: String
}
// MARK: - internal
extension Columns {
init(_ stmt : String,format:String?=nil) {
self.stmt = stmt +
(format ?? "") +
" "
}
init(_ stmt : String,columns:[String]) {
func columnsToString(_ columns:[String]) -> String {
var columnsString = String()
columnsString.append("(")
for (index,element) in columns.enumerated() {
if index == 0 {
columnsString.append(element)
}else{
columnsString.append(","+element)
}
}
columnsString.append(")")
return columnsString
}
self.init(stmt, format: columnsToString(columns))
}
}
// MARK : - Values
extension Columns {
public func values(_ count:Int) -> Values {
return Values(stmt, count: count)
}
public func values(_ values:String) -> Values {
return Values(stmt, format: values)
}
}
| apache-2.0 | 984aecc5e63458b9d7dedf4465e01a11 | 22.660377 | 63 | 0.507974 | 4.369338 | false | false | false | false |
spacedrabbit/stanfordHappiness | Happiness/FaceView.swift | 1 | 3589 | //
// FaceView.swift
// Happiness
//
// Created by Louis Tur on 9/10/15.
// Copyright (c) 2015 Louis Tur. All rights reserved.
//
import UIKit
@IBDesignable // holy shit
class FaceView: UIView
{
// because changing the line width requires redrawing, we can add a property observer to this default
// value in order to call setNeedsDisplay() whenever the value changes
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
var color : UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } }
var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } }
var faceCenter: CGPoint {
return convertPoint(center, fromView: superview)
}
var faceRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10.0
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3.0
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1.0
static let FaceRadiusToMouthHeightRatio: CGFloat = 3.0
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3.0
}
private enum Eye { case Left, Right }
private func bezierPathForEye(whichEye: Eye) -> UIBezierPath {
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticalOffset
switch whichEye{
case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right: eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
path.lineWidth = lineWidth
return path
}
private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath {
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset)
let end = CGPoint(x: start.x + mouthWidth, y: start.y)
let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y)
let path = UIBezierPath()
path.moveToPoint(start)
path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
override func drawRect(rect: CGRect)
{
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: true)
facePath.lineWidth = 3
color.set()
facePath.stroke()
bezierPathForEye(.Left).stroke()
bezierPathForEye(.Right).stroke()
let smiliness = 0.75
let smilePath = bezierPathForSmile(smiliness)
smilePath.stroke()
contentMode = .Redraw // this ensures that when the phone is rotated, the circle doesnt stretch
}
}
| mit | e056eec285575ecaad4b0327e1dc3102 | 37.591398 | 139 | 0.657008 | 4.836927 | false | false | false | false |
jindulys/GithubPilot | Sources/GithubRequest.swift | 2 | 12314 | //
// Request.swift
// GitPocket
//
// Created by yansong li on 2016-02-16.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
import Alamofire
open class GithubNetWorkClient {
var manager: Alamofire.SessionManager
var baseHosts: [String: String]
func additionalHeaders(_ needoauth: Bool) -> [String: String] {
return [:]
}
init(manager: Alamofire.SessionManager, baseHosts: [String: String]) {
self.manager = manager
self.baseHosts = baseHosts
}
}
func utf8Decode(_ data: Data) -> String {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
}
open class Box<T> {
open let value: T
init(_ value: T) {
self.value = value
}
}
internal struct GPHttpResponseHandler {
static var PageHandler: (HTTPURLResponse?) -> String? {
return generateSingleSearchHandler(searchText: "page=")
}
static var SinceHandler: (HTTPURLResponse?) -> String? {
return generateSingleSearchHandler(searchText: "since=")
}
static func generateSingleSearchHandler(searchText: String) -> (HTTPURLResponse?) -> String? {
return { (response: HTTPURLResponse?) in
if let nonNilResponse = response,
let link = (nonNilResponse.allHeaderFields["Link"] as? String),
let sinceRange = link.range(of: searchText) {
var retVal = ""
var checkIndex = sinceRange.upperBound
while checkIndex != link.endIndex {
let character = link.characters[checkIndex]
let characterInt = character.zeroCharacterBasedunicodeScalarCodePoint()
if characterInt>=0 && characterInt<=9 {
retVal += String(character)
} else {
break
}
checkIndex = link.index(after: checkIndex)
}
return retVal
}
return nil
}
}
}
/// A Custom ParameterEncoding Structure encoding JSON Params.
internal struct JSONPostEncoding: ParameterEncoding {
let postJSONParams: JSON
init(json: JSON) {
self.postJSONParams = json
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard var urlRequest = urlRequest.urlRequest else {
throw GithubRequestError.InvalidRequest
}
urlRequest.httpBody = dumpJSON(postJSONParams)
return urlRequest
}
}
internal struct DataPostEncoding: ParameterEncoding {
let postData: Data
init(data: Data) {
self.postData = data
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard var urlRequest = urlRequest.urlRequest else {
throw GithubRequestError.InvalidRequest
}
let length = postData.count
urlRequest.setValue("\(length)", forHTTPHeaderField: "Content-Length")
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = postData
return urlRequest
}
}
public enum RequestError<EType> : CustomStringConvertible {
case badRequest(Int, Box<EType>)
case internalServerError(Int, String?)
case rateLimitError
case httpError(Int?, String?)
public var description: String {
switch self {
case let .badRequest(code, box):
var ret = ""
ret += "Bad Request - Code: \(code)"
ret += " : \(box.value)"
return ret
case let .internalServerError(code, message):
var ret = ""
ret += "Internal Server Error: \(code)"
if let m = message {
ret += " : \(m)"
}
return ret
case .rateLimitError:
return "Rate limited"
case let .httpError(code, message):
var ret = "HTTP Error"
if let c = code {
ret += " code: \(c)"
}
if let m = message {
ret += " : \(m)"
}
return ret
}
}
}
public enum GithubRequestError: Error {
case InvalidRequest
}
/// Represents a request object
///
/// Pass in a closure to the `response` method to handle a response or error.
open class GithubRequest<RType: JSONSerializer, EType: JSONSerializer> {
let responseSerializer: RType
let errorSerializer: EType
let request: Alamofire.DataRequest
init(request: Alamofire.DataRequest, responseSerializer: RType, errorSerializer: EType) {
self.request = request
self.responseSerializer = responseSerializer
self.errorSerializer = errorSerializer
}
func handleResponseError(_ response: HTTPURLResponse?,
data: Data?,
error: Error?) -> RequestError<EType.ValueType> {
if let code = response?.statusCode {
switch code {
case 500...599:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .internalServerError(code, message)
case 429:
return .rateLimitError
case 400, 403, 404, 422:
if let d = data {
let messageJSON = parseJSON(d)
switch messageJSON {
case .dictionary(let dic):
let message = self.errorSerializer.deserialize(dic["message"]!)
return .badRequest(code, Box(message))
default:
fatalError("Failed to parse error type")
}
}
fatalError("Failed to parse error type")
default:
return .httpError(code, "HTTP Error")
}
} else {
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .httpError(nil, message)
}
}
}
/// A Request Object could directly use `API url`, provided by Github
open class DirectAPIRequest<RType: JSONSerializer, EType: JSONSerializer>: GithubRequest<RType, EType> {
/**
Initialize a DirectAPIRequest Object
- parameter apiURL: An API URL provided by some Github JSON response.
*/
init(client: GithubNetWorkClient,
apiURL: String,
method: Alamofire.HTTPMethod,
params: [String: String] = ["" : ""],
responseSerializer: RType,
errorSerializer: EType) {
var headers = ["Content-Type": "application/json"]
for (header, val) in client.additionalHeaders(true) {
headers[header] = val
}
let request = client.manager.request(apiURL, method:method, parameters: params, headers: headers)
super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer)
request.resume()
}
/**
Response function for DirectAPIRequest.
- parameter complitionHandler: complitionHandler.
- returns: self.
*/
@discardableResult
open func response(_ complitionHandler:@escaping (RType.ValueType?, RequestError<EType.ValueType>?) -> Void) -> Self {
self.request.validate().response { response in
let d = response.data!
if let error = response.error, let response = response.response {
complitionHandler(nil, self.handleResponseError(response, data: d, error: error))
} else {
complitionHandler(self.responseSerializer.deserialize(parseJSON(d)), nil)
}
}
return self
}
}
/// An "rpc-style" request
open class RpcRequest<RType: JSONSerializer, EType: JSONSerializer>: GithubRequest<RType, EType> {
/**
Initialize a RpcRequest Object
- parameter client: Client to get URL Host.
- parameter host: host key to get from client.
- parameter route: url path.
- parameter method: HTTP Method.
- parameter params: url parameters.
- parameter postParams: HTTP Body parameters used for POST Request.
- parameter postData: HTTP Body parameters used with NSData format.
- parameter responseSerializer: responseSerializer used to generate response object.
- parameter errorSerializer: errorSerializer.
- returns: an initialized RpcRequest.
*/
init(client: GithubNetWorkClient,
host: String,
route: String,
method: Alamofire.HTTPMethod,
params: [String: String] = ["" : ""],
postParams: JSON? = nil,
postData: Data? = nil,
encoding: ParameterEncoding = URLEncoding.default,
responseSerializer: RType,
errorSerializer: EType) {
let url = "\(client.baseHosts[host]!)\(route)"
var headers = ["Content-Type": "application/json"]
let needOauth = (host == "api")
for (header, val) in client.additionalHeaders(needOauth) {
headers[header] = val
}
var request: Alamofire.DataRequest
switch method {
case .get:
request = client.manager.request(url,
method: .get,
parameters: params,
encoding: encoding,
headers: headers)
case .post:
if let pParams = postParams {
request = client.manager.request(url,
method: .post,
parameters: ["" : ""],
encoding: JSONPostEncoding(json: pParams),
headers: headers)
} else if let pData = postData {
request = client.manager.request(url,
method: .post,
parameters: ["" : ""],
encoding: DataPostEncoding(data: pData),
headers: headers)
} else {
request = client.manager.request(url,
method: .post,
parameters: ["" : ""],
headers: headers)
}
default:
fatalError("Wrong RpcRequest Method Type, should only be \"GET\" \"POST\"")
}
super.init(request: request, responseSerializer: responseSerializer, errorSerializer: errorSerializer)
request.resume()
}
/**
Response function for RpcRequest.
- parameter complitionHandler: complitionHandler.
- returns: self.
*/
@discardableResult
open func response(_ complitionHandler: @escaping (RType.ValueType?, RequestError<EType.ValueType>?) -> Void) -> Self {
self.request.validate().response { response in
let d = response.data!
if let error = response.error, let response = response.response {
complitionHandler(nil, self.handleResponseError(response, data: d, error:error))
} else {
complitionHandler(self.responseSerializer.deserialize(parseJSON(d)), nil)
}
}
return self
}
}
/// An "rpc-style" request, which has a `httpResponseHandler` that could do some custom operation with HTTPResponse Header.
open class RpcCustomResponseRequest<RType: JSONSerializer, EType: JSONSerializer, T>: RpcRequest<RType, EType> {
var httpResponseHandler: ((HTTPURLResponse?)->T?)?
// DefaultResponseQueue, set this if you want your response return to queue other than main queue.
var defaultResponseQueue: DispatchQueue?
/**
Designated Initializer
- parameter customResponseHandler: custom handler to deal with HTTPURLResponse, usually you want to use this to extract info from Response's allHeaderFields.
- parameter defaultResponseQueue : The queue you want response block to be executed on.
*/
init(client: GithubNetWorkClient,
host: String,
route: String,
method: Alamofire.HTTPMethod,
params: [String: String] = ["": ""],
postParams: JSON? = nil,
postData: Data? = nil,
encoding: ParameterEncoding = URLEncoding.default,
customResponseHandler: ((HTTPURLResponse?)->T?)? = nil,
defaultResponseQueue: DispatchQueue? = nil,
responseSerializer: RType,
errorSerializer: EType) {
httpResponseHandler = customResponseHandler
self.defaultResponseQueue = defaultResponseQueue
super.init(client: client,
host: host,
route: route,
method: method,
params: params,
postParams: postParams,
postData: postData,
encoding: encoding,
responseSerializer: responseSerializer,
errorSerializer: errorSerializer)
}
/**
Response function for RpcCustomResponseRequest.
- parameter complitionHandler: complitionHandler.
- returns: self.
*/
@discardableResult
open func response(_ complitionHandler:@escaping (T?, RType.ValueType?, RequestError<EType.ValueType>?) -> Void) -> Self {
self.request.validate().response(queue: defaultResponseQueue) { response in
let d = response.data!
let responseResult = self.httpResponseHandler?(response.response)
if let error = response.error, let response = response.response {
complitionHandler(responseResult, nil, self.handleResponseError(response, data: d, error:error))
} else {
complitionHandler(responseResult, self.responseSerializer.deserialize(parseJSON(d)), nil)
}
}
return self
}
}
| mit | b0c8948d52386f174c3bfbf95aba0dd3 | 30.491049 | 158 | 0.663445 | 4.173898 | false | false | false | false |
ceskasporitelna/CSATMLocator | CSATMLocator WatchKit 1 Extension/InterfaceController.swift | 1 | 2945 | //
// InterfaceController.swift
// CSATMLocator WatchKit 1 Extension
//
// Created by Filip Kirschner on 19/09/15.
// Copyright © 2015 Vratislav Kalenda. All rights reserved.
//
import WatchKit
import Foundation
import MapKit
import WatchConnectivity
class InterfaceController: WKInterfaceController, WCSessionDelegate {
@IBOutlet var label: WKInterfaceLabel!
@IBOutlet var map: WKInterfaceMap!
@IBOutlet var nameLabel: WKInterfaceLabel!
@IBOutlet var addressLabel: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
func initWatchCommunication()
{
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
self.requestData()
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject])
{
if message["error"] == nil{
if let name = message["name"] as? String,
address = message["address"] as? String,
alat = message["alat"] as? Double,
alon = message["alon"] as? Double,
ulat = message["ulat"] as? Double,
ulon = message["ulon"] as? Double {
self.nameLabel.setText(name)
self.addressLabel.setText(address)
let latDelta = ulat - alat
let lonDelta = ulon - alon
self.map.removeAllAnnotations()
//Add user annotation
self.map.addAnnotation(CLLocationCoordinate2D(latitude: ulat, longitude: ulon), withImage: UIImage(named: "marker"), centerOffset: CGPoint(x: 0, y: -12))
//Add ATM annotation
self.map.addAnnotation(CLLocationCoordinate2D(latitude: alat, longitude: alon), withImage: UIImage(named: "markerATM"), centerOffset: CGPoint(x: 0, y: -12))
//Set reasonable region bounds
self.map.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: ulat - latDelta*(latDelta < 0 ? 2/3 : 1/3), longitude: ulon - lonDelta/2), span: MKCoordinateSpanMake(abs(latDelta*1.6), abs(lonDelta*1.6))))
}else{
self.nameLabel.setText("Data corrupted")
}
}else{
self.nameLabel.setText(message["error"] as? String)
}
}
override func willActivate()
{
initWatchCommunication()
self.requestData()
super.willActivate()
}
func sendDataToPhone(data: [String : AnyObject])
{
if WCSession.defaultSession().reachable {
WCSession.defaultSession().sendMessage(data, replyHandler: nil, errorHandler: nil)
}
}
func requestData()
{
sendDataToPhone([
"command": "data request"])
}
override func didDeactivate()
{
super.didDeactivate()
}
}
| mit | 4d45d59d09b64971f40a9f55af92a9c1 | 32.454545 | 232 | 0.613791 | 4.63622 | false | false | false | false |
lee0741/Glider | Glider Widget/TodayViewController.swift | 1 | 2637 | //
// TodayViewController.swift
// Glider Widget
//
// Created by Yancen Li on 3/3/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import UIKit
import NotificationCenter
@objc(TodayViewController)
class TodayViewController: UITableViewController, NCWidgetProviding {
let cellId = "widgetCell"
var stories = [Story]()
override func viewDidLoad() {
super.viewDidLoad()
self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
tableView.rowHeight = 55
Story.getStories() { stories in
self.stories = stories
self.tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
let story = stories[indexPath.row]
cell.textLabel?.text = story.title
cell.detailTextLabel?.text = story.domain
cell.textLabel?.font = UIFont(name: "AvenirNext-Medium", size: 17)
cell.detailTextLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
cell.detailTextLabel?.textColor = .gray
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let itemId = stories[indexPath.row].id
self.extensionContext?.open(URL(string: "glider://\(itemId)")!)
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
Story.getStories() { stories in
self.stories = stories
self.tableView.reloadData()
completionHandler(NCUpdateResult.newData)
}
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .compact {
self.preferredContentSize = maxSize
} else {
self.preferredContentSize = CGSize(width: 0, height: 550)
}
}
}
| mit | cf0910e35aad7bc1d40b95b2ca41d478 | 33.684211 | 118 | 0.656677 | 5.098646 | false | false | false | false |
ZackKingS/Tasks | task/Classes/Others/Lib/TakePhoto/PhotoPreviewBottomBarView.swift | 2 | 3822 |
//
// PhotoPreviewBottomBarView.swift
// PhotoPicker
//
// Created by liangqi on 16/3/9.
// Copyright © 2016年 dailyios. All rights reserved.
//
import UIKit
protocol PhotoPreviewBottomBarViewDelegate:class{
func onDoneButtonClicked()
}
class PhotoPreviewBottomBarView: UIView {
var doneNumberAnimationLayer: UIView?
var labelTextView: UILabel?
var buttonDone: UIButton?
var doneNumberContainer: UIView?
weak var delegate: PhotoPreviewBottomBarViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.configView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configView()
}
private func configView(){
self.backgroundColor = PhotoPickerConfig.PreviewBarBackgroundColor
// button
self.buttonDone = UIButton(type: .custom)
let toolbarHeight = bounds.height
let buttonWidth: CGFloat = 40
let buttonHeight: CGFloat = 40
let padding:CGFloat = 5
let width = self.bounds.width
buttonDone!.frame = CGRect(x: width - buttonWidth - padding, y: (toolbarHeight - buttonHeight) / 2, width: buttonWidth, height: buttonHeight)
buttonDone!.setTitle(PhotoPickerConfig.ButtonDone, for: .normal)
buttonDone!.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
buttonDone!.setTitleColor(PhotoPickerConfig.GreenTinColor, for: .normal)
buttonDone!.addTarget(self, action: #selector(PhotoPreviewBottomBarView.eventDoneClicked), for: .touchUpInside)
buttonDone!.isEnabled = true
buttonDone!.setTitleColor(UIColor.black, for: .disabled)
self.addSubview(self.buttonDone!)
// done number
let labelWidth:CGFloat = 20
let labelX = buttonDone!.frame.minX - labelWidth
let labelY = (toolbarHeight - labelWidth) / 2
self.doneNumberContainer = UIView(frame: CGRect(x:labelX, y:labelY, width: labelWidth, height:labelWidth))
let labelRect = CGRect(x:0, y:0, width: labelWidth, height: labelWidth)
self.doneNumberAnimationLayer = UIView.init(frame: labelRect)
self.doneNumberAnimationLayer!.backgroundColor = PhotoPickerConfig.GreenTinColor
self.doneNumberAnimationLayer!.layer.cornerRadius = labelWidth / 2
doneNumberContainer!.addSubview(self.doneNumberAnimationLayer!)
self.labelTextView = UILabel(frame: labelRect)
self.labelTextView!.textAlignment = .center
self.labelTextView!.backgroundColor = UIColor.clear
self.labelTextView!.textColor = UIColor.white
doneNumberContainer!.addSubview(self.labelTextView!)
self.addSubview(self.doneNumberContainer!)
}
// MARK: - Event delegate
func eventDoneClicked(){
if let delegate = self.delegate{
delegate.onDoneButtonClicked()
}
}
func changeNumber(number:Int,animation:Bool){
self.labelTextView?.text = String(number)
if number > 0 {
self.buttonDone?.isEnabled = true
self.doneNumberContainer?.isHidden = false
if animation {
self.doneNumberAnimationLayer!.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
self.doneNumberAnimationLayer!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
}
} else {
self.buttonDone?.isEnabled = false
self.doneNumberContainer?.isHidden = true
}
}
}
| apache-2.0 | faea651fe6dde34ee9c34464bdcb2081 | 36.441176 | 188 | 0.654622 | 4.744099 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.