repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kezuino/SMPT31
|
refs/heads/master
|
NOtification/NOKit/JSONManager.swift
|
mit
|
1
|
//
// JSONManager.swift
// NOtification
//
// Created by Bas on 29/05/2015.
// Copyright (c) 2015 Bas. All rights reserved.
//
import Foundation
import SwiftyJSON
import SwiftSerializer
import SocketRocket
public class JSONManager: NSObject {
/// The Singleton instance of this class.
public static let sharedInstance = JSONManager()
let request = NSURLRequest(URL: NSURL(string: "ws://192.168.27.20:8821")!)
let webSocket: SRWebSocket!
var openSocket = false
private override init() {
self.webSocket = SRWebSocket(URLRequest: request)
super.init()
self.webSocket.delegate = self
self.webSocket.open()
}
/**
Creates a User instance from JSON.
:param: json The JSON to parse.
:returns: The User instance if valid, else nil.
*/
public func userFromJSON(json: JSON) -> User? {
if let name = json["name"].string, phoneNumber = json["phoneNumber"].string {
return User(name: name, phoneNumber: phoneNumber)
}
println("Something went wrong in \(__FUNCTION__) with JSON: \(json)")
return nil
}
/**
Creates a Message instance from JSON.
:param: json The JSON to parse.
:returns: The Message instance if valid, else nil.
*/
public func messageFromJSON(json: JSON) -> Message? {
if let _from = json["from"].dictionary, _to = json["to"].dictionary, message = json["message"].string, timestamp = json["timestamp"].double {
if let from = self.userFromDictionary(_from), let to = self.userFromDictionary(_to) {
return Message(from: from, to: to, message: message, timestamp: timestamp)
}
}
println("Something went wrong in \(__FUNCTION__) with JSON: \(json)")
return nil
}
/**
Creates a Location instance from JSON.
:param: json The JSON to parse.
:returns: The Location instance if valid, else nil.
*/
public func locationFromJSON(json: JSON) -> Location? {
if let name = json["name"].string, ssid = json["ssid"].string, _vips = json["vips"].array {
var vips = [VIP]()
for vip in _vips {
if let vipName = vip.string {
vips.append(VIP(name: vipName))
}
}
return Location(name: name, ssid: ssid, vips: vips)
}
println("Something went wrong in \(__FUNCTION__) with JSON: \(json)")
return nil
}
/**
Creates JSON from a User instance.
:param: location The User instance to convert to JSON.
:returns: The JSON if valid, else nil.
*/
public func JSONFromUser(user: User) -> JSON? {
return JSON(data: user.toJson())
}
/**
Creates JSON from a Message instance.
:param: location The Message instance to convert to JSON.
:returns: The JSON if valid, else nil.
*/
public func JSONFromMessage(message: Message) -> JSON? {
return JSON(data: message.toJson())
}
/**
Creates JSON from a Location instance.
:param: location The Location instance to convert to JSON.
:returns: The JSON if valid, else nil.
*/
public func JSONFromLocation(location: Location) -> JSON? {
return JSON(data: location.toJson())
}
}
extension JSONManager {
/**
Creates a User instance from a dictionary.
:param: dictionary The dictionary to parse.
:returns: The User instance if valid, else nil.
*/
private func userFromDictionary(dictionary: [String: JSON]) -> User? {
if let name = dictionary["name"]!.string, phoneNumber = dictionary["phoneNumber"]!.string {
return User(name: name, phoneNumber: phoneNumber)
}
return nil
}
}
// MARK: - SRWebSocketDelegate
extension JSONManager: SRWebSocketDelegate {
public func webSocketDidOpen(webSocket: SRWebSocket!) {
println("\(__FUNCTION__), webSocket: \(webSocket)")
self.openSocket = true
let thing = "{message: {From: {Name: \"Bas\", PhoneNumber: \"+31681789369\"}, Type: 0}}"
webSocket.send("\(thing)")
}
public func webSocket(webSocket: SRWebSocket!, didReceiveMessage message: AnyObject!) {
println("\(__FUNCTION__), message: \(message)")
let messages = Testsetup().messages()
let message1 = messages[0]
webSocket.send("{message: {From: {Name: \"Bas\", PhoneNumber: \"+31681789369\"}, To: {Name: \"Joost\", PhoneNumber: \"+31652849963\"}, Type: 3}}")
}
public func webSocket(webSocket: SRWebSocket!, didFailWithError error: NSError!) {
println("\(__FUNCTION__), error: \(error.localizedDescription)")
}
public func webSocket(webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
println("\(__FUNCTION__), closeCode: \(code), reason: \(reason), wasClean: \(wasClean)")
}
}
|
32e350ae08fc57f1dc4b262ab7d7e47a
| 24.553672 | 148 | 0.669394 | false | false | false | false |
Nexmind/Swiftizy
|
refs/heads/master
|
Swiftizy/Classes/Manager/Counting.swift
|
mit
|
1
|
//
// Counting.swift
// Pods
//
// Created by Julien Henrard on 2/05/16.
//
//
import Foundation
import CoreData
public class Counting {
var managedContext : NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
init(context: NSManagedObjectContext) {
self.managedContext = context
}
public func all(entity: AnyClass) -> Int {
let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: NSStringFromClass(entity).pathExtension)
request.includesSubentities = false
do {
let count: Int = try self.managedContext.count(for: request)
if(count == NSNotFound) {
return 0
}
return count
} catch {
return 0
}
}
public func custom(entity: AnyClass, predicate: NSPredicate) -> Int{
let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: NSStringFromClass(entity).pathExtension)
request.predicate = predicate
request.includesSubentities = false
do {
let count: Int = try self.managedContext.count(for: request)
if(count == NSNotFound) {
return 0
}
return count
} catch {
return 0
}
}
}
|
3955d1dfe3b5f4144eac4774842e5592
| 26.5 | 127 | 0.598545 | false | false | false | false |
hryk224/IPhotoBrowser
|
refs/heads/master
|
IPhotoBrowserExample/IPhotoBrowserExample/Sources/View/TableViewCell/WebImageTableViewCell.swift
|
mit
|
1
|
//
// WebImageTableViewCell.swift
// IPhotoBrowserExample
//
// Created by yoshida hiroyuki on 2017/02/16.
// Copyright © 2017年 hryk224. All rights reserved.
//
import UIKit.UITableViewCell
final class WebImageTableViewCell: UITableViewCell {
private static let className: String = "WebImageTableViewCell"
static var identifier: String {
return className
}
static var nib: UINib {
return UINib(nibName: className, bundle: Bundle(for: self))
}
@IBOutlet weak var webImageView: UIImageView!
@IBOutlet weak var indicatorView: UIActivityIndicatorView!
private var imageUrl: URL?
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
override func prepareForReuse() {
super.prepareForReuse()
webImageView.image = nil
}
func configure(imageUrl: URL) {
self.imageUrl = imageUrl
self.indicatorView.isHidden = false
webImageView.loadWebImage(imageUrl: imageUrl) { [weak self] image, imageUrl in
guard self?.imageUrl?.absoluteString == imageUrl.absoluteString else { return }
self?.webImageView.image = image
self?.indicatorView.isHidden = true
self?.setNeedsLayout()
self?.layoutIfNeeded()
}
}
}
|
a624d649607dfc98f780b92b3e0acf75
| 31 | 91 | 0.664634 | false | false | false | false |
daher-alfawares/model
|
refs/heads/master
|
Model/Model/Notifier.swift
|
apache-2.0
|
1
|
//
// ModelNotifier.swift
// Model
//
// Created by Brandon Chow on 5/13/16.
// Copyright © 2016 Brandon Chow, 2016 Daher Alfawares. All rights reserved.
//
import Foundation
public class Notifier {
static let sharedInstance = Notifier()
private var listenerGroups = [String : WeakRef<ListenerGroup>]()
public func notify(newModel model: Model) {
listenerGroups[model.key()]?.reference?.notify(newModel: model)
}
internal func addListener(listener: Listener, forModelType modelType: Model.Type){
let modelTypeKey = "\(modelType)"
let group = groupFor(modelTypeKey)
group.add(listener)
listener.group = group
}
private func groupFor(modelTypeKey: String) -> ListenerGroup {
if let group = listenerGroups[modelTypeKey]?.reference {
return group
} else {
let group = ListenerGroup(key: modelTypeKey)
listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group)
return group
}
}
private func addListenerToNewGroup(newListener: Listener, forModelTypeKey modelTypeKey: String){
let group = ListenerGroup(key: modelTypeKey)
newListener.group = group
listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group)
group.add(newListener)
}
internal func remove(listenerGroup : ListenerGroup) {
listenerGroups.removeValueForKey(listenerGroup.key)
}
}
|
048f4f0484abfcfd341988c02f59096c
| 29 | 100 | 0.653333 | false | false | false | false |
ryanorendorff/tablescope
|
refs/heads/develop
|
tablescope/ViewController.swift
|
gpl-3.0
|
1
|
//
// ViewController.swift
// tablescope
//
// Created by Ryan Orendorff on 6/2/15.
// Copyright (c) 2015 cellscope. All rights reserved.
//
// TODO: Make this not backwards (specify start time as the start of the
// day mode instead of the start of the night mode).
// Taken from the tutorial at
// jamesonquave.com/blog/
// taking-control-of-the-iphone-camera-in-ios-8-with-swift-part-1/
import UIKit
import AVFoundation
let day_in_sec : NSTimeInterval = 86400
let sleepTimeStart = (hour: 17, minute: 30)
let sleepTimeStop = (hour: 8, minute: 30)
class ViewController: UIViewController {
var startToday : NSDate?
var stopToday : NSDate?
let captureSession = AVCaptureSession()
var previewLayer : AVCaptureVideoPreviewLayer?
// If we find a device we'll store it here for later use
var captureDevice : AVCaptureDevice?
override func viewDidLoad() -> Void {
super.viewDidLoad()
// Do any additional setup after loading the view.
captureSession.sessionPreset = AVCaptureSessionPresetHigh
let devices = AVCaptureDevice.devices()
// Loop through all the capture devices on this phone
for device in devices {
// Make sure this particular device supports video
if (device.hasMediaType(AVMediaTypeVideo)) {
// Check the position and confirm we've got the back camera
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
captureSession.sessionPreset =
AVCaptureSessionPresetPhoto
do {
try captureSession.addInput(
AVCaptureDeviceInput(device: captureDevice))
} catch {
print("error initializing device")
}
}
}
}
}
// Disable the screen lock from occurring.
UIApplication.sharedApplication().idleTimerDisabled = true
assert(sleepTimeStart.hour > sleepTimeStop.hour ||
(sleepTimeStart.hour == sleepTimeStop.hour &&
sleepTimeStart.minute > sleepTimeStop.minute),
"Sleep start and stop are in the wrong order!")
// When starting the app, we are going to figure out if we are
// in a night session time or a day session time.
let now = NSDate()
setStartStopDate(now)
// TODO: If we switch to Swift 1.2+, use the late binding let
// instead of var.
//
// Here we will start the manipulations of the [start/stop]Today
// dates to reflect the correct days to trigger on. This case
// corresponds to being in the morning night session.
var startDate = startToday!
var stopDate = stopToday!
// Figure out if we are in a day or night session, and start the
// app in the correct configuration when first launched.
if now < startToday && now >= stopToday {
daySession()
// We are during the day so we need to move the stop date to
// trigger tomorrow for the first time (today's time has passed)
stopDate = stopToday!.dateByAddingTimeInterval(day_in_sec)
} else {
nightSession()
// We are during the later night period so we need to move both
// the start and the stop stop date to trigger tomorrow for the
// first time (today's time has passed)
if now >= startToday {
startDate = startToday!.dateByAddingTimeInterval(day_in_sec)
stopDate = stopToday!.dateByAddingTimeInterval(day_in_sec)
}
}
// Finally set the timers.
Timer.scheduledTimerWithTimeInterval(
startDate, interval: day_in_sec,
repeats: true, f: { self.nightSession() })
Timer.scheduledTimerWithTimeInterval(
stopDate, interval: day_in_sec,
repeats: true, f: { self.daySession() })
// If we press down on the screen for 2 seconds switch current
// mode
let longPressRecognizer = UILongPressGestureRecognizer(target: self,
action: "longPress:")
longPressRecognizer.minimumPressDuration = 2.0
self.view.addGestureRecognizer(longPressRecognizer)
} // end viewDidLoad
// Session modes
func daySession() -> Void {
UIScreen.mainScreen().brightness = CGFloat(1)
if !captureSession.running{
previewLayer =
AVCaptureVideoPreviewLayer(session: captureSession)
//previewLayer?.transform = CATransform3DMakeScale(-1, -1, 1)
self.view.layer.addSublayer(previewLayer!)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()
}
}
func nightSession() -> Void {
UIScreen.mainScreen().brightness = CGFloat(0)
if captureSession.running{
self.previewLayer?.removeFromSuperlayer()
captureSession.stopRunning()
}
}
func switchSession() -> Void {
if !captureSession.running{
daySession()
} else {
nightSession()
}
}
// Used by the long press to switch the session mode
func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
switchSession()
}
}
func modeWakeUpFromBackground(){
let now = NSDate()
if now < startToday && now >= stopToday {
daySession()
} else {
nightSession()
}
}
func setStartStopDate(now : NSDate) {
let calendar = NSCalendar(
calendarIdentifier: NSCalendarIdentifierGregorian)
// The components and [start/stop]Today are specified for a start
// and stop time that are both in the current day. This situation
// only occurs if we are before the stop time on the current day.
// Otherwise we will need to either add a day to the start or the
// end dates in order to trigger them correctly.
let start_components = calendar!.components([.Year, .Month, .Day],
fromDate: now)
start_components.hour = sleepTimeStart.hour
start_components.minute = sleepTimeStart.minute
self.startToday = calendar!.dateFromComponents(start_components)
let stop_components = calendar!.components([.Year, .Month, .Day],
fromDate: startToday!)
stop_components.hour = sleepTimeStop.hour
stop_components.minute = sleepTimeStop.minute
self.stopToday = calendar!.dateFromComponents(stop_components)
}
}
|
c2788f953529d502dc16f68b972be022
| 32.736585 | 76 | 0.607577 | false | false | false | false |
baiyidjp/SwiftWB
|
refs/heads/master
|
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/SwiftExtension/UIPageControl+Extensions.swift
|
mit
|
1
|
//
// UIPageControl+Extensions.swift
// SwiftWeibo
//
// Created by tztddong on 2016/11/28.
// Copyright © 2016年 dongjiangpeng. All rights reserved.
//
import Foundation
extension UIPageControl {
/// UIPageControl
///
/// - Parameters:
/// - frame: 布局
/// - numberOfPages: 总页数
/// - currentPage: 当前页数
/// - pageIndicatorTintColor: 未选中页颜色
/// - currentPageIndicatorTintColor: 当前选中页颜色
convenience init(numberOfPages: Int = 0,currentPage: Int = 0,pageIndicatorTintColor: UIColor = UIColor.black,currentPageIndicatorTintColor :UIColor = UIColor.orange) {
self.init()
self.numberOfPages = numberOfPages
self.currentPage = currentPage
self.pageIndicatorTintColor = pageIndicatorTintColor
self.currentPageIndicatorTintColor = currentPageIndicatorTintColor
}
}
|
00a93f0e3aca08f2613c5f2795683a8d
| 28.482759 | 171 | 0.681871 | false | false | false | false |
tresorit/ZeroKit-Realm-encrypted-tasks
|
refs/heads/master
|
ios/RealmTasks iOS/AccountViewController.swift
|
bsd-3-clause
|
1
|
import UIKit
import RealmSwift
import ZeroKit
class AccountViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var zeroKitIdLabel: UILabel!
@IBOutlet weak var realmIdLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.title = "Account"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.usernameLabel.text = nil
self.zeroKitIdLabel.text = nil
ZeroKitManager.shared.backend.getProfile { profile, _ in
if let profile = profile,
let profileData = profile.data(using: .utf8),
let json = (try? JSONSerialization.jsonObject(with: profileData, options: [])) as? [String: Any] {
self.usernameLabel.text = json[ProfileField.alias.rawValue] as? String
} else {
self.usernameLabel.text = nil
}
}
ZeroKitManager.shared.zeroKit.whoAmI { (userId, _) in
self.zeroKitIdLabel.text = userId
}
realmIdLabel.text = SyncUser.current?.identity
}
@IBAction func logoutButtonTapped(sender: UIButton) {
let alert = UIAlertController(title: "Log out?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Log out", style: .default, handler: { _ in
(UIApplication.shared.delegate as! AppDelegate).logOut()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
|
82f6b9f3f91f11fe5e8633086b3e0351
| 33.659574 | 114 | 0.635359 | false | false | false | false |
Eonil/EditorLegacy
|
refs/heads/trial1
|
Modules/Editor/Sources/Documents/RustProjectDocument.swift
|
mit
|
1
|
////
//// RustProjectDocument.swift
//// RustCodeEditor
////
//// Created by Hoon H. on 11/11/14.
//// Copyright (c) 2014 Eonil. All rights reserved.
////
//
//import Foundation
//import AppKit
//import PrecompilationOfExternalToolSupport
//
//class RustProjectDocument : NSDocument {
// let projectWindowController = PlainFileFolderWindowController()
// let programExecutionController = RustProgramExecutionController()
//
// override func makeWindowControllers() {
// super.makeWindowControllers()
// self.addWindowController(projectWindowController)
// }
//
// override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// let s1 = projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string!
// let d1 = s1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// return d1
// }
//
// override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// let s1 = NSString(data: data, encoding: NSUTF8StringEncoding)!
// projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string = s1
//// let p2 = self.fileURL!.path!
//// let p3 = p2.stringByDeletingLastPathComponent
//// projectWindowController.mainViewController.navigationViewController.fileTreeViewController.pathRepresentation = p3
//
// let u2 = self.fileURL!.URLByDeletingLastPathComponent
// projectWindowController.mainViewController.navigationViewController.fileTreeViewController.URLRepresentation = u2
// return true
// }
//
//
//
// override func saveDocument(sender: AnyObject?) {
// // Do not route save messages to current document.
// // Saving of a project will be done at somewhere else, and this makes annoying alerts.
// /// This prevents the alerts.
//// super.saveDocument(sender)
//
// projectWindowController.codeEditingViewController.trySavingInPlace()
// }
//
//
//
//
//
// override class func autosavesInPlace() -> Bool {
// return false
// }
//}
//
//extension RustProjectDocument {
//
// @IBAction
// func menuProjectRun(sender:AnyObject?) {
// if let u1 = self.fileURL {
// self.saveDocument(self)
// let srcFilePath1 = u1.path!
// let srcDirPath1 = srcFilePath1.stringByDeletingLastPathComponent
// let outFilePath1 = srcDirPath1.stringByAppendingPathComponent("program.executable")
// let conf1 = RustProgramExecutionController.Configuration(sourceFilePaths: [srcFilePath1], outputFilePath: outFilePath1, extraArguments: ["-Z", "verbose"])
// // let s1 = mainEditorWindowController.splitter.codeEditingViewController.textViewController.textView.string!
// let r1 = programExecutionController.execute(conf1)
// projectWindowController.commandConsoleViewController.textView.string = r1
//
// let ss1 = RustCompilerIssueParsing.process(r1, sourceFilePath: srcFilePath1)
// projectWindowController.mainViewController.navigationViewController.issueListingViewController.issues = ss1
//
// } else {
// NSAlert(error: NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "This file has not been save yet. Cannot compile now."])).runModal()
// }
// }
//
//}
//
//
//
|
d7a487c4b0b238b81c2d7979d2bd34c4
| 36.588235 | 161 | 0.746792 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/Authentication/Event Handlers/Post-Login/Backup/AuthenticationBackupReadyEventHandler.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import WireSyncEngine
/**
* Handles the notification informing the user that backups are ready to be imported.
*/
final class AuthenticationBackupReadyEventHandler: AuthenticationEventHandler {
weak var statusProvider: AuthenticationStatusProvider?
func handleEvent(currentStep: AuthenticationFlowStep, context: Bool) -> [AuthenticationCoordinatorAction]? {
let existingAccount = context
// Automatically complete the backup for @fastLogin automation
guard AutomationHelper.sharedHelper.automationEmailCredentials == nil else {
return [.showLoadingView, .configureNotifications, .completeBackupStep]
}
// Get the signed-in user credentials
let authenticationCredentials: ZMCredentials?
switch currentStep {
case .authenticateEmailCredentials(let credentials):
authenticationCredentials = credentials
case .authenticatePhoneCredentials(let credentials):
authenticationCredentials = credentials
case .companyLogin:
authenticationCredentials = nil
case .noHistory:
return [.hideLoadingView]
default:
return nil
}
// Prepare the backup step
let context: NoHistoryContext = existingAccount ? .loggedOut : .newDevice
let nextStep = AuthenticationFlowStep.noHistory(credentials: authenticationCredentials, context: context)
return [.hideLoadingView, .transition(nextStep, mode: .reset)]
}
}
|
f4cb253c9fda20c223e57e2a1bb79498
| 35.451613 | 113 | 0.720354 | false | false | false | false |
gitkong/FLTableViewComponent
|
refs/heads/master
|
FLComponentDemo/FLComponentDemo/FLCollectionViewHandler.swift
|
mit
|
2
|
//
// FLCollectionViewHandler.swift
// FLComponentDemo
//
// Created by 孔凡列 on 2017/6/19.
// Copyright © 2017年 YY Inc. All rights reserved.
//
import UIKit
@objc protocol FLCollectionViewHandlerDelegate {
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, itemAt indexPath : IndexPath)
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, headerAt section : NSInteger)
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, footerAt section : NSInteger)
}
class FLCollectionViewHandler: NSObject {
private(set) lazy var componentsDict : NSMutableDictionary = {
return NSMutableDictionary.init()
}()
var components : Array<FLCollectionBaseComponent> = [] {
didSet {
self.collectionView?.handler = self
componentsDict.removeAllObjects()
for section in 0..<components.count {
let component = components[section]
component.section = section
// same key will override the old value, so the last component will alaways remove first
componentsDict.setValue(component, forKey: component.componentIdentifier)
}
}
}
var delegate : FLCollectionViewHandlerDelegate?
var collectionView : UICollectionView? {
return components.first?.collectionView
}
}
// Mark : component control
extension FLCollectionViewHandler : FLCollectionViewHandlerProtocol {
func component(at index : NSInteger) -> FLCollectionBaseComponent? {
guard components.count > 0, index < components.count else {
return nil
}
return components[index]
}
func exchange(_ component : FLCollectionBaseComponent, by exchangeComponent : FLCollectionBaseComponent) {
self.components.exchange(component.section!, by: exchangeComponent.section!)
}
func replace(_ component : FLCollectionBaseComponent, by replacementComponent : FLCollectionBaseComponent) {
self.components.replaceSubrange(component.section!...component.section!, with: [replacementComponent])
}
func addAfterIdentifier(_ component : FLCollectionBaseComponent, after identifier : String) {
if let afterComponent = self.component(by: identifier) {
self.addAfterComponent(component, after: afterComponent)
}
}
func addAfterComponent(_ component : FLCollectionBaseComponent, after afterComponent : FLCollectionBaseComponent) {
self.addAfterSection(component, after: afterComponent.section!)
}
func addAfterSection(_ component : FLCollectionBaseComponent, after index : NSInteger) {
guard components.count > 0, index < components.count else {
return
}
self.components.insert(component, at: index)
}
func add(_ component : FLCollectionBaseComponent) {
guard components.count > 0 else {
return
}
self.components.append(component)
}
func removeComponent(by identifier : String, removeType : FLComponentRemoveType) {
guard components.count > 0 else {
return
}
if let component = self.component(by: identifier) {
self.componentsDict.removeObject(forKey: identifier)
if removeType == .All {
self.components = self.components.filter({ $0 != component })
}
else if removeType == .Last {
self.removeComponent(component)
}
}
}
func removeComponent(_ component : FLCollectionBaseComponent?) {
guard component != nil else {
return
}
self.removeComponent(at: component!.section!)
}
func removeComponent(at index : NSInteger) {
guard index < components.count else {
return
}
self.components.remove(at: index)
}
func reloadComponents() {
self.collectionView?.reloadData()
}
func reloadComponents(_ components : [FLCollectionBaseComponent]) {
guard self.components.count > 0, components.count <= self.components.count else {
return
}
for component in components {
self.reloadComponent(at: component.section!)
}
}
func reloadComponent(_ component : FLCollectionBaseComponent) {
self.reloadComponent(at: component.section!)
}
func reloadComponent(at index : NSInteger) {
guard components.count > 0, index < components.count else {
return
}
self.collectionView?.reloadSections(IndexSet.init(integer: index))
}
func component(by identifier : String) -> FLCollectionBaseComponent? {
guard componentsDict.count > 0, !identifier.isEmpty else {
return nil
}
return componentsDict.value(forKey: identifier) as? FLCollectionBaseComponent
}
}
// MARK : dataSources customizaion
extension FLCollectionViewHandler : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
final func numberOfSections(in collectionView: UICollectionView) -> Int {
return components.count
}
final func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard components.count > 0 else {
return 0
}
return components[section].numberOfItems()
}
final func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard components.count > 0 else {
return UICollectionViewCell()
}
let component : FLCollectionBaseComponent = components[indexPath.section]
component.section = indexPath.section
return component.cellForItem(at: indexPath.item)
}
}
// MARK : display method customizaion
extension FLCollectionViewHandler : UICollectionViewDelegate {
final func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(willDisplayCell: cell, at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(didEndDisplayCell: cell, at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(willDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind)
}
final func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath){
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(didEndDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind)
}
}
// MARK : header or footer customizaion
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard components.count > 0, section < components.count else {
return CGSize.zero
}
return CGSize.init(width: collectionView.bounds.size.width,
height: components[section].heightForHeader())
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard components.count > 0, section < components.count else {
return CGSize.zero
}
return CGSize.init(width: collectionView.bounds.size.width,
height: components[section].heightForFooter())
}
final func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard components.count > 0, indexPath.section < components.count else {
return UICollectionReusableView()
}
let component = components[indexPath.section]
let headerFooterView :FLCollectionHeaderFooterView = component.collectionView(viewOfKind: kind)
headerFooterView.delegate = self
headerFooterView.section = indexPath.section
// add gesture
let tapG : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.headerFooterDidClick))
headerFooterView.addGestureRecognizer(tapG)
return headerFooterView
}
func headerFooterDidClick(GesR : UIGestureRecognizer) {
let headerFooterView : FLCollectionHeaderFooterView = GesR.view as! FLCollectionHeaderFooterView
guard let identifierType = FLIdentifierType.type(of: headerFooterView.reuseIdentifier) , let section = headerFooterView.section else {
return
}
switch identifierType {
case .Header:
self.collectionHeaderView(headerFooterView, didClickSectionAt: section)
case .Footer:
self.collectionFooterView(headerFooterView, didClickSectionAt: section)
default : break
}
}
}
// MARK : layout customization
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard components.count > 0, indexPath.section < components.count else {
return CGSize.zero
}
var size : CGSize = components[indexPath.section].sizeForItem(at: indexPath.item)
if size == .zero {
if self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
size = flowLayout.itemSize
}
else {
size = (collectionViewLayout.layoutAttributesForItem(at: indexPath) != nil) ? collectionViewLayout.layoutAttributesForItem(at: indexPath)!.size : CGSize.zero
}
}
return size
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
guard components.count > 0, section < components.count else {
return UIEdgeInsets.zero
}
let inset : UIEdgeInsets = components[section].sectionInset()
// set sectionInset, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.sectionInsetArray.append(inset)
}
return inset
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
guard components.count > 0, section < components.count else {
return 0
}
let minimumLineSpacing : CGFloat = components[section].minimumLineSpacing()
// set minimumLineSpacing, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.minimumLineSpacingArray.append(minimumLineSpacing)
}
return minimumLineSpacing
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
guard components.count > 0, section < components.count else {
return 0
}
let minimumInteritemSpacing : CGFloat = components[section].minimumInteritemSpacing()
// set minimumInteritemSpacing, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.minimumInteritemSpacingArray.append(minimumInteritemSpacing)
}
return minimumInteritemSpacing
}
}
// MARK : Managing Actions for Cells
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
guard components.count > 0, indexPath.section < components.count else {
return false
}
return components[indexPath.section].shouldShowMenu(at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
guard components.count > 0, indexPath.section < components.count else {
return false
}
return components[indexPath.section].canPerform(selector: action, forItemAt: indexPath.item, withSender: sender)
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].perform(selector: action, forItemAt: indexPath.item, withSender: sender)
}
}
// MARK :Event
extension FLCollectionViewHandler : FLCollectionComponentEvent {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate?.collectionViewDidClick?(self, itemAt: indexPath)
}
func collectionHeaderView(_ headerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) {
self.delegate?.collectionViewDidClick?(self, headerAt: section)
}
func collectionFooterView(_ footerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) {
self.delegate?.collectionViewDidClick?(self, footerAt: section)
}
}
|
8c7523a9f74c46d944231621018ca338
| 40.706704 | 195 | 0.688835 | false | false | false | false |
Stitch7/Instapod
|
refs/heads/master
|
Instapod/Player/Remote/ProgressSlider/PlayerRemoteProgressSliderScrubbingSpeed.swift
|
mit
|
1
|
//
// PlayerRemoteProgressSliderScrubbingSpeed.swift
// Instapod
//
// Created by Christopher Reitz on 16.04.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
enum PlayerRemoteProgressSliderScrubbingSpeed: Float {
case high = 1.0
case half = 0.5
case slow = 0.25
case fine = 0.1
var allValues: [PlayerRemoteProgressSliderScrubbingSpeed] {
return [
.high,
.half,
.slow,
.fine,
]
}
var stringValue: String {
// TODO: i18n
switch self {
case .high: return "High-Speed Scrubbing"
case .half: return "Half-Speed Scrubbing"
case .slow: return "Quarter-Speed Scrubbing"
case .fine: return "Fine Scrubbing"
}
}
var offset: Float {
switch self {
case .high: return 0.0
case .half: return 50.0
case .slow: return 150.0
case .fine: return 225.0
}
}
var offsets: [Float] {
var offsets = [Float]()
for value in allValues {
offsets.append(value.offset)
}
return offsets
}
func lowerScrubbingSpeed(forOffset offset: CGFloat) -> PlayerRemoteProgressSliderScrubbingSpeed? {
var lowerScrubbingSpeedIndex: Int?
for (i, scrubbingSpeedOffset) in self.offsets.enumerated() {
if Float(offset) > scrubbingSpeedOffset {
lowerScrubbingSpeedIndex = i
}
}
if let newScrubbingSpeedIndex = lowerScrubbingSpeedIndex {
if self != allValues[newScrubbingSpeedIndex] {
return allValues[newScrubbingSpeedIndex]
}
}
return nil
}
}
|
53b0e484cb5dec703a170e71c5f59d4a
| 24.115942 | 102 | 0.579342 | false | false | false | false |
karstengresch/rw_studies
|
refs/heads/master
|
RWBooks/RWBooks/StatView.swift
|
unlicense
|
1
|
//
// StatView.swift
// MyStats3
//
// Created by Main Account on 5/11/15.
// Copyright (c) 2015 Razeware LLC. All rights reserved.
//
import UIKit
@IBDesignable
class StatView: UIView {
let circleBackgroundLayer = CAShapeLayer()
let circleForegroundLayer = CAShapeLayer()
let percentLabel = UILabel()
let captionLabel = UILabel()
@IBInspectable var circleBackgroundColor: UIColor = UIColor.grayColor() {
didSet {
configure()
}
}
@IBInspectable var circleForegroundColor: UIColor = UIColor.whiteColor() {
didSet {
configure()
}
}
var range = CGFloat(10)
var curValue = CGFloat(0) {
didSet {
// configure()
animateCircle()
}
}
let margin = CGFloat(10)
override func awakeFromNib() {
super.awakeFromNib()
setup()
configure()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
configure()
}
func setup() {
// Setup circle background layer
circleBackgroundLayer.lineWidth = CGFloat(20.0)
circleBackgroundLayer.fillColor = UIColor.clearColor().CGColor
circleBackgroundLayer.strokeEnd = 1
layer.addSublayer(circleBackgroundLayer)
// Setup circle foreground layer
circleForegroundLayer.lineWidth = CGFloat(20.0)
circleForegroundLayer.fillColor = UIColor.clearColor().CGColor
circleForegroundLayer.strokeEnd = 0
layer.addSublayer(circleForegroundLayer)
// Setup percent label
percentLabel.font = UIFont(name: "Avenir Next", size: 26)
percentLabel.textColor = UIColor.whiteColor()
percentLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(percentLabel)
// Setup caption label
captionLabel.font = UIFont(name: "Avenir Next", size: 26)
captionLabel.text = "Chapters Read"
captionLabel.textColor = UIColor.whiteColor()
captionLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(captionLabel)
// Setup constraints
let percentLabelCenterX = NSLayoutConstraint(item: percentLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0)
let percentLabelCenterY = NSLayoutConstraint(item: percentLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activateConstraints([percentLabelCenterX, percentLabelCenterY])
let captionLabelCenterX = NSLayoutConstraint(item: captionLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: -margin)
let captionLabelBottomY = NSLayoutConstraint(item: captionLabel, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -margin)
NSLayoutConstraint.activateConstraints([captionLabelCenterX, captionLabelBottomY])
}
func configure() {
percentLabel.text = String(format: "%.0f/%.0f", curValue, range)
circleBackgroundLayer.strokeColor = circleBackgroundColor.CGColor
circleForegroundLayer.strokeColor = circleForegroundColor.CGColor
}
override func layoutSubviews() {
super.layoutSubviews()
setupShapeLayer(circleBackgroundLayer)
setupShapeLayer(circleForegroundLayer)
}
func setupShapeLayer(shapeLayer: CAShapeLayer) {
shapeLayer.frame = self.bounds
let center = percentLabel.center
let radius = CGFloat(CGRectGetWidth(self.bounds) * 0.35)
let startAngle = DegreesToRadians(135.0)
let endAngle = DegreesToRadians(45.0)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
shapeLayer.path = path.CGPath
}
func animateCircle() {
percentLabel.text = String(format: "%.0f/%.0f",curValue, range)
// setup values
var fromValue = circleForegroundLayer.strokeEnd
let toValue = curValue / range
if let _ = circleForegroundLayer.presentationLayer() as? CAShapeLayer {
fromValue = (circleForegroundLayer.presentationLayer()?.strokeEnd)!
}
let percentageChange = abs(fromValue - toValue)
// setup animation
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = fromValue
animation.toValue = toValue
animation.duration = CFTimeInterval(percentageChange * 4)
circleForegroundLayer.removeAnimationForKey("stroke")
circleForegroundLayer.addAnimation(animation, forKey: "stroke")
CATransaction.begin()
CATransaction.setDisableActions(true)
circleForegroundLayer.strokeEnd = toValue
CATransaction.commit()
}
}
|
9287923065c4563642993c19650eb8fa
| 31.622378 | 179 | 0.721484 | false | false | false | false |
jozsef-vesza/algorithms
|
refs/heads/master
|
Swift/Algorithms.playground/Pages/Sorting.xcplaygroundpage/Contents.swift
|
mit
|
1
|
import Foundation
extension Array {
func randomElement() -> Generator.Element {
return self[Int(arc4random_uniform(UInt32(count)))]
}
}
extension Array where Element: Comparable {
func mergeWith(other:[Generator.Element]) -> [Generator.Element] {
var output: [Generator.Element] = []
var leftIndex = startIndex
var rightIndex = other.startIndex
while leftIndex != endIndex && rightIndex != other.endIndex {
let leftValue = self[leftIndex]
let rightValue = other[rightIndex]
if leftValue < rightValue {
output.append(leftValue)
leftIndex = leftIndex.successor()
} else {
output.append(rightValue)
rightIndex = rightIndex.successor()
}
}
output += self[leftIndex ..< endIndex]
output += other[rightIndex ..< other.endIndex]
return output
}
}
extension CollectionType where Generator.Element: Comparable, Index.Distance == Int {
func insertionSort() -> [Generator.Element] {
var output = Array(self)
for primaryIndex in 0 ..< output.count {
let key = output[primaryIndex]
for var secondaryIndex = primaryIndex; secondaryIndex > -1; secondaryIndex-- {
if key < output[secondaryIndex] {
output.removeAtIndex(secondaryIndex + 1)
output.insert(key, atIndex: secondaryIndex)
}
}
}
return output
}
func selectionSort() -> [Generator.Element] {
var output = Array(self)
var indexOfSmallest = 0
for primaryIndex in 0 ..< output.count {
indexOfSmallest = primaryIndex
for secondaryIndex in primaryIndex + 1 ..< output.count {
if output[secondaryIndex] < output[indexOfSmallest] {
indexOfSmallest = secondaryIndex
}
}
if primaryIndex != indexOfSmallest {
swap(&output[primaryIndex], &output[indexOfSmallest])
}
}
return output
}
func bubbleSort() -> [Generator.Element] {
var output = Array(self)
var shouldRepeat = true
while shouldRepeat {
shouldRepeat = false
for index in 1 ..< output.count {
if output[index] < output[index - 1] {
swap(&output[index], &output[index - 1])
shouldRepeat = true
}
}
}
return output
}
func mergeSort() -> [Generator.Element] {
let arrayRepresentation = Array(self)
if count < 2 {
return arrayRepresentation
}
let middleIndex = count / 2
let left = arrayRepresentation[0 ..< middleIndex].mergeSort()
let right = arrayRepresentation[middleIndex ..< count].mergeSort()
return left.mergeWith(right)
}
func quickSort() -> [Generator.Element] {
if self.count < 1 { return [] }
let unsorted = Array(self)
var less: [Generator.Element] = []
var more: [Generator.Element] = []
let pivot = unsorted.randomElement()
for element in unsorted where element != pivot {
if element < pivot { less.append(element) }
else { more.append(element) }
}
return less.quickSort() + [pivot] + more.quickSort()
}
}
let numbers = [9, 8, 7, 5, 6]
let strings = ["gnu", "zebra", "antelope", "aardvark", "yak", "iguana"]
let nums2 = numbers.insertionSort()
let sortedStr2 = strings.insertionSort()
let set = Set(numbers)
let sortedSet = set.insertionSort()
let selectionSortedNums = numbers.selectionSort()
let selectionSortedStrings = strings.selectionSort()
let bubbleSortedNums = numbers.bubbleSort()
let mergeSortedNums = numbers.mergeSort()
let quickSortedNums = numbers.quickSort()
//: [Next](@next)
|
09e777cbff3bbfb953b7ce276465b921
| 25.885542 | 90 | 0.514452 | false | false | false | false |
cuzv/Redes
|
refs/heads/master
|
RedesSample/Helpers.swift
|
mit
|
1
|
//
// Helpers.swift
// Copyright (c) 2015-2016 Moch Xiao (http://mochxiao.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Dictionary {
/// URL query string.
public var queryString: String {
let mappedList = map {
return "\($0.0)=\($0.1)"
}
return mappedList.sorted().joined(separator: "&")
}
}
// MARK: - md5
// https://github.com/onevcat/Kingfisher/blob/master/Sources/String%2BMD5.swift
public extension String {
var md5: String {
if let data = self.data(using: .utf8, allowLossyConversion: true) {
let message = data.withUnsafeBytes { bytes -> [UInt8] in
return Array(UnsafeBufferPointer(start: bytes, count: data.count))
}
let MD5Calculator = MD5(message)
let MD5Data = MD5Calculator.calculate()
let MD5String = NSMutableString()
for c in MD5Data {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
} else {
return self
}
}
}
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] {
let totalBytes = length ?? (MemoryLayout<T>.size * 8)
let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
valuePointer.pointee = value
let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in
var bytes = [UInt8](repeating: 0, count: totalBytes)
for j in 0..<min(MemoryLayout<T>.size, totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
}
return bytes
}
valuePointer.deinitialize()
valuePointer.deallocate(capacity: 1)
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
func appendBytes(_ arrayOfBytes: [UInt8]) {
append(arrayOfBytes, length: arrayOfBytes.count)
}
}
protocol HashProtocol {
var message: Array<UInt8> { get }
/** Common part for hash calculation. Prepare header data. */
func prepare(_ len: Int) -> Array<UInt8>
}
extension HashProtocol {
func prepare(_ len: Int) -> Array<UInt8> {
var tmpMessage = message
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
tmpMessage += Array<UInt8>(repeating: 0, count: counter)
return tmpMessage
}
}
func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> {
var result = Array<UInt32>()
result.reserveCapacity(16)
for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) {
let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24
let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16
let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8
let d3 = UInt32(slice[idx])
let val: UInt32 = d0 | d1 | d2 | d3
result.append(val)
}
return result
}
struct BytesIterator: IteratorProtocol {
let chunkSize: Int
let data: [UInt8]
init(chunkSize: Int, data: [UInt8]) {
self.chunkSize = chunkSize
self.data = data
}
var offset = 0
mutating func next() -> ArraySlice<UInt8>? {
let end = min(chunkSize, data.count - offset)
let result = data[offset..<offset + end]
offset += result.count
return result.count > 0 ? result : nil
}
}
struct BytesSequence: Sequence {
let chunkSize: Int
let data: [UInt8]
func makeIterator() -> BytesIterator {
return BytesIterator(chunkSize: chunkSize, data: data)
}
}
func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 {
return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
}
class MD5: HashProtocol {
static let size = 16 // 128 / 8
let message: [UInt8]
init (_ message: [UInt8]) {
self.message = message
}
/** specifies the per-round shift amounts */
private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> [UInt8] {
var tmpMessage = prepare(64)
tmpMessage.reserveCapacity(tmpMessage.count + 4)
// hash values
var hh = hashes
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.count * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage += lengthBytes.reversed()
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = toUInt32Array(chunk)
assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A: UInt32 = hh[0]
var B: UInt32 = hh[1]
var C: UInt32 = hh[2]
var D: UInt32 = hh[3]
var dTemp: UInt32 = 0
// Main loop
for j in 0 ..< sines.count {
var g = 0
var F: UInt32 = 0
switch j {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
hh.forEach {
let itemLE = $0.littleEndian
result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)]
}
return result
}
}
|
bad9671d738164af86b015fa8f0af4ae
| 33.820069 | 133 | 0.530856 | false | false | false | false |
OpenMindBR/swift-diversidade-app
|
refs/heads/master
|
Diversidade/Address.swift
|
mit
|
1
|
//
// Address.swift
// Diversidade
//
// Created by Francisco José A. C. Souza on 07/04/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
class Address: NSObject {
let line1: String
let number: String
let neighborhood: String
let city: String
let region: String
let zip: String
init(line1: String, number:String, neighborhood: String, city: String, region: String, zip: String) {
self.line1 = line1
self.number = number
self.neighborhood = neighborhood
self.city = city
self.region = region
self.zip = zip
}
override var description: String {
return "\(self.line1), \(self.number), \(self.neighborhood) \n \(self.city) - \(self.region)"
}
}
|
cbabd34fe24bb1e093a42231856b44e5
| 24 | 105 | 0.61375 | false | false | false | false |
pccole/GitHubJobs-iOS
|
refs/heads/master
|
GitHubJobs/PreviewContent/PreviewData.swift
|
mit
|
1
|
//
// PreviewData.swift
// GitHubJobs
//
// Created by Phil Cole on 4/22/20.
// Copyright © 2020 Cole LLC. All rights reserved.
//
import Foundation
public struct PreviewData {
public static func load() -> [GithubJob] {
let data: Data
let filename = "Jobs.json"
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext else {
fatalError("Failed to retrieve context")
}
let decoder = JSONDecoder()
decoder.userInfo[codingUserInfoKeyManagedObjectContext] = DataStore.shared.persistentContainer.viewContext
let json = try decoder.decode([GithubJob].self, from: data)
// print(json)
return json
} catch {
fatalError("Couldn't parse \(filename) as \([GithubJob].self):\n\(error)")
}
}
}
|
2e9b76a0f09cc5f7a26906a102020e79
| 30.675 | 118 | 0.575375 | false | false | false | false |
SwiftKitz/Appz
|
refs/heads/master
|
Appz/AppzTests/AppsTests/InstagramTests.swift
|
mit
|
1
|
//
// InstagramTests.swift
// Appz
//
// Created by Suraj Shirvankar on 12/6/15.
// Copyright © 2015 kitz. All rights reserved.
//
import XCTest
@testable import Appz
class InstagramTests: XCTestCase {
let appCaller = ApplicationCallerMock()
func testConfiguration() {
let instagram = Applications.Instagram()
XCTAssertEqual(instagram.scheme, "instagram:")
XCTAssertEqual(instagram.fallbackURL, "https://instagram.com/")
}
func testOpen() {
let action = Applications.Instagram.Action.open
XCTAssertEqual(action.paths.app.pathComponents, ["app"])
XCTAssertEqual(action.paths.app.queryParameters, [:])
XCTAssertEqual(action.paths.web, Path())
}
func testCamera() {
let action = Applications.Instagram.Action.camera
XCTAssertEqual(action.paths.app.pathComponents, ["camera"])
XCTAssertEqual(action.paths.app.queryParameters, [:])
XCTAssertEqual(action.paths.web, Path())
}
func testLibrary() {
let action = Applications.Instagram.Action.library(id: "1")
XCTAssertEqual(action.paths.app.pathComponents, ["library"])
XCTAssertEqual(action.paths.app.queryParameters, ["LocalIdentifier":"1"])
XCTAssertEqual(action.paths.web, Path())
}
func testMedia() {
let action = Applications.Instagram.Action.media(id: "1")
XCTAssertEqual(action.paths.app.pathComponents, ["media"])
XCTAssertEqual(action.paths.app.queryParameters, ["id":"1"])
XCTAssertEqual(action.paths.web.pathComponents, ["p", "1"])
}
func testUsername() {
let action = Applications.Instagram.Action.username("test")
XCTAssertEqual(action.paths.app.pathComponents, ["user"])
XCTAssertEqual(action.paths.app.queryParameters, ["username":"test"])
XCTAssertEqual(action.paths.web.pathComponents, ["test"])
}
func testLocation() {
let action = Applications.Instagram.Action.location(id: "111")
XCTAssertEqual(action.paths.app.pathComponents, ["location"])
XCTAssertEqual(action.paths.app.queryParameters, ["id":"111"])
XCTAssertEqual(action.paths.web, Path())
}
func testTag() {
let action = Applications.Instagram.Action.tag(name: "tag")
XCTAssertEqual(action.paths.app.pathComponents, ["tag"])
XCTAssertEqual(action.paths.app.queryParameters, ["name":"tag"])
XCTAssertEqual(action.paths.web.pathComponents, ["explore", "tags", "tag"])
}
}
|
85d90100c1d82a4e8995f674c03720e1
| 30.395349 | 83 | 0.623333 | false | true | false | false |
NSSimpleApps/WatchConnector
|
refs/heads/master
|
WatchConnector/WatchConnector/Keys.swift
|
mit
|
1
|
//
// Keys.swift
// WatchConnector
//
// Created by NSSimpleApps on 13.03.16.
// Copyright © 2016 NSSimpleApps. All rights reserved.
//
import Foundation
let UpdateUIKey = "UpdateUIKey"
let DataRequest = "DataRequest"
let DeleteNote = "DeleteNote"
let Notes = "Notes"
let URIRepresentation = "URIRepresentation"
let ReloadData = "ReloadData"
|
f5650b2d352e8320ac9ca371e8c5dc36
| 17.473684 | 55 | 0.731429 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/Extensions/Challenge-Extensions.swift
|
gpl-3.0
|
1
|
//
// Challenge-Extensions.swift
// Habitica
//
// Created by Elliot Schrock on 1/30/18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
extension ChallengeProtocol {
func shouldBePublishable() -> Bool {
if !isOwner() {
return false
} else {
return hasTasks()
}
}
func shouldBeUnpublishable() -> Bool {
if !isOwner() {
return false
} else {
return !hasTasks()
}
}
func shouldEnable() -> Bool {
if !isOwner() {
return true
} else {
return hasTasks()
}
}
func isOwner() -> Bool {
return false
}
func isPublished() -> Bool {
return true
}
func isEndable() -> Bool {
return isOwner() && isPublished()
}
func hasTasks() -> Bool {
let hasDailies = dailies.isEmpty == false
let hasHabits = habits.isEmpty == false
let hasTodos = todos.isEmpty == false
let hasRewards = rewards.isEmpty == false
return hasDailies || hasHabits || hasTodos || hasRewards
}
}
|
583c078fa50e46a25d141f53c19053ea
| 19.644068 | 64 | 0.517241 | false | false | false | false |
stockx/Punchcard
|
refs/heads/master
|
Source/UIView+AutoLayout.swift
|
mit
|
1
|
//
// UIView+AutoLayout.swift
// Punchcard
//
// Created by Josh Sklar on 2/1/17.
// Copyright © 2017 StockX. All rights reserved.
//
import UIKit
extension UIView {
// MARK: Edges
/**
Makes the edges of the receiver equal to the edges of `view`.
Note: `view` must already be constrained, and both the receiver
and `view` must have a common superview.
*/
func makeEdgesEqualTo(_ view: UIView) {
makeAttribute(.leading, equalToOtherView: view, attribute: .leading)
makeAttribute(.trailing, equalToOtherView: view, attribute: .trailing)
makeAttribute(.top, equalToOtherView: view, attribute: .top)
makeAttribute(.bottom, equalToOtherView: view, attribute: .bottom)
}
/**
Makes the edges of the receiver equal to its superview with an otion to
specify an inset value.
If the receiver does not have a superview, this does nothing.
*/
func makeEdgesEqualToSuperview(inset: CGFloat = 0) {
makeAttributesEqualToSuperview([.leading, .top], offset: inset)
makeAttributesEqualToSuperview([.trailing, .bottom], offset: -inset)
}
// MARK: Attributes
/**
Applies constraints to the receiver with attributes `attributes` all
equal to its superview.
*/
func makeAttributesEqualToSuperview(_ attributes: [NSLayoutAttribute], offset: CGFloat = 0) {
guard let superview = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
attributes.forEach {
superview.addConstraint(NSLayoutConstraint(item: self,
attribute: $0,
relatedBy: .equal,
toItem: superview,
attribute: $0,
multiplier: 1.0,
constant: offset))
}
}
/**
Applies a constraint to the receiver with attribute `attribute` and
the specified constant.
*/
func makeAttribute(_ attribute: NSLayoutAttribute, equalTo constant: CGFloat) {
guard let superview = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
superview.addConstraint(NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: constant))
}
/**
Applies a constraint with the attribute `attribute` from the receiver to
the view `otherView` with attribute `attribute`.
*/
func makeAttribute(_ attribute: NSLayoutAttribute,
equalToOtherView otherView: UIView,
attribute otherAttribute: NSLayoutAttribute,
constant: CGFloat = 0) {
guard let sv = otherView.superview,
sv == self.superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
sv.addConstraint(NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: otherView,
attribute: otherAttribute,
multiplier: 1.0,
constant: constant))
}
// MARK: Utility
/**
Removes all the constrains where the receiver is either the
firstItem or secondItem.
If the receiver does not have a superview, this only removes the
constraints that the receiver owns.
*/
func removeAllConstraints() {
guard let superview = superview else {
removeConstraints(constraints)
return
}
for constraint in superview.constraints where (constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self) {
superview.removeConstraint(constraint)
}
removeConstraints(constraints)
}
}
|
aa488cb4f9a1b87e3d169e1832be93a3
| 35.046512 | 141 | 0.517849 | false | false | false | false |
eselkin/DirectionFieldiOS
|
refs/heads/master
|
DirectionField/Complex.swift
|
gpl-3.0
|
1
|
//
// Complex.swift
// DirectionField
//
// Created by Eli Selkin on 12/27/15.
// Copyright © 2015 DifferentialEq. All rights reserved.
//
import Foundation
enum ComplexError: ErrorType {
case BadRegexConstruction(message: String)
case BadStringConstruction(message: String)
}
class Complex : CustomStringConvertible {
let epsilon:Float32 = 1e-5
var real:Float32
var imaginary:Float32
var description:String {
get {
return String(format: "%+5.4f%+5.4fi", self.real, self.imaginary)
}
}
/*
constructor -- initializer with 0, 1, or 2 Float32 attributes
*/
init(r: Float32 = 0.0, i: Float32 = 0.0){
self.real = r
self.imaginary = i
}
/*
constructor -- initializer with 0, 1, or 2 integer attributes
*/
init(r: Int = 0, i: Int = 0){
self.real = Float32(r)
self.imaginary = Float32(i)
}
/*
Constructor -- initializer for string interpolation FAILABLE convenience!
*/
convenience init (realimag: String) throws {
// first conveniently create a new Complex instance
self.init(r: 0.0, i: 0.0)
// then try to store the real values
do {
let internalRegularExpression = try NSRegularExpression(pattern: "^([+-]?[0-9]*[.]?[0-9]+)([+-][0-9]*[.]?[0-9]+)[i]$", options: .CaseInsensitive)
let matches = internalRegularExpression.matchesInString(realimag, options: .Anchored, range: NSRange(location: 0, length: realimag.utf16.count))
for match in matches as [NSTextCheckingResult] {
let realString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(1))
self.real = realString.floatValue
let imagString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(2))
self.imaginary = imagString.floatValue
}
} catch {
throw ComplexError.BadRegexConstruction(message: "Bad expression")
}
}
/**
* http://floating-point-gui.de/errors/comparison/ Comparing complex conjugate to 0.0+0.0i
*/
func isZero() -> Bool {
let absR = abs(self.real)
let absI = abs(self.imaginary)
if (self.real == 0 && self.imaginary == 0){
return true
} else if (absR <= epsilon && absI <= epsilon){
self.real = 0
self.imaginary = 0
return true
} else {
return false
}
}
/**
Distance on CxR plane
*/
func distanceFromZero() -> Float32 {
return sqrtf((self.real*self.real)+(self.imaginary*self.imaginary))
}
}
func +(LHS: Complex, RHS: Complex) -> Complex{
return Complex(r: (LHS.real + RHS.real), i: (LHS.imaginary + RHS.imaginary))
}
func -(LHS: Complex, RHS: Complex) -> Complex {
return Complex(r: (LHS.real - RHS.real), i: (LHS.imaginary - RHS.imaginary))
}
func *(LHS: Complex, RHS: Complex) -> Complex {
return Complex(r: (LHS.real*RHS.real)-(LHS.imaginary*RHS.imaginary), i: (LHS.real*RHS.imaginary)+(LHS.imaginary*RHS.real))
}
func /(LHS: Complex, RHS: Complex) -> Complex {
if LHS.isZero() {
return Complex(r: 0.0, i: 0.0)
}
var real:Float32 = LHS.real * RHS.real
real += LHS.imaginary * RHS.imaginary
var imaginary = LHS.real * RHS.imaginary * -1.0
imaginary += LHS.imaginary * RHS.real
let denominator:Float32 = RHS.real * RHS.real + RHS.imaginary * RHS.imaginary
return Complex(r: real/denominator, i: imaginary/denominator)
}
func >= (LHS: Complex, RHS: Complex) -> Bool {
return (LHS.real >= RHS.real)
}
func == (LHS: Complex, RHS: Complex) -> Bool {
return (approxEqual(LHS.real, RHS: RHS.real, epsilon: 1E-10) && approxEqual(LHS.imaginary, RHS: RHS.imaginary, epsilon: 1E-10))
}
func square(base:Complex) -> Complex {
return base*base
}
func realSqrt(radicand: Complex) -> Complex {
return Complex(r: sqrtf(radicand.real))
}
|
6ff74241a24e62ec779a3cf500a60132
| 30.390625 | 157 | 0.610254 | false | false | false | false |
tadija/AELog
|
refs/heads/master
|
Sources/AELog/Settings.swift
|
mit
|
1
|
/**
* https://github.com/tadija/AELog
* Copyright © 2016-2020 Marko Tadić
* Licensed under the MIT license
*/
import Foundation
/// Log settings
open class Settings {
// MARK: Constants
private struct Defaults {
static let isEnabled = true
static let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
static let template = "{date} -- [{thread}] {file} ({line}) -> {function} > {text}"
}
// MARK: Properties
/// Logging enabled flag (defaults to `true`)
public var isEnabled = Defaults.isEnabled
/// Date format which will be used in log lines. (defaults to "yyyy-MM-dd HH:mm:ss.SSS")
public var dateFormat = Defaults.dateFormat {
didSet {
dateFormatter.dateFormat = dateFormat
}
}
/// Log lines template.
/// Defaults to: "{date} -- [{thread}] {file} ({line}) -> {function} > {text}"
public var template = Defaults.template
/// Key: file name without extension (defaults to empty - logging enabled in all files)
public var files = [String : Bool]()
internal let dateFormatter = DateFormatter()
// MARK: Init
internal init() {
dateFormatter.dateFormat = dateFormat
}
}
|
db095f15c97cc93312b19a14508c1574
| 24.723404 | 92 | 0.61952 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Localization/Sources/Localization/LocalizationConstants+Tour.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
// swiftlint:disable all
import Foundation
extension LocalizationConstants {
public enum Tour {
public static let carouselBrokerageScreenMessage = NSLocalizedString(
"Instantly Buy, Sell and Swap Crypto.",
comment: "Main text that appears in the Brokerage view inside the onboarding tour"
)
public static let carouselEarnScreenMessage = NSLocalizedString(
"Earn Rewards on Your Crypto.",
comment: "Main text that appears in the Earn view inside the onboarding tour"
)
public static let carouselKeysScreenMessage = NSLocalizedString(
"Control Your Crypto with Private Keys.",
comment: "Main text that appears in the Keys view inside the onboarding tour"
)
public static let carouselPricesScreenTitle = NSLocalizedString(
"Never Miss a Crypto Moment.",
comment: "Title text that appears in the Prices view inside the onboarding tour"
)
public static let carouselPricesScreenLivePrices = NSLocalizedString(
"Live Prices",
comment: "Message that appears as a header of the prices list on the Prices screen inside the onboarding tour"
)
public static let createAccountButtonTitle = NSLocalizedString(
"Create an Account",
comment: "Title of the button the user can tap when they want to create an account"
)
public static let restoreButtonTitle = NSLocalizedString(
"Restore",
comment: "Title of the button the user can tap when they want to restore an account"
)
public static let loginButtonTitle = NSLocalizedString(
"Log In ->",
comment: "Title of the button the user can tap when they want to login into an account"
)
public static let manualLoginButtonTitle = NSLocalizedString(
"Manual Pairing",
comment: "Title of the button the user can tap when they want to manual pair the wallet"
)
}
}
|
735c68247651af2065e2494a40a6e967
| 37.836364 | 122 | 0.654963 | false | false | false | false |
jearle/DeckOCards
|
refs/heads/master
|
Pod/Classes/Deck.swift
|
mit
|
1
|
//
// Deck.swift
// Pods
//
// Created by Jesse Earle on 8/6/15.
//
//
public func createDeck() -> [Card] {
println("Creating Deck")
var deck = [Card]()
var suitValue = 0
while let suit = Suit(rawValue: suitValue) {
var rankValue = 0
while let rank = Rank(rawValue: rankValue) {
deck.append(Card(suit: suit, rank: rank))
rankValue++
}
suitValue++
}
return deck
}
public func shuffledDeck () -> [Card] {
return shuffle(createDeck())
}
// http://stackoverflow.com/a/24029847
public func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let c = count(list)
if c < 2 { return list }
for i in 0..<(c - 1) {
let j = Int(arc4random_uniform(UInt32(c - i))) + i
swap(&list[i], &list[j])
}
return list
}
|
cf8031a5cd5d1c46a61e8f65b96974ea
| 16.084746 | 86 | 0.47123 | false | false | false | false |
damouse/DSON
|
refs/heads/master
|
DSONTests/ConversionTests.swift
|
mit
|
1
|
//
// ConversionTests.swift
// Deferred
//
// Created by damouse on 5/17/16.
// Copyright © 2016 I. All rights reserved.
//
// These tests cover converstion TO swift types
// Note that "Primitives" refers to JSON types that arent collections
import XCTest
@testable import DSON
// Primitives
class StringConversion: XCTestCase {
func testSameType() {
let a: String = "asdf"
let b = try! convert(a, to: String.self)
XCTAssert(a == b)
}
func testFromFoundation() {
let a: NSString = "asdf"
let b = try! convert(a, to: String.self)
XCTAssert(a == b)
}
}
class IntConversion: XCTestCase {
func testSameType() {
let a: Int = 1
let b = try! convert(a, to: Int.self)
XCTAssert(a == b)
}
func testFromFoundation() {
let a: NSNumber = 1
let b = try! convert(a, to: Int.self)
XCTAssert(a == b)
}
}
class FloatConversion: XCTestCase {
func testSameType() {
let a: Float = 123.456
let b = try! convert(a, to: Float.self)
XCTAssert(a == b)
}
func testFromFoundation() {
let a: NSNumber = 123.456
let b = try! convert(a, to: Float.self)
XCTAssert(b == 123.456)
}
}
class DoubleConversion: XCTestCase {
func testSameType() {
let a: Double = 123.456
let b = try! convert(a, to: Double.self)
XCTAssert(a == b)
}
func testFromFoundation() {
let a: NSNumber = 123.456
let b = try! convert(a, to: Double.self)
XCTAssert(b == 123.456)
}
}
class BoolConversion: XCTestCase {
func testSameType() {
let a: Bool = true
let b = try! convert(a, to: Bool.self)
XCTAssert(a == b)
}
func testFromFoundation() {
let a: ObjCBool = true
let b = try! convert(a, to: Bool.self)
XCTAssert(b == true)
}
}
// Collections
class ArrayConversion: XCTestCase {
func testSameType() {
let a: [String] = ["asdf", "qwer"]
let b = try! convert(a, to: [String].self)
XCTAssert(a == b)
}
// NSArray with Convertible elements
func testFoundationArray() {
let a: NSArray = NSArray(objects: "asdf", "qwer")
let b = try! convert(a, to: [String].self)
XCTAssert(a == b)
}
// Swift array with Foundation elements
func testFoundationElements() {
let a: [NSString] = [NSString(string: "asdf"), NSString(string: "qwer")]
let b = try! convert(a, to: [String].self)
XCTAssert(a == b)
}
// NSArray array with Foundation elements
func testFoundationArrayElements() {
let a: NSArray = NSArray(objects: NSString(string: "asdf"), NSString(string: "qwer"))
let b = try! convert(a, to: [String].self)
XCTAssert(a == b)
}
}
class DictionaryConversion: XCTestCase {
func testSameType() {
let a: [String: String] = ["asdf": "qwer"]
let b = try! convert(a, to: [String: String].self)
XCTAssert(a == b)
}
func testAnyObject() {
let a: [String: AnyObject] = ["asdf": "qwer"]
let b = try! convert(a, to: [String: String].self)
XCTAssert(b.count == 1)
XCTAssert(b["asdf"] == "qwer")
}
func testFoundationDictionary() {
let a: NSDictionary = NSDictionary(dictionary: ["asdf": "qwer"])
let b = try! convert(a, to: [String: String].self)
XCTAssert(a == b)
}
func testFoundationKeys() {
let a: [NSString: String] = [NSString(string: "asdf"): "qwer"]
let b = try! convert(a, to: [String: String].self)
XCTAssert(b.count == 1)
XCTAssert(b["asdf"] == "qwer")
}
func testFoundationValues() {
let a: [String: NSString] = ["asdf": NSString(string: "qwer")]
let b = try! convert(a, to: [String: String].self)
XCTAssert(b.count == 1)
XCTAssert(b["asdf"] == "qwer")
}
func testFoundationKeysValues() {
let a: [NSString: NSString] = [NSString(string: "asdf"): NSString(string: "qwer")]
let b = try! convert(a, to: [String: String].self)
XCTAssert(b.count == 1)
XCTAssert(b["asdf"] == "qwer")
}
}
|
bbcd270bdb214842128fd14bb790ab70
| 19.9375 | 93 | 0.547646 | false | true | false | false |
coderMONSTER/iosstar
|
refs/heads/master
|
iOSStar/Model/StarListModel/StarListModel.swift
|
gpl-3.0
|
1
|
//
// StarListModel.swift
// iOSStar
//
// Created by sum on 2017/5/11.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import RealmSwift
class BaseModel: OEZModel {
override class func jsonKeyPostfix(_ name: String!) -> String! {
return "";
}
deinit {
}
}
class StarListModel: BaseModel {
var depositsinfo : [StarInfoModel]?
class func depositsinfoModelClass() ->AnyClass {
return StarInfoModel.classForCoder()
}
}
class StartModel: Object {
dynamic var accid : String = ""
dynamic var brief : Int64 = 0
dynamic var code : String = " "
dynamic var gender : Int64 = 0
dynamic var name : String = ""
dynamic var phone : String = ""
dynamic var price : Int64 = 0
dynamic var pic_url = ""
override static func primaryKey() -> String?{
return "code"
}
static func getStartName(startCode:String,complete: CompleteBlock?){
let realm = try! Realm()
let filterStr = "code = '\(startCode)'"
let user = realm.objects(StartModel.self).filter(filterStr).first
if user != nil{
complete?(user as AnyObject)
}else{
complete?(nil)
}
}
}
class StarInfoModel: NSObject {
var faccid : String = ""
var status : Int64 = 0
var ownseconds : Int64 = 0
var appoint : Int64 = 0
var starcode : String = ""
var starname : String = ""
var uid : Int64 = 0
var accid : String = ""
}
|
a3f6bc4011f8e5c3779668ba116bd845
| 19.76 | 73 | 0.574823 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue
|
refs/heads/master
|
iOS/Venue/Views/POIAnnotation.swift
|
epl-1.0
|
1
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/// Subclass of VenueMapAnnotation. Represents a Point of Interest on the map.
class POIAnnotation: VenueMapAnnotation {
var poiObject: POI!
private var referencePoint = CGPoint()
private let scale: CGFloat = 0.7
init(poi: POI, location: CGPoint, zoomScale: CGFloat) {
self.poiObject = poi
let firstType = poiObject.types.first!
let backgroundImage = UIImage(named: firstType.pin_image_name)!
let width = backgroundImage.size.width * scale
let height = backgroundImage.size.height * scale
// Setup the frame of the button. The bottom middle point of the annotation is the reference point
referencePoint = location
let x = self.referencePoint.x * zoomScale - (width / 2)
let y = self.referencePoint.y * zoomScale - (height)
super.init(frame: CGRect(x: x, y: y, width: width, height: height))
self.setBackgroundImage(backgroundImage, forState: UIControlState.Normal)
self.accessibilityIdentifier = self.poiObject.name
self.accessibilityHint = firstType.name
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func updateLocation(mapZoomScale: CGFloat) {
// This point needs to move to keep the bottom middle of the image in the same location. The other annotation
// types moves to keep the center of the annotation in the same relative spot
self.frame.origin.x = (self.referencePoint.x * mapZoomScale) - (self.frame.size.width / 2)
self.frame.origin.y = (self.referencePoint.y * mapZoomScale) - (self.frame.size.height)
}
override func updateReferencePoint(newReferencePoint: CGPoint, mapZoomScale: CGFloat) {
self.referencePoint = newReferencePoint
self.updateLocation(mapZoomScale)
}
override func getReferencePoint() -> CGPoint {
return self.referencePoint
}
private func calculateOriginPoint(width: CGFloat, height: CGFloat, zoomScale: CGFloat) -> CGPoint {
let x = (self.referencePoint.x * zoomScale) - (width / 2)
let y = (self.referencePoint.y * zoomScale) - (height)
return CGPoint(x: x, y: y)
}
/**
When this annotation is selected, change the frame of the annotation accordingly.
- parameter mapZoomScale: The zoom scale of the containing scroll view
*/
override func annotationSelected(mapZoomScale: CGFloat) {
currentlySelected = !currentlySelected
let backgroundImage = self.backgroundImageForState(.Normal)!
let width : CGFloat!
let height : CGFloat!
if currentlySelected {
width = backgroundImage.size.width
height = backgroundImage.size.height
} else {
width = backgroundImage.size.width * scale
height = backgroundImage.size.height * scale
}
let newOrigin = self.calculateOriginPoint(width, height: height, zoomScale: mapZoomScale)
UIView.animateWithDuration(0.3, animations: { Void in
self.frame = CGRect(x: newOrigin.x, y: newOrigin.y, width: width, height: height)
})
}
/**
Applies the given filters to this annotation
- parameter filter: The filter array of the different types
*/
func applyFilter(filter: [Type]) {
// Filter based on type
for poiType in poiObject.types {
for type in filter {
if poiType.id == type.id {
if type.shouldDisplay {
self.hidden = false
return
} else {
self.hidden = true
}
}
}
}
}
/**
Filter based on the minimum height requirement
- parameter heightFilter: The int value for minimum height
- returns: Bool indicating if this annotation is now hidden or not
*/
func filterHeight(heightFilter: Int) -> Bool {
if (poiObject.height_requirement > 0) && (poiObject.height_requirement > heightFilter) {
self.hidden = true
} else {
self.hidden = false
}
return self.hidden
}
/**
Filter based on maximum wait time
- parameter waitTime: The int value for maximum wait
- returns: Bool indicating if this annotation is now hidden or not
*/
func filterWaitTime(waitTime: Int) -> Bool {
if (poiObject.wait_time > 0) && (poiObject.wait_time > waitTime) {
self.hidden = true
} else {
self.hidden = false
}
return self.hidden
}
}
|
928978c8720299ac5809e97caf534d0a
| 34.202899 | 117 | 0.615274 | false | false | false | false |
ZamzamInc/SwiftyPress
|
refs/heads/main
|
Sources/SwiftyPress/Repositories/Author/AuthorAPI.swift
|
mit
|
1
|
//
// AuthorAPI.swift
// SwiftyPress
//
// Created by Basem Emara on 2018-06-04.
// Copyright © 2019 Zamzam Inc. All rights reserved.
//
import ZamzamCore
// MARK: - Services
public protocol AuthorService {
func fetch(with request: AuthorAPI.FetchRequest, completion: @escaping (Result<Author, SwiftyPressError>) -> Void)
}
// MARK: - Cache
public protocol AuthorCache {
func fetch(with request: AuthorAPI.FetchRequest, completion: @escaping (Result<Author, SwiftyPressError>) -> Void)
func createOrUpdate(_ request: Author, completion: @escaping (Result<Author, SwiftyPressError>) -> Void)
func subscribe(
with request: AuthorAPI.FetchRequest,
in cancellable: inout Cancellable?,
change block: @escaping (ChangeResult<Author, SwiftyPressError>) -> Void
)
}
// MARK: - Namespace
public enum AuthorAPI {
public struct FetchRequest: Hashable {
public let id: Int
public init(id: Int) {
self.id = id
}
}
public struct FetchCancellable {
private let service: AuthorService
private let cache: AuthorCache?
private let request: FetchRequest
private let block: (ChangeResult<Author, SwiftyPressError>) -> Void
init(
service: AuthorService,
cache: AuthorCache?,
request: FetchRequest,
change block: @escaping (ChangeResult<Author, SwiftyPressError>) -> Void
) {
self.service = service
self.cache = cache
self.request = request
self.block = block
}
/// Stores the cancellable object for subscriptions to be delievered during its lifetime.
///
/// A subscription is automatically cancelled when the object is deinitialized.
///
/// - Parameter cancellable: A subscription token which must be held for as long as you want updates to be delivered.
public func store(in cancellable: inout Cancellable?) {
guard let cache = cache else {
service.fetch(with: request, completion: { $0(self.block) })
return
}
cache.subscribe(with: request, in: &cancellable, change: block)
}
}
}
|
a89e407ba0158ebfe5ed26ed1b36999b
| 30.094595 | 125 | 0.615385 | false | false | false | false |
22377832/swiftdemo
|
refs/heads/master
|
TouchsDemo/TouchsDemo/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// TouchsDemo
//
// Created by adults on 2017/4/5.
// Copyright © 2017年 adults. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
guard let splitVC = self.window?.rootViewController as? UISplitViewController else {
print("error")
fatalError("error")
}
splitVC.delegate = self
return true
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
// Return true if the `sampleTitle` has not been set, collapsing the secondary controller.
return topAsDetailController.sampleTitle == nil
}
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:.
}
}
|
ec96dce000fc0d75e8418f6e17ff6200
| 47.301587 | 285 | 0.739073 | false | false | false | false |
JadenGeller/Mailbox
|
refs/heads/master
|
mailbox.swift
|
mit
|
1
|
import Foundation
public protocol OutgoingMailboxType {
typealias Message
func send(message: Message)
}
public protocol IncomingMailboxType {
typealias Message
func receive() -> Message
}
public protocol ClosableMailboxType {
typealias Message
func close()
}
public protocol ClosableIncomingMailboxType : ClosableMailboxType {
func receive() -> Message?
}
// Used to connect concurrent threads and communicate values across them.
// For more info, visit https://gobyexample.com/channels
public class Mailbox<T> : IncomingMailboxType, OutgoingMailboxType {
// Signals--communicating mailbox and delivery status between threads
private let mailboxNotFull: dispatch_queue_t
private let messageSent: dispatch_queue_t
private let messageReceived: dispatch_queue_t
// Locks--syncronizing blocks of code so that only one thread can perform
// a given action at a time, preventing state corruption
private let receiveMessage = dispatch_semaphore_create(1)
private let sendMessage = dispatch_semaphore_create(1)
private let openMailbox = dispatch_semaphore_create(1)
// Stores messages in transit between threads
private var mailbox = [T]()
// Maximum number of messages that can be stored in our given mailbox at
// a time before we start blocking threads
public let capacity: Int
// Capacity argument specifies the number of messages that can be sent,
// unreceieved, before sending starts to block the thread. By default,
// the capacity is 0, and every sent message is blocking until it is
// received.`
public init(capacity: Int = 0) {
// Check to make sure that the capacity is non-negative
assert(capacity >= 0, "Channel capacity must be a positive value")
self.capacity = capacity
// Keeps track of how much space is left in our mailbox so that
// only add new values when there is enough space. Our mailbox can hold
// one more than capacity messages because we need to hold also hold the
// message currently in transit.
self.mailboxNotFull = dispatch_semaphore_create(capacity + 1)
// Notifies the recipient when a message has been sent so that it can
// pick it up. If multiple messages are sent without being received,
// these notifcations to the recipient pile up, waiting.
self.messageSent = dispatch_semaphore_create(0)
// Keeps track of how many messages in our mailbox are still waiting to
// be received. This allows us to block the thread when our mailbox is
// over capacity and unblock it once a message has been received so we
// are again at normal capacity.
self.messageReceived = dispatch_semaphore_create(capacity)
}
public func send(message: T) {
// Wait in the line to send your message.
dispatch_semaphore_wait(sendMessage, DISPATCH_TIME_FOREVER)
// Wait until there is space in the mailbox to store your message.
dispatch_semaphore_wait(mailboxNotFull, DISPATCH_TIME_FOREVER)
// Claim the mailbox once it's not in use, and store your message in it.
dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER)
mailbox.append(message)
dispatch_semaphore_signal(openMailbox) // Close the mailbox
// Let the recipient know that there is a message waiting for them.
dispatch_semaphore_signal(messageSent)
// If the mailbox too full, don't leave your message unattended
// until another message is received first.
dispatch_semaphore_wait(messageReceived, DISPATCH_TIME_FOREVER)
// You sent your message, so get out of line and let the next thread
// send its mail!
dispatch_semaphore_signal(sendMessage)
}
public func receive() -> T {
// Wait in the line to receive you message.
dispatch_semaphore_wait(receiveMessage, DISPATCH_TIME_FOREVER)
// Wait until somebody sends a message so that there's a message
// available for you in the mailbox.
dispatch_semaphore_wait(messageSent, DISPATCH_TIME_FOREVER)
// Claim the mailbox once it's not in use, and grab your message from it.
dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER)
let message = mailbox.removeAtIndex(0)
dispatch_semaphore_signal(openMailbox) // Close the mailbox
// Signal that the mailbox is no longer full (as we just removed a
// message from it) so that senders can put more messages in it.
dispatch_semaphore_signal(mailboxNotFull)
// Signal that the mailbox is no longer too full so that any other poor
// thread waiting next to it can finally insert his message and leave.
dispatch_semaphore_signal(messageReceived)
// You received your message, so get out of line and let the next thead
// retrieve its mail!
dispatch_semaphore_signal(receiveMessage)
return message
}
}
public class ClosableMailbox<T> : Mailbox<T>, ClosableMailboxType, SequenceType {
// Signals when a message is added to the mailbox so we can defer checking
// the closed state to the last possible moment.
private let mailboxReady = dispatch_semaphore_create(0)
// Lock used to keep synchronous the checking and changing of the closed flag
private let keepState = dispatch_semaphore_create(1)
override init(capacity: Int = 0) {
super.init(capacity: capacity)
}
// Tracks whether or not the mailbox has been closed
private var isClosed = false
override public func send(message: T) {
// Signals that a message was sent to that we can stop deferring our
// empty and closed checks
dispatch_semaphore_signal(mailboxReady)
super.send(message)
}
// Receieve optional messages: T? while the mailbox is open
// and nil once the mailbox has been closed
public func receive() -> T? {
// Defers checking the mailbox until last minute (aka until something
// has actually been added).
dispatch_semaphore_wait(mailboxReady, DISPATCH_TIME_FOREVER)
// Claims the mailbox and checks if it is empty
dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER)
let empty = mailbox.isEmpty
dispatch_semaphore_signal(openMailbox)
// If the mailbox was empty, we should check if it is closed
if empty {
// Claim mailbox so that we can check if it is closed
dispatch_semaphore_wait(keepState, DISPATCH_TIME_FOREVER)
let closed = self.isClosed
dispatch_semaphore_signal(keepState)
// It the mailbox was closed, we ought to return nil from this
// function
if closed { return nil }
}
return super.receive()
}
override public func receive() -> T {
fatalError("ClosableMailbox instance must use the optional recieve function")
}
public func close() {
// Claim mailbox so that we can set the closed state
dispatch_semaphore_wait(self.keepState, DISPATCH_TIME_FOREVER)
self.isClosed = true
dispatch_semaphore_signal(self.keepState)
dispatch_semaphore_signal(mailboxReady)
}
public func generate() -> ClosableMailboxGenerator<T> {
return ClosableMailboxGenerator<T>(mailbox: self)
}
}
public struct ClosableMailboxGenerator<T> : GeneratorType {
private let mailbox: ClosableMailbox<T>
public mutating func next() -> T? {
return mailbox.receive()
}
}
// Custom operators for sending and recieving mail.
prefix operator <- { }
infix operator <- { }
public prefix func <-<M : IncomingMailboxType>(rhs: M) -> M.Message { return rhs.receive() }
public prefix func <-<M : ClosableIncomingMailboxType>(rhs: M) -> M.Message? { return rhs.receive() }
public func <-<M : OutgoingMailboxType>(lhs: M, rhs: M.Message) { return lhs.send(rhs) }
// Calls the passed in function or closure on a background thread. Equivalent
// to Go's "go" keyword.
public func dispatch(routine: () -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), routine)
}
// Calls the passed in function or closure on the main thead. Important for
// UI work!
public func main(routine: () -> ()) {
dispatch_async(dispatch_get_main_queue(), routine)
}
|
6264cc36df4a124e9eb777461b2f7df3
| 37.564444 | 101 | 0.669356 | false | false | false | false |
bastiangardel/EasyPayClientSeller
|
refs/heads/master
|
TB_Client_Seller/TB_Client_Seller/ViewControllerLogin.swift
|
mit
|
1
|
//
// ViewController.swift
// TB_Client_Seller
//
// Created by Bastian Gardel on 20.06.16.
//
// Copyright © 2016 Bastian Gardel
//
// 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 KeychainSwift
import BButton
import MBProgressHUD
import SCLAlertView
// ** Class ViewControllerLogin **
//
// View Login Controller
//
// Author: Bastian Gardel
// Version: 1.0
class ViewControllerLogin: UIViewController {
@IBOutlet weak var LoginTF: UITextField!
@IBOutlet weak var PasswordTF: UITextField!
@IBOutlet weak var SaveLP: UISwitch!
@IBOutlet weak var loginButton: BButton!
let keychain = KeychainSwift()
var httpsSession = HTTPSSession.sharedInstance
var hud: MBProgressHUD?
//End edition mode if click outside of the textfield
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
LoginTF.endEditing(true)
PasswordTF.endEditing(true)
}
//View initialisation
override func viewDidLoad() {
super.viewDidLoad()
loginButton.color = UIColor.bb_successColorV2()
loginButton.setStyle(BButtonStyle.BootstrapV2)
loginButton.setType(BButtonType.Success)
loginButton.addAwesomeIcon(FAIcon.FASignIn, beforeTitle: false)
if ((keychain.get("login")) != nil && (keychain.get("password")) != nil) {
LoginTF.text = keychain.get("login");
PasswordTF.text = keychain.get("password")
}
if keychain.getBool("SaveLP") != nil {
SaveLP.setOn(keychain.getBool("SaveLP")!, animated: false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Click on login button handler
@IBAction func loginAction(sender: AnyObject) {
keychain.set(SaveLP.on, forKey: "SaveLP");
let appearance = SCLAlertView.SCLAppearance(
kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!,
kTextFont: UIFont(name: "HelveticaNeue", size: 30)!,
kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!,
kWindowWidth: 500.0,
kWindowHeight: 500.0,
kTitleHeight: 50
)
loginButton.enabled = false
LoginTF.endEditing(true)
PasswordTF.endEditing(true)
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud?.labelText = "Login Request in Progress"
hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)!
httpsSession.login(LoginTF.text!, password: PasswordTF.text!){
(success: Bool, errorDescription:String) in
self.hud!.hide(true)
if(success)
{
if(self.SaveLP.on)
{
self.keychain.set(self.LoginTF.text!, forKey: "login");
self.keychain.set(self.PasswordTF.text!, forKey: "password");
}
else
{
self.keychain.delete("login")
self.keychain.delete("password");
}
self.performSegueWithIdentifier("loginSegue", sender: self)
}
else
{
let alertView = SCLAlertView(appearance: appearance)
alertView.showError("Login Error", subTitle: errorDescription)
self.loginButton.enabled = true
}
}
}
}
|
e9d3ce6e7cfd11799365df9b57e8af0c
| 30.479167 | 86 | 0.641518 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode
|
refs/heads/master
|
精通Swift设计模式/Chapter 16/Facade/Facade/Facade.swift
|
mit
|
1
|
import Foundation
enum TreasureTypes {
case SHIP; case BURIED; case SUNKEN;
}
class PirateFacade {
let map = TreasureMap();
let ship = PirateShip();
let crew = PirateCrew();
func getTreasure(type:TreasureTypes) -> Int? {
var prizeAmount:Int?;
// select the treasure type
var treasureMapType:TreasureMap.Treasures;
var crewWorkType:PirateCrew.Actions;
switch (type) {
case .SHIP:
treasureMapType = TreasureMap.Treasures.GALLEON;
crewWorkType = PirateCrew.Actions.ATTACK_SHIP;
case .BURIED:
treasureMapType = TreasureMap.Treasures.BURIED_GOLD;
crewWorkType = PirateCrew.Actions.DIG_FOR_GOLD;
case .SUNKEN:
treasureMapType = TreasureMap.Treasures.SUNKEN_JEWELS;
crewWorkType = PirateCrew.Actions.DIVE_FOR_JEWELS;
}
let treasureLocation = map.findTreasure(treasureMapType);
// convert from map to ship coordinates
let sequence:[Character] = ["A", "B", "C", "D", "E", "F", "G"];
let eastWestPos = find(sequence, treasureLocation.gridLetter);
let shipTarget = PirateShip.ShipLocation(NorthSouth:
Int(treasureLocation.gridNumber), EastWest: eastWestPos!);
let semaphore = dispatch_semaphore_create(0);
// relocate ship
ship.moveToLocation(shipTarget, callback: {location in
self.crew.performAction(crewWorkType, {prize in
prizeAmount = prize;
dispatch_semaphore_signal(semaphore);
});
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return prizeAmount;
}
}
|
e2f2bc6478323e77db599deff8043a29
| 32.358491 | 71 | 0.60181 | false | false | false | false |
Dreezydraig/actor-platform
|
refs/heads/master
|
actor-apps/app-ios/ActorApp/Controllers Support/EditTextController.swift
|
mit
|
34
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class EditTextController: AAViewController {
private var textView = UITextView()
private var completition: (String) -> ()
init(title: String, actionTitle: String, content: String, completition: (String) -> ()) {
self.completition = completition
super.init(nibName: nil, bundle: nil)
self.navigationItem.title = title
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: actionTitle, style: UIBarButtonItemStyle.Done, target: self, action: "doSave")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: localized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: "doCancel")
self.textView.text = content
self.textView.font = UIFont.systemFontOfSize(18)
self.view.backgroundColor = UIColor.whiteColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(textView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.textView.becomeFirstResponder()
}
func doSave() {
self.completition(textView.text)
self.dismissViewControllerAnimated(true, completion: nil)
}
func doCancel() {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.textView.frame = CGRectMake(7, 7, self.view.bounds.width - 14, self.view.bounds.height - 14)
}
}
|
c49017f1d726ae0caa8d676b31bdbd87
| 29.508475 | 170 | 0.647778 | false | false | false | false |
raphaelhanneken/iconizer
|
refs/heads/master
|
Iconizer/Helper/Asset/AssetSize.swift
|
mit
|
1
|
//
// AssetSize.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
import Foundation
struct AssetSize {
let string: String
let width: Float
let height: Float
/** Parse string like 50x45
* or 50.5x25.5
* ! 50.5.5x60.5.6 will not work
*/
init(size: String) throws {
let regex = "^([\\d\\.]+)x([\\d\\.]+)$"
if let expression = try? NSRegularExpression(pattern: regex) {
let range = NSRange(size.startIndex..<size.endIndex, in: size)
var widthResult: Float?
var heightResult: Float?
expression.enumerateMatches(in: size, options: [], range: range) { (match, _, stop) in
defer { stop.pointee = true }
guard let match = match else { return }
if match.numberOfRanges == 3,
let wRange = Range(match.range(at: 1), in: size),
let hRange = Range(match.range(at: 2), in: size) {
widthResult = Float(size[wRange])
heightResult = Float(size[hRange])
}
}
if let width = widthResult, let height = heightResult {
self.string = size
self.width = width
self.height = height
return
}
}
throw AssetCatalogError.invalidFormat(format: .size)
}
func multiply(_ scale: AssetScale) -> NSSize {
let width = Int(self.width * Float(scale.value))
let height = Int(self.height * Float(scale.value))
return NSSize(width: width, height: height)
}
}
|
50086a8da78d22c9046d774260dcf077
| 28.763636 | 98 | 0.532682 | false | false | false | false |
tilltue/TLPhotoPicker
|
refs/heads/master
|
TLPhotoPicker/Classes/TLBundle.swift
|
mit
|
1
|
//
// TLBundle.swift
// Pods
//
// Created by wade.hawk on 2017. 5. 9..
//
//
import UIKit
open class TLBundle {
open class func podBundleImage(named: String) -> UIImage? {
let podBundle = Bundle(for: TLBundle.self)
if let url = podBundle.url(forResource: "TLPhotoPickerController", withExtension: "bundle") {
let bundle = Bundle(url: url)
return UIImage(named: named, in: bundle, compatibleWith: nil)
}
return nil
}
class func bundle() -> Bundle {
let podBundle = Bundle(for: TLBundle.self)
if let url = podBundle.url(forResource: "TLPhotoPicker", withExtension: "bundle") {
let bundle = Bundle(url: url)
return bundle ?? podBundle
}
return podBundle
}
}
|
ed150af073829585cd943b70cd1f94ce
| 26.37931 | 101 | 0.595718 | false | false | false | false |
alexandreblin/ios-car-dashboard
|
refs/heads/master
|
CarDash/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// CarDash
//
// Created by Alexandre Blin on 12/06/2016.
// Copyright © 2016 Alexandre Blin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private var dashboardViewController: DashboardViewController? {
return self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController") as? DashboardViewController
}
var externalWindow: UIWindow?
var sleepPreventer: MMPDeepSleepPreventer {
return MMPDeepSleepPreventer()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
sleepPreventer.startPreventSleep()
// Register for connect/disconnect notifications
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.screenDidConnect(_:)), name: NSNotification.Name.UIScreenDidConnect, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.screenDidDisconnect(_:)), name: NSNotification.Name.UIScreenDidDisconnect, object: nil)
// Setup external screen if it's already connected when starting the app
if UIScreen.screens.count >= 2 {
setupScreen(UIScreen.screens[1])
}
return true
}
func setupScreen(_ screen: UIScreen) {
// Undocumented overscanCompensation value to disable it completely
screen.overscanCompensation = UIScreenOverscanCompensation(rawValue: 3)!
let window = UIWindow(frame: screen.bounds)
window.screen = screen
window.rootViewController = dashboardViewController
window.isHidden = false
window.makeKeyAndVisible()
externalWindow = window
}
func screenDidConnect(_ notification: Notification) {
guard let screen = notification.object as? UIScreen else {
return
}
if UIScreen.screens.index(of: screen) == 1 {
setupScreen(screen)
}
}
func screenDidDisconnect(_ notification: Notification) {
externalWindow?.isHidden = true
externalWindow = nil
}
}
|
6aff814ef933bb25fb97b9af231486af
| 32.279412 | 172 | 0.702607 | false | false | false | false |
darren90/Gankoo_Swift
|
refs/heads/master
|
Gankoo/Gankoo/Classes/Home/HomeViewController.swift
|
apache-2.0
|
1
|
//
// HomeViewController.swift
// Gankoo
//
// Created by Fengtf on 2017/2/7.
// Copyright © 2017年 ftf. All rights reserved.
//
import UIKit
import SafariServices
class HomeViewController: BaseViewController {
@IBOutlet weak var tableView: UITableView!
var getDate:Date = Date()
var dataArray:[DataListModel]? {
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
launchAnimation()
automaticallyAdjustsScrollViewInsets = false
tableView.separatorStyle = .none
//最底部的空间,设置距离底部的间距(autolayout),然后再设置这两个属性,就可以自动计算高度
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(self.loadNew))
tableView.mj_header = header
tableView.mj_header.beginRefreshing()
}
func loadNew() {
GankooApi.shareInstance.getHomeData(date:getDate) { ( result : [DataListModel]?, error : NSError?) in
self.endReresh()
if error == nil{
self.dataArray = result
}else{
}
}
}
func endReresh(){
self.tableView.mj_header.endRefreshing()
self.tableView.mj_header.isHidden = true
// self.tableView.mj_footer.endRefreshing()
}
@IBAction func dateAction(_ sender: UIBarButtonItem) {
datePickAction()
}
func datePickAction() {
let current = Date()
let min = Date().addingTimeInterval(-60 * 60 * 24 * 15)
let max = Date().addingTimeInterval(60 * 60 * 24 * 15)
let picker = DateTimePicker.show(selected: current, minimumDate: min, maximumDate: max)
picker.highlightColor = UIColor(red: 255.0/255.0, green: 138.0/255.0, blue: 138.0/255.0, alpha: 1)
picker.doneButtonTitle = "!! DONE DONE !!"
picker.todayButtonTitle = "Today"
picker.completionHandler = { date in
// self.current = date
self.getDate = date
self.loadNew()
}
}
}
extension HomeViewController : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
noDataView.isHidden = !(dataArray?.count == 0)
return dataArray?.count ?? 0;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let array = dataArray?[section].dataArray
return array?.count ?? 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = DataSectionHeaderView.headerWithTableView(tableView: tableView)
let listModel = dataArray?[section]
header.title = listModel?.name
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0000001
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = DataListCell.cellWithTableView(tableView: tableView)
let listModel = dataArray?[indexPath.section]
let model = listModel?.dataArray?[indexPath.row]
cell.model = model
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let listModel = dataArray?[indexPath.section]
let model = listModel?.dataArray?[indexPath.row]
guard let urlStr = model?.url else {
return
}
let url = URL(string: urlStr)
let vc = DataDetailController(url: url!, entersReaderIfAvailable: true)
vc.model = model
present(vc, animated: true, completion: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension HomeViewController {
//播放启动画面动画
func launchAnimation() {
//获取启动视图
let vc = UIStoryboard(name: "LaunchScreen", bundle: nil)
.instantiateViewController(withIdentifier: "launch")
let launchview = vc.view!
let delegate = UIApplication.shared.delegate
delegate?.window!!.addSubview(launchview)
//self.view.addSubview(launchview) //如果没有导航栏,直接添加到当前的view即可
//播放动画效果,完毕后将其移除
UIView.animate(withDuration: 1, delay: 1.2, options: .curveLinear,
animations: {
launchview.alpha = 0.0
let transform = CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1.0)
launchview.layer.transform = transform
}) { (finished) in
launchview.removeFromSuperview()
}
}
}
|
f0bc2e6ff9038fdc0aeccc2459885f52
| 30.56129 | 109 | 0.623671 | false | false | false | false |
SioJL13/tec_ios
|
refs/heads/master
|
Serie_numeros.playground/Contents.swift
|
gpl-2.0
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var numeros = 0...100
for n in numeros{
//Div 5, par y rango
if n%5 == 0 && n%2==0 && n>=30 && n<=40{
println("\(n) Bingo, #par, Viva Swift")
}
//Div 5, impar y rango
if n%5 == 0 && n%2 != 0 && n>=30 && n<=40{
println("\(n) Bingo, #impar, Viva Swift")
}
//Div 5 y par
else if n%5 == 0 && n%2==0{
println("\(n) Bingo y #par ")
}
//Div 5 e impar
else if n%5 == 0 && n%2 != 0{
println("\(n) Bingo e #impar")
}
//Par
else if n%2 == 0{
println("\(n) #par")
}
//Impar
else if n%2 != 0{
println("\(n) #impar")
}
//Rango
else if n>30 && n<40{
println("\(n) Viva swift")
}
}
|
875b10121e8660722dabbe7626f3e38e
| 20.081081 | 52 | 0.44359 | false | false | false | false |
kazarus/OcPack
|
refs/heads/master
|
Sources/NetClient.swift
|
mit
|
1
|
//
// NetEngine.swift
// example10014
//
// Created by kazarus on 7/19/16.
// Copyright © 2016 kazarus. All rights reserved.
//
import Foundation
enum THttpMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
class TNetClient:NSObject,URLSessionDelegate{
private let baseURL: String
/*
func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let credential = URLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(URLSession.AuthChallengeDisposition.UseCredential, credential)
}
}
*/
public init(baseURL: String) {
self.baseURL = baseURL
}
public func run(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){
let session = URLSession.shared
//var request = NSMutableURLRequest(url:URL(string:target)!)
var request = URLRequest(url:URL(string:target)!)
request.httpMethod=method.rawValue
if params.count>0{
} else{
}
/*
let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
callback(data,response,error)
})
*/
let task = session.dataTask(with: request){
(data,response,error) in
DispatchQueue.main.async {
completionHandler(data,response,error)
}
}
task.resume()
}
public func mul(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){
//#let session = URLSession.shared
let session = URLSession(configuration:URLSession.shared.configuration,delegate:self,delegateQueue:URLSession.shared.delegateQueue)
//#let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue))
//#print(charset as Any)
var request = URLRequest(url:URL(string:self.baseURL+target)!)
request.httpMethod=method.rawValue;
//var request = URLRequest(url:URL(string:target)!)
//#request.httpMethod=method.rawValue
//request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
var para = ""
for item in params {
para = item.key+"="+(item.value as! String)
}
print(para)
request.httpBody = para.data(using: String.Encoding.utf8)//; charset=\(charset)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//#request.addValue("application/json;text/html", forHTTPHeaderField: "Content-Type")
//#request.addValue("application/json", forHTTPHeaderField: "Accept")
//#request.addValue("\(paramsData.count)", forHTTPHeaderField: "Content-Length")
//#request.addValue("192.168.0.3", forHTTPHeaderField: "Host")
let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
DispatchQueue.main.async {
completionHandler(data,response,error)
}
})
task.resume()
}
static func joinPath(with path:String)->String{
let result = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]+"/"+path
return result
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
}
|
1093002b971f140e80942b403526ce70
| 35.087302 | 222 | 0.638223 | false | false | false | false |
mlilback/MessagePackSwift
|
refs/heads/master
|
MessagePackSwift/MessageValue.swift
|
isc
|
1
|
//
// MessageValue.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
public class MessageValueArray: NSObject {
let array:[MessageValue]
///creates a wrapper around inArray
public init(_ inArray:[MessageValue]) {
array = inArray
}
///creates a new array converting each value in nativeArray to an appropriate MessageValue
public init(nativeArray:[AnyObject]) {
array = nativeArray.map() { MessageValue.forValue($0) }
}
override public func isEqual(object: AnyObject?) -> Bool {
guard let other = object as? MessageValueArray else { return false }
if array.count != other.array.count { return false }
if array.dynamicType != other.array.dynamicType { return false }
if array.count < 1 { return true }
for i in 0..<array.count {
if array[i] != other.array[i] { return false }
}
return true
}
public func nativeValue() -> [AnyObject] {
return array.map() { $0.nativeValue() }
}
}
public class MessageValueDictionary: NSObject {
let dict:[String:MessageValue]
///creates a wrapper around inDict
public init(_ inDict:[String:MessageValue]) {
self.dict = inDict
}
///creates a new dictionary converting each value in nativeDict to an appropriate MessageValue
public init(nativeDict:[String:AnyObject]) {
var converted = [String:MessageValue]()
for aKey in nativeDict.keys {
let aValue = MessageValue.forValue(nativeDict[aKey]!)
converted[aKey] = aValue
}
dict = converted
}
public func nativeValue() -> [String:AnyObject] {
var nativeDict = [String:AnyObject]()
for aKey in dict.keys {
let aValue = dict[aKey]!.nativeValue()
nativeDict[aKey] = aValue
}
return nativeDict
}
override public func isEqual(object: AnyObject?) -> Bool {
guard let other = object as? MessageValueDictionary else { return false }
guard dict.count == other.dict.count else { return false }
for aKey in dict.keys {
if dict[aKey] != other.dict[aKey] { return false }
}
return true
}
}
public enum MessageValue: Equatable {
case NilValue
case BooleanValue(Bool)
///on 64-bit platforms, this is returned for all int/uint values except 64 bit uints which are returned as UInt
case IntValue(Int)
///this is only returned for 64-bit uints. all others can fit in range of Int
case UIntValue(UInt)
case FloatValue(Float)
case DoubleValue(Double)
case StringValue(String)
case BinaryValue(NSData)
case ExtValue(NSData)
case ArrayValue(MessageValueArray)
case DictionaryValue(MessageValueDictionary)
static public func forValue(value:AnyObject) -> MessageValue {
switch(value) {
case is NSNull:
return .NilValue
//due to foundation, this case will catch anything that can be represented by NSNumber
//likely only need one of the tests, but doesn't hurt to add them all
case is NSNumber:
return forNumericValue(value as! NSNumber)
case is String:
return .StringValue(value as! String)
case is NSData:
return .BinaryValue(value as! NSData)
case is MessageValueArray:
return .ArrayValue(value as! MessageValueArray)
case is Array<AnyObject>:
return .ArrayValue(MessageValueArray(nativeArray: value as! Array<AnyObject>))
case is MessageValueDictionary:
return .DictionaryValue(value as! MessageValueDictionary)
case is Dictionary<String,AnyObject>:
return .DictionaryValue(MessageValueDictionary(nativeDict: value as! Dictionary<String,AnyObject>))
default: fatalError("\(value) cannot be converted to a MessageValue")
}
}
static public func forNumericValue(value:NSNumber) -> MessageValue {
if value === kCFBooleanTrue { return .BooleanValue(true) }
if value === kCFBooleanFalse { return .BooleanValue(false) }
let type = String.fromCString(value.objCType)!
if type == "Q" { return .UIntValue(UInt(value.unsignedLongLongValue)) }
return .IntValue(Int(value))
}
static public func forValue(dict:[String:MessageValue]) -> MessageValue {
return .DictionaryValue(MessageValueDictionary(dict))
}
static public func forValue(value:[MessageValue]) -> MessageValue {
return .ArrayValue(MessageValueArray(value))
}
public func nativeValue() -> AnyObject {
switch(self) {
case .NilValue:
return NSNull()
case .BooleanValue(let bval):
return bval
case .StringValue(let sval):
return sval
case .IntValue(let ival):
return ival
case .UIntValue(let u64val):
return u64val
case .BinaryValue(let data):
return data
case .ExtValue(let ext):
return ext
case .FloatValue(let fval):
return fval
case .DoubleValue(let dval):
return dval
case .ArrayValue(let arrayvalue):
// return arrayvalue
return arrayvalue.nativeValue()
case .DictionaryValue(let dict):
return dict.nativeValue()
}
}
var nilValue:NSNull? {
if case MessageValue.NilValue = self { return NSNull() }
return nil
}
var booleanValue:Bool? {
if case MessageValue.BooleanValue(let bval) = self { return bval }
return nil
}
var floatValue:Float? {
if case MessageValue.FloatValue(let val) = self { return val }
return nil
}
var doubleValue:Double? {
if case MessageValue.DoubleValue(let val) = self { return val }
return nil
}
var intValue:Int? {
if case MessageValue.IntValue(let val) = self { return val }
return nil
}
var uintValue:UInt? {
if case MessageValue.UIntValue(let val) = self { return val }
return nil
}
var stringValue:String? {
if case MessageValue.StringValue(let val) = self { return val }
return nil
}
var binaryValue:NSData? {
if case MessageValue.BinaryValue(let val) = self { return val }
return nil
}
var arrayValue:MessageValueArray? {
if case MessageValue.ArrayValue(let val) = self { return val }
return nil
}
var dictionaryValue:MessageValueDictionary? {
if case MessageValue.DictionaryValue(let val) = self { return val }
return nil
}
var nativeDictionaryValue:[String:AnyObject]? {
if case MessageValue.DictionaryValue(let val) = self { return val.nativeValue() }
return nil
}
}
public func ==(lhs:MessageValue, rhs:MessageValue) -> Bool {
switch(lhs, rhs) {
case (.BooleanValue(let a), .BooleanValue(let b)): return a == b
case (.NilValue, .NilValue): return true
case (.IntValue(let a), .IntValue(let b)): return a == b
case (.UIntValue(let a), .UIntValue(let b)): return a == b
case (.StringValue(let a), .StringValue(let b)): return a == b
case (.BinaryValue(let a), .BinaryValue(let b)): return a == b
case (.FloatValue(let a), .FloatValue(let b)): return a == b
case (.DoubleValue(let a), .DoubleValue(let b)): return a == b
case (.ArrayValue(let a), .ArrayValue(let b)): return a == b
case (.DictionaryValue(let a), .DictionaryValue(let b)): return a == b
case (.ExtValue(let a), .ExtValue(let b)): return a == b
default: return false
}
}
public enum MessagePackError: Int, ErrorType {
case InvalidBinaryData
case UnsupportedDictionaryKey
case NoMoreData
}
|
429932c63b61c8367aac46bb014bca68
| 28.164557 | 112 | 0.716869 | false | false | false | false |
pyanfield/ataturk_olympic
|
refs/heads/master
|
swift_programming_properties_methods.playground/section-1.swift
|
mit
|
1
|
// Playground - noun: a place where people can play
import UIKit
// 2.10
// 由于结构体(struct)属于值类型。当值类型的实例被声明为常量的时候,它的所有属性也就成了常量。
// 引用类型的类(class)则不一样,把一个引用类型的实例赋给一个常量后,仍然可以修改实例的变量属性。
// 延迟存储属性
// 延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性。在属性声明前使用 lazy 来标示一个延迟存储属性。
// 必须将延迟存储属性声明成变量(使用 var 关键字),因为属性的值在实例构造完成之前可能无法得到。
// 而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。
// 延迟属性很有用,当属性的值依赖于在实例的构造过程结束前无法知道具体值的外部因素时,或者当属性的值需要复杂或大量计算时,可以只在需要的时候来计算它。
// 因为对于某些诸如导入文件等消耗时间的操作,可以将其声明为 lazy 属性,这样只有在用的时候再去实例化。
class DataImporter {
/*
DataImporter 是一个将外部文件中的数据导入的类。
这个类的初始化会消耗不少时间。
*/
var fileName = "data.txt"
// 这是提供数据导入功能
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// 这是提供数据管理功能
}
let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
// DataImporter 实例的 importer 属性还没有被创建
println(manager.importer.fileName)
// DataImporter 实例的 importer 属性现在被创建了
// 输出 "data.txt”
// 计算属性
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) { // 如果不设置 newCenter,将自动使用 newValue 作为设置的新值的参数名
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
println("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// 只读计算属性
// 只有 getter 没有 setter 的计算属性就是只读计算属性。只读计算属性总是返回一个值,可以通过点运算符访问,但不能设置新的值。
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
// 只读属性,可以省略 get 关键字和花括号
var volume: Double {
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// 属性观察器
// 属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。
// willSet 在设置新的值之前调用
// didSet 在新的值被设置之后立即调用, 如果在didSet观察器里为属性赋值,这个值会替换观察器之前设置的值。
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) { // 如果不设置参数名,则默认是 newValue
println("About to set totalSteps to \(newTotalSteps)")
}
didSet { // 可以自定义参数名称,如果不设置参数名,则默认是 oldValue
if totalSteps > oldValue {
println("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
stepCounter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
// 计算属性和属性观察器所描述的模式也可以用于全局变量和局部变量.
// 全局的常量或变量都是延迟计算的,跟延迟存储属性相似,不同的地方在于,全局的常量或变量不需要标记lazy特性。
// 局部范围的常量或变量不会延迟计算。
// 类型属性
// 类型属性用于定义特定类型所有实例共享的数据,比如所有实例都能用的一个常量(就像 C 语言中的静态常量),或者所有实例都能访问的一个变量(就像 C 语言中的静态变量)。
// 使用关键字static来定义值类型的类型属性,关键字class来为类(class)定义类型属性。
struct SomeStructure {
// 对于 struct , enum 这样值类型的,可以定义存储型,也可以是计算类型属性
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int{
return 999
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty = 2
}
class SomeClass {
// 对于类,只能定义计算类型属性
class var computedTypeProperty: Int{
return 999
}
}
SomeClass.computedTypeProperty
SomeEnumeration.storedTypeProperty
SomeStructure.computedTypeProperty
// 2.11
class Counter {
var count: Int = 0
// 默认第二个参数如果没有设置外部参数名,则外部参数名和内部参数名一致,类似默认条件了 #
func incrementBy(amount: Int, numberOfTimes: Int) {
// 该处可以使用 self.count, 如果参数名中有 count ,则必须使用 self.count
count += amount * numberOfTimes
}
// 设置外部参数名给第二个参数
// 默认调用的时候可以省略第一参数名
func add(number: Int, toNumber number2: Int) -> Int{
return number + number2
}
// 强制第一个参数名内外一致, 第二个参数省略参数名
func subduction(#number:Int, _ second:Int) -> Int{
return number - second
}
}
let counter = Counter()
counter.incrementBy(10, numberOfTimes: 2)
counter.count
counter.add(10, toNumber: 10)
counter.subduction(number: 10, 10)
// 结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改。
// 如果你确实需要在某个具体的方法中修改结构体或者枚举的属性,你可以选择变异(mutating)这个方法,然后方法就可以从方法内部改变它的属性
struct MutablePoint {
var x = 0.0, y = 0.0
// 注意这里用 mutating 来修饰
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
mutating func moveBackBy(deltaX: Double, deltaY: Double){
// mutating 方法能赋值给隐含属性 self 一个全新的实例
self = MutablePoint(x: x-deltaX, y: y-deltaY)
}
}
var somePoint = MutablePoint(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
println("The point is now at (\(somePoint.x), \(somePoint.y))")
somePoint.moveBackBy(1.0, deltaY: 1.0)
println("The point is now at (\(somePoint.x), \(somePoint.y))")
enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight 现在等于 .High
ovenLight.next()
// ovenLight 现在等于 .Off
// 类型方法(Type Methods)
// 声明类的类型方法,在方法的func关键字之前加上关键字class;声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static。
class SomeClassA {
class func someTypeMethod() {
println("called from class method")
}
}
SomeClassA.someTypeMethod()
// 游戏初始时,所有的游戏等级(除了等级 1)都被锁定。每次有玩家完成一个等级,这个等级就对这个设备上的所有玩家解锁。
// 同时检测玩家的当前等级。
struct LevelTracker {
static var highestUnlockedLevel = 1
// 类型方法
static func unlockLevel(level: Int) {
if level > highestUnlockedLevel {
// bug here: 在 playground 中,如果直接给 highestUnlockedLevel = level ,会报错 EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
// 但是如果在 Application 中就不会有这个错误
LevelTracker.highestUnlockedLevel = level
}
}
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level: Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
// 注意这里是 let 定义的常量,在 init 初始化的时候可以设置初始值,之后就不能改变了。
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level + 1)
tracker.advanceToLevel(level + 1)
}
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios")
player.completedLevel(2)
player.playerName
//println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
|
aaab314c592cdd034f03711faf340bca
| 26.808765 | 117 | 0.663037 | false | false | false | false |
codwam/NPB
|
refs/heads/master
|
Demos/SystemDemo/SystemDemo/Custom Test/TestPopAnimation.swift
|
mit
|
1
|
//
// TestPopAnimation.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/7.
// Copyright © 2017年 codwam. All rights reserved.
//
import UIKit
/*
Copy From https://github.com/zys456465111/CustomPopAnimation
里面写得很详细,不清楚的可以看里面的源码
*/
enum PopAnimationType {
case pop
case flipFromLeft
case cube
}
class TestPopAnimation: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate var transitionContext: UIViewControllerContextTransitioning?
fileprivate let popAnimationType: PopAnimationType = .pop
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)!
let toViewController = transitionContext.viewController(forKey: .to)!
let containerView = transitionContext.containerView
containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)
// 动画时间
let duration = transitionDuration(using: transitionContext)
self.transitionContext = transitionContext
switch self.popAnimationType {
case .pop:
// 模仿系统pop
UIView.animate(withDuration: duration, animations: {
let x = fromViewController.view.bounds.width
let transform = CGAffineTransform(translationX: x, y: 0)
fromViewController.view.transform = transform
// 实际上系统的左边还有点偏移
// let toTransform = CGAffineTransform(translationX: -20, y: 0)
// toViewController.view.transform = toTransform
}) { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
// toViewController.view.transform = .identity
}
case .flipFromLeft:
//----------------pop动画一-------------------------//
UIView.beginAnimations("View Flip", context: nil)
UIView.setAnimationDuration(duration)
UIView.setAnimationTransition(.flipFromLeft, for: containerView, cache: true)
UIView.setAnimationDelegate(self)
UIView.setAnimationDidStop(#selector(TestPopAnimation.animationDidStop(_:finished:)))
UIView.commitAnimations()
containerView.exchangeSubview(at: 0, withSubviewAt: 1)
case .cube:
//----------------pop动画二-------------------------//
let transition = CATransition()
transition.type = "cube"
transition.subtype = kCATransitionFromLeft
transition.duration = duration
transition.isRemovedOnCompletion = false
transition.fillMode = kCAFillModeForwards
transition.delegate = self
containerView.layer.add(transition, forKey: nil)
containerView.exchangeSubview(at: 0, withSubviewAt: 1)
}
}
}
extension TestPopAnimation: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if let transitionContext = self.transitionContext {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
|
c89730549e308cd78e0f8528e485016b
| 38.034483 | 109 | 0.655183 | false | false | false | false |
Quick/Spry
|
refs/heads/master
|
Source/Spry/Matchers/beginWith.swift
|
apache-2.0
|
1
|
import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith<S: Sequence, T: Equatable>(_ startingElement: T) -> Matcher<S>
where S.Iterator.Element == T {
return Matcher { actualExpression in
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return actualGenerator.next() == startingElement
}
return false
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(_ startingSubstring: String) -> Matcher<String> {
return Matcher { actualExpression in
if let actual = try actualExpression.evaluate() {
let range = actual.range(of: startingSubstring)
return range != nil && range!.lowerBound == actual.startIndex
}
return false
}
}
|
c7fd85b1ac23e372349693d0026b0bbc
| 37.148148 | 85 | 0.659223 | false | false | false | false |
LDlalala/LDZBLiving
|
refs/heads/master
|
LDZBLiving/LDZBLiving/Classes/Main/LDPageView/LDContentView.swift
|
mit
|
1
|
//
// LDContentView.swift
// LDPageView
//
// Created by 李丹 on 17/8/2.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
private let cellID : String = "cellID"
protocol LDContentViewDelegate : class {
func contentView(_ contentView : LDContentView, targetIndex : Int, progress : CGFloat)
}
class LDContentView: UIView {
weak var delegate : LDContentViewDelegate?
fileprivate var childVcs : [UIViewController]!
fileprivate var parent : UIViewController!
fileprivate var startOffsetX : CGFloat = 0
fileprivate lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: self.bounds.width, height: self.bounds.height)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.scrollsToTop = false
return collectionView
}()
init(frame : CGRect , childVcs : [UIViewController] , parent : UIViewController) {
super.init(frame: frame)
self.childVcs = childVcs
self.parent = parent
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LDContentView {
fileprivate func setupUI(){
for vc in childVcs {
parent.addChildViewController(vc)
}
// 添加conllection
addSubview(collectionView)
}
}
// MARK:- UICollectionViewDataSource
extension LDContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
cell.backgroundColor = UIColor.randomColor()
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
let childVc = childVcs[indexPath.row]
childVc.view.frame = cell.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- UICollectionViewDelegate
extension LDContentView : UICollectionViewDelegate {
// 开始拖拽
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffsetX = scrollView.contentOffset.x
}
// 停止滚动
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollEnd(scrollView)
}
// 手动拖拽时停止
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {
scrollEnd(scrollView)
}
}
// 滚动停止的事件处理
private func scrollEnd(_ scrollView : UIScrollView){
// 记录偏移量
let offsetX = scrollView.contentOffset.x - startOffsetX
let targetIndex = scrollView.contentOffset.x / bounds.width
// 通知titleview做点击选中处理
delegate?.contentView(self, targetIndex: Int(targetIndex), progress: offsetX)
}
}
// MARK:- 实现titleView的代理方法
extension LDContentView : LDTitleViewDelegate{
func titleView(_ titleView : LDTitleView, targetIndex : Int) {
let indexPath = IndexPath.init(row: targetIndex, section: 0)
collectionView.scrollToItem(at: indexPath, at: .right, animated: false)
}
}
|
a27a60c959974d1ced55b096a3a21a13
| 28.15942 | 121 | 0.66327 | false | false | false | false |
netguru/inbbbox-ios
|
refs/heads/develop
|
Unit Tests/AutoScrollableShotsAnimatorSpec.swift
|
gpl-3.0
|
1
|
//
// AutoScrollableShotsAnimatorSpec.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 31/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
@testable import Inbbbox
class AutoScrollableShotsAnimatorSpec: QuickSpec {
override func spec() {
var sut: AutoScrollableShotsAnimator!
var collectionViews: [UICollectionView]! // keep reference to be able to check expectation
let content = [
UIImage.referenceImageWithColor(.green),
UIImage.referenceImageWithColor(.yellow),
UIImage.referenceImageWithColor(.red)
]
var mockSuperview: UIView!
beforeEach {
let collectionView_1 = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout())
let collectionView_2 = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout())
collectionViews = [collectionView_1, collectionView_2]
let bindForAnimation = collectionViews.map {
(collectionView: $0, shots: content)
}
mockSuperview = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
mockSuperview.addSubview(collectionView_1)
mockSuperview.addSubview(collectionView_2)
sut = AutoScrollableShotsAnimator(bindForAnimation: bindForAnimation)
}
afterEach {
sut = nil
collectionViews = nil
mockSuperview = nil
}
it("when newly created, content offset should be 0") {
expect(collectionViews.map{ $0.contentOffset }).to(equal([CGPoint.zero, CGPoint.zero]))
}
describe("when scrolling to middle") {
beforeEach {
sut.scrollToMiddleInstantly()
}
it("collection views should be in the middle") {
let middlePoint = CGPoint(x: 0, y: -100)
expect(collectionViews.map{ $0.contentOffset }).to(equal([middlePoint, middlePoint]))
}
}
describe("when performing scroll animation") {
afterEach {
sut.stopAnimation()
}
context("first collection view") {
var initialValueY: CGFloat!
beforeEach {
initialValueY = collectionViews[0].contentOffset.y
sut.startScrollAnimationInfinitely()
RunLoop.current.run(until: NSDate() as Date)
}
it("should be scrolled up") {
expect(collectionViews[0].contentOffset.y).toEventually(beGreaterThan(initialValueY))
}
}
context("collection view") {
var initialValueY: CGFloat!
beforeEach {
initialValueY = collectionViews[1].contentOffset.y
sut.startScrollAnimationInfinitely()
RunLoop.current.run(until: NSDate() as Date)
}
it("should be scrolled down") {
expect(collectionViews[1].contentOffset.y).toEventually(beLessThan(initialValueY))
}
}
context("and stopping it") {
beforeEach {
sut.stopAnimation()
}
context("first collection view") {
var initialValueY: CGFloat!
beforeEach {
initialValueY = collectionViews[0].contentOffset.y
}
it("first collection view should be in same place") {
expect(collectionViews[0].contentOffset.y).toEventually(equal(initialValueY))
}
}
context("second collection view") {
var initialValueY: CGFloat!
beforeEach {
initialValueY = collectionViews[1].contentOffset.y
}
it("first collection view should be in same place") {
expect(collectionViews[1].contentOffset.y).toEventually(equal(initialValueY))
}
}
}
}
}
}
|
0003c5f52118619525eaa3da256155ef
| 34.644444 | 155 | 0.497091 | false | false | false | false |
jorjuela33/JOCoreDataKit
|
refs/heads/master
|
JOCoreDataKit/Extensions/NSPersistentStoreCoordinator+Additions.swift
|
mit
|
1
|
//
// NSPersistentStoreCoordinator+Additions.swift
//
// Copyright © 2017. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreData
extension NSPersistentStoreCoordinator {
// MARK: Instance methods
/// creates a new store
///
/// url - the location for the store
/// type - the store type
@discardableResult
public func createPersistentStore(atURL url: URL?, type: String = NSSQLiteStoreType) -> Error? {
var error: Error?
do {
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
try addPersistentStore(ofType: type, configurationName: nil, at: url, options: options)
}
catch let storeError {
error = storeError
}
return error
}
/// destroy the persistent store for the given context
///
/// url - the url for the store location
/// type - the store type
public func destroyPersistentStore(atURL url: URL, type: String = NSSQLiteStoreType) {
do {
if #available(iOS 9.0, *) {
try destroyPersistentStore(at: url, ofType: type, options: nil)
}
else if let persistentStore = persistentStores.last {
try remove(persistentStore)
try FileManager.default.removeItem(at: url)
}
}
catch {
print("unable to destroy perstistent store at url: \(url), type: \(type)")
}
}
/// migrates the current store to the given url
///
/// url - the new location for the store
public func migrate(to url: URL) {
guard let currentStore = persistentStores.last else { return }
try! migratePersistentStore(currentStore, to: url, options: nil, withType: NSSQLiteStoreType)
}
}
|
2522ff002fdaa8d0489d6e35465f8cb7
| 38.2 | 124 | 0.662245 | false | false | false | false |
SASAbus/SASAbus-ios
|
refs/heads/master
|
SASAbus/Data/Vdv/DataDownloader.swift
|
gpl-3.0
|
1
|
import Foundation
import RxSwift
import RxCocoa
import Alamofire
class DataDownloader {
static let FILENAME_OFFLINE = "data.zip"
static func downloadFile(destinationUrl: URL) -> Observable<Float> {
return Observable.create { observer in
Log.debug("Downloading planned data to \(destinationUrl)")
let fileManager = FileManager.default
// Delete old files
let dataDirectory = IOUtils.dataDir()
if fileManager.fileExists(atPath: dataDirectory.path) {
do {
try fileManager.removeItem(at: dataDirectory)
Log.warning("Deleted old data directory")
} catch let error {
ErrorHelper.log(error, message: "Could not delete old data directory: \(error)")
}
}
if fileManager.fileExists(atPath: destinationUrl.path) {
do {
try fileManager.removeItem(at: destinationUrl)
Log.warning("Deleted old data.zip")
} catch let error {
ErrorHelper.log(error, message: "Could not delete data.zip: \(error)")
}
}
// Download new planned data
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
return (destinationUrl, [.removePreviousFile, .createIntermediateDirectories])
}
let progress: Alamofire.Request.ProgressHandler = { progress in
observer.on(.next(Float(progress.fractionCompleted)))
}
let zipUrl = Endpoint.newDataApiUrl
Log.info("Data url is '\(zipUrl)'")
// Download new data
let request = Alamofire.download(zipUrl, to: destination)
.downloadProgress(queue: DispatchQueue.main, closure: progress)
.response(queue: DispatchQueue(label: "com.sasabus.download", qos: .utility, attributes: [.concurrent])) { response in
if let error = response.error {
observer.on(.error(error))
return
}
do {
Log.info("Unzipping zip file '\(destination)'")
try ZipUtils.unzipFile(from: destinationUrl, to: IOUtils.dataDir())
let fileManager = FileManager.default
try fileManager.removeItem(atPath: destinationUrl.path)
} catch {
observer.on(.error(error))
return
}
PlannedData.dataAvailable = true
PlannedData.setUpdateAvailable(false)
PlannedData.setUpdateDate()
do {
try VdvHandler.loadBlocking(observer)
} catch {
observer.on(.error(error))
return
}
observer.on(.completed)
}
return Disposables.create {
request.cancel()
}
}
}
static func downloadPlanData() -> Observable<Float> {
Log.warning("Starting plan data download")
let baseUrl = IOUtils.storageDir()
let destinationUrl = baseUrl.appendingPathComponent(FILENAME_OFFLINE)
return downloadFile(destinationUrl: destinationUrl)
}
}
|
ab8b048476603e0fc2a2f5dd23012bc9
| 35.823529 | 134 | 0.492545 | false | false | false | false |
iachievedit/moreswift
|
refs/heads/master
|
foundation/notification.swift
|
apache-2.0
|
1
|
import Foundation
import Glibc
let inputNotificationName = Notification.Name(rawValue:"InputNotification")
let inputNotification = Notification(name:inputNotificationName, object:nil)
let nc = NotificationCenter.default
var availableData = ""
let readThread = Thread(){
print("Entering thread... type something and have it echoed.")
let delim:Character = "\n"
var input:String = ""
while true {
let c = Character(UnicodeScalar(UInt32(fgetc(stdin)))!)
if c == delim {
availableData = input
nc.post(inputNotification)
input = ""
} else {
input.append(c)
}
}
// Our read thread never exits
}
_ = nc.addObserver(forName:inputNotificationName, object:nil, queue:nil) {
(_) in
print("Echo: \(availableData)")
}
readThread.start()
select(0, nil, nil, nil, nil) // Forever sleep
|
efd57d6d322e8e22e9f050b9bb64ec49
| 24.333333 | 76 | 0.686603 | false | false | false | false |
elliottminns/blackfire
|
refs/heads/master
|
Sources/Blackfire/RequestHandler.swift
|
apache-2.0
|
2
|
//
// RequestHandler.swift
// Blackfire
//
// Created by Elliott Minns on 20/01/2017.
//
//
import Foundation
struct RequestHandler {
let nodes: [Node]
init(nodes: [Node]) {
self.nodes = nodes
}
func handle(request: HTTPRequest, response: HTTPResponse) {
let handlers = nodes.last?.handlers[request.method] ?? []
guard handlers.count > 0 else {
response.send(status: 404)
return
}
/*
let comps = request.path.components(separatedBy: "/")
let params = self.nodes.reduce((0, [:])) { (result, node) -> (Int, [String: String]) in
if !node.path.isEmpty && node.path[node.path.startIndex] == ":" {
let key = node.path.substring(from: node.path.index(after: node.path.startIndex))
let value = comps[result.0]
return (result.0 + 1, [key: value])
} else {
return (result.0 + 1, result.1)
}
}.1
*/
let params: [String: String] = [:]
let request = Request(params: params, raw: request)
handlers.forEach { handler in
handler(request, response)
}
}
}
|
859bf2bafff6aa152bb891d2106c872b
| 24.116279 | 91 | 0.597222 | false | false | false | false |
uvitar/EMSProject
|
refs/heads/master
|
OpenEmsConnectorTests/OpenEmsConnectorTests.swift
|
gpl-3.0
|
2
|
//
// OpenEmsConnectorTests.swift
// OpenEmsConnectorTests
//
// Created by steff3 on 02/09/16.
// Copyright © 2016 touchLOGIE. All rights reserved.
//
import XCTest
@testable import OpenEmsConnector
class OpenEmsConnectorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testMessage() {
let mess1 = OpenEmsHelper.constructMessage(channel: 0, intensity: 85, onTime: 100)
let mess2 = OpenEmsHelper.constructMessage(channel: 1, intensity: 50, onTime: 100)
let mess3 = OpenEmsHelper.constructMessage(channel: 4, intensity: 150, onTime: 10000)
XCTAssertTrue(mess1.payload == "C0I85T100G")
XCTAssertTrue(mess2.payload == "C1I50T100G")
XCTAssertTrue(mess3.payload == "C1I100T1000G")
}
func testDescriptorCheckPasses() {
XCTAssertTrue(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5365-7276-6963652D424C4531",
descriptor: OpenEmsConstants.serviceDescriptor))
XCTAssertTrue(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5374-6575-6572756E672D4348",
descriptor: OpenEmsConstants.characteristicDescriptor))
}
func testDescriptorCheckFails() {
XCTAssertFalse(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5365-7276-6963652D424C4531",
descriptor: OpenEmsConstants.characteristicDescriptor))
XCTAssertFalse(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5374-6575-6572756E672D4348",
descriptor: OpenEmsConstants.serviceDescriptor))
}
}
|
82420f502f25e790bcdefaf3ad46b47f
| 37.301587 | 111 | 0.628678 | false | true | false | false |
spire-inc/JustLog
|
refs/heads/master
|
JustLog/Extensions/Dictionary+Flattening.swift
|
apache-2.0
|
1
|
//
// Dictionary+Flattening.swift
// JustLog
//
// Created by Alberto De Bortoli on 15/12/2016.
// Copyright © 2017 Just Eat. All rights reserved.
//
import Foundation
extension Dictionary {
mutating func merge(with dictionary: Dictionary) {
dictionary.forEach { _ = updateValue($1, forKey: $0) }
}
func merged(with dictionary: Dictionary) -> Dictionary {
var dict = self
dict.merge(with: dictionary)
return dict
}
func flattened() -> [String : Any] {
var retVal = [String : Any]()
for (k, v) in self {
switch v {
case is String:
retVal.updateValue(v, forKey: k as! String)
case is Int:
retVal.updateValue(v, forKey: k as! String)
case is Double:
retVal.updateValue(v, forKey: k as! String)
case is Bool:
retVal.updateValue(v, forKey: k as! String)
case is Dictionary:
let inner = (v as! [String : Any]).flattened()
retVal = retVal.merged(with: inner)
case is Array<Any>:
retVal.updateValue(String(describing: v), forKey: k as! String)
case is NSError:
let inner = (v as! NSError)
retVal = retVal.merged(with: inner.userInfo.flattened())
default:
continue
}
}
return retVal
}
}
|
c37c63a9bde1184c644cd379517f91f1
| 27.132075 | 79 | 0.519115 | false | false | false | false |
wangyaqing/LeetCode-swift
|
refs/heads/master
|
Solutions/12. Integer to Roman.playground/Contents.swift
|
mit
|
1
|
import UIKit
class Solution {
func intToRoman(_ num: Int) -> String {
if num >= 1000 {
return "M"+intToRoman(num-1000)
} else if num >= 900 {
return "CM"+intToRoman(num-900)
} else if num >= 500 {
return "D"+intToRoman(num-500)
} else if num >= 400 {
return "CD"+intToRoman(num-400)
} else if num >= 100 {
return "C"+intToRoman(num-100)
} else if num >= 90 {
return "XC"+intToRoman(num-90)
} else if num >= 50 {
return "L"+intToRoman(num-50)
} else if num >= 40 {
return "XL"+intToRoman(num-40)
} else if num >= 10 {
return "X"+intToRoman(num-10)
} else if num >= 9 {
return "IX"+intToRoman(num-9)
} else if num >= 5 {
return "V"+intToRoman(num-5)
} else if num >= 4 {
return "IV"+intToRoman(num-4)
} else if num >= 1 {
return "I"+intToRoman(num-1)
}
return ""
}
}
Solution().intToRoman(200)
|
7d20c593642481949f016b3cc3e91133
| 28.944444 | 43 | 0.474954 | false | false | false | false |
MarkQSchultz/NilLiterally
|
refs/heads/master
|
LiterallyNil.playground/Pages/Optional.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Next](@next)
//: ### Optionals
//: #### `.None`
/*:
public enum Optional<Wrapped> {
case None
case Some(Wrapped)
}
*/
let a: Int? = nil
let aIsNil = a == nil
let aIsNone = a == .None
//: `Int? == Optional<Int>`
//: [Previous](@previous)
|
e5b8f3c6e08886532fabe9a26b96da44
| 6 | 35 | 0.465986 | false | false | false | false |
klone1127/yuan
|
refs/heads/master
|
yuan/UIView+Common.swift
|
mit
|
1
|
//
// UIView+Common.swift
// yuan
//
// Created by CF on 2017/6/10.
// Copyright © 2017年 klone. All rights reserved.
//
import Foundation
import UIKit
private let colorValue: CGFloat = 1.0
extension UIView {
/// add line
open func addLine() {
self.addLineToTop()
self.addLineToBottom()
}
/// 底部添加 Line
open func addLineToBottom() {
let line = UIView()
line.backgroundColor = UIColor.init(red: colorValue, green: colorValue, blue: colorValue, alpha: 1.0)
self.addSubview(line)
line.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(1.0)
}
}
/// 顶部添加 Line
open func addLineToTop() {
let line = UIView()
line.backgroundColor = UIColor.init(red: colorValue, green: colorValue, blue: colorValue, alpha: 1.0)
self.addSubview(line)
line.snp.makeConstraints { (make) in
make.left.right.top.equalTo(self)
make.height.equalTo(1.0)
}
}
/// 拖拽卡片
///
/// - Parameters:
/// - translation: point
/// - Returns:
open func panTransform(for translation: CGPoint) -> CGAffineTransform {
let moveBy = CGAffineTransform(translationX: translation.x, y: translation.y)
let rotation = -sin(translation.x / (self.frame.width * 4.0))
return moveBy.rotated(by: rotation)
}
/// 抖动
open func shakeAnimation() {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.4,
initialSpringVelocity: 1.0,
options: [],
animations: {
self.transform = .identity
},
completion: nil)
}
}
|
d02b0faa408c6fddec7c3f5acd6ae3c1
| 24.581081 | 109 | 0.538299 | false | false | false | false |
darkzero/SimplePlayer
|
refs/heads/master
|
SimplePlayer/UI/Library/PlaylistViewController.swift
|
mit
|
1
|
//
// PlaylistViewController.swift
// SimplePlayer
//
// Created by darkzero on 14-6-11.
// Copyright (c) 2014 darkzero. All rights reserved.
//
import UIKit
import MediaPlayer
class PlaylistViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var songsTable : UITableView!;
var playlistList:NSMutableArray;
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.playlistList = MusicLibrary.defaultPlayer().getiPodPlaylists();
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
self.playlistList = MusicLibrary.defaultPlayer().getiPodPlaylists();
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated);
//self.songsTable.reloadData();
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// #pragma mark - Navigation
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.playlistList.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "SongCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell;
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier);
}
cell!.textLabel!.text = (self.playlistList[indexPath.row] as MPMediaPlaylist).name;
//NSLog("%@", self.playlistList[indexPath.row]);
return cell!;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//var mediaItem:MPMediaItem = self.playlistList[indexPath.row] as MPMediaItem;
var songsVC:SongsViewController = SongsViewController(nibName: "SongsViewController", bundle: nil);
var mCollection:MPMediaItemCollection = self.playlistList[indexPath.row] as MPMediaItemCollection;
songsVC.itemCollection = mCollection;
self.navigationController?.pushViewController(songsVC, animated: true);
// var player = MusicPlayer.defaultPlayer();
// player.player.setQueueWithItemCollection(MPMediaItemCollection(items:self.getiPodPlaylists));
// player.player.nowPlayingItem = mediaItem;
// player.player.play();
//self.dismissModalViewControllerAnimated(true);
}
}
|
648d4e0fc67b662c8bf5d3d79119fcdc
| 34.467391 | 109 | 0.682807 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK
|
refs/heads/master
|
DemoVideoByGPU/DemoVideoByGPU/ModelController.swift
|
mit
|
1
|
//
// ModelController.swift
// DemoVideoByGPU
//
// Created by Nguyen Minh on 5/2/17.
// Copyright © 2017 AHDEnglish. All rights reserved.
//
import UIKit
/*
A controller object that manages a simple model -- a collection of month names.
The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:.
It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application.
There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand.
*/
class ModelController: NSObject, UIPageViewControllerDataSource {
var pageData: [String] = []
override init() {
super.init()
// Create the data model.
let dateFormatter = DateFormatter()
pageData = dateFormatter.monthSymbols
}
func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> DataViewController? {
// Return the data view controller for the given index.
if (self.pageData.count == 0) || (index >= self.pageData.count) {
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard.instantiateViewController(withIdentifier: "DataViewController") as! DataViewController
dataViewController.dataObject = self.pageData[index]
return dataViewController
}
func indexOfViewController(_ viewController: DataViewController) -> Int {
// Return the index of the given data view controller.
// For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index.
return pageData.index(of: viewController.dataObject) ?? NSNotFound
}
// MARK: - Page View Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if (index == 0) || (index == NSNotFound) {
return nil
}
index -= 1
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if index == NSNotFound {
return nil
}
index += 1
if index == self.pageData.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
}
|
d77ed7a30c0446603756cea2dc341c81
| 39.571429 | 225 | 0.709987 | false | false | false | false |
ddaguro/clintonconcord
|
refs/heads/master
|
OIMApp/Requests.swift
|
mit
|
1
|
//
// Requests.swift
// OIMApp
//
// Created by Linh NGUYEN on 5/26/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import Foundation
public class Requests {
var reqId : String!
var reqStatus : String!
var reqCreatedOn : String!
var reqType : String!
var reqJustification : String!
var reqTargetEntities : [TargetEntities]!
var reqBeneficiaryList : [BeneficiaryList]!
init(data : NSDictionary){
self.reqId = Utils.getStringFromJSON(data, key: "reqId")
self.reqStatus = Utils.getStringFromJSON(data, key: "reqStatus")
self.reqCreatedOn = Utils.getStringFromJSON(data, key: "reqCreatedOn")
self.reqType = Utils.getStringFromJSON(data, key: "reqType")
self.reqJustification = Utils.getStringFromJSON(data, key: "reqJustification")
if let results: NSArray = data["reqTargetEntities"] as? NSArray {
var ents = [TargetEntities]()
for ent in results{
let ent = TargetEntities(data: ent as! NSDictionary)
ents.append(ent)
}
self.reqTargetEntities = ents
}
if let beneficiaryresults: NSArray = data["reqBeneficiaryList"] as? NSArray {
var bens = [BeneficiaryList]()
for ben in beneficiaryresults {
let ben = BeneficiaryList(data: ben as! NSDictionary)
bens.append(ben)
}
self.reqBeneficiaryList = bens
}
}
}
class TargetEntities {
var catalogid: String!
var entityid: String!
var entitytype: String!
var entityname: String!
init(data : NSDictionary){
self.catalogid = Utils.getStringFromJSON(data, key: "catalogId")
self.entityid = Utils.getStringFromJSON(data, key: "entityId")
self.entitytype = Utils.getStringFromJSON(data, key: "entityType")
self.entityname = Utils.getStringFromJSON(data, key: "entityName")
}
}
class BeneficiaryList {
var userlogin: String!
var displayname: String!
init(data : NSDictionary){
self.userlogin = Utils.getStringFromJSON(data, key: "User Login")
self.displayname = Utils.getStringFromJSON(data, key: "Display Name")
}
}
class OperationCounts {
var approvals : Int!
var certifications : Int!
var requests : Int!
init(data : NSDictionary){
self.approvals = data["approvals"] as! Int
self.certifications = data["certifications"] as! Int
self.requests = data["requests"] as! Int
}
}
|
a7dfd1f7138b6d1d6fff39d37787d27d
| 28.153846 | 86 | 0.611006 | false | false | false | false |
ioscreator/ioscreator
|
refs/heads/master
|
IOSSpriteKitParallaxScrollingTutorial/IOSSpriteKitParallaxScrollingTutorial/GameScene.swift
|
mit
|
1
|
//
// GameScene.swift
// IOSSpriteKitParallaxScrollingTutorial
//
// Created by Arthur Knopper on 19/01/2020.
// Copyright © 2020 Arthur Knopper. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
createBackground()
}
override func update(_ currentTime: TimeInterval) {
scrollBackground()
}
func createBackground() {
for i in 0...2 {
let sky = SKSpriteNode(imageNamed: "clouds")
sky.name = "clouds"
sky.size = CGSize(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
sky.position = CGPoint(x: CGFloat(i) * sky.size.width , y: (self.frame.size.height / 2))
self.addChild(sky)
}
}
func scrollBackground(){
self.enumerateChildNodes(withName: "clouds", using: ({
(node, error) in
node.position.x -= 4
print("node position x = \(node.position.x)")
if node.position.x < -(self.scene?.size.width)! {
node.position.x += (self.scene?.size.width)! * 3
}
}))
}
}
|
c2cddc676bbb38ed4161b539f5b6196d
| 26.355556 | 100 | 0.549959 | false | false | false | false |
modesty/wearableD
|
refs/heads/master
|
WearableD/HomeViewController.swift
|
apache-2.0
|
2
|
//
// ViewController.swift
// WearableD
//
// Created by Zhang, Modesty on 1/9/15.
// Copyright (c) 2015 Intuit. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleWatchKitNotification:", name: "WearableDWKMsg", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
// self.navigationController?.setNavigationBarHidden(true, animated: animated)
self.title = "Wearable Transcript"
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
// self.navigationController?.setNavigationBarHidden(false, animated: animated)
self.title = "Home"
super.viewWillDisappear(animated)
}
func handleWatchKitNotification(notification: NSNotification) {
println("Got notification: \(notification.object)")
if let userInfo = notification.object as? [String:String] {
if let viewNameStr = userInfo["viewName"] {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let topVC = self.navigationController?.topViewController
var bleVC: UIViewController? = nil
if viewNameStr == "requestDoc" {
if (topVC is CentralViewController) == false {
self.returnToRoot()
bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("CentralViewController") as! CentralViewController
}
}
else if viewNameStr == "shareDoc" {
if (topVC is PeripheralViewController) == false {
self.returnToRoot()
bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("PeripheralViewController") as! PeripheralViewController
}
}
if bleVC != nil {
self.navigationController?.pushViewController(bleVC!, animated: true)
}
}
}
}
func returnToRoot() {
self.dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
|
5fed0124e12d87d740c359e5ce755c80
| 35.184211 | 143 | 0.610182 | false | false | false | false |
sheepy1/SelectionOfZhihu
|
refs/heads/master
|
SelectionOfZhihu/Constant.swift
|
mit
|
1
|
//
// Constant.swift
// SelectionOfZhihu
//
// Created by 杨洋 on 15/12/22.
// Copyright © 2015年 Sheepy. All rights reserved.
//
import UIKit
let ScreenBounds = UIScreen.mainScreen().bounds
let ScreenWidth = ScreenBounds.width
let ScreenHeight = ScreenBounds.height
let BarHeight = UIApplication.sharedApplication().statusBarFrame.height
struct ArticleCagetory {
static let categoryDict = [
"archive": "历史精华",
"recent": "近日热门",
"yesterday": "昨日最新"
]
}
struct CellReuseIdentifier {
static let Home = "HomeCell"
static let Answer = "AnswerCell"
static let User = "UserCell"
static let UserInfo = "UserInfo"
static let UserMenu = "UserMenu"
static let UserDynamic = "UserDynamic"
static let TopAnswer = "TopAnswer"
static let SearchedUser = "SearchedUser"
}
struct SegueId {
static let PopoverSortOrderMenu = "PopoverSortOrderMenu"
static let SelectedTableItem = "SelectedTableItem"
static let UserDetail = "UserDetail"
}
struct API {
static let APIHost = "http://api.kanzhihu.com/"
static let ArticleHost = "http://www.zhihu.com"
static let ZhuanlanHost = "http://zhuanlan.zhihu.com"
static let Home = APIHost + "getposts"
static let AnswerList = APIHost + "getpostanswers/"
static let Article = ArticleHost + "/question/"
static let TopUserAPI = APIHost + "topuser/"
static let TopUserOrderByAgreeNum = TopUserAPI + "agree/"
static let UserDetail = APIHost + "userdetail2/"
static let SearchUser = APIHost + "searchuser/"
}
|
bb4194c3b4da772c396ffb9c8cae08cd
| 25.032787 | 71 | 0.679269 | false | false | false | false |
quells/SwiftManagedModel
|
refs/heads/master
|
Example/Person.swift
|
mit
|
1
|
//
// Person.swift
// SQLiteDB Example
//
// Created by Kai Wells on 8/11/14.
// Copyright (c) 2014 Kai Wells. All rights reserved.
//
import UIKit
public class Person: Model {
override public func className() -> String {
return "Person"
}
public var id: String = NSUUID.UUID().UUIDString
public var name: String = ""
public var age: Int = 0
public var dateCreated: NSDate = NSDate()
public var dateModified: NSDate = NSDate()
override init() {
super.init()
shouldUpdate()
}
override public func shouldUpdate() -> Bool {
dateModified = NSDate()
self._properties = [id, name, age, dateCreated, dateModified]
return true
}
override public func shouldInsert() -> Bool {
shouldUpdate()
return true
}
override public func shouldDelete() -> Bool {
shouldUpdate()
return true
}
override public var description: String {
return "<\(self.name) age \(self.age), created \(self.dateCreated)>"
}
}
public class People: Model {
override public func className() -> String {
return "People"
}
public var id: Int = 0
public var people: NSArray = NSArray()
public var dateModified: NSDate = NSDate()
override init() {
super.init()
shouldUpdate()
}
override public func shouldUpdate() -> Bool {
dateModified = NSDate()
self._properties = [id, people, dateModified]
return true
}
public func add(person: Person) {
var temp = self.people.mutableCopy() as NSMutableArray
temp.insertObject(person.id, atIndex: 0)
self.people = temp.copy() as NSArray
shouldUpdate()
}
public func remove(person: Person) {
var temp = self.people.mutableCopy() as NSMutableArray
temp.removeObject(person.id)
self.people = temp.copy() as NSArray
shouldUpdate()
}
}
|
48152f46ffac57ea96fe23b62c767ae6
| 22.752941 | 76 | 0.587215 | false | false | false | false |
antonyharfield/grader
|
refs/heads/master
|
Sources/App/Web/ViewRenderers/ViewWrapper.swift
|
mit
|
1
|
import Vapor
func render(_ viewName: String, _ data: [String: NodeRepresentable] = [:], for request: HTTP.Request, with renderer: ViewRenderer) throws -> View {
var wrappedData = wrap(data, request: request)
if let user = request.user {
wrappedData = wrap(wrappedData, user: user)
}
return try renderer.make(viewName, wrappedData, for: request)
}
fileprivate func wrap(_ data: [String: NodeRepresentable], user: User) -> [String: NodeRepresentable] {
var result = data
result["authenticated"] = true
result["authenticatedUser"] = user
user.role.permitted.forEach { result["can\($0.rawValue.capitalized)"] = true }
return result
}
fileprivate func wrap(_ data: [String: NodeRepresentable], request: HTTP.Request) -> [String: NodeRepresentable] {
var result = data
result["path"] = request.uri.path.components(separatedBy: "/").filter { $0 != "" }
result["flash"] = try! request.storage["_flash"].makeNode(in: nil)
return result
}
|
3e0267095d5c823594083dc6502b7ff9
| 36 | 147 | 0.676677 | false | false | false | false |
anurse/advent-of-code
|
refs/heads/main
|
2021/adventofcode/day02.swift
|
apache-2.0
|
1
|
//
// Created by Andrew Stanton-Nurse on 12/3/21.
//
import Foundation
struct Coordinate {
var depth = 0
var position = 0
}
extension Coordinate {
static func +(left: Coordinate, right: Coordinate) -> Coordinate {
Coordinate(depth: left.depth + right.depth, position: left.position + right.position)
}
}
class Submarine {
var location = Coordinate()
var aim = 0
func move(by: Coordinate) {
aim += by.depth
location = Coordinate(
depth: location.depth + (by.position * aim),
position: location.position + by.position)
}
}
func parseInstruction(s: Substring) throws -> Coordinate {
let splat = s.split(separator: " ")
if splat.count != 2 {
throw SimpleError.error("Invalid instruction: \(s))")
}
guard let count = Int(splat[1]) else {
throw SimpleError.error("Distance is not an integer: \(splat[1])")
}
switch splat[0] {
case "forward":
return Coordinate(depth: 0, position: count)
case "down":
return Coordinate(depth: count, position: 0)
case "up":
return Coordinate(depth: -count, position: 0)
case let x:
throw SimpleError.error("Unknown direction: \(x)")
}
}
func day02(_ args: ArraySlice<String>) throws {
guard let input = args.first else {
throw SimpleError.error("Usage: adventofcode 2 <input>")
}
let data = try parseLines(path: input, converter: parseInstruction)
let part1 = data.reduce(Coordinate(), +)
print("Part 1:")
dumpResult(result: part1)
let sub = Submarine()
for inst in data {
sub.move(by: inst)
}
print("Part 2")
dumpResult(result: sub.location)
}
func dumpResult(result: Coordinate) {
print(" Depth: \(result.depth)")
print(" Position: \(result.position)")
print(" Result: \(result.position * result.depth)")
}
|
5a162acfdad1d49d0034b1cc55e7f5b1
| 24.890411 | 93 | 0.620434 | false | false | false | false |
xiaoyouPrince/WeiBo
|
refs/heads/master
|
WeiBo/WeiBo/Classes/Main/Visitor/VisitorView.swift
|
mit
|
1
|
//
// VisitorView.swift
// WeiBo
//
// Created by 渠晓友 on 2017/5/19.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
class VisitorView: UIView {
// 创建一个对外的公开快速创建的方法
class func visitorView() -> VisitorView {
return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)?.first as! VisitorView
}
// MARK: - 内部属性
@IBOutlet weak var rotationView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipsLabel: UILabel!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var loginBtn: UIButton!
/// 设置内部visitorView的信息
func setupVisitorViewInfo(iconName : String , tips : String) {
rotationView.isHidden = true
iconView.image = UIImage(named: iconName)
tipsLabel.text = tips
}
/// 设置rotationView旋转起来
func addRotationAnim() {
// 创建动画
let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
// 设置动画基本属性
rotationAnim.fromValue = 0
rotationAnim.toValue = Double.pi * 2
rotationAnim.repeatCount = MAXFLOAT
rotationAnim.duration = 5
// 设置当完成不消失,退后台和其他页面无影响
rotationAnim.isRemovedOnCompletion = false
// 将动画添加到对应的layer层上面
rotationView.layer.add(rotationAnim, forKey: nil)
}
}
|
4a4d0c7605d4aa36eb1e928809e215de
| 22.916667 | 103 | 0.612544 | false | false | false | false |
webim/webim-client-sdk-ios
|
refs/heads/master
|
Example/WebimClientLibrary/AppearanceSettings/StringConstants.swift
|
mit
|
1
|
//
// StringConstants.swift
// WebimClientLibrary_Example
//
// Created by Nikita Lazarev-Zubov on 19.10.17.
// Copyright © 2017 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
enum PopupAction: String {
case reply = "Reply" // "Reply".localized
case copy = "Copy" // "Copy".localized
case edit = "Edit" // "Edit".localized
case delete = "Delete" // "Delete".localized
case like = "Like"
case dislike = "Dislike"
}
enum OperatorAvatar: String {
case placeholder = "NoAvatarURL"
case empty = "GhostImage"
}
|
73d14d25bd9558e2dfdeead68636bb07
| 38.902439 | 82 | 0.724939 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceKit/Sources/EurofurenceWebAPI/Requests/Login.swift
|
mit
|
1
|
import Foundation
extension APIRequests {
/// A request to login to the Eurofurence application service.
public struct Login: APIRequest {
public typealias Output = AuthenticatedUser
/// The registration number of the user within the registration system.
public var registrationNumber: Int
/// The associated username of the user within the registration system.
public var username: String
/// The password associated with the user's registration number.
public var password: String
public init(registrationNumber: Int, username: String, password: String) {
self.registrationNumber = registrationNumber
self.username = username
self.password = password
}
public func execute(with context: APIRequestExecutionContext) async throws -> AuthenticatedUser {
let url = context.makeURL(subpath: "Tokens/RegSys")
let request = LoginPayload(RegNo: registrationNumber, Username: username, Password: password)
let encoder = JSONEncoder()
let body = try encoder.encode(request)
let networkRequest = NetworkRequest(url: url, body: body, method: .post)
let response = try await context.network.perform(request: networkRequest)
let loginResponse = try context.decoder.decode(LoginResponse.self, from: response)
return AuthenticatedUser(
userIdentifier: loginResponse.Uid,
username: loginResponse.Username,
token: loginResponse.Token,
tokenExpires: loginResponse.TokenValidUntil
)
}
private struct LoginPayload: Encodable {
var RegNo: Int
var Username: String
var Password: String
}
private struct LoginResponse: Decodable {
private enum CodingKeys: String, CodingKey {
case Uid
case Username
case Token
case TokenValidUntil
}
var Uid: Int
var Username: String
var Token: String
var TokenValidUntil: Date
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// UIDs look like: RegSys:EF26:<ID>
let uidString = try container.decode(String.self, forKey: .Uid)
let splitIdentifier = uidString.components(separatedBy: ":")
if let stringIdentifier = splitIdentifier.last, let registrationIdentifier = Int(stringIdentifier) {
Uid = registrationIdentifier
} else {
throw CouldNotParseRegistrationIdentifier(uid: uidString)
}
Username = try container.decode(String.self, forKey: .Username)
Token = try container.decode(String.self, forKey: .Token)
TokenValidUntil = try container.decode(Date.self, forKey: .TokenValidUntil)
}
private struct CouldNotParseRegistrationIdentifier: Error {
var uid: String
}
}
}
}
|
b0184c7377bddc10e939151702261f32
| 37.411111 | 116 | 0.56523 | false | false | false | false |
buyiyang/iosstar
|
refs/heads/master
|
iOSStar/Scenes/Discover/Controllers/StarInteractiveViewController.swift
|
gpl-3.0
|
3
|
//
// StarInteractiveViewController.swift
// iOSStar
//
// Created by J-bb on 17/7/6.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import MJRefresh
class StarInteractiveViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dataSource:[StarSortListModel]?
var imageNames:[String]?
let header = MJRefreshNormalHeader()
override func viewDidLoad() {
super.viewDidLoad()
header.setRefreshingTarget(self, refreshingAction: #selector(requestStar))
self.tableView!.mj_header = header
self.tableView.mj_header.beginRefreshing()
tableView.register(NoDataCell.self, forCellReuseIdentifier: "NoDataCell")
configImageNames()
// requestStar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func configImageNames() {
imageNames = []
for index in 0...10 {
imageNames?.append("starList_back\(index)")
}
}
func requestStar() {
let requestModel = StarSortListRequestModel()
AppAPIHelper.discoverAPI().requestStarList(requestModel: requestModel, complete: { (response) in
if let models = response as? [StarSortListModel] {
self.header.endRefreshing()
self.dataSource = models
self.tableView.reloadData()
}
self.header.endRefreshing()
}) { (error) in
self.header.endRefreshing()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if dataSource == nil || dataSource!.count == 0{
return
}
if let indexPath = sender as? IndexPath {
let model = dataSource![indexPath.item]
let vc = segue.destination
if segue.identifier == "InterToIntroduce" {
if let introVC = vc as? StarIntroduceViewController {
introVC.starModel = model
}
}
if segue.identifier == "StarNewsVC" {
if let introVC = vc as? StarNewsVC {
introVC.starModel = model
}
}
}
}
}
extension StarInteractiveViewController:UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.dataSource == nil ? UIScreen.main.bounds.size.height - 150 : 130
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource?.count ?? 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.dataSource == nil{
let cell = tableView.dequeueReusableCell(withIdentifier: NoDataCell.className(), for: indexPath) as! NoDataCell
cell.imageView?.image = UIImage.init(named: "nodata")
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: StarInfoCell.className(), for: indexPath) as! StarInfoCell
cell.setStarModel(starModel:dataSource![indexPath.row])
cell.setBackImage(imageName: (imageNames?[indexPath.row % 10])!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if dataSource == nil || dataSource?.count == 0{
return
}
if checkLogin(){
if let model: StarSortListModel = dataSource![indexPath.row] as? StarSortListModel{
ShareDataModel.share().selectStarCode = model.symbol
performSegue(withIdentifier: StarNewsVC.className(), sender: indexPath)
}
}
}
}
|
ce7a4f0d460ccc07613a71d677ca7709
| 32.8 | 123 | 0.602521 | false | false | false | false |
NicholasMata/SimpleTabBarController
|
refs/heads/master
|
SimpleTabBarController/SimpleAnimators/SimpleIrregularAppearance.swift
|
mit
|
1
|
//
// SimpleIrregularAnimator.swift
// Pods
//
// Created by Nicholas Mata on 10/25/16.
//
//
import UIKit
open class SimpleIrregularAppearance: SimpleBarItemAppearance {
open var borderWidth: CGFloat = 3.0
open var borderColor = UIColor(white: 235 / 255.0, alpha: 1.0)
open var radius: CGFloat = 35
open var insets: UIEdgeInsets = UIEdgeInsets(top: -32, left: 0, bottom: 0, right: 0)
open var irregularBackgroundColor: UIColor = .gray
open override var content: UIView? {
didSet {
if let content = content as? SimpleBarItemContent {
content.imageView.backgroundColor = irregularBackgroundColor
content.imageView.layer.borderWidth = borderWidth
content.imageView.layer.borderColor = borderColor.cgColor
content.imageView.layer.cornerRadius = radius
content.insets = insets
let transform = CGAffineTransform.identity
content.imageView.transform = transform
content.superview?.bringSubviewToFront(content)
}
}
}
public required init() {
super.init()
textColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightTextColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
iconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
highlightIconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
backgroundColor = UIColor.clear
highlightBackgroundColor = UIColor.clear
}
open override func selectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) {
super.selectAnimation(content: content, animated: animated, completion: completion)
}
open override func reselectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) {
super.reselectAnimation(content: content, animated: animated, completion: completion)
}
open override func deselectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) {
super.deselectAnimation(content: content, animated: animated, completion: completion)
}
open override func highlightAnimation(content: UIView, animated: Bool, completion: (() -> ())?) {
super.highlightAnimation(content: content, animated: animated, completion: completion)
}
open override func dehighlightAnimation(content: UIView, animated: Bool, completion: (() -> ())?) {
super.dehighlightAnimation(content: content, animated: animated, completion: completion)
}
}
|
7c8a300dbca3a0ba261951176797795d
| 35.633803 | 103 | 0.64975 | false | false | false | false |
billdonner/sheetcheats9
|
refs/heads/master
|
sc9/ColorUtil.swift
|
apache-2.0
|
1
|
//
// ColorUtil.swift
// sc9
//
// Created by william donner on 12/20/16.
// Copyright © 2016 shovelreadyapps. All rights reserved.
//
// from
// ColorUtil.swift
//
// Created by Ben Dalziel on 2/17/16.
//https://medium.com/ios-os-x-development/codifying-style-guides-in-swift-6a27b742f441#.uo3m17xvd
//import SwiftHEXColors
struct Col {
enum AppUIColors: Int {
case navBarBackground,
navBarTint,
navBarShadow,
launchBackground,
mainViewControllerBackground,
modalmenuBackground,
previewBackground,
// all help and info
helpActivityIndicator,
helpBackground,
helpText,
helpAltText,
//settings page
settingsBackground,
settingsButton,
settingsText,
settingsAltText,
//search,list,history
tableActivityIndicator,
tableBackground,
tableSeparator,
tableCellSelectedBackground,
tableCellSelectedBackgroundDark,
tableSearchIndexText,
tableSectionText,
tableSectionHeaderText,
tableSectionHeaderAltText,
tableRefreshText,
//gig matrix is collection view
collectionActivityIndicator,
collectionBackground,
collectionSeparator,
collectionCellSelectedBackground,
collectionCellSelectedBackgroundDark,
collectionSectionText,
collectionSectionHeaderText,
collectionSectionHeaderAltText,
collectionRefreshText,
//colors on outer menus
gigMatrixMenuTitle,
gigMatrixMenuBackground,
searchMenuTitle,
searchMenuBackground,
gigListMenuTitle,
gigListMenuBackground,
settingsMenuTitle,
settingsMenuBackground,
historyMenuTitle,
historyMenuBackground
}
private enum AppColors: String {
case // colors on the menu should be all we use
lightBlue = "#3091FF",
green = "#38BD00",
red = "#F53B36",
purple = "#8225FF",
orange = "#FF6200",
blue = "#141459",
almostWhite = "#F8FAFD",
darkGray = "#222222",
black = "#000000",
//old detritus
beige = "#f5efe0",
gold = "#cda582",
goldAlt = "#e1b996"
}
/// usage: Col.r( appUIColor)
/// eg let backgroundColor = Col.r(.gigListMenuBackgrond)
static func r(_ appUIColor: AppUIColors) -> UIColor {
func colorWithAlpha(_ appColor: AppColors, alpha: Float) -> UIColor {
return UIColor(hexString: appColor.rawValue, alpha: alpha)!
}
func color(_ appColor: AppColors) -> UIColor {
return UIColor(hexString: appColor.rawValue)!
}
switch appUIColor {
case .navBarBackground:
return color(.beige)
case .navBarTint :
return color(.gold)
case .navBarShadow :
return colorWithAlpha(.goldAlt, alpha: 0.7)
case .modalmenuBackground:
return color(.blue)
// settings
case .settingsBackground,.previewBackground:
return color(.almostWhite)
case .settingsText :
return color(.lightBlue)
case .settingsAltText:
return color(.green)
case .settingsButton:
return color(.black)
// help
case .helpBackground,.helpActivityIndicator:
return color(.almostWhite)
case .helpText,.helpAltText:
return color(.black)
// all lists
case .tableSearchIndexText:
return color(.red)
case .tableBackground,
.tableSeparator,
.tableCellSelectedBackground,
.tableCellSelectedBackgroundDark:
return color(.blue)
case .tableActivityIndicator, .tableSectionText,
.tableSectionHeaderText,
.tableSectionHeaderAltText,
.tableRefreshText:
return color(.almostWhite)
//GigMatrix is collectionview
case .collectionBackground,
.collectionSeparator,
.collectionCellSelectedBackground,
.collectionCellSelectedBackgroundDark :
return color(.blue)
case .collectionActivityIndicator, .collectionSectionText,
.collectionSectionHeaderText,
.collectionSectionHeaderAltText,
.collectionRefreshText:
return color(.almostWhite)
// menus
case .gigMatrixMenuTitle:
return color(.almostWhite)
case .gigMatrixMenuBackground:
return color(.lightBlue)
case .searchMenuTitle:
return color(.almostWhite)
case .searchMenuBackground:
return color(.green)
case .gigListMenuTitle:
return color(.almostWhite)
case .gigListMenuBackground:
return color(.red)
case .settingsMenuTitle:
return color(.almostWhite)
case .settingsMenuBackground:
return color(.purple)
case .historyMenuTitle:
return color(.almostWhite)
case .historyMenuBackground:
return color(.orange)
default:
return color(.gold)
}
}
/// Background Pattern Images
// not currently used
enum AppUIPatterns: Int {
case gigMatrixBackground,
exportsBackground,
grabPhotosBackground,
importItunesBackground,
remoteImportBackground,
helpBackground,
settingsBackground,
launchBackground
}
static func uiPattern(appUIPattern: AppUIPatterns) -> UIColor {
switch appUIPattern {
case .gigMatrixBackground:
return UIColor(patternImage: UIImage.init(named: "FML Pattern Light")!)
case .exportsBackground,
.grabPhotosBackground,
.importItunesBackground,
.remoteImportBackground,
. helpBackground,
.settingsBackground:
// Subtle
return UIColor(patternImage: UIImage.init(named: "FML Pattern Light")!)
case .launchBackground :
return UIColor(patternImage: UIImage.init(named: "FML Pattern Dark Subtle - Launch")!)
}
}
}
|
4c9169d56a532d37b374966698f3b0f4
| 27.106557 | 98 | 0.555118 | false | false | false | false |
bmichotte/HSTracker
|
refs/heads/master
|
HSTracker/Hearthstone/Secrets/Secret.swift
|
mit
|
1
|
//
// Secret.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
import RealmSwift
class Secret {
private(set) var cardId: String
var count: Int
init(cardId: String, count: Int) {
self.cardId = cardId
self.count = count
}
private func activeDeckIsConstructed(game: Game) -> Bool {
guard let deck = game.currentDeck else { return false }
return !deck.isArena
}
func adjustedCount(game: Game) -> Int {
return ((game.currentGameMode == .casual || game.currentGameMode == .ranked
|| game.currentGameMode == .friendly || game.currentGameMode == .practice
|| activeDeckIsConstructed(game: game))
&& game.opponent.revealedEntities.filter { $0.id < 68 && $0.cardId == self.cardId }
.count >= 2) ? 0 : self.count
}
}
|
e210851d4e47f5b4024d4569d3b2769e
| 25.916667 | 95 | 0.617131 | false | false | false | false |
azizuysal/NetKit
|
refs/heads/master
|
NetKit/NetKit/WebRequest.swift
|
mit
|
1
|
//
// WebRequest.swift
// NetKit
//
// Created by Aziz Uysal on 2/12/16.
// Copyright © 2016 Aziz Uysal. All rights reserved.
//
import Foundation
public struct WebRequest {
public struct Headers {
public static let userAgent = "User-Agent"
public static let contentType = "Content-Type"
public static let contentLength = "Content-Length"
public static let accept = "Accept"
public static let cacheControl = "Cache-Control"
public struct ContentType {
public static let json = "application/json"
public static let xml = "text/xml"
public static let formEncoded = "application/x-www-form-urlencoded"
}
}
public enum Method: String {
case HEAD = "HEAD"
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
public enum ParameterEncoding {
case percent, json
public func encodeURL(_ url: URL, parameters: [String:Any]) -> URL? {
if var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
components.appendPercentEncodedQuery(parameters.percentEncodedQueryString)
return components.url
}
return nil
}
public func encodeBody(_ parameters: [String:Any]) -> Data? {
switch self {
case .percent:
return parameters.percentEncodedQueryString.data(using: String.Encoding.utf8, allowLossyConversion: false)
case .json:
do {
return try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
return nil
}
}
}
}
let method: Method
private(set) var url: URL
var body: Data?
var cachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy
var urlParameters = [String:Any]()
var bodyParameters = [String:Any]()
var parameterEncoding = ParameterEncoding.percent {
didSet {
if parameterEncoding == .json {
contentType = Headers.ContentType.json
}
}
}
var restPath = "" {
didSet {
url = url.appendingPathComponent(restPath)
}
}
var headers = [String:String]()
var contentType: String? {
set { headers[Headers.contentType] = newValue }
get { return headers[Headers.contentType] }
}
var urlRequest: URLRequest {
let request = NSMutableURLRequest(url: url)
request.httpMethod = method.rawValue
request.cachePolicy = cachePolicy
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
if urlParameters.count > 0 {
if let url = request.url, let encodedURL = parameterEncoding.encodeURL(url, parameters: urlParameters) {
request.url = encodedURL
}
}
if bodyParameters.count > 0 {
if let data = parameterEncoding.encodeBody(bodyParameters) {
request.httpBody = data
if request.value(forHTTPHeaderField: Headers.contentType) == nil {
request.setValue(Headers.ContentType.formEncoded, forHTTPHeaderField: Headers.contentType)
}
}
}
if let body = body {
request.httpBody = body
}
return request.copy() as! URLRequest
}
public init(method: Method, url: URL) {
self.method = method
self.url = url
}
}
extension URLComponents {
mutating func appendPercentEncodedQuery(_ query: String) {
percentEncodedQuery = percentEncodedQuery == nil ? query : "\(percentEncodedQuery ?? "")&\(query)"
}
}
extension Dictionary {
var percentEncodedQueryString: String {
var components = [String]()
for (name, value) in self {
if let percentEncodedPair = percentEncode((name, value)) {
components.append(percentEncodedPair)
}
}
return components.joined(separator: "&")
}
func percentEncode(_ element: Element) -> String? {
let (name, value) = element
if let encodedName = "\(name)".percentEncodeURLQueryCharacters, let encodedValue = "\(value)".percentEncodeURLQueryCharacters {
return "\(encodedName)=\(encodedValue)"
}
return nil
}
}
extension String {
var percentEncodeURLQueryCharacters: String? {
let allowedCharacterSet = CharacterSet(charactersIn: "\\!*'();:@&=+$,/?%#[] ").inverted
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet /*.urlQueryAllowed*/)
}
}
|
d7e81ab69ad4e63eb9e7a790a5dd7f4b
| 26.717949 | 131 | 0.654024 | false | false | false | false |
ChristianKienle/highway
|
refs/heads/master
|
Sources/FSKit/Implementations/AnchoredFileSystem.swift
|
mit
|
1
|
import Foundation
public final class AnchoredFileSystem {
// MARK: - Init
public init(underlyingFileSystem: FileSystem, achnoredAt root: Absolute) {
self.underlyingFileSystem = underlyingFileSystem
self.root = root
}
// MARL: Properties
public let underlyingFileSystem: FileSystem
public let root: Absolute
}
extension AnchoredFileSystem: FileSystem {
public func assertItem(at url: Absolute, is itemType: Metadata.ItemType) throws {
let meta = try itemMetadata(at: url)
guard meta.type == itemType else {
throw FSError.typeMismatch
}
}
public func itemMetadata(at url: Absolute) throws -> Metadata {
return try underlyingFileSystem.itemMetadata(at: _completeUrl(url))
}
public func homeDirectoryUrl() throws -> Absolute {
return try underlyingFileSystem.homeDirectoryUrl()
}
public func temporaryDirectoryUrl() throws -> Absolute {
return try underlyingFileSystem.temporaryDirectoryUrl()
}
public func createDirectory(at url: Absolute) throws {
try underlyingFileSystem.createDirectory(at: _completeUrl(url))
}
public func writeData(_ data: Data, to url: Absolute) throws {
try underlyingFileSystem.writeData(data, to: _completeUrl(url))
}
public func data(at url: Absolute) throws -> Data {
return try underlyingFileSystem.data(at: _completeUrl(url))
}
public func deleteItem(at url: Absolute) throws {
try underlyingFileSystem.deleteItem(at: _completeUrl(url))
}
public func writeString(_ string: String, to url: Absolute) throws {
guard let data = string.data(using: .utf8) else {
throw FSError.other("Failed to convert data to utf8 string.")
}
try writeData(data, to: url)
}
// MARK: - Convenience
public func file(at url: Absolute) -> File {
return File(url: url, fileSystem: self)
}
public func directory(at url: Absolute) -> Directory {
return Directory(url: url, in: self)
}
public func stringContentsOfFile(at url: Absolute) throws -> String {
return try file(at: _completeUrl(url)).string()
}
public func dataContentsOfFile(at url: Absolute) throws -> Data {
return try file(at: _completeUrl(url)).data()
}
private func _completeUrl(_ proposedUrl: Absolute) -> Absolute {
if proposedUrl == Absolute.root {
return root
} else {
let relativePath = proposedUrl.asRelativePath
return Absolute(path: relativePath, relativeTo: root)
}
}
}
|
4d53edb42a0e61ccc6ce47a9b2061565
| 32.721519 | 85 | 0.649399 | false | false | false | false |
catloafsoft/AudioKit
|
refs/heads/master
|
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Telephone Digits.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Telephone Digits
//: ### The dial tone is not the only sound on your phone that is just two sine waves, so are all the digits.
import XCPlayground
import AudioKit
//: Here is the canonical specification of DTMF Tones
var keys = [String: [Double]]()
keys["1"] = [697, 1209]
keys["2"] = [697, 1336]
keys["3"] = [697, 1477]
keys["4"] = [770, 1209]
keys["5"] = [770, 1336]
keys["6"] = [770, 1477]
keys["7"] = [852, 1209]
keys["8"] = [852, 1336]
keys["9"] = [852, 1477]
keys["*"] = [941, 1209]
keys["0"] = [941, 1336]
keys["#"] = [941, 1477]
let keyPressTone = AKOperation.sineWave(frequency: AKOperation.parameters(0)) +
AKOperation.sineWave(frequency: AKOperation.parameters(1))
let momentaryPress = keyPressTone.triggeredWithEnvelope(
AKOperation.trigger, attack: 0.01, hold: 0.1, release: 0.01)
let generator = AKOperationGenerator(
operation: momentaryPress * 0.4)
AudioKit.output = generator
AudioKit.start()
generator.start()
//: Let's call Jenny and Mary!
let phoneNumber = "8675309 3212333 222 333 3212333322321"
for number in phoneNumber.characters {
if keys.keys.contains(String(number)) {
generator.trigger(keys[String(number)]!)
}
usleep(250000)
}
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
263d2670671805afa15a207a5733c457
| 27.479167 | 109 | 0.664228 | false | false | false | false |
apple-programmer/general_mac_anonymizer
|
refs/heads/master
|
MKO project/Network setup.swift
|
artistic-2.0
|
1
|
//
// Network setup.swift
// MKO project
//
// Created by Roman Nikitin on 08.02.16.
// Copyright © 2016 NikRom. All rights reserved.
//
import Foundation
import Cocoa
func configureProxy() {
let services = runCommand(command: "networksetup -listallnetworkservices | grep -vw \"An asterisk\"").componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
for serv in services {
if !serv.isEmpty {
runCommand(command: "\(askpass) sudo -Ak networksetup -setsecurewebproxy \"\(serv)\" 127.0.0.1 8118")
runCommand(command: "\(askpass) sudo -Ak networksetup -setwebproxy \"\(serv)\" 127.0.0.1 8118")
runCommand(command: "\(askpass) sudo -Ak networksetup -setsocksfirewallproxy \"\(serv)\" 127.0.0.1 9050")
printToGUI("Configured proxy on service \(serv)")
}
}
}
func getCurrentLocation() {
let output = runCommand(command: "\(askpass) sudo -Ak networksetup -getcurrentlocation").componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).first
if output == "Automatic" || output == "Авто" {
createLocation(locationName: "Main Location")
switchToLocation(locationName: "Main Location")
runCommand(command: "\(askpass) sudo -Ak -deletelocation \"\(output)\"")
NSUserDefaults.standardUserDefaults().setObject("Main Location", forKey: "OldLocation")
}
else {
NSUserDefaults.standardUserDefaults().setObject(output, forKey: "OldLocation")
}
}
func createLocation(locationName name : String = "Secret Location") {
runCommand(command: "\(askpass) sudo -Ak networksetup -createlocation \"\(name)\" populate")
print("Location created")
printToGUI("Created location \(name)")
}
func switchToLocation(locationName name : String = "Secret Location") {
var name = name
let result = runCommand(command: "\(askpass) sudo -Ak networksetup -switchtolocation \"\(name)\"")
if result.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).contains("** Error: The parameters were not valid.") {
printToGUI("Could not find old location")
createLocation(locationName: "Main Location")
switchToLocation(locationName: "Main Location")
name = "Main Location"
}
print("Switched to location \(name)")
printToGUI("Switched to location \(name)")
}
func initNetwork() {
getPassword()
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
getCurrentLocation()
createLocation()
switchToLocation()
configureProxy()
})
dispatch_sync(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), {
if !isTorInstalled() || !isPrivoxyInstalled() {
initBrew()
}
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
initPrivoxy()
initTor()
})
}
func deinitNetwork() {
var location = NSUserDefaults.standardUserDefaults().objectForKey("OldLocation") as! String
if location == "Secret Location" {
location = "Main Location"
}
switchToLocation(locationName: location)
runCommand(command: "\(askpass) sudo -Ak networksetup -deletelocation \"Secret Location\"")
print("Deleted location")
printToGUI("Deleted location \"Secret Location\"")
isTorLaunched = false
runCommand(command: "killall tor")
runCommand(command: "killall privoxy")
printToGUI("Killed Privoxy")
}
|
9d379fe7e73d8dd7ba12f18b96264c16
| 37.811111 | 180 | 0.678408 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
refs/heads/master
|
数据优化/数据优化/MainViewController.swift
|
apache-2.0
|
1
|
//
// MainViewController.swift
// 数据优化
//
// Created by bingoogol on 14/9/23.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
let CELL_ID = "MYCELL"
let HEADER_ID = "MYHEADER"
class MainViewController: UITableViewController {
override func loadView() {
self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 10
} else if section == 1 {
return 20
} else {
return 15
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
println("实例化单元格\(indexPath.section)组\(indexPath.row)行")
}
cell?.textLabel?.text = "\(indexPath.section)组\(indexPath.row)行"
return cell!
}
// 如果是字符串形式,本身不需要进行优化,因为通常会有一个数据字典维护,需要显示字符串,直接通过section从数组中提取即可
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "第\(section)组"
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(HEADER_ID) as? UITableViewHeaderFooterView
var button:UIButton
if header == nil {
header = UITableViewHeaderFooterView(reuseIdentifier: HEADER_ID)
header?.frame = CGRectMake(0, 0, self.tableView.bounds.width, 44)
// Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = header!.bounds
header?.addSubview(button)
println("实例化标题行")
} else {
button = header?.subviews[2] as UIButton
}
button.setTitle("组\(section)", forState: UIControlState.Normal)
return header
}
}
|
7b288aba6d16e55fe90b0025432d491e
| 33.162162 | 143 | 0.648199 | false | false | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
Classes/Issues/Title/IssueTitleSectionController.swift
|
mit
|
1
|
//
// IssueTitleSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 5/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
final class IssueTitleSectionController: ListSectionController {
var object: IssueTitleModel?
override init() {
super.init()
inset = UIEdgeInsets(top: Styles.Sizes.rowSpacing, left: 0, bottom: 0, right: 0)
}
override func didUpdate(to object: Any) {
guard let object = object as? IssueTitleModel else { return }
self.object = object
}
override func sizeForItem(at index: Int) -> CGSize {
return collectionContext.cellSize(
with: object?.string.viewSize(in: collectionContext.safeContentWidth()).height ?? 0
)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let object = self.object,
let cell = collectionContext?.dequeueReusableCell(of: IssueTitleCell.self, for: self, at: index) as? IssueTitleCell
else { fatalError("Collection context must be set, missing object, or cell incorrect type") }
cell.set(renderer: object.string)
return cell
}
}
|
80238028a2e2cbbf4a9850cd9efa4509
| 29.2 | 127 | 0.667219 | false | false | false | false |
r9ronaldozhang/ZYColumnViewController
|
refs/heads/master
|
ZYColumnViewDemo/ZYColumnViewDemo/ZYColumnView/ZYColumnConfig.swift
|
mit
|
1
|
//
// ZYColumnConfig.swift
// 掌上遂宁
//
// Created by 张宇 on 2016/10/10.
// Copyright © 2016年 张宇. All rights reserved.
//
import UIKit
/******** 在此文件中定义了此控件常用的常用尺寸变量,用户可根据自己需求进行修改 ********/
let kColumnScreenW = UIScreen.main.bounds.size.width
let kColumnScreenH = UIScreen.main.bounds.size.height
let kColumnItemEqualWidth = true // 默认横向item是否等宽 还是根据文字匹配
let kColumnViewH:CGFloat = 40.0 // 默认高度
let kColumnViewW = kColumnScreenW // 默认宽度
let kSpreadMaxH:CGFloat = kColumnScreenH - 64 // 默认下拉展开的最大高度
let kSpreadDuration = 0.4 // 动画展开收拢的时长
let kColumnLayoutCount = 4 // 排序item 每行个数
let kColumnItemH:CGFloat = (ZYinch55()) ? 40: 30 // item的高度
let kColumnItemW:CGFloat = (ZYinch55()) ? 85: 70 // item的宽度
let kColumnMarginW:CGFloat = (ZYScreenWidth-CGFloat(kColumnLayoutCount)*kColumnItemW)/CGFloat(kColumnLayoutCount+1) // item的横向间距
let kColumnMarginH:CGFloat = (ZYinch55()) ? 20:((ZYinch47()) ? 20: 15) // item的纵向间距
let kColumnEditBtnW:CGFloat = 60 // 排序删除按钮的宽度
let kColumnEditBtnH:CGFloat = 36 // 排序删除按钮的高度
let kColumnEditBtnFont:CGFloat = 10 // 排序删除按钮的字体
let kColumnEditBtnNorTitle = "排序删除" // 排序删除普通状态文字
let kColumnEditBtnSelTitle = "完成" // 排序删除选中状态文字
let kColumnItemBorderColor = UIColor.red.cgColor // item的色环
let kColumnItemColor = UIColor.red // item的文字颜色
let kColumnTitleMargin:CGFloat = 8 // title按钮之间默认没有间距,这个值保证两个按钮的间距
let kColumnTitleNorColor = UIColor.darkText // title普通状态颜色
let kColumnTitleSelColor = UIColor.red // title选中状态颜色
let kColumnTitleNorFont:CGFloat = (ZYinch47() || ZYinch55()) ? 14 : 13 // title普通状态字体
let kColumnTitleSelFont:CGFloat = (ZYinch47() || ZYinch55()) ? 16 : 15 // title选中状态字体
let kColumnHasIndicator = true // 默认有指示线条
let kColumnIndictorH:CGFloat = 2.0 // 指示线条高度
let kColumnIndictorMinW : CGFloat = 60 // 指示条默认最小宽度
let kColumnIndicatorColor = UIColor.red // 默认使用系统风格颜色
/************** 常量定义 ****************/
/// 是否是3.5英寸屏
func ZYinch35() -> Bool {
return UIScreen.main.bounds.size.height == 480.0
}
/// 是否是4.0英寸屏
func ZYinch40() -> Bool {
return UIScreen.main.bounds.size.height == 568.0
}
/// 是否是4.7英寸屏
func ZYinch47() -> Bool {
return UIScreen.main.bounds.size.height == 667.0
}
/// 是否是5.5英寸屏
func ZYinch55() -> Bool {
return UIScreen.main.bounds.size.height == 736.0
}
let ZYScreenWidth = UIScreen.main.bounds.width
let ZYScreenHeight = UIScreen.main.bounds.height
|
b798c8398a81a55b08aa71f0050e0c01
| 48 | 166 | 0.542411 | false | false | false | false |
farion/eloquence
|
refs/heads/master
|
Eloquence/EloquenceIOS/RosterViewController.swift
|
apache-2.0
|
1
|
import Foundation
import UIKit
import XMPPFramework
class RosterViewController:UIViewController, UITableViewDelegate, UITableViewDataSource, EloRosterDelegate {
@IBOutlet weak var tableView: UITableView!
var roster = EloRoster()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
roster.delegate = self
roster.initializeData()
}
/* private */
func configureCell(cell:RosterCell, atIndexPath: NSIndexPath){
NSLog("IP %d",atIndexPath.row)
let contactListItem = roster.getContactListItem(atIndexPath.row);
cell.name.text = contactListItem.bareJidStr
cell.viaLabel.text = "via " + contactListItem.streamBareJidStr
// cell.imageView!.image = user.photo;
}
/* UITableViewDataSource */
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return roster.numberOfRowsInSection(section);
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RosterCell") as! RosterCell
configureCell(cell,atIndexPath:indexPath)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
roster.chatWishedByUserAction(indexPath.row)
}
/* NSFetchedResultsControllerDelegate */
func rosterWillChangeContent() {
NSLog("rosterwillchange")
tableView.beginUpdates()
}
func roster(didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch(type){
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
case .Delete:
tableView.deleteRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
case .Update:
configureCell(tableView.cellForRowAtIndexPath(indexPath!) as! RosterCell ,atIndexPath: indexPath!)
break
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
}
}
func rosterDidChangeContent() {
tableView.endUpdates()
}
}
|
83617c57247d801920053ce051f1d5dc
| 34.155844 | 167 | 0.668267 | false | false | false | false |
tzef/BmoImageLoader
|
refs/heads/master
|
BmoImageLoader/Classes/ProgressAnimation/BaseProgressAnimation.swift
|
mit
|
1
|
//
// BaseProgressAnimation.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/7.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
class BaseProgressAnimation: BmoProgressAnimator {
// Progress Animation View
weak var imageView: UIImageView?
var newImage: UIImage?
let helpPointView = BmoProgressHelpView()
// Progress Parameters
var completionBlock: ((BmoProgressCompletionResult<UIImage, NSError>) -> Void)?
var completionState = BmoProgressCompletionState.proceed
var progress = Progress(totalUnitCount: 100)
var progressColor = UIColor.black
var displayLink: CADisplayLink? = nil
var percentFont: UIFont?
// Animation Parameters
let transitionDuration = 0.33
let enlargeDuration = 0.33
var progressDuration = 0.5
var marginPercent: CGFloat = 0.1
// MARK: - Public
@objc func displayLinkAction(_ dis: CADisplayLink) {
}
func successAnimation(_ imageView: UIImageView) {
}
func failureAnimation(_ imageView: UIImageView, error: NSError?) {
}
// MARK : - Private
fileprivate func initDisplayLink() {
displayLink?.invalidate()
displayLink = nil
displayLink = CADisplayLink(target: self, selector: #selector(BaseProgressAnimation.displayLinkAction(_:)))
displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode)
displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
}
// MARK: - ProgressAnimator Protocol
func setCompletionBlock(_ completion: ((BmoProgressCompletionResult<UIImage, NSError>) -> Void)?) -> BmoProgressAnimator {
self.completionBlock = completion
return self
}
func setCompletionState(_ state: BmoProgressCompletionState) -> BmoProgressAnimator {
self.completionState = state
switch self.completionState {
case .succeed:
self.setCompletedUnitCount(progress.totalUnitCount).closure()
case .failed(_):
self.setCompletedUnitCount(0).closure()
default:
break
}
return self
}
func setTotalUnitCount(_ count: Int64) -> BmoProgressAnimator {
progress.totalUnitCount = count
return self
}
func setCompletedUnitCount(_ count: Int64) -> BmoProgressAnimator {
guard let strongImageView = self.imageView else {
return self
}
progress.completedUnitCount = count
initDisplayLink()
helpPointView.bounds = helpPointView.layer.presentation()?.bounds ?? helpPointView.bounds
helpPointView.layer.removeAllAnimations()
UIView.animate(withDuration: progressDuration, animations: {
self.helpPointView.bounds = CGRect(x: CGFloat(self.progress.fractionCompleted), y: 0, width: 0, height: 0)
}, completion: { (finished) in
if finished {
if self.progress.completedUnitCount >= self.progress.totalUnitCount {
switch self.completionState {
case .succeed:
self.successAnimation(strongImageView)
default:
break
}
}
if self.progress.completedUnitCount == 0 {
switch self.completionState {
case .failed(let error):
self.failureAnimation(strongImageView, error: error)
default:
break
}
}
}
})
return self
}
func resetAnimation() -> BmoProgressAnimator {
return self
}
func setAnimationDuration(_ duration: TimeInterval) -> BmoProgressAnimator {
self.progressDuration = duration
return self
}
func setNewImage(_ image: UIImage) -> BmoProgressAnimator {
self.newImage = image
return self
}
func setMarginPercent(_ percent: CGFloat) -> BmoProgressAnimator {
self.marginPercent = percent
self.resetAnimation().closure()
return self
}
func setProgressColor(_ color: UIColor) -> BmoProgressAnimator {
self.progressColor = color
self.resetAnimation().closure()
return self
}
func setPercentFont(_ font: UIFont) -> BmoProgressAnimator {
self.percentFont = font
self.resetAnimation().closure()
return self
}
/**
Do nothing, in order to avoid the warning about result of call is unused
*/
func closure() {
return
}
}
|
b261e75930b6d12fee890f21d162ba07
| 33.492537 | 126 | 0.622458 | false | false | false | false |
SergeMaslyakov/audio-player
|
refs/heads/master
|
app/src/data/realm/CacheDescriptor.swift
|
apache-2.0
|
1
|
//
// CacheDescriptor.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 09/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import Foundation
import RealmSwift
class CacheDescriptor: Object {
dynamic var shouldUsingCache = false
dynamic var cacheInitialized = false
dynamic var rootPath: String = "/Library/Caches"
dynamic var playlistsPath: String = "/playlists"
dynamic var tracksPath: String = "/tracks"
}
|
3bed23f5d3b8ea29903f1af0eec0cbe3
| 23.105263 | 52 | 0.720524 | false | false | false | false |
rbaumbach/SpikeyMcSpikerson
|
refs/heads/master
|
SpikeyMcSpikerson/SecondViewController.swift
|
mit
|
1
|
import UIKit
class SecondViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: Constants
let NumberCollectionViewIdentifier = "NumberCollectionViewCell"
// MARK: IBOutlets
@IBOutlet private weak var collectionView: UICollectionView!
// MARK: Private Properties
private let junk: [String] = {
print("Junk has been setup")
var someJunk: [String] = []
for index in 0...25 {
someJunk.append(String(index))
}
return someJunk
}()
// MARK: Init Methods
// if you implement the init() method for the view controller, you must implement the required init method
// for coder junk
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
title = "2nd"
}
init() {
super.init(nibName: nil, bundle: nil)
title = "2nd"
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
// MARK: <UICollectionViewDataSource>
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return junk.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NumberCollectionViewIdentifier, for: indexPath) as! NumberCollectionViewCell
cell.numLabel.text = junk[indexPath.row]
return cell
}
// MARK: Private Methods
private func setupCollectionView() {
let numberCollectionViewCellNib = UINib(nibName: NumberCollectionViewIdentifier, bundle: nil)
collectionView.register(numberCollectionViewCellNib, forCellWithReuseIdentifier: NumberCollectionViewIdentifier)
}
}
|
ee2ef3f8e007e583952edfb664c07596
| 28.202899 | 151 | 0.645658 | false | false | false | false |
danielsaidi/iExtra
|
refs/heads/master
|
iExtra/UI/Extensions/UIImage/UIImage+Rotated.swift
|
mit
|
1
|
//
// UIImage+Rotated.swift
// iExtra
//
// Created by Daniel Saidi on 2016-01-12.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
// Source: http://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift
//
import UIKit
public extension UIImage {
func rotated(byDegrees degrees: CGFloat) -> UIImage? {
return rotated(byDegrees: degrees, flipped: false)
}
func rotated(byDegrees degrees: CGFloat, flipped flip: Bool) -> UIImage? {
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(Double.pi)
}
// Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size))
let transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
rotatedViewBox.transform = transform
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin so we will rotate and scale around the center.
bitmap?.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
// Rotate the image context
bitmap?.rotate(by: degreesToRadians(degrees))
// Draw the rotated/scaled image into the context
var yFlip: CGFloat
yFlip = flip ? CGFloat(-1.0) : CGFloat(1.0)
bitmap?.scaleBy(x: yFlip, y: -1.0)
bitmap?.draw(cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
|
2651bdf312a3a86fb85d37544b712467
| 34.634615 | 123 | 0.636805 | false | false | false | false |
ZachOrr/TBAKit
|
refs/heads/master
|
Testing/XCTestCase+Mock.swift
|
mit
|
1
|
import Foundation
import XCTest
import TBAKit
public protocol TBAKitMockable: class {
var kit: TBAKit! { get set }
var session: MockURLSession! { get set }
}
extension TBAKitMockable where Self: XCTestCase {
public func setUpTBAKitMockable() {
kit = TBAKit(apiKey: "abcd123")
session = MockURLSession()
kit.urlSession = session
}
}
extension XCTestCase {
public func sendUnauthorizedStub(for task: URLSessionDataTask, data: Data?) {
guard let mockRequest = task as? MockURLSessionDataTask else {
XCTFail()
return
}
guard let requestURL = mockRequest.testRequest?.url else {
XCTFail()
return
}
let response = HTTPURLResponse(url: requestURL, statusCode: 401, httpVersion: nil, headerFields: nil)
mockRequest.testResponse = response
if let completionHandler = mockRequest.completionHandler {
completionHandler(data, response, nil)
}
}
public func sendSuccessStub(for task: URLSessionDataTask, data: Data?, with code: Int = 200, headerFields: [String : String]? = nil) {
guard let mockRequest = task as? MockURLSessionDataTask else {
XCTFail()
return
}
guard let requestURL = mockRequest.testRequest?.url else {
XCTFail()
return
}
let response = HTTPURLResponse(url: requestURL, statusCode: code, httpVersion: nil, headerFields: headerFields)
mockRequest.testResponse = response
if let completionHandler = mockRequest.completionHandler {
completionHandler(data, response, nil)
}
}
}
|
ed9df41dda9af2941d74a4e846bbcad5
| 29.298246 | 138 | 0.62652 | false | true | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
FreetimeWatch Extension/RepoInboxController.swift
|
mit
|
1
|
//
// RepoInboxController.swift
// FreetimeWatch Extension
//
// Created by Ryan Nystrom on 4/27/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import WatchKit
import Foundation
import GitHubAPI
import DateAgo
import StringHelpers
final class RepoInboxController: WKInterfaceController {
struct Context {
let client: Client
let repo: V3Repository
let notifications: [V3Notification]
let dataController: InboxDataController
}
@IBOutlet var table: WKInterfaceTable!
private var context: Context?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard let context = context as? Context else { return }
self.context = context
setTitle(context.repo.name)
reload()
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
// only handle selections on the "mark read" button
guard rowIndex == 0, let context = self.context else { return }
let repo = context.repo
let dataController = context.dataController
dataController.read(repository: repo)
context.client.send(V3MarkRepositoryNotificationsRequest(
owner: repo.owner.login,
repo: repo.name
)) { result in
// will unwind the read even though the controller is pushed
if case .failure = result {
dataController.unread(repository: repo)
}
}
pop()
}
// MARK: Private API
func reload() {
guard let context = self.context else { return }
table.insertRows(at: IndexSet(integer: 0), withRowType: ReadAllRowController.rowControllerIdentifier)
let controller = table.rowController(at: 0) as? ReadAllRowController
controller?.setup()
table.insertRows(at: IndexSet(integersIn: 1 ..< context.notifications.count + 1), withRowType: RepoInboxRowController.rowControllerIdentifier)
for (i, n) in context.notifications.enumerated() {
guard let row = table.rowController(at: i+1) as? RepoInboxRowController else { continue }
row.setup(with: n)
}
}
}
|
f980e53bfa592084655988c69cc51166
| 28.613333 | 150 | 0.652859 | false | false | false | false |
yidahis/ShopingCart
|
refs/heads/master
|
ShopingCart/ShopingCartView.swift
|
apache-2.0
|
1
|
//100
// ShopingCartView.swift
// ShopingCart
//
// Created by zhouyi on 2017/9/15.
// Copyright © 2017年 NewBornTown, Inc. All rights reserved.
//
import UIKit
let XSpace: CGFloat = 10
typealias shopCartViewDoneAction = (SKUModel?) -> Void
class ShopingCartView: UIView {
//MARK: - property
var tableView: UITableView!
var doneButton: UIButton!
let doneButtonHeight: CGFloat = 50
var selectDoneAction: shopCartViewDoneAction?
var closeActionBlock: NoneArgmentAction?
var isShowing: Bool = false
var viewModel: ShopingCartViewModel = ShopingCartViewModel()
//MARK: - life
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(ShopingCartViewHeaderCell.classForCoder(), forCellReuseIdentifier: "header")
tableView.register(ShopingCartViewCell.classForCoder(), forCellReuseIdentifier: "cell")
tableView.register(ShopingCartViewBottomCell.classForCoder(), forCellReuseIdentifier: "bottom")
tableView.layoutMargins = UIEdgeInsets.zero
self.addSubview(tableView)
doneButton = UIButton()
self.addSubview(doneButton)
doneButton.setTitle("确定", for: UIControlState.normal)
doneButton.backgroundColor = UIColor.red
doneButton.addTarget(self, action: #selector(doneButtonAction), for: UIControlEvents.touchUpInside)
tableView.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("keypath: " + keyPath!)
print(change)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
if isShowing {
self.tableView.frame = CGRect(x: 0, y: self.height/3, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}else{
tableView.frame = CGRect(x: 0, y: self.height, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
doneButton.frame = CGRect(x: 0, y: tableView.bottom, width: self.width, height: self.doneButtonHeight)
}
}
func show() {
isShowing = true
self.superview?.bringSubview(toFront: self)
UIView.animate(withDuration: 0.25, delay: 0.25, options: .curveEaseIn, animations: {
self.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
self.tableView.frame = CGRect(x: 0, y: self.height/3, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}) { (finished) in
}
}
//MARK: - private method
@objc func doneButtonAction(){
selectDoneAction?(viewModel.selectSkuModel)
}
func close(){
isShowing = false
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: {
self.backgroundColor = UIColor(white: 0, alpha: 0)
self.tableView.frame = CGRect(x: 0, y: self.height, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}) { (finished) in
self.superview?.sendSubview(toBack: self)
}
}
//计算第一行minY 到 最后一行 MaxY 之间的差值
func height(contentItem items: [SpecItem]) -> CGFloat{
let maxX: CGFloat = self.width - XSpace * 2
var minY: CGFloat = 0
var minX: CGFloat = XSpace
items.forEach { (item) in
let width = item.content.stringWidthWithSpace(fontSize: 14)
minX = minX + width + XSpace + 2
if minX >= maxX {
minY = minY + 28 + XSpace
minX = XSpace
}
}
return minY + 28
}
func updateShopingCartViewCellData(tip: String, title: String){
for i in 0..<viewModel.mySpecs.count {
let specs = viewModel.mySpecs[i]
if specs.key == tip {
for j in 0..<specs.vaules.count {
let item = specs.vaules[j]
if item.content == title{
viewModel.mySpecs[i].vaules[j].isSelected = true
}else{
viewModel.mySpecs[i].vaules[j].isSelected = false
}
}
}
}
}
/// 筛选已选样式的数据
///
/// - Returns: ShopingCartViewHeaderCellModel
func headerViewData() -> ShopingCartViewHeaderCellModel?{
var selectedKeyValue = [String: String]()
//筛选出已选的样式选项
viewModel.mySpecs.forEach { (specs) in
specs.vaules.forEach({ (item) in
if item.isSelected == true {
selectedKeyValue[specs.key] = item.content
}
})
}
guard let selectedSpec = selectedKeyValue.first else{
return nil
}
var skuModel: SKUModel?
viewModel.skuArray.forEach { (model) in
model.specs.forEach({ (spec) in
if spec.spec_key == selectedSpec.key, spec.spec_value == selectedSpec.value {
skuModel = model
}
})
}
guard let model = skuModel else {
return nil
}
if model.specs.count == selectedKeyValue.count{
viewModel.selectSkuModel = model
}
var content: String = ""
selectedKeyValue.forEach { (keyValue) in
content.append(keyValue.value + " ")
}
return ShopingCartViewHeaderCellModel(thumbUrl: model.thumb_url, price: model.group_price, content: content)
}
func lowAndHightPriceModel() -> (SKUModel?, SKUModel?){
guard let first = viewModel.skuArray.first else {
return (nil, nil)
}
var low: SKUModel = first
var high: SKUModel = first
viewModel.skuArray.forEach { (model) in
if model.group_price > high.group_price {
high = model
}
if model.group_price < low.group_price {
low = model
}
}
return (low, high)
}
}
//MARK: - UITableViewDelegate,UITableViewDataSource
extension ShopingCartView: UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return 112
case viewModel.mySpecs.count + 1:
return 55
default:
if viewModel.mySpecs.count > indexPath.row - 1 {
return 34 + height(contentItem: Array(viewModel.mySpecs[indexPath.row - 1].vaules)) + 2*XSpace
}
return 0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if viewModel.mySpecs.count > 0{
return viewModel.mySpecs.count + 2
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
guard let cell: ShopingCartViewHeaderCell = tableView.dequeueReusableCell(withIdentifier: "header") as? ShopingCartViewHeaderCell else {
return ShopingCartViewHeaderCell()
}
//是否有选择颜色尺码等,有就直接加载已选数据,否则加载默认数据
if let model = headerViewData() {
cell.viewModel = model
}else {
let (low, high) = lowAndHightPriceModel()
if let lowModel = low, let hightModel = high {
cell.priceModel(low: lowModel, high: hightModel)
}
}
cell.clossButtonActionBlock = { [weak self] in
self?.close()
}
return cell
case viewModel.mySpecs.count + 1 :
guard let cell: ShopingCartViewBottomCell = tableView.dequeueReusableCell(withIdentifier: "bottom") as? ShopingCartViewBottomCell else {
return ShopingCartViewBottomCell()
}
return cell
default:
guard let cell: ShopingCartViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ShopingCartViewCell else {
return ShopingCartViewCell()
}
if viewModel.mySpecs.count > indexPath.row - 1 {
cell.model = viewModel.mySpecs[indexPath.row - 1]
}
cell.buttonTapAction = { [weak self] (tip,title) in
print(tip + " " + title)
self?.updateShopingCartViewCellData(tip: tip, title: title)
self?.tableView.reloadData()
}
return cell
}
}
}
|
5337f5c4b0d046396b0f7f60c38c325f
| 34.412639 | 151 | 0.576842 | false | false | false | false |
saurabytes/JSQCoreDataKit
|
refs/heads/develop
|
Example/ExampleModel/ExampleModel/Employee.swift
|
mit
|
1
|
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import CoreData
public final class Employee: NSManagedObject {
static public let entityName = "Employee"
@NSManaged public var name: String
@NSManaged public var birthDate: NSDate
@NSManaged public var salary: NSDecimalNumber
@NSManaged public var company: Company?
public init(context: NSManagedObjectContext,
name: String,
birthDate: NSDate,
salary: NSDecimalNumber,
company: Company? = nil) {
let entity = NSEntityDescription.entityForName(Employee.entityName, inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.name = name
self.birthDate = birthDate
self.salary = salary
self.company = company
}
public class func newEmployee(context: NSManagedObjectContext, company: Company? = nil) -> Employee {
let name = "Employee " + String(NSUUID().UUIDString.characters.split { $0 == "-" }.first!)
return Employee(context: context,
name: name,
birthDate: NSDate.distantPast(),
salary: NSDecimalNumber(unsignedInt: arc4random_uniform(100_000)),
company: company)
}
@objc
private override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
|
77fd52eb5320947705c6bc92070da679
| 28.444444 | 121 | 0.650674 | false | false | false | false |
kkolli/MathGame
|
refs/heads/master
|
client/Speedy/AppDelegate.swift
|
gpl-2.0
|
1
|
//
// AppDelegate.swift
// SwiftBook
//
// Created by Krishna Kolli
// Copyright (c) Krishna Kolli. All rights reserved.
//import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var mpcHandler:MPCHandler = MPCHandler()
var user:FBGraphUser?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
FBLoginView.self
FBProfilePictureView.self
// google analytics
GAI.sharedInstance().trackUncaughtExceptions = true
GAI.sharedInstance().dispatchInterval = 20
GAI.sharedInstance().logger.logLevel = GAILogLevel.Verbose
GAI.sharedInstance().trackerWithTrackingId("UA-36281325-2")
// fabric - crashlytics
Fabric.with([Crashlytics()])
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
var wasHandled:Bool = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
return wasHandled
}
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:.
}
}
|
4655fba9f3fc3bf46a6e81a4b60fb4ec
| 43.742424 | 285 | 0.727057 | false | false | false | false |
katsumeshi/PhotoInfo
|
refs/heads/master
|
PhotoInfo/Classes/TabBarController.swift
|
mit
|
1
|
//
// tabBarController.swift
// photoinfo
//
// Created by Yuki Matsushita on 7/16/15.
// Copyright (c) 2015 Yuki Matsushita. All rights reserved.
//
import FontAwesome
import ReactiveCocoa
class TabBarController: UITabBarController, UITabBarControllerDelegate {
let reviewUrl = NSURL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=998243965&mt=8&type=Purple+Software")!
override func viewDidLoad() {
super.viewDidLoad()
setUpAppearance()
didBecomeNotificationAction()
self.delegate = self
}
}
extension TabBarController {
// MARK: - Private Methods
private func setUpAppearance() {
self.view.backgroundColor = UIColor.whiteColor()
UITabBar.appearance().tintColor = UIColor.whiteColor()
self.childViewControllers.enumerate().forEach {
$0.element.tabBarItem = TabType(rawValue: $0.index)?.item
}
}
private func didBecomeNotificationAction() {
let didbecomeSignal = NSNotificationCenter.addObserver(UIApplicationDidBecomeActiveNotification)
didbecomeSignal.subscribeNext { _ in
if AppReview.canShow() {
self.showAppReviewRequestAlert()
}
}
}
private func showAppReviewRequestAlert() {
let alertView = UIAlertController(title: "Review the app, please".toGrobal(),
message: "Thank you for using the app:) Review tha app for updating the next feature".toGrobal(),
preferredStyle: .Alert)
let reviewAction = UIAlertAction(title: "Review due to satisfied".toGrobal(),
style: .Default) { _ in
UIApplication.sharedApplication().openURL(self.reviewUrl)
}
let noAction = UIAlertAction(title: "Don't review due to unsatisfied".toGrobal(), style: .Default, handler: nil)
let laterAction = UIAlertAction(title: "Review later".toGrobal(), style: .Default, handler: nil)
alertView.addAction(reviewAction)
alertView.addAction(noAction)
alertView.addAction(laterAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
}
|
77b01802fba31e51ec06a79e1069c34e
| 29.115942 | 148 | 0.71078 | false | false | false | false |
mlilback/rc2SwiftClient
|
refs/heads/master
|
Networking/ImageCache.swift
|
isc
|
1
|
//
// ImageCache.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Dispatch
import MJLLogger
import ReactiveSwift
import Model
public enum ImageCacheError: Error, Rc2DomainError {
case noSuchImage
case failedToLoadFromNetwork
}
/// Handles caching of SessionImage(s)
public class ImageCache {
///to allow dependency injection
var fileManager: Foundation.FileManager
///to allow dependency injection
var workspace: AppWorkspace?
/// the client used to fetch images from the network
let restClient: Rc2RestClient
///caching needs to be unique for each server. we don't care what the identifier is, just that it is unique per host
///mutable because we need to be able to read it from an archive
fileprivate(set) var hostIdentifier: String
fileprivate var cache: NSCache<AnyObject, AnyObject>
fileprivate var metaCache: [Int: SessionImage]
/// all cached images sorted in batches
public let images: Property< [SessionImage] >
private let _images: MutableProperty< [SessionImage] >
fileprivate(set) lazy var cacheUrl: URL =
{
var result: URL?
do {
result = try AppInfo.subdirectory(type: .cachesDirectory, named: "\(self.hostIdentifier)/images")
} catch let error as NSError {
Log.error("got error creating image cache direcctory: \(error)", .cache)
assertionFailure("failed to create image cache dir")
}
return result!
}()
public static var supportsSecureCoding: Bool { return true }
init(restClient: Rc2RestClient, fileManager fm: Foundation.FileManager = Foundation.FileManager(), hostIdentifier hostIdent: String)
{
self.restClient = restClient
fileManager = fm
cache = NSCache()
metaCache = [:]
hostIdentifier = hostIdent
_images = MutableProperty< [SessionImage] >([])
images = Property< [SessionImage] >(capturing: _images)
}
/// loads cached data from json serialized by previous call to toJSON()
///
/// - Parameter sate: the state data to restore from
/// - Throws: decoding errors
public func restore(state: SessionState.ImageCacheState) throws {
self.hostIdentifier = state.hostIdentifier
state.images.forEach { metaCache[$0.id] = $0 }
adjustImageArray()
}
/// serializes cache state
///
/// - Parameter state: where to save the state to
public func save(state: inout SessionState.ImageCacheState) throws
{
state.hostIdentifier = hostIdentifier
state.images = Array(metaCache.values)
}
/// Returns an image from the cache if it is in memory or on disk. returns nil if not in cache
///
/// - Parameter imageId: the id of the image to get
/// - Returns: the image, or nil if there is no cached image with that id
func image(withId imageId: Int) -> PlatformImage? {
if let pitem = cache.object(forKey: imageId as AnyObject) as? NSPurgeableData {
defer { pitem.endContentAccess() }
if pitem.beginContentAccess() {
return PlatformImage(data: NSData(data: pitem as Data) as Data)
}
}
//read from disk
let imgUrl = URL(fileURLWithPath: "\(imageId).png", relativeTo: cacheUrl)
guard let imgData = try? Data(contentsOf: imgUrl) else {
return nil
}
cache.setObject(NSPurgeableData(data: imgData), forKey: imageId as AnyObject)
return PlatformImage(data: imgData)
}
/// caches to disk and in memory
private func cacheImageFromServer(_ img: SessionImage) {
//cache to disk
Log.info("caching image \(img.id)", .cache)
let destUrl = URL(fileURLWithPath: "\(img.id).png", isDirectory: false, relativeTo: cacheUrl)
try? img.imageData.write(to: destUrl, options: [.atomic])
//cache in memory
let pdata = NSData(data: img.imageData) as Data
cache.setObject(pdata as AnyObject, forKey: img.id as AnyObject)
metaCache[img.id] = img
}
/// Stores an array of SessionImage objects
///
/// - Parameter images: the images to save to the cache
func cache(images: [SessionImage]) {
images.forEach { cacheImageFromServer($0) }
adjustImageArray()
}
/// Returns the images belonging to a particular batch
///
/// - Parameter batchId: the batch to get images for
/// - Returns: an array of images
public func sessionImages(forBatch batchId: Int) -> [SessionImage] {
Log.debug("look for batch \(batchId)", .cache)
return metaCache.values.filter({ $0.batchId == batchId }).sorted(by: { $0.id < $1.id })
}
/// Removes all images from the in-memory cache
public func clearCache() {
cache.removeAllObjects()
metaCache.removeAll()
_images.value = []
}
/// image(withId:) should have been called at some point to make sure the image is cached
public func urlForCachedImage(_ imageId: Int) -> URL {
return URL(fileURLWithPath: "\(imageId).png", isDirectory: false, relativeTo: self.cacheUrl).absoluteURL
}
/// Loads an image from memory, disk, or the network based on if it is cached
public func image(withId imageId: Int) -> SignalProducer<PlatformImage, ImageCacheError> {
assert(workspace != nil, "imageCache.workspace must be set before using")
let fileUrl = URL(fileURLWithPath: "\(imageId).png", isDirectory: false, relativeTo: self.cacheUrl)
return SignalProducer<PlatformImage, ImageCacheError> { observer, _ in
// swiftlint:disable:next force_try
if try! fileUrl.checkResourceIsReachable() {
observer.send(value: PlatformImage(contentsOf: fileUrl)!)
observer.sendCompleted()
return
}
//need to fetch from server
let sp = self.restClient.downloadImage(imageId: imageId, from: self.workspace!, destination: fileUrl)
sp.startWithResult { result in
if case .success(let imgUrl) = result, let pimg = PlatformImage(contentsOf: imgUrl) {
observer.send(value: pimg)
observer.sendCompleted()
} else {
observer.send(error: .failedToLoadFromNetwork)
}
}
}
}
/// reset the images property grouped by batch
private func adjustImageArray() {
_images.value = metaCache.values.sorted { img1, img2 in
guard img1.batchId == img2.batchId else { return img1.batchId < img2.batchId }
//using id because we know they are in proper order, might be created too close together to use dateCreated
return img1.id < img2.id
}
}
}
|
edfaed8a60c2f91db8621ffcc2a5aad5
| 34.114286 | 133 | 0.720749 | false | false | false | false |
lakshay35/UGA-Calendar
|
refs/heads/master
|
EITS/AddViewController.swift
|
apache-2.0
|
1
|
//
// AddViewController.swift
// EITS
//
// Created by Lakshay Sharma on 12/9/16.
// Copyright © 2016 Lakshay Sharma. All rights reserved.
//
import UIKit
class AddViewController: UIViewController {
@IBOutlet weak var eventNameLabel: UITextField!
@IBOutlet weak var fromDatePicker: UIDatePicker!
@IBOutlet weak var toDatePicker: UIDatePicker!
var cell: Event? // The cell that populates the objects in the view
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.backgroundColor = UIColor.red
// Do any additional setup after loading the view.
/*
*
*
Sets up the view for editing if cell is not empty,
which means that the user selected a cell
*
*
*/
if let cell = cell {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
eventNameLabel.text = cell.eventName
fromDatePicker.date = dateFormatter.date(from: cell.eventStartDate)!
toDatePicker.date = dateFormatter.date(from: cell.eventEndDate)!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancel(_ sender: Any) {
if(presentingViewController is UINavigationController) {
self.dismiss(animated: true, completion: nil)
} else {
self.navigationController!.popViewController(animated: true)
}
}
/*
*
*
Configures error handling if eventNameLabel is empty
or if there is a logic error between event timing
so that the application does not crash
*
*
*/
@IBAction func saveButton(_ sender: UIBarButtonItem) {
if (eventNameLabel.text == "") {
let alert = UIAlertController(title: "Error", message: "\"Event\" field empty", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else if (fromDatePicker.date > toDatePicker.date) {
let alert = UIAlertController(title: "Error", message: "Event start date is after end date. Please correct logic error", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else {
performSegue(withIdentifier: "saveButtonPressed", sender: Any?.self)
}
}
/*
*
*
Edits data so that appropriate data
can be pulled from the this file in
the root view controller
*
*
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
cell = Event(name: eventNameLabel.text!, start: dateToString(date: fromDatePicker.date), end: dateToString(date: toDatePicker.date))
}
/*
*
*
Custom function to convert Date object to
a String for assignment to String type variables
*
*
*/
func dateToString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
return dateFormatter.string(from: date)
}
/*
// 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.
}
*/
}
|
8745f91fd1ffd19f13c2c387d34877e5
| 31.016949 | 156 | 0.625463 | false | false | false | false |
jonasman/TeslaSwift
|
refs/heads/master
|
Sources/TeslaSwift/Model/Authentication.swift
|
mit
|
1
|
//
// AuthToken.swift
// TeslaSwift
//
// Created by Joao Nunes on 04/03/16.
// Copyright © 2016 Joao Nunes. All rights reserved.
//
import Foundation
import CryptoKit
private let oAuthClientID: String = "81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384"
private let oAuthWebClientID: String = "ownerapi"
private let oAuthClientSecret: String = "c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3"
private let oAuthScope: String = "openid email offline_access"
private let oAuthRedirectURI: String = "https://auth.tesla.com/void/callback"
open class AuthToken: Codable {
open var accessToken: String?
open var tokenType: String?
open var createdAt: Date? = Date()
open var expiresIn: TimeInterval?
open var refreshToken: String?
open var idToken: String?
open var isValid: Bool {
if let createdAt = createdAt, let expiresIn = expiresIn {
return -createdAt.timeIntervalSinceNow < expiresIn
} else {
return false
}
}
public init(accessToken: String) {
self.accessToken = accessToken
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
accessToken = try? container.decode(String.self, forKey: .accessToken)
tokenType = try? container.decode(String.self, forKey: .tokenType)
createdAt = (try? container.decode(Date.self, forKey: .createdAt)) ?? Date()
expiresIn = try? container.decode(TimeInterval.self, forKey: .expiresIn)
refreshToken = try? container.decode(String.self, forKey: .refreshToken)
idToken = try? container.decode(String.self, forKey: .idToken)
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case tokenType = "token_type"
case createdAt = "created_at"
case expiresIn = "expires_in"
case refreshToken = "refresh_token"
case idToken = "id_token"
}
}
class AuthTokenRequest: Encodable {
enum GrantType: String, Encodable {
case password
case refreshToken = "refresh_token"
}
var grantType: GrantType
var clientID: String = oAuthClientID
var clientSecret: String = oAuthClientSecret
var email: String?
var password: String?
var refreshToken: String?
init(email: String? = nil, password: String? = nil, grantType: GrantType = .password, refreshToken: String? = nil) {
self.email = email
self.password = password
self.grantType = grantType
self.refreshToken = refreshToken
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case grantType = "grant_type"
case clientID = "client_id"
case clientSecret = "client_secret"
case email = "email"
case password = "password"
case refreshToken = "refresh_token"
}
}
class AuthTokenRequestWeb: Encodable {
enum GrantType: String, Encodable {
case refreshToken = "refresh_token"
case authorizationCode = "authorization_code"
}
var grantType: GrantType
var clientID: String = oAuthWebClientID
var clientSecret: String = oAuthClientSecret
var codeVerifier: String?
var code: String?
var redirectURI: String?
var refreshToken: String?
var scope: String?
init(grantType: GrantType = .authorizationCode, code: String? = nil, refreshToken: String? = nil) {
if grantType == .authorizationCode {
codeVerifier = oAuthClientID.codeVerifier
self.code = code
redirectURI = oAuthRedirectURI
} else if grantType == .refreshToken {
self.refreshToken = refreshToken
self.scope = oAuthScope
}
self.grantType = grantType
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case grantType = "grant_type"
case clientID = "client_id"
case clientSecret = "client_secret"
case code = "code"
case redirectURI = "redirect_uri"
case refreshToken = "refresh_token"
case codeVerifier = "code_verifier"
case scope = "scope"
}
}
class AuthCodeRequest: Encodable {
var responseType: String = "code"
var clientID = oAuthWebClientID
var clientSecret = oAuthClientSecret
var redirectURI = oAuthRedirectURI
var scope = oAuthScope
let codeChallenge: String
var codeChallengeMethod = "S256"
var state = "teslaSwift"
init() {
self.codeChallenge = clientID.codeVerifier.challenge
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case clientID = "client_id"
case redirectURI = "redirect_uri"
case responseType = "response_type"
case scope = "scope"
case codeChallenge = "code_challenge"
case codeChallengeMethod = "code_challenge_method"
case state = "state"
}
func parameters() -> [URLQueryItem] {
return[
URLQueryItem(name: CodingKeys.clientID.rawValue, value: clientID),
URLQueryItem(name: CodingKeys.redirectURI.rawValue, value: redirectURI),
URLQueryItem(name: CodingKeys.responseType.rawValue, value: responseType),
URLQueryItem(name: CodingKeys.scope.rawValue, value: scope),
URLQueryItem(name: CodingKeys.codeChallenge.rawValue, value: codeChallenge),
URLQueryItem(name: CodingKeys.codeChallengeMethod.rawValue, value: codeChallengeMethod),
URLQueryItem(name: CodingKeys.state.rawValue, value: state)
]
}
}
extension String {
var codeVerifier: String {
let verifier = self.data(using: .utf8)!.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
.trimmingCharacters(in: .whitespaces)
return verifier
}
var challenge: String {
let hash = self.sha256
let challenge = hash.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
.trimmingCharacters(in: .whitespaces)
return challenge
}
var sha256: String {
let inputData = Data(self.utf8)
let hashed = SHA256.hash(data: inputData)
let hashString = hashed.compactMap { String(format: "%02x", $0) }.joined()
return hashString
}
func base64EncodedString() -> String {
let inputData = Data(self.utf8)
return inputData.base64EncodedString()
}
}
|
bdd465327ae24374ff6cb6f77a19ce75
| 30.032407 | 120 | 0.663136 | false | false | false | false |
quickthyme/PUTcat
|
refs/heads/master
|
PUTcat/Presentation/_Shared/AppColor.swift
|
apache-2.0
|
1
|
import UIKit
struct AppColor {
struct Blue {
static let Light = UIColor(red: 15/255, green: 150/255, blue: 230/255, alpha: 1)
static let Dark = UIColor(red: 0/255, green: 50/255, blue: 95/255, alpha: 1)
}
struct Gray {
static let Dark = UIColor(red: 85/255, green: 85/255, blue: 90/255, alpha: 1)
static let Light = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
}
struct Text {
static let Dark = UIColor.black
static let Light = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
static let VariableName = UIColor(red: 0.5, green: 0.0, blue: 0.25, alpha: 1.0)
static let VariableValue = UIColor(red: 0.0, green: 0.5, blue: 0.50, alpha: 1.0)
static let TransactionMethod = UIColor(red: 1.0, green: 0.4, blue: 0.4, alpha: 1.0)
static let TransactionDelivery = UIColor(red: 0.0, green: 0.50, blue: 0.00, alpha: 1.0)
static let TransactionURL = UIColor(red: 0.0, green: 0.25, blue: 0.50, alpha: 1.0)
static let TransactionPath = UIColor(red: 0.0, green: 0.50, blue: 0.50, alpha: 1.0)
}
static func setupGlobalAppearance() {
UINavigationBar.appearance().barStyle = UIBarStyle.blackTranslucent
UINavigationBar.appearance().barTintColor = AppColor.Gray.Dark
UINavigationBar.appearance().tintColor = UIColor.white
UITabBar.appearance().tintColor = AppColor.Gray.Dark
}
}
|
51c563f2a85c97b2c232e64532d7f59c
| 43.636364 | 95 | 0.624576 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
refs/heads/master
|
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/CellFactory/HLHotelDetailsAmenityCellFactory.swift
|
mit
|
1
|
struct AmenityConst {
static let depositKey = "deposit"
static let cleaningKey = "cleaning"
static let privateBathroomKey = "private_bathroom"
static let sharedBathroomKey = "shared_bathroom"
static let slugKey = "slug"
static let priceKey = "price"
}
class HLHotelDetailsAmenityCellFactory: HLHotelDetailsCellFactory {
static let kMaxAmenitiesCells = 5
static let kDefaultAmenityIconName = "amenitiesDefault"
fileprivate static let amenityImageNames: [String: String] = [
"free_parking": "amenitiesParking",
"parking" : "amenitiesParking",
"24_hours_front_desk_service" : "24hoursAmenitiesIcon",
"low_mobility_guests_welcome" : "disabledFriendly",
"restaurant_cafe" : "amenitiesRestaurant",
"bar" : "barAmenitiesIcon",
"business_centre" : "centerAmenitiesIcon",
"laundry_service" : "amenitiesLaundry",
"concierge_service" : "conciergeAmenitiesIcon",
"wi-fi_in_public_areas" : "amenitiesInternet",
"gym" : "amenitiesFitness",
"spa" : "spaAmenitiesIcon",
"pets_allowed" : "amenitiesPets",
"swimming_pool" : "amenitiesPool",
"lgbt_friendly" : "gayFriendlyAmenitiesIcon",
"medical_service" : "medicalServiceAmenitiesIcon",
"babysitting" : "babysittingAmenitiesIcon",
"children_care_activities" : "childrenActivitiesAmenitiesIcon",
"animation" : "animationAmenitiesIcon",
"bathtub" : "amenitiesTube",
"shower" : "showerAmenitiesIcon",
"tv" : "amenitiesTV",
"air_conditioning" : "amenitiesSnow",
"safe_box" : "safeAmenitiesIcon",
"mini_bar" : "minibarAmenitiesIcon",
"hairdryer" : "amenitiesHairdryer",
"coffee_tea" : "optionsBreakfast",
"bathrobes" : "robeAmenitiesIcon",
"daily_housekeeping" : "cleaningAmenitiesIcon",
"connecting_rooms" : "doorAmenitiesIcon",
"smoking_room" : "amenitiesSmoking",
"wi-fi_in_rooms" : "amenitiesInternet",
AmenityConst.privateBathroomKey : "amenitiesPrivateBathroom"
]
private static let amenitiesBlackList = [AmenityConst.depositKey, AmenityConst.cleaningKey, AmenityConst.sharedBathroomKey]
class func createAmenitiesInRoom(_ hotel: HDKHotel, tableView: UITableView) -> [TableItem] {
return createAmenitiesFromArray(hotel.roomAmenities(), tableView: tableView)
}
class func createAmenitiesInHotel(_ hotel: HDKHotel, tableView: UITableView) -> [TableItem] {
return createAmenitiesFromArray(hotel.hotelAmenities(), tableView: tableView)
}
fileprivate class func createAmenitiesFromArray(_ array: [HDKAmenity], tableView: UITableView) -> [TableItem] {
var flattenAmenities: [NamedHotelDetailsItem] = []
for amenity in array {
let key = amenity.slug
if !amenitiesBlackList.contains(key) && !amenity.name.isEmpty {
let keyWithPrice: String
if amenity.isFree {
keyWithPrice = "free_" + key
} else {
keyWithPrice = key
}
let itemImageKey = amenityImageNames[keyWithPrice] != nil ? keyWithPrice : key
let image = amenityIconWithKey(itemImageKey as NSString)
let item = AmenityItem(name: amenity.name, image: image)
flattenAmenities.append(item)
}
}
return HLTwoColumnCellsDataSource(flattenedItems: flattenAmenities, cellWidth: tableView.bounds.width, canFillHalfScreen: HLHotelDetailsFeaturesCell.canFillHalfScreen).splitItemsLongAtBottom()
}
class func amenityIconWithKey(_ key: NSString) -> UIImage {
if let imageName = amenityImageNames[key as String], let image = UIImage(named: imageName) {
return image
} else {
return UIImage(named: kDefaultAmenityIconName)!
}
}
}
|
c584bc5cbbb181ac3952efa816bbfdc7
| 41.06383 | 200 | 0.651239 | false | false | false | false |
Henawey/TheArabianCenter
|
refs/heads/master
|
TheArabianCenter/ShareWorker.swift
|
mit
|
1
|
//
// ShareWorker.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/23/17.
// Copyright (c) 2017 Ahmed Henawey. 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
import FacebookShare
import Social
import TwitterKit
import Result
class ShareWorker
{
// MARK: - Business Logic
func twitterShare(from viewController:UIViewController,request:Share.Request,
compilation:@escaping (Result<Share.Response,Share.Error>)->()) {
guard var urlAsString = Configuration.sharedInstance.twitterAppCardConfigurationLink() else{
compilation(.failure(Share.Error.configurationMissing))
return
}
guard let image = request.image else{
compilation(.failure(Share.Error.invalidData))
return
}
urlAsString.append("&offerId=\(request.id)")
guard let url = URL(string: urlAsString) else {
compilation(.failure(Share.Error.unknownError))
return
}
let composer = TWTRComposer()
composer.setText("\(request.title) - \(request.description)")
composer.setURL(url)
composer.setImage(image)
composer.show(from: viewController) { (result) in
switch result{
case .done:
let response = Share.Response(id: request.id, title: request.title, description: request.description,image:image)
compilation(.success(response))
case .cancelled:
compilation(.failure(Share.Error.shareCancelled))
}
}
}
func facebookShare(request:Share.Request,
compilation:@escaping (Result<Share.Response,Share.Error>)->()){
guard var urlAsString = Configuration.sharedInstance.facebookApplink() else{
compilation(.failure(Share.Error.configurationMissing))
return
}
guard let imageURL = request.imageURL else{
compilation(.failure(Share.Error.invalidData))
return
}
urlAsString.append("?offerId=\(request.id)")
guard let url = URL(string: urlAsString) else {
compilation(.failure(Share.Error.unknownError))
return
}
let shareContent = LinkShareContent(url: url, title: request.title, description: request.description, quote: nil, imageURL: imageURL)
let shareDialog:ShareDialog = ShareDialog(content: shareContent)
shareDialog.completion = { result in
switch result {
case let .success(result):
guard (result.postId != nil) else {
compilation(.failure(Share.Error.shareCancelled))
return
}
let response = Share.Response(id:request.id,title: request.title, description: request.description,imageURL:imageURL)
compilation(.success(response))
case .cancelled:
compilation(.failure(Share.Error.shareCancelled))
case let .failed(error):
compilation(.failure(Share.Error.failure(error: error)))
}
}
do{
try shareDialog.show()
}catch{
compilation(.failure(Share.Error.failure(error: error)))
}
}
}
|
86c77657b7e6f4355375a1d50e1a6003
| 32.971429 | 141 | 0.590692 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceKit/Sources/EurofurenceKit/Properties/AppGroupModelProperties.swift
|
mit
|
1
|
import EurofurenceWebAPI
import Foundation
public class AppGroupModelProperties: EurofurenceModelProperties {
public static let shared = AppGroupModelProperties()
private let userDefaults: UserDefaults
convenience init() {
guard let appGroupUserDefaults = UserDefaults(suiteName: SecurityGroup.identifier) else {
fatalError("Cannot instantiate App Group user defaults")
}
self.init(userDefaults: appGroupUserDefaults)
// Make sure the container directory and subdirectories exist.
let fileManager = FileManager.default
var unused: ObjCBool = false
if fileManager.fileExists(atPath: imagesDirectory.path, isDirectory: &unused) == false {
do {
try fileManager.createDirectory(at: imagesDirectory, withIntermediateDirectories: true)
} catch {
print("Failed to prepare images directory!")
}
}
}
init(userDefaults: UserDefaults) {
self.userDefaults = userDefaults
}
private struct Keys {
static let synchronizationGenerationTokenData = "EFKSynchronizationGenerationTokenData"
}
public var containerDirectoryURL: URL {
let fileManager = FileManager.default
guard let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: SecurityGroup.identifier) else {
fatalError("Couldn't resolve URL for shared container")
}
return url
}
public var synchronizationChangeToken: SynchronizationPayload.GenerationToken? {
get {
guard let data = userDefaults.data(forKey: Keys.synchronizationGenerationTokenData) else { return nil }
let decoder = JSONDecoder()
return try? decoder.decode(SynchronizationPayload.GenerationToken.self, from: data)
}
set {
if let newValue = newValue {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(newValue) else { return }
userDefaults.set(data, forKey: Keys.synchronizationGenerationTokenData)
} else {
userDefaults.set(nil, forKey: Keys.synchronizationGenerationTokenData)
}
}
}
public func removeContainerResource(at url: URL) throws {
try FileManager.default.removeItem(at: url)
}
}
|
e43851a781f302d2feb50f84d62a26c6
| 35.117647 | 120 | 0.640879 | false | false | false | false |
ZevEisenberg/Padiddle
|
refs/heads/main
|
Padiddle/Padiddle/View Model/DrawingViewModel.swift
|
mit
|
1
|
//
// DrawingViewModel.swift
// Padiddle
//
// Created by Zev Eisenberg on 10/7/15.
// Copyright © 2015 Zev Eisenberg. All rights reserved.
//
import UIKit
protocol DrawingViewModelDelegate: AnyObject {
func startDrawing()
func pauseDrawing()
func drawingViewModelUpdatedLocation(_ newLocation: CGPoint)
}
protocol DrawingViewBoundsVendor: AnyObject {
var bounds: CGRect { get }
}
class DrawingViewModel: NSObject { // must inherit from NSObject for @objc callbacks to work
private(set) var isDrawing = false
var needToMoveNibToNewStartLocation = true
let contextSize: CGSize
let contextScale: CGFloat
private let brushDiameter: CGFloat = 12
weak var delegate: DrawingViewModelDelegate?
weak var view: DrawingViewBoundsVendor?
private var colorManager: ColorManager?
private let spinManager: SpinManager
private let maxRadius: CGFloat
private var offscreenContext: CGContext!
private var points = Array(repeating: CGPoint.zero, count: 4)
private let screenScale = UIScreen.main.scale
private var displayLink: CADisplayLink?
var imageUpdatedCallback: ((CGImage) -> Void)?
lazy private var contextScaleFactor: CGFloat = {
// The context image is scaled as Aspect Fill, so the larger dimension
// of the bounds is the limiting factor
let maxDimension = max(self.contextSize.width, self.contextSize.height)
assert(maxDimension > 0)
// Given context side length L and bounds max dimension l,
// We are looking for a factor, ƒ, such that L * ƒ = l
// So we divide both sides by L to get ƒ = l / L
let ƒ = maxDimension / self.contextSize.width
return ƒ
}()
private var currentColor: UIColor {
guard let colorManager = colorManager else {
return UIColor.magenta
}
return colorManager.currentColor
}
required init(maxRadius: CGFloat, contextSize: CGSize, contextScale: CGFloat, spinManager: SpinManager) {
assert(maxRadius > 0)
self.maxRadius = maxRadius
self.contextSize = contextSize
self.contextScale = contextScale
self.spinManager = spinManager
super.init()
let success = configureOffscreenContext()
assert(success, "Problem creating bitmap context")
displayLink = CADisplayLink(target: self, selector: #selector(DrawingViewModel.displayLinkUpdated))
if #available(iOS 15.0, *) {
displayLink?.preferredFrameRateRange = .init(minimum: 60, maximum: 120, preferred: 120)
}
displayLink?.add(to: .main, forMode: .default)
}
func addPoint(_ point: CGPoint) {
let scaledPoint = convertViewPointToContextCoordinates(point)
let distance = CGPoint.distanceBetween(points[3], scaledPoint)
if distance > 2.25 {
points.removeFirst()
points.append(scaledPoint)
addLineSegmentBasedOnUpdatedPoints()
}
}
// MARK: Drawing
func startDrawing() {
isDrawing = true
}
func stopDrawing() {
isDrawing = false
}
func clear() {
offscreenContext.setFillColor(UIColor.white.cgColor)
offscreenContext.fill(CGRect(origin: .zero, size: contextSize))
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
func restartAtPoint(_ point: CGPoint) {
let convertedPoint = convertViewPointToContextCoordinates(point)
points = Array(repeating: convertedPoint, count: points.count)
addLineSegmentBasedOnUpdatedPoints()
}
func setInitialImage(_ image: UIImage) {
let rect = CGRect(origin: .zero, size: contextSize)
offscreenContext.draw(image.cgImage!, in: rect)
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
private func addLineSegmentBasedOnUpdatedPoints() {
let pathSegment = CGPath.smoothedPathSegment(points: points)
offscreenContext.addPath(pathSegment)
offscreenContext.setStrokeColor(currentColor.cgColor)
offscreenContext.strokePath()
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
// Saving & Loading
func snapshot(_ orientation: UIInterfaceOrientation) -> UIImage {
let (imageOrientation, rotation) = orientation.imageRotation
let cacheCGImage = offscreenContext.makeImage()!
let unrotatedImage = UIImage(cgImage: cacheCGImage, scale: UIScreen.main.scale, orientation: imageOrientation)
let rotatedImage = unrotatedImage.imageRotatedByRadians(rotation)
return rotatedImage
}
func getSnapshotImage(interfaceOrientation: UIInterfaceOrientation, completion: @escaping (EitherImage) -> Void) {
DispatchQueue.global(qos: .default).async {
let image = self.snapshot(interfaceOrientation)
// Share raw PNG data if we can, because it results in sharing a PNG image,
// which is desirable for the large chunks of color in this app.
if let pngData = image.pngData() {
DispatchQueue.main.async {
completion(.png(pngData))
}
}
else {
// If there was a problem, fall back to saving the original image
DispatchQueue.main.async {
completion(.image(image))
}
}
}
}
func persistImageInBackground() {
let image = self.snapshot(.portrait)
ImageIO.persistImageInBackground(image, contextScale: contextScale, contextSize: contextSize)
}
func loadPersistedImage() {
ImageIO.loadPersistedImage(contextScale: contextScale, contextSize: contextSize) { image in
if let image = image {
self.setInitialImage(image)
}
}
}
}
extension DrawingViewModel {
@objc func displayLinkUpdated() {
updateMotion()
}
}
extension DrawingViewModel: RecordingDelegate {
@objc func recordingStatusChanged(_ recording: Bool) {
if recording {
delegate?.startDrawing()
}
else {
delegate?.pauseDrawing()
}
}
@objc func motionUpdatesStatusChanged(_ updates: Bool) {
if updates {
startMotionUpdates()
}
else {
stopMotionUpdates()
}
}
}
extension DrawingViewModel: RootColorManagerDelegate {
func colorManagerPicked(_ colorManager: ColorManager) {
var newManager = colorManager
newManager.maxRadius = maxRadius
self.colorManager = newManager
}
}
extension DrawingViewModel { // Coordinate conversions
private func convertViewPointToContextCoordinates(_ point: CGPoint) -> CGPoint {
guard let view = view else {
fatalError("Not having a view represents a programmer error")
}
var newPoint = point
// 1. Multiply the point by the reciprocal of the context scale factor
newPoint.x *= (1 / contextScaleFactor)
newPoint.y *= (1 / contextScaleFactor)
// 2. Get the size of self in context coordinates
let viewSize = view.bounds.size
let scaledViewSize = CGSize(
width: viewSize.width * (1 / contextScaleFactor),
height: viewSize.height * (1 / contextScaleFactor)
)
// 3. Get the difference in size between self and the context
let difference = CGSize(
width: contextSize.width - scaledViewSize.width,
height: contextSize.height - scaledViewSize.height
)
// 4. Shift the point by half the difference in width and height
newPoint.x += difference.width / 2
newPoint.y += difference.height / 2
return newPoint
}
func convertContextRectToViewCoordinates(_ rect: CGRect) -> CGRect {
guard !rect.equalTo(CGRect.null) else { return CGRect.null }
guard let view = view else { fatalError("Not having a view represents a programmer error") }
// 1. Get the size of the context in self coordinates
let scaledContextSize = CGSize(
width: contextSize.width * contextScaleFactor,
height: contextSize.height * contextScaleFactor
)
// 2. Get the difference in size between self and the context
let boundsSize = view.bounds.size
let difference = CGSize(
width: scaledContextSize.width - boundsSize.width,
height: scaledContextSize.height - boundsSize.height
)
// 3. Scale the rect by the context scale factor
let scaledRect = rect.applying(CGAffineTransform(scaleX: contextScaleFactor, y: contextScaleFactor))
// 4. Shift the rect by negative the half the difference in width and height
let offsetRect = scaledRect.offsetBy(dx: -difference.width / 2.0, dy: -difference.height / 2.0)
return offsetRect
}
func convertContextPointToViewCoordinates(_ point: CGPoint) -> CGPoint {
guard let view = view else {
fatalError("Not having a view represents a programmer error")
}
// 1. Get the size of the context in self coordinates
let scaledContextSize = CGSize(
width: contextSize.width * contextScaleFactor,
height: contextSize.height * contextScaleFactor
)
// 2. Get the difference in size between self and the context
let boundsSize = view.bounds.size
let difference = CGSize(
width: scaledContextSize.width - boundsSize.width,
height: scaledContextSize.height - boundsSize.height
)
// 3. Scale the rect by the context scale factor
let scaledPoint = point.applying(CGAffineTransform(scaleX: contextScaleFactor, y: contextScaleFactor))
// 4. Shift the rect by negative the half the difference in width and height
let offsetPoint = scaledPoint.offsetBy(dx: -difference.width / 2.0, dy: -difference.height / 2.0)
return offsetPoint
}
}
// MARK: Context configuration
private extension DrawingViewModel {
func configureOffscreenContext() -> Bool {
let bitmapBytesPerRow: Int
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes: 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = Int(contextSize.width) * bytesPerPixel * Int(screenScale)
let widthPx = Int(contextSize.width * screenScale)
let heightPx = Int(contextSize.height * screenScale)
let context = CGContext(
data: nil,
width: widthPx,
height: heightPx,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bitmapBytesPerRow,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
)
guard context != nil else {
assertionFailure("Problem creating context")
return false
}
offscreenContext = context
// Scale by screen scale because the context is in pixels, not points.
// If we don't invert the y axis, the world will be turned upside down
offscreenContext?.translateBy(x: 0, y: CGFloat(heightPx))
offscreenContext?.scaleBy(x: screenScale, y: -screenScale)
offscreenContext?.setLineCap(.round)
offscreenContext?.setLineWidth(brushDiameter)
clear()
return true
}
}
// MARK: Core Motion
extension DrawingViewModel {
func startMotionUpdates() {
// startDrawing()
spinManager.startMotionUpdates()
}
func stopMotionUpdates() {
stopDrawing()
spinManager.stopMotionUpdates()
}
@objc func updateMotion() {
if let deviceMotion = spinManager.deviceMotion {
let zRotation = deviceMotion.rotationRate.z
let radius = maxRadius / UIDevice.gyroMaxValue * CGFloat(fabs(zRotation))
// Yaw is on the range [-π...π]. Remap to [0...π]
let theta = deviceMotion.attitude.yaw + .pi
let x = radius * CGFloat(cos(theta)) + contextSize.width / 2.0
let y = radius * CGFloat(sin(theta)) + contextSize.height / 2.0
colorManager?.radius = radius
colorManager?.theta = CGFloat(theta)
delegate?.drawingViewModelUpdatedLocation(CGPoint(x: x, y: y))
}
}
}
enum EitherImage {
case png(Data)
case image(UIImage)
var valueForSharing: Any {
switch self {
case .png(let data): return data
case .image(let image): return image
}
}
}
|
8941202782ebded219df83e81529dfba
| 30.126829 | 118 | 0.642846 | false | false | false | false |
yeziahehe/Gank
|
refs/heads/master
|
Gank/ViewControllers/New/NewViewController.swift
|
gpl-3.0
|
1
|
//
// NewViewController.swift
// Gank
//
// Created by 叶帆 on 2016/10/27.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
import Kingfisher
import UserNotifications
final class NewViewController: BaseViewController {
fileprivate var isNoData = false
@IBOutlet var dailyGankButton: UIBarButtonItem!
@IBOutlet var calendarButton: UIBarButtonItem!
@IBOutlet weak var tipView: UIView!
@IBOutlet weak var newTableView: UITableView! {
didSet {
newTableView.isScrollEnabled = false
newTableView.tableHeaderView = coverHeaderView
newTableView.tableFooterView = UIView()
newTableView.separatorStyle = .none
newTableView.rowHeight = 158
newTableView.registerNibOf(DailyGankCell.self)
newTableView.registerNibOf(DailyGankLoadingCell.self)
}
}
fileprivate lazy var activityIndicatorView: UIActivityIndicatorView = {
let activityView = UIActivityIndicatorView(style: .white)
activityView.hidesWhenStopped = true
return activityView
}()
fileprivate lazy var coverHeaderView: CoverHeaderView = {
let headerView = CoverHeaderView.instanceFromNib()
headerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 235)
return headerView
}()
fileprivate lazy var noDataFooterView: NoDataFooterView = {
let noDataFooterView = NoDataFooterView.instanceFromNib()
noDataFooterView.reasonAction = { [weak self] in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let networkViewController = storyboard.instantiateViewController(withIdentifier: "NetworkViewController")
self?.navigationController?.pushViewController(networkViewController , animated: true)
}
noDataFooterView.reloadAction = { [weak self] in
self?.updateNewView()
}
noDataFooterView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: GankConfig.getScreenHeight()-64)
return noDataFooterView
}()
fileprivate lazy var customFooterView: CustomFooterView = {
let footerView = CustomFooterView.instanceFromNib()
footerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 73)
return footerView
}()
fileprivate var isGankToday: Bool = true
fileprivate var meiziGank: Gank?
fileprivate var gankCategories: [String] = []
fileprivate var gankDictionary: [String: Array<Gank>] = [:]
deinit {
NotificationCenter.default.removeObserver(self)
newTableView?.delegate = nil
gankLog.debug("deinit NewViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
updateNewView()
NotificationCenter.default.addObserver(self, selector: #selector(NewViewController.refreshUIWithNotification(_:)), name: GankConfig.NotificationName.chooseGank, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(NewViewController.refreshUIWithPush(_:)), name: GankConfig.NotificationName.push, object: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showDetail":
let vc = segue.destination as! GankDetailViewController
let url = sender as! String
vc.gankURL = url
default:
break
}
}
@IBAction func closeTip(_ sender: UIButton) {
tipView.isHidden = true
}
@IBAction func getNewGank(_ sender: UIBarButtonItem) {
updateNewView(mode: .today)
}
@IBAction func showCalendar(_ sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "showCalendar", sender: nil)
}
@objc fileprivate func refreshUIWithNotification(_ notification: Notification) {
guard let date = notification.object as? String else {
return
}
updateNewView(mode: .date, isChoose: true, date: date)
}
@objc fileprivate func refreshUIWithPush(_ notification: Notification) {
updateNewView(mode: .today)
}
}
extension NewViewController {
fileprivate enum RightBarType {
case all
case only
case indicator
case none
}
fileprivate func setRightBarButtonItems(type: RightBarType) {
switch type {
case .only:
navigationItem.setRightBarButtonItems([calendarButton], animated: false)
case .indicator:
navigationItem.setRightBarButtonItems([calendarButton, UIBarButtonItem(customView: activityIndicatorView)], animated: false)
case .all:
navigationItem.setRightBarButtonItems([calendarButton, dailyGankButton], animated: false)
case .none:
navigationItem.setRightBarButtonItems(nil, animated: false)
}
}
fileprivate enum UpdateNewViewMode {
case lastest
case today
case date
}
fileprivate func updateNewView(mode: UpdateNewViewMode = .lastest, isChoose: Bool = false, date: String = "") {
isNoData = false
switch mode {
case .lastest:
setRightBarButtonItems(type: .none)
gankLog.debug("UpdateNewViewMode lastest")
case .date:
isGankToday = false
meiziGank = nil
gankCategories = []
gankDictionary = [:]
newTableView.isScrollEnabled = false
newTableView.separatorColor = .none
newTableView.tableFooterView = UIView()
newTableView.rowHeight = 158
newTableView.reloadData()
coverHeaderView.refresh()
tipView.isHidden = true
setRightBarButtonItems(type: .only)
gankLog.debug("UpdateNewViewMode date")
case .today:
GankConfig.heavyFeedbackEffectAction?()
activityIndicatorView.startAnimating()
setRightBarButtonItems(type: .indicator)
gankLog.debug("UpdateNewViewMode today")
}
let failureHandler: FailureHandler = { reason, message in
SafeDispatch.async { [weak self] in
self?.isNoData = true
self?.newTableView.tableHeaderView = UIView()
self?.newTableView.isScrollEnabled = false
self?.newTableView.tableFooterView = self?.noDataFooterView
self?.newTableView.reloadData()
gankLog.debug("加载失败")
}
}
switch mode {
case .lastest:
gankLatest(failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI()
}
})
case .today:
gankLatest(failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.activityIndicatorView.stopAnimating()
guard isToday else {
self?.makeAlert()
return
}
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI()
}
})
case .date:
gankWithDay(date: date, failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI(isChoose:true)
}
})
}
}
fileprivate func configureData(_ isToday: Bool, _ meizi: Gank, _ categories: Array<String>, _ lastestGank: Dictionary<String, Array<Gank>>) {
isGankToday = isToday
meiziGank = meizi
gankCategories = categories
gankDictionary = lastestGank
}
fileprivate func makeUI(isChoose: Bool = false) {
newTableView.isScrollEnabled = true
newTableView.tableHeaderView = coverHeaderView
newTableView.tableFooterView = customFooterView
newTableView.estimatedRowHeight = 195.5
newTableView.rowHeight = UITableView.automaticDimension
let height = coverHeaderView.configure(meiziData: meiziGank)
coverHeaderView.frame.size = CGSize(width: GankConfig.getScreenWidth(), height: height)
newTableView.reloadData()
if isChoose == false {
tipView.isHidden = isGankToday
}
if isGankToday {
setRightBarButtonItems(type: .only)
return
}
setRightBarButtonItems(type: .all)
}
fileprivate func makeAlert() {
setRightBarButtonItems(type: .all)
guard GankNotificationService.shared.isAskAuthorization == true else {
GankAlert.confirmOrCancel(title: nil, message: String.messageOpenNotification, confirmTitle: String.promptConfirmOpenNotification, cancelTitle: String.promptCancelOpenNotification, inViewController: self, withConfirmAction: {
GankNotificationService.shared.checkAuthorization()
}, cancelAction: {})
return
}
GankAlert.alertKnown(title: nil, message: String.messageNoDailyGank, inViewController: self)
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension NewViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
guard !isNoData else {
return 0
}
return gankCategories.isEmpty ? 1 : gankCategories.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard !isNoData else {
return 0
}
guard !gankCategories.isEmpty else {
return 2
}
let key: String = gankCategories[section]
return gankDictionary[key]!.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard gankCategories.isEmpty || isNoData else {
return 56
}
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard gankCategories.isEmpty else {
let headerView = GankHeaderView.instanceFromNib()
headerView.configure(titleString: gankCategories[section])
return headerView
}
return nil
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard gankCategories.isEmpty else {
let cell: DailyGankCell = tableView.dequeueReusableCell()
let key: String = gankCategories[indexPath.section]
let gankDetail: Gank = gankDictionary[key]![indexPath.row]
cell.configure(withGankDetail: gankDetail)
cell.selectionStyle = UITableViewCell.SelectionStyle.default
return cell
}
let cell: DailyGankLoadingCell = tableView.dequeueReusableCell()
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer {
tableView.deselectRow(at: indexPath, animated: true)
}
if !gankCategories.isEmpty {
let key: String = gankCategories[indexPath.section]
let gankDetail: Gank = gankDictionary[key]![indexPath.row]
self.performSegue(withIdentifier: "showDetail", sender: gankDetail.url)
}
}
}
|
892c52d33f3912d8b0a6b5176efe7950
| 34.40884 | 237 | 0.613746 | false | false | false | false |
xqz001/WWDC
|
refs/heads/master
|
WWDC/LiveEvent.swift
|
bsd-2-clause
|
1
|
//
// LiveEvent.swift
// WWDC
//
// Created by Guilherme Rambo on 16/05/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Foundation
private let _dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'ZZZZ"
struct LiveEvent {
var id: Int
var title: String
var startsAt: NSDate
var description: String
var stream: NSURL?
var isLiveRightNow: Bool
private struct Keys {
static let id = "id"
static let title = "title"
static let description = "description"
static let stream = "stream"
static let startsAt = "starts_at"
static let isLiveRightNow = "isLiveRightNow"
}
init(jsonObject: JSON) {
id = jsonObject[Keys.id].intValue
title = jsonObject[Keys.title].string!
description = jsonObject[Keys.description].string!
stream = NSURL(string: jsonObject[Keys.stream].string!)
isLiveRightNow = jsonObject[Keys.isLiveRightNow].boolValue
let formatter = NSDateFormatter()
formatter.dateFormat = _dateFormat
startsAt = formatter.dateFromString(jsonObject[Keys.startsAt].string!)!
}
}
|
9f0697a1f590fcb59e98161be83a1f02
| 27.243902 | 79 | 0.645635 | false | false | false | false |
mlilback/rc2SwiftClient
|
refs/heads/master
|
MacClient/Searchable.swift
|
isc
|
1
|
//
// Searchable.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import ClientCore
protocol MacCodeEditor: CodeEditor, Searchable {}
protocol Searchable {
func performFind(action: NSTextFinder.Action)
var supportsSearchBar: Bool { get }
var searchBarVisible: Bool { get }
var searchableTextView: NSTextView? { get }
}
extension Searchable {
func performFind(action: NSTextFinder.Action) {
if let textView = searchableTextView {
let menuItem = NSMenuItem(title: "foo", action: #selector(NSTextView.performFindPanelAction(_:)), keyEquivalent: "")
menuItem.tag = action.rawValue
textView.performFindPanelAction(menuItem)
if action == .hideFindInterface {
textView.enclosingScrollView?.isFindBarVisible = false
}
}
}
var supportsSearchBar: Bool { return false }
var searchBarVisible: Bool { return searchableTextView?.enclosingScrollView?.isFindBarVisible ?? false }
var searchableTextView: NSTextView? { return nil }
}
|
ba2a4785d5250b1f6542d49278df47f6
| 29.575758 | 119 | 0.755203 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift
|
refs/heads/master
|
TLTranstionLib-swift/Classes/Interactors/TLBaseSwipeInteraction.swift
|
mit
|
1
|
//
// TLBaseSwipeInteraction.swift
// Pods
//
// Created by Andrew on 16/8/8.
//
//
import UIKit
/*
UIPercentDrivenInteractiveTransition。这个类的对象会根据我们的手势,来决定我们的自定义过渡的完成度。我们把这些都放到手势识别器的 action 方法中去
当手势刚刚开始,我们创建一个 UIPercentDrivenInteractiveTransition 对象,然后让 navigationController 去把当前这个 viewController 弹出。
当手慢慢划入时,我们把总体手势划入的进度告诉 UIPercentDrivenInteractiveTransition 对象。
当手势结束,我们根据用户的手势进度来判断过渡是应该完成还是取消并相应的调用 finishInteractiveTransition 或者 cancelInteractiveTransition 方法.
*/
private let TLBaseSwipeInteractionDefaultCompletionPercentage:CGFloat = 0.3
public class TLBaseSwipeInteraction: UIPercentDrivenInteractiveTransition,TLTransitionInteractionProtocol,UIGestureRecognizerDelegate {
var fromViewController:UIViewController?
/// 滑动的手势
var gestureRecognizer:UIPanGestureRecognizer{
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
gesture.delegate = self
return gesture
}
/// 当手势滑动的方向相反时是否触发手势
public var reverseGestureDirection:Bool = false
//MARK: - TLTransitionInteractionProtocol属性
public var isInteractive: Bool = true
public var shouldCompleteTransition: Bool = false
public var action: TLTranstionAction = TLTranstionAction.tl_Any
public var nextControllerDelegate: TLTransitionInteractionControllerDelegate?
public func attachViewController(viewController viewController: UIViewController, action: TLTranstionAction) {
self.fromViewController = viewController
self.action = action
//给当前控制器添加手势
self.attachGestureRecognizerToView((self.fromViewController?.view)!)
}
deinit{
self.gestureRecognizer.view?.removeGestureRecognizer(self.gestureRecognizer)
}
/**
添加手势
- parameter view:
*/
func attachGestureRecognizerToView(view:UIView) -> Void {
view.addGestureRecognizer(self.gestureRecognizer)
}
//MARK: - UIPercentDrivenInteractiveTransition
/**
Flag if the gesture is in the positive or negative direction
- parameter panGestureRecognizer: 滑动手势
- returns: Flag if the gesture is in the positive or negative direction
*/
func isGesturePositive(panGestureRecognizer:UIPanGestureRecognizer) -> Bool {
fatalError("子类必须实现这个方法\(isGesturePositive)")
return true
}
/**
当手势滑动的时候该方法会被触发
滑动手势的百分比
- parameter precent: 滑动的百分比
- returns: 距离完成手势操作的百分比
*/
func swipeCompletionPercent() -> CGFloat {
return TLBaseSwipeInteractionDefaultCompletionPercentage
}
/**
The translation percentage of the passed gesture recognizer
- parameter panGestureRecognizer:
- returns: 完成手势的百分比
*/
func translationPercentageWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer:UIPanGestureRecognizer) -> CGFloat {
fatalError("子类必须覆盖这个方法:\(translationPercentageWithPanGestureRecongizer))")
return 0
}
/**
The physical translation that is on the the view due to the panGestureRecognizer
- parameter panGestureRecognizer: 滑动手势
- returns: the translation that is currently on the view.
*/
func translationWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer:UIPanGestureRecognizer) -> CGFloat {
fatalError("子类必须覆盖这个方法:\(translationWithPanGestureRecongizer))")
return 0
}
//MARK: - UIPanGestureRecognizer Delegate
func handlePanGesture(panGestureRecognizer:UIPanGestureRecognizer) -> Void {
let percentage = self.translationPercentageWithPanGestureRecongizer(panGestureRecognizer: panGestureRecognizer)
//判断是否是正向还是逆向
let positiveDirection = self.reverseGestureDirection ? !self.isGesturePositive(panGestureRecognizer) : self.isGesturePositive(panGestureRecognizer)
switch panGestureRecognizer.state {
case .Began:
//允许用户交互
self.isInteractive = true
//如果是正向操作,并且下一个控制器实现了TLTransitionInteractionProtocol协议
if let nextDelegate = self.nextControllerDelegate{
if positiveDirection && nextDelegate is TLTransitionInteractionControllerDelegate{
//如果操作类型是 push
if action == TLTranstionAction.tl_Push{
self.fromViewController?.navigationController?.pushViewController((self.nextControllerDelegate?.nextViewControllerForInteractor(self))!, animated: true)
}else if (action == TLTranstionAction.tl_Present){
self.fromViewController?.presentViewController((self.nextControllerDelegate?.nextViewControllerForInteractor(self))!, animated: true, completion: nil)
}
}else{
//如果是逆向操作
if action == TLTranstionAction.tl_Pop{
self.fromViewController?.navigationController?.popViewControllerAnimated(true)
}else if action == TLTranstionAction.tl_Dismiss{
self.fromViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
}
case .Changed:
//如果是允许交互
if self.isInteractive{
self.shouldCompleteTransition = (percentage >= TLBaseSwipeInteractionDefaultCompletionPercentage)
self.updateInteractiveTransition(percentage)
}
break
case .Cancelled:
break
case .Ended:
if isInteractive{
//如果交互没有完成
if self.shouldCompleteTransition == false{
self.cancelInteractiveTransition()
}else{
self.finishInteractiveTransition()
}
}
self.isInteractive = false
break
default:
break
}
}
}
|
0d9eeee8022ed14ac3f47c086f381876
| 32.714286 | 176 | 0.655802 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.