repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wojteklu/logo | Logo/Logo/Parser/Nodes/IfExpression.swift | 1 | 678 | import Foundation
struct IfExpression: Expression {
let token: Token
let condition: Expression
let consequence: BlockStatement
let alternative: BlockStatement?
init(token: Token, condition: Expression, consequence: BlockStatement, alternative: BlockStatement? = nil) {
self.token = token
self.condition = condition
self.consequence = consequence
self.alternative = alternative
}
var description: String {
var result = "if (\(condition)) [ \(consequence) ]"
if let alternative = alternative {
result += " else [ \(alternative) ]"
}
return result
}
}
| mit | 9c882d852f8a9a6115f4b79bd7974f1f | 26.12 | 112 | 0.619469 | 5.097744 | false | false | false | false |
hanjoes/Smashtag | Smashtag/ImageCollectionViewController.swift | 1 | 2860 | //
// ImageCollectionViewController.swift
// Smashtag
//
// Created by Hanzhou Shi on 1/15/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
class ImageCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var tweets = [Tweet]()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.reloadData()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.reloadData()
}
// MARK: - Delegate Methods
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
if let ic = cell as? ImageCollectionViewCell {
let tweet = tweets[indexPath.row]
if tweet.media.count > 0 {
ic.imageURL = tweet.media[0].url
}
}
return cell
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let ic = cell as? ImageCollectionViewCell {
ic.imageView.image = nil
}
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tweets.count
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier(Constants.ShowDetailSegue, sender: nil)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let frameSize = collectionView.frame.size
let itemHeight = Constants.ItemHeight
let itemWidth = frameSize.width - 10
return CGSize(width: itemWidth, height: itemHeight)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destination = segue.destinationViewController
if let dtvc = destination as? DetailTableViewController {
if let indexPaths = collectionView?.indexPathsForSelectedItems() {
let indexPath = indexPaths[0]
dtvc.tweet = tweets[indexPath.row]
}
}
}
// MARK: - Private
private struct Constants {
static let ItemHeight: CGFloat = 150
static let ShowDetailSegue = "ShowDetailFromCollection"
}
}
| mit | 8f9747f2a9e3d0099f4bf0fc31b6846a | 33.865854 | 169 | 0.67751 | 6.082979 | false | false | false | false |
ljubinkovicd/Lingo-Chat | Lingo Chat/NewMessageController.swift | 1 | 5148 | //
// NewMessageController.swift
// Lingo Chat
//
// Created by Dorde Ljubinkovic on 9/25/17.
// Copyright © 2017 Dorde Ljubinkovic. All rights reserved.
//
import UIKit
import Firebase
private let reuseIdentifier = "Cell"
class NewMessageController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var myFriends: [MyFriend] = []
private lazy var myFriendsRef: DatabaseReference = Database.database().reference().child("users")
private var myFriendsRefHandle: DatabaseHandle? // Will hold a handle to the reference so you can remove it later on...
var senderDisplayName: String?
lazy var dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateStyle = .none
df.timeStyle = .medium
return df
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Cancel button to cancel creating a new message."), style: .plain, target: self, action: #selector(handleCancel))
self.collectionView?.alwaysBounceVertical = true
self.collectionView?.register(UINib(nibName: "MyFriendCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
fetchUser()
}
func fetchUser() {
myFriendsRefHandle = myFriendsRef.observe(.childAdded, with: { [weak self] (snapshot) in
guard let strongSelf = self else { return }
if let dictionary = snapshot.value as? [String: Any] {
print(dictionary["name"]!)
print(dictionary["email"]!)
// Get user value
let id = snapshot.key
let name = dictionary["name"] as? String ?? "Unknown User"
let profileImage = dictionary["profileImage"] as? String ?? "userAvatar"
strongSelf.myFriends.append(MyFriend(id: id, name: name, profileImageName: profileImage))
strongSelf.collectionView?.reloadData()
DispatchQueue.main.async {
strongSelf.collectionView?.reloadData()
}
}
}, withCancel: nil)
}
@objc private func handleCancel() {
dismiss(animated: true, completion: nil)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myFriends.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyFriendCell
cell.userNameLabel.text = myFriends[indexPath.row].name
if let profileImageName = myFriends[indexPath.row].profileImageName {
cell.userProfileImageView.image = UIImage(named: profileImageName)
cell.hasSeenMessageImageView.image = UIImage(named: profileImageName)
}
let userLastMessage = cell.userLastMessageLabel.text
let messageCreatedAt = cell.dateSentLabel.text
if userLastMessage == "" {
cell.userLastMessageLabel.text = "You are now friends with \(myFriends[indexPath.row].name!). You should send him/her a message."
}
if messageCreatedAt == "" {
let currentDateShort = Date()
cell.dateSentLabel.text = dateFormatter.string(from: currentDateShort)
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("didSelectItemAt Method Called")
let myFriend = myFriends[(indexPath as NSIndexPath).row]
self.performSegue(withIdentifier: "ShowChatController", sender: myFriend)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 100)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let myFriend = sender as? MyFriend {
let navigationController = segue.destination as! UINavigationController
let chatController = navigationController.viewControllers.first as! ChatController
senderDisplayName = myFriend.name
chatController.senderDisplayName = senderDisplayName
chatController.myFriend = myFriend
chatController.myFriendsRef = myFriendsRef.child(myFriend.id!)
}
}
// MARK: Deinitialize
deinit {
if let refHandle = myFriendsRefHandle {
myFriendsRef.removeObserver(withHandle: refHandle)
}
}
}
| mit | 18bb0f817eb9289c282119536dbed3cc | 36.845588 | 216 | 0.630076 | 5.487207 | false | false | false | false |
johnno1962/GitDiff | LNProvider/AppDelegate.swift | 1 | 2934 | //
// AppDelegate.swift
// LNProvider
//
// Created by John Holdsworth on 31/03/2017.
// Copyright © 2017 John Holdsworth. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var defaults: DefaultManager!
@IBOutlet var formatChecked: NSButton!
@IBOutlet var gitDiffChecked: NSButton!
@IBOutlet var gitBlameChecked: NSButton!
@IBOutlet var inferChecked: NSButton!
var services = [LNExtensionClient]()
private var statusItem: NSStatusItem!
lazy var buttonMap: [NSButton: String] = [
self.formatChecked: "com.johnholdsworth.FormatRelay",
self.gitDiffChecked: "com.johnholdsworth.GitDiffRelay",
self.gitBlameChecked: "com.johnholdsworth.GitBlameRelay",
self.inferChecked: "com.johnholdsworth.InferRelay",
]
func applicationDidFinishLaunching(_: Notification) {
startServiceAndRegister(checkButton: formatChecked)
startServiceAndRegister(checkButton: gitDiffChecked)
startServiceAndRegister(checkButton: gitBlameChecked)
startServiceAndRegister(checkButton: inferChecked)
let statusBar = NSStatusBar.system
statusItem = statusBar.statusItem(withLength: statusBar.thickness)
statusItem.toolTip = "GitDiff Preferences"
statusItem.highlightMode = true
statusItem.target = self
statusItem.action = #selector(show(sender:))
statusItem.isEnabled = true
statusItem.title = ""
setMenuIcon(tiffName: "icon_16x16")
NSColorPanel.shared.showsAlpha = true
window.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
}
func setMenuIcon(tiffName: String) {
if let path = Bundle.main.path(forResource: tiffName, ofType: "tiff"),
let image = NSImage(contentsOfFile: path) {
image.isTemplate = true
statusItem.image = image
statusItem.alternateImage = statusItem.image
}
}
@IBAction func show(sender: Any) {
window.makeKeyAndOrderFront(sender)
NSApp.activate(ignoringOtherApps: true)
}
func startServiceAndRegister(checkButton: NSButton) {
if checkButton.state == .on, let serviceName = buttonMap[checkButton] {
services.append(LNExtensionClient(serviceName: serviceName, delegate: nil))
}
}
@IBAction func serviceDidChange(checkButton: NSButton) {
if checkButton.state == .on {
startServiceAndRegister(checkButton: checkButton)
} else if let serviceName = buttonMap[checkButton] {
services.first(where: { $0.serviceName == serviceName })?.deregister()
services = services.filter { $0.serviceName != serviceName }
}
}
func applicationWillTerminate(_: Notification) {
_ = services.map { $0.deregister() }
}
}
| mit | d930a8537576c988cc4b8c84ef8e46eb | 34.337349 | 87 | 0.67985 | 4.582813 | false | false | false | false |
unsignedapps/Turms | Turms/MessageController.swift | 1 | 6373 | //
// MessageController.swift
// Turms
//
// Created by Robert Amos on 6/11/2015.
// Copyright © 2015 Unsigned Apps. All rights reserved.
//
import UIKit
open class MessageController: NSObject
{
static let sharedInstance = MessageController()
fileprivate let queue: OperationQueue
var delegate: MessageControllerDelegate?
override init()
{
self.queue = OperationQueue();
self.queue.maxConcurrentOperationCount = 1;
super.init();
}
public static func show (_ message: Message, controller: UIViewController)
{
let view = MessageView(message: message);
let op = MessageOperation(view: view, controller: controller);
self.sharedInstance.queue.addOperation(op);
}
public static func show (type: MessageType, message: String, controller: UIViewController)
{
self.show(Message(type: type, message: message), controller: controller);
}
public static func show (_ type: MessageType, title: String, subtitle: String? = nil, duration: MessageDuration = .automatic, image: UIImage? = nil, position: MessagePosition = .navBarOverlay, dismissible: Bool = true, controller: UIViewController)
{
self.show(Message(type: type, title: title, subtitle: subtitle, duration: duration, image: image, position: position, dismissible: dismissible), controller: controller);
}
}
protocol MessageControllerDelegate
{
func locationOfView (_ view: MessageView) -> CGFloat
func customise (_ view: MessageView)
}
class MessageOperation: Operation
{
fileprivate let view: MessageView;
fileprivate var tapGestureRecognizer: UITapGestureRecognizer? = nil
fileprivate var timer: Timer? = nil
fileprivate let controller: UIViewController
fileprivate var _cancelled: Bool = false
{
willSet (value) { self.willChangeValue(forKey: "isCancelled"); }
didSet (value) { self.didChangeValue(forKey: "isCancelled"); }
}
override var isCancelled: Bool
{
get { return self._cancelled; }
}
fileprivate var _executing: Bool = false
{
willSet (value) { self.willChangeValue(forKey: "isExecuting"); }
didSet (value) { self.didChangeValue(forKey: "isExecuting"); }
}
override var isExecuting: Bool
{
get { return self._executing; }
}
fileprivate var _finished: Bool = false
{
willSet (value) { self.willChangeValue(forKey: "isFinished"); }
didSet (value) { self.didChangeValue(forKey: "isFinished"); }
}
override var isFinished: Bool
{
get { return self._finished; }
}
override var isConcurrent: Bool
{
get { return true; }
}
override var isAsynchronous: Bool
{
get { return true; }
}
init(view: MessageView, controller: UIViewController)
{
self.view = view;
self.controller = controller;
super.init();
}
override func start()
{
self._executing = true;
self.show();
}
func show ()
{
// hang on, are we being dismissed?
var controller = self.controller;
if controller.isBeingDismissed {
controller = controller.presentingViewController ?? controller
}
// handle cases where we are a nav bar
DispatchQueue.main.async
{
if let nav = controller as? UINavigationController
{
controller.view.insertSubview(self.view, aboveSubview: nav.navigationBar);
} else
{
controller.view.addSubview(self.view);
}
controller.view.layoutIfNeeded(); // The first layout pass is to get the bounds calculated
self.configureDismissal();
// align it off screen
if let constraint = self.view.topConstraint, let message = self.view.message
{
constraint.constant = self.view.frame.height * -1;
controller.view.layoutIfNeeded(); // The second is to push the view off screen
constraint.constant = 0.0;
// and animate in!
UIView.animate(withDuration: message.animationDuration, animations:
{
controller.view.layoutIfNeeded(); // And then animate back in
});
}
}
}
fileprivate func configureDismissal ()
{
guard let message = self.view.message else { return; }
// configure for automatic dismissal
if message.duration == .automatic
{
let displayTime = message.displayTimeBase + (message.displayTimePerPixel * Double(self.view.frame.height));
self.timer = Timer.scheduledTimer(timeInterval: displayTime, target: self, selector: #selector(MessageOperation.hide), userInfo: nil, repeats: false);
}
// tap to dismiss
if message.dismissible
{
let recognizer = UITapGestureRecognizer(target: self, action: #selector(MessageOperation.hide));
self.tapGestureRecognizer = recognizer;
self.view.addGestureRecognizer(recognizer);
}
}
override func cancel()
{
self._cancelled = true;
self.hide();
}
@objc func hide ()
{
if let timer = self.timer
{
timer.invalidate();
self.timer = nil;
}
if let constraint = self.view.topConstraint, let message = self.view.message, let superview = self.view.superview
{
constraint.constant = self.view.frame.height * -1;
UIView.animate(withDuration: message.animationDuration, delay: 0.0, options: UIView.AnimationOptions(), animations:
{
superview.layoutIfNeeded();
}, completion:
{
completed in
self.view.removeFromSuperview();
self.stop();
});
} else
{
self.view.removeFromSuperview();
self.stop();
}
}
func stop ()
{
self._finished = true;
self._executing = false;
}
}
| mit | f74535b6585dc7d4e27cb760ebfd3d4b | 29.488038 | 252 | 0.584903 | 5.057143 | false | false | false | false |
VoIPGRID/vialer-ios | Vialer/Helpers/VialerLogger.swift | 1 | 2933 | //
// VialerLogger.swift
// Copyright © 2017 VoIPGRID. All rights reserved.
//
import Foundation
/// Log a message to VialerLogger.
///
/// Simple wrapper around Objective C Logger.
///
/// - Parameters:
/// - flag: LogLevel
/// - file: File that dispatched the message
/// - function: Function that dispatched the message
/// - line: Line that dispatched the message
/// - message: Message that will be logged
func VialerLog(flag: DDLogFlag, file: String, function: String, line: UInt, _ message: String) {
VialerLogger.log(flag: flag, file: file, function: function, line: line, message: message)
}
/// Verbose logging
///
/// - Parameters:
/// - file: (optional)File that dispatched the message
/// - function: (optional)Function that dispatched the message
/// - line: (optional)Line that dispatched the message
/// - message: Message that will be logged
func VialerLogVerbose(file: String = #file, function: String = #function, line: UInt = #line, _ message: String) {
VialerLog(flag: .verbose, file: file, function: function, line: line, message)
}
/// Debug logging
///
/// - Parameters:
/// - file: (optional)File that dispatched the message
/// - function: (optional)Function that dispatched the message
/// - line: (optional)Line that dispatched the message
/// - message: Message that will be logged
func VialerLogDebug(file: String = #file, function: String = #function, line: UInt = #line, _ message: String) {
VialerLog(flag: .debug, file: file, function: function, line: line, message)
}
/// Info logging
///
/// - Parameters:
/// - file: (optional)File that dispatched the message
/// - function: (optional)Function that dispatched the message
/// - line: (optional)Line that dispatched the message
/// - message: Message that will be logged
func VialerLogInfo(file: String = #file, function: String = #function, line: UInt = #line, _ message: String) {
VialerLog(flag: .info, file: file, function: function, line: line, message)
}
/// Waring logging
///
/// - Parameters:
/// - file: (optional)File that dispatched the message
/// - function: (optional)Function that dispatched the message
/// - line: (optional)Line that dispatched the message
/// - message: Message that will be logged
func VialerLogWarning(file: String = #file, function: String = #function, line: UInt = #line, _ message: String) {
VialerLog(flag: .warning, file: file, function: function, line: line, message)
}
/// Error logging
///
/// - Parameters:
/// - file: (optional)File that dispatched the message
/// - function: (optional)Function that dispatched the message
/// - line: (optional)Line that dispatched the message
/// - message: Message that will be logged
func VialerLogError(file: String = #file, function: String = #function, line: UInt = #line, _ message: String) {
VialerLog(flag: .error, file: file, function: function, line: line, message)
}
| gpl-3.0 | 521e85f3db798082395d9365a77d9b37 | 37.578947 | 114 | 0.687244 | 3.807792 | false | false | false | false |
mattermost/ios | Mattermost/CreateViewController.swift | 1 | 1825 | // Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import UIKit
class CreateViewController: UIViewController, UITextFieldDelegate, MattermostApiProtocol {
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var nameField: UITextField!
var api: MattermostApi = MattermostApi()
override func viewDidLoad() {
super.viewDidLoad()
emailField.delegate = self
nameField.delegate = self
api.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
emailField.resignFirstResponder()
nameField.resignFirstResponder()
api.signup(emailField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString, name: nameField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString)
return true
}
@IBAction func dismissKeyboard(sender: AnyObject) {
emailField.resignFirstResponder()
nameField.resignFirstResponder()
}
@IBAction func sendClick(sender: AnyObject) {
api.signup(emailField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString, name: nameField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func didRecieveResponse(results: JSON) {
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
}
func didRecieveError(message: String) {
Utils.HandleUIError(message, label: displayLabel)
}
}
| apache-2.0 | fa91958c746123bf27da05687d82b966 | 36.244898 | 237 | 0.723836 | 5.812102 | false | false | false | false |
CalQL8ed-K-OS/Swift-RPG | Swift RPG/FightViewController.swift | 1 | 3094 | //
// FightViewController.swift
// Simple RPG
//
// Created by Xavi Matos on 9/17/14.
// Copyright (c) 2014 Xavi Matos. All rights reserved.
//
import UIKit
class FightViewController: UIViewController {
@IBOutlet weak var playerNameLabel: UILabel!
@IBOutlet weak var playerHealthBar: UIProgressView!
@IBOutlet weak var playerHealthLabel: UILabel!
@IBOutlet weak var enemyNameLabel: UILabel!
@IBOutlet weak var enemyHealthBar: UIProgressView!
@IBOutlet weak var enemyHealthLabel: UILabel!
@IBOutlet weak var strikeButton: UIButton!
@IBOutlet weak var strikeOutcomeLabel: UILabel!
@IBOutlet weak var strikeOutcomeExplainButton: UIButton!
@IBOutlet weak var escapeButton: UIButton!
@IBOutlet weak var escapeOutcomeLabel: UILabel!
@IBOutlet weak var escapeOutcomeExplainButton: UIButton!
var player = Combatant(plistName: "Xavi")
var enemy = Combatant(plistName: "Rabid Dog")
override func viewDidLoad() {
super.viewDidLoad()
self.refreshViews()
}
func refreshViews() {
let format = ".2"
playerNameLabel.text = player.name
playerHealthBar.progress = player.curHP
playerHealthLabel.text = "\((player.curHP * 100).format(format))%"
enemyNameLabel.text = enemy.name
enemyHealthBar.progress = enemy.curHP
enemyHealthLabel.text = "\((enemy.curHP * 100).format(format))%"
}
enum Action {
case Strike
case Escape
}
var playerAction = Action.Strike
var enemyAction = Action.Strike
@IBAction func strike() {
playerAction = .Strike
resolveTurn()
}
@IBAction func escape() {
playerAction = .Escape
resolveTurn()
}
func chooseEnemyAction() {
enemyAction = .Strike
}
func resolveTurn() {
chooseEnemyAction()
combatant(player, performAction: playerAction, toCombatant: enemy)
combatant(enemy, performAction: enemyAction, toCombatant: player)
refreshViews()
}
func combatant(actor:Combatant, performAction action:Action, toCombatant target:Combatant) {
switch action {
case .Strike:
combatant(actor, attacks: target)
case .Escape:
let alert = UIAlertController(title: "failed", message: nil, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
func combatant(aggressor:Combatant, attacks target:Combatant) {
let result = target.takeDmg(aggressor.pow - target.def)
if result == .Died {
let alert = UIAlertController(title: "\(target.name) is dead", message: nil, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
}
| mit | e375554d5482997aed122523f3f167d2 | 31.229167 | 112 | 0.647382 | 4.451799 | false | false | false | false |
jakubgert/JGSwiftUI | JGUI/JGUI/ViewControllers/JGUIViewWithTableViewController.swift | 1 | 3353 | //
// JGUIViewWithTableViewController.swift
// JGUI
//
// Created by Jakub Gert on 02/01/15.
// Copyright (c) 2015 Planktovision. All rights reserved.
//
import UIKit
public class JGUIViewWithTableViewController: JGUIViewController,UITableViewDataSource,UITableViewDelegate {
// MARK: - Properties
@IBOutlet public var tableView:UITableView?
@IBOutlet public var refreshControl:UIRefreshControl?
public var reloadDataAfterSetListOfElements:Bool=true
public var createPullToRefresh:Bool=true
public var assignDataSourceToSelf:Bool=true
public var assignDelegateToSelf:Bool=true
// MARK: - Default values for table and cells
public func defaultTableViewStyle() -> UITableViewStyle {
return UITableViewStyle.Plain
}
public func defaultTableViewCellIdentifier() -> String! {
return "Cell"
}
public func defaultTableViewCell() -> AnyClass! {
return UITableViewCell.self
}
public override func viewDidLoad() {
if self.tableView==nil {
self.tableView = UITableView(frame: self.view.bounds, style: self.defaultTableViewStyle())
self.tableView?.registerClass( defaultTableViewCell(), forCellReuseIdentifier: defaultTableViewCellIdentifier())
self.tableView?.delegate = self
self.tableView?.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(self.tableView!)
let views = ["tableView":self.tableView!]
let constraintsHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views )
let constraintsVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[tableView]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views)
self.view.addConstraints(constraintsHorizontal)
self.view.addConstraints(constraintsVertical)
}
if(self.assignDataSourceToSelf){
self.tableView?.dataSource = self
}
if(self.assignDelegateToSelf){
self.tableView?.delegate = self
}
if(self.createPullToRefresh){
var pullControll = UIRefreshControl()
self.tableView?.addSubview(pullControll)
pullControll.addTarget(self, action: Selector("pullToRefreshDidDone:"), forControlEvents: .ValueChanged)
self.refreshControl = pullControll
}
}
// MARK: - UITableViewDataSource
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = self.defaultTableViewCellIdentifier()
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as UITableViewCell
return cell
}
// MARK: - UIRefreshControl
@IBAction public func pullToRefreshDidDone(sender:AnyObject?){
}
}
| mit | 63bda8eab0034cdee9dbabb528bf3ac3 | 35.053763 | 175 | 0.670146 | 5.741438 | false | false | false | false |
testpress/ios-app | ios-app/UI/VideoContentViewController.swift | 1 | 18403 | //
// VideoContentViewController.swift
// ios-app
//
//
// Copyright © 2019 Testpress. 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 UIKit
import AVKit
import AVFoundation
import Alamofire
import Sentry
import TTGSnackbar
import RealmSwift
class VideoContentViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {
var content: Content!
var contents: [Content]!
var videoPlayerView: VideoPlayerView!
var viewModel: VideoContentViewModel!
var customView: UIView!
var warningLabel: UILabel!
var bookmarkHelper: BookmarkHelper!
var bookmarkDelegate: BookmarkDelegate?
var bookmarkContent: Content?
var position: Int! = 0
@IBOutlet weak var videoPlayer: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var desc: UITextView!
@IBOutlet weak var titleToggleButton: UIButton!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var titleStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = VideoContentViewModel(content)
initVideoPlayerView()
view.addSubview(videoPlayerView)
viewModel.videoPlayerView = videoPlayerView
showOrHideBottomBar()
titleLabel.text = viewModel.getTitle()
initializeDescription()
bookmarkContent = content
viewModel.createContentAttempt()
addCustomView()
udpateBookmarkButtonState(bookmarkId: content!.bookmarkId.value)
bookmarkHelper = BookmarkHelper(viewController: self)
bookmarkHelper.delegate = self
tableView.dataSource = self
tableView.delegate = self
addGestures()
handleExternalDisplay()
if #available(iOS 11.0, *) {
handleScreenCapture()
}
}
func initializeDescription() {
desc.attributedText = parseVideoDescription()
desc.isHidden = true
desc.delegate = self
}
func showOrHideDescription() {
if (self.desc.isHidden) {
showDescription()
} else {
hideDescription()
}
}
func showDescription() {
self.desc.isHidden = false
self.titleToggleButton.setImage(Images.CaretUp.image, for: .normal)
}
func hideDescription() {
self.desc.isHidden = true
self.titleToggleButton.setImage(Images.CaretDown.image, for: .normal)
}
func parseVideoDescription() -> NSMutableAttributedString? {
let description = """
<html>
<head>
<style>
body {
font-family: -apple-system;
font-size: 16px;
}
</style>
</head>
<body>
\(viewModel.getDescription())
</body>
</html>
"""
let data = description.data(using: .utf8)!
let urlAttribute = [
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0),
NSAttributedString.Key.link: URL(string: "dummy_link")!,
] as [NSAttributedString.Key : Any]
let attributedString = try? NSMutableAttributedString(
data: data,
options: [.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil
)
let durationRegex = "([0-2]?[0-9]?:?[0-5]?[0-9]:[0-5][0-9])"
let ranges = attributedString!.string.nsRanges(of: durationRegex, options: .regularExpression)
for range in ranges {
attributedString!.addAttributes(urlAttribute, range: range)
}
return attributedString
}
func addGestures() {
titleStackView.addTapGestureRecognizer {
self.showOrHideDescription()
}
titleToggleButton.addTapGestureRecognizer{
self.showOrHideDescription()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RelatedContentsCell", for: indexPath) as! RelatedContentsCell
cell.initCell(index: indexPath.row, contents: contents!, viewController: self, is_current: content.id == contents[indexPath.row].id)
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func addCustomView() {
warningLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40))
warningLabel.textColor = UIColor.white
warningLabel.textAlignment = .center
warningLabel.numberOfLines = 3
customView = UIView(frame: videoPlayerView.frame)
customView.backgroundColor = UIColor.black
customView.center = CGPoint(x: view.center.x, y: videoPlayerView.center.y)
warningLabel.center = customView.center
customView.addSubview(warningLabel)
customView.isHidden = true
view.addSubview(customView)
}
func showWarning(text: String) {
videoPlayerView.pause()
videoPlayerView.isHidden = true
warningLabel.text = text
warningLabel.sizeToFit()
customView.isHidden = false
}
func addOrRemoveBookmark(content: Content?) {
bookmarkContent = content ?? self.content
bookmarkHelper?.onClickBookmarkButton(bookmarkId: bookmarkContent?.bookmarkId.value)
}
func udpateBookmarkButtonState(bookmarkId: Int?) {
if bookmarkContent?.id == content.id {
content.bookmarkId = RealmOptional<Int>(bookmarkId)
tableView.reloadData()
if let contentDetailPageViewController = self.parent?.parent as? ContentDetailPageViewController {
if bookmarkId != nil {
contentDetailPageViewController.navigationBarItem.rightBarButtonItem?.image = Images.RemoveBookmark.image
} else {
contentDetailPageViewController.navigationBarItem.rightBarButtonItem?.image = Images.AddBookmark.image
}
}
} else {
if let cellContentId = contents.firstIndex(where: { $0.id == bookmarkContent?.id }) {
contents[cellContentId].bookmarkId = RealmOptional<Int>(bookmarkId)
tableView.reloadData()
}
}
}
func hideWarning() {
videoPlayerView.isHidden = false
customView.isHidden = true
}
@objc func handleExternalDisplay() {
if (UIScreen.screens.count > 1) {
showWarning(text: "Please stop casting to external devices")
} else {
hideWarning()
}
}
@available(iOS 11.0, *)
@objc func handleScreenCapture() {
if (UIScreen.main.isCaptured) {
showWarning(text: "Please stop screen recording to continue watching video")
} else {
hideWarning()
}
}
func initVideoPlayerView() {
let playerFrame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y, width: view.frame.width, height: videoPlayer.frame.height)
let drmLicenseURL = content.video?.isDRMProtected == true ? TPEndpointProvider.getDRMLicenseURL(contentID: content.id) : nil
videoPlayerView = VideoPlayerView(frame: playerFrame, url: URL(string: content.video!.getHlsUrl())!, drmLicenseURL: drmLicenseURL)
videoPlayerView.playerDelegate = self
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
showOrHideBottomBar()
}
func showOrHideBottomBar() {
if let contentDetailPageViewController = self.parent?.parent as? ContentDetailPageViewController {
contentDetailPageViewController.disableSwipeGesture()
if (UIDevice.current.orientation.isLandscape) {
contentDetailPageViewController.hideBottomNavBar()
} else {
contentDetailPageViewController.showBottomNavbar()
}
}
}
func handleFullScreen() {
var playerFrame = CGRect(x: 0, y: 0, width: view.frame.width, height: videoPlayer.frame.height)
UIApplication.shared.keyWindow?.removeVideoPlayerView()
view.addSubview(videoPlayerView)
if (UIDevice.current.orientation.isLandscape) {
playerFrame = UIScreen.main.bounds
UIApplication.shared.keyWindow!.addSubview(videoPlayerView)
}
videoPlayerView.frame = playerFrame
customView.frame = videoPlayerView.frame
videoPlayerView.layoutIfNeeded()
videoPlayerView.playerLayer?.frame = playerFrame
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addObservers()
videoPlayerView.addObservers()
if let contentDetailPageViewController = self.parent?.parent as? ContentDetailPageViewController {
contentDetailPageViewController.disableSwipeGesture()
contentDetailPageViewController.hideNavbarTitle()
contentDetailPageViewController.enableBookmarkOption()
}
}
func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleExternalDisplay), name: UIScreen.didConnectNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleExternalDisplay), name: UIScreen.didDisconnectNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateVideoAttempt), name: UIApplication.willResignActiveNotification, object: nil)
if #available(iOS 11.0, *) {
NotificationCenter.default.addObserver(self, selector: #selector(handleScreenCapture), name: UIScreen.capturedDidChangeNotification, object: nil)
}
}
@objc func updateVideoAttempt() {
viewModel.updateVideoAttempt()
}
@objc func willEnterForeground() {
videoPlayerView.play()
}
func changeVideo(content: Content!) {
self.content = content
try! Realm().write {
self.content.index = contents.firstIndex(where: { $0.id == content.id })!
}
viewModel.content = content
hideDescription()
viewModel.createContentAttempt()
videoPlayerView.playVideo(url: URL(string: content.video!.getHlsUrl())!)
tableView.reloadData()
titleLabel.text = viewModel.getTitle()
desc.text = viewModel.getDescription()
titleStackView.layoutIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewModel.updateVideoAttempt()
videoPlayerView.deallocate()
if let contentDetailPageViewController = self.parent?.parent as? ContentDetailPageViewController {
contentDetailPageViewController.disableSwipeGesture()
}
NotificationCenter.default.removeObserver(self, name: UIScreen.didConnectNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIScreen.didDisconnectNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
if #available(iOS 11.0, *) {
NotificationCenter.default.removeObserver(self, name: UIScreen.capturedDidChangeNotification, object: nil)
}
}
func showPlaybackSpeedMenu() {
var alert: UIAlertController!
if (UIDevice.current.userInterfaceIdiom == .pad) {
alert = UIAlertController(title: "Playback Speed", message: nil, preferredStyle: .alert)
} else {
alert = UIAlertController(title: "Playback Speed", message: nil, preferredStyle: .actionSheet)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
PlaybackSpeed.allCases.forEach{ playbackSpeed in
let action = UIAlertAction(title: playbackSpeed.rawValue, style: .default, handler: { (_) in
self.videoPlayerView.changePlaybackSpeed(speed: playbackSpeed)
})
if (playbackSpeed.value == self.videoPlayerView.getCurrenPlaybackSpeed()){
action.setValue(Images.TickIcon.image, forKey: "image")
} else if(self.videoPlayerView.getCurrenPlaybackSpeed() == 0.0 && playbackSpeed == .normal) {
action.setValue(Images.TickIcon.image, forKey: "image")
}
alert.addAction(action)
}
alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true)
}
func showQualitySelector() {
var alert: UIAlertController!
if (UIDevice.current.userInterfaceIdiom == .pad) {
alert = UIAlertController(title: "Quality", message: nil, preferredStyle: .alert)
} else {
alert = UIAlertController(title: "Quality", message: nil, preferredStyle: .actionSheet)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
for resolutionInfo in videoPlayerView.resolutionInfo {
let action = UIAlertAction(title: resolutionInfo.resolution, style: .default, handler: { (_) in
self.videoPlayerView.changeBitrate(resolutionInfo.bitrate)
})
if (Double(resolutionInfo.bitrate) == videoPlayerView.getCurrentBitrate()) {
action.setValue(Images.TickIcon.image, forKey: "image")
}
alert.addAction(action)
}
alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true)
}
func displayOptions() {
var alert: UIAlertController!
if (UIDevice.current.userInterfaceIdiom == .pad) {
alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
} else {
alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "Playback Speed", style: .default, handler: { _ in
self.showPlaybackSpeedMenu()
}))
alert.addAction(UIAlertAction(title: "Video Quality", style: .default, handler: { _ in
self.showQualitySelector()
}))
alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
desc.sizeToFit()
handleFullScreen()
if let tableHeaderView = tableView.tableHeaderView {
if !desc.isHidden && desc.text != nil {
tableHeaderView.frame.size.height = titleStackView.frame.size.height + desc.frame.size.height + 20
} else {
tableHeaderView.frame.size.height = titleStackView.frame.size.height + 20
}
tableView.tableHeaderView = tableHeaderView
}
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
let duration = textView.text.substring(with: characterRange)
if duration != nil {
let seconds = TimeUtils.convertDurationStringToSeconds(durationString: String(duration!))
self.videoPlayerView.goTo(seconds: Float(seconds))
}
return true
}
}
extension VideoContentViewController: VideoPlayerDelegate {
func showOptionsMenu() {
displayOptions()
}
}
extension UIWindow {
func removeVideoPlayerView() {
for subview in self.subviews {
if subview is VideoPlayerView {
subview.removeFromSuperview()
}
}
}
}
extension VideoContentViewController: BookmarkDelegate {
func displayMoveButton() {
}
func displayBookmarkButton() {
}
func onClickMoveButton() {
}
func removeBookmark() {
}
func displayRemoveButton() {
}
func onClickBookmarkButton() {
}
func getBookMarkParams() -> Parameters? {
var parameters: Parameters = Parameters()
parameters["object_id"] = bookmarkContent?.id
parameters["content_type"] = ["model": "chaptercontent", "app_label": "courses"]
return parameters
}
func updateBookmark(bookmarkId: Int?) {
self.udpateBookmarkButtonState(bookmarkId: bookmarkId)
}
}
| mit | edf9df37157281509a7dd1fa7bca0f0e | 35.951807 | 160 | 0.646941 | 5.121625 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/Expression/ChatExpression.swift | 1 | 2983 | //
// ChatExpression.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/27.
// Copyright © 2017年 李莎鑫. All rights reserved.
// 表情集
import UIKit
import LSXPropertyTool
class ChatExpression: NSObject {
//MARK: 属性
//: 默认表情 Face
var defaultFace:ChatEmojiGroup = { () -> ChatEmojiGroup in
let emojiGroup = ChatEmojiGroup()
emojiGroup.type = .Face
emojiGroup.iconPath = "EmotionsEmojiHL"
let path = Bundle.main.path(forResource: "FaceEmoji.json", ofType: nil)
let data = NSData(contentsOfFile: path!)
var array:Array<Any>?
do {
array = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as? Array<Any>
}
catch{
}
emojiGroup.emojis = ExchangeToModel.model(withClassName: "Emoji", withArray: array)
for i in 0..<emojiGroup.emojis!.count {
let emoji = emojiGroup.emojis![i] as! Emoji
emoji.type = .Face
}
return emojiGroup
}()
//: 默认系统Emoji
var defaultEmoji:ChatEmojiGroup = { () -> ChatEmojiGroup in
let emojiGroup = ChatEmojiGroup()
emojiGroup.type = .Emoji
emojiGroup.iconPath = "EmotionsEmojiHL"
let path = Bundle.main.path(forResource: "SystemEmoji.json", ofType: nil)
let data = NSData(contentsOfFile: path!)
var array:Array<Any>?
do {
array = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as? Array<Any>
}
catch{
}
emojiGroup.emojis = ExchangeToModel.model(withClassName: "Emoji", withArray: array)
for i in 0..<emojiGroup.emojis!.count {
let emoji = emojiGroup.emojis![i] as! Emoji
emoji.type = .Emoji
}
return emojiGroup
}()
//: 用户表情组
var usrEmoji:Array<ChatEmojiGroup>?
//: 用户偏好组
var usrPreferEmoji:ChatEmojiGroup?
//MARK: 单例
static let shared = ChatExpression()
//MARK: 构造方法
override init() {
super.init()
}
//MARK: 外部接口
//: 添加表情组
func addExpression(emoji:ChatEmojiGroup) -> Bool {
return true
}
//: 删除表情组
func deleteExpression(id:String) -> Bool {
return true
}
//: 表情包是否在使用
func isExpressionInUseing(id:String) -> Bool{
return true
}
func downloadExpression(emoji:ChatEmojiGroup,progress:(_ progress:CGFloat)->()
,success:(_ emoji:ChatEmojiGroup) ->()
,failure:(_ emoji:ChatEmojiGroup,_ error:Error)->()) {
}
//: 列出表情包
func listExpression() -> Array<ChatEmojiGroup>?{
return nil
}
}
| mit | 2474b1441c526c66fc9be3cacc2a7d91 | 25.635514 | 114 | 0.553333 | 4.324734 | false | false | false | false |
xuephil/Perfect | PerfectLib/Threading.swift | 1 | 8471 | //
// Threading.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-03.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
#if USE_LIBDISPATCH
// !FIX! This code no longer supports libdispatch and needs updating for Lock, Event and RWLock
import Dispatch
#else
#if os(Linux)
import SwiftGlibc
#else
import Darwin
#endif
#endif
/// A wrapper around a variety of threading related functions and classes.
public class Threading {
/// Non-instantiable.
private init() {}
/// The function type which can be given to `Threading.once`.
public typealias ThreadOnceFunction = @convention(c) () -> ()
#if USE_LIBDISPATCH
public typealias ThreadClosure = () -> ()
public typealias ThreadQueue = dispatch_queue_t
public typealias ThreadOnce = dispatch_once_t
#else
/// The function type which can be given to `Threading.dispatchBlock`.
public typealias ThreadClosure = () -> ()
/// A thread queue type. Note that only concurrent queues are supported.
public typealias ThreadQueue = Int // bogus
/// The key type used for `Threading.once`.
public typealias ThreadOnce = pthread_once_t
typealias ThreadFunction = @convention(c) (UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void>
class IsThisRequired {
let closure: ThreadClosure
init(closure: ThreadClosure) {
self.closure = closure
}
}
#endif
/// A mutex-type thread lock.
/// The lock can be held by only one thread. Other threads attempting to secure the lock while it is held will block.
/// The lock is initialized as being recursive. The locking thread may lock multiple times, but each lock should be accompanied by an unlock.
public class Lock {
var mutex = pthread_mutex_t()
/// Initialize a new lock object.
public init() {
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
pthread_mutexattr_settype(&attr, Int32(PTHREAD_MUTEX_RECURSIVE))
pthread_mutex_init(&mutex, &attr)
}
deinit {
pthread_mutex_destroy(&mutex)
}
/// Attempt to grab the lock.
/// Returns true if the lock was successful.
public func lock() -> Bool {
return 0 == pthread_mutex_lock(&self.mutex)
}
/// Attempt to grab the lock.
/// Will only return true if the lock was not being held by any other thread.
/// Returns false if the lock is currently being held by another thread.
public func tryLock() -> Bool {
return 0 == pthread_mutex_trylock(&self.mutex)
}
/// Unlock. Returns true if the lock was held by the current thread and was successfully unlocked. ior the lock count was decremented.
public func unlock() -> Bool {
return 0 == pthread_mutex_unlock(&self.mutex)
}
}
/// A thread event object. Inherits from `Threading.Lock`.
/// The event MUST be locked before `wait` or `signal` is called.
/// While inside the `wait` call, the event is automatically placed in the unlocked state.
/// After `wait` or `signal` return the event will be in the locked state and must be unlocked.
public class Event: Lock {
var cond = pthread_cond_t()
/// Initialize a new Event object.
override init() {
super.init()
var __c_attr = pthread_condattr_t()
pthread_condattr_init(&__c_attr)
#if os (Linux)
// pthread_condattr_setclock(&__c_attr, CLOCK_REALTIME)
#endif
pthread_cond_init(&cond, &__c_attr)
pthread_condattr_destroy(&__c_attr)
}
deinit {
pthread_cond_destroy(&cond)
}
/// Signal at most ONE thread which may be waiting on this event.
/// Has no effect if there is no waiting thread.
public func signal() -> Bool {
return 0 == pthread_cond_signal(&self.cond)
}
/// Signal ALL threads which may be waiting on this event.
/// Has no effect if there is no waiting thread.
public func broadcast() -> Bool {
return 0 == pthread_cond_broadcast(&self.cond)
}
/// Wait on this event for another thread to call signal.
/// Blocks the calling thread until a signal is received or the timeout occurs.
/// Returns true only if the signal was received.
/// Returns false upon timeout or error.
public func wait(waitMillis: Int = -1) -> Bool {
if waitMillis == -1 {
return 0 == pthread_cond_wait(&self.cond, &self.mutex)
}
var tm = timespec()
#if os(Linux)
var tv = timeval()
// !FIX! use clock_gettime
// CLOCK_MONOTONIC isn't exported by Glibc
gettimeofday(&tv, nil)
tm.tv_sec = tv.tv_sec + waitMillis / 1000;
tm.tv_nsec = (tv.tv_usec + 1000 * waitMillis) * 1000
let ret = pthread_cond_timedwait(&self.cond, &self.mutex, &tm)
#else
tm.tv_sec = waitMillis / 1000
tm.tv_nsec = (waitMillis - (tm.tv_sec * 1000)) * 1000000
let ret = pthread_cond_timedwait_relative_np(&self.cond, &self.mutex, &tm)
#endif
return ret == 0;
}
}
/// A read-write thread lock.
/// Permits multiple readers to hold the while, while only allowing at most one writer to hold the lock.
/// For a writer to acquire the lock all readers must have unlocked.
/// For a reader to acquire the lock no writers must hold the lock.
public class RWLock {
var lock = pthread_rwlock_t()
/// Initialize a new read-write lock.
public init() {
pthread_rwlock_init(&self.lock, nil)
}
deinit {
pthread_rwlock_destroy(&self.lock)
}
/// Attempt to acquire the lock for reading.
/// Returns false if an error occurs.
public func readLock() -> Bool {
return 0 == pthread_rwlock_rdlock(&self.lock)
}
/// Attempts to acquire the lock for reading.
/// Returns false if the lock is held by a writer or an error occurs.
public func tryReadLock() -> Bool {
return 0 == pthread_rwlock_tryrdlock(&self.lock)
}
/// Attempt to acquire the lock for writing.
/// Returns false if an error occurs.
public func writeLock() -> Bool {
return 0 == pthread_rwlock_wrlock(&self.lock)
}
/// Attempt to acquire the lock for writing.
/// Returns false if the lock is held by readers or a writer or an error occurs.
public func tryWriteLock() -> Bool {
return 0 == pthread_rwlock_trywrlock(&self.lock)
}
/// Unlock a lock which is held for either reading or writing.
/// Returns false if an error occurs.
public func unlock() -> Bool {
return 0 == pthread_rwlock_unlock(&self.lock)
}
}
/// Call the given closure on a new thread.
/// Returns immediately.
public static func dispatchBlock(closure: ThreadClosure) {
#if USE_LIBDISPATCH
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), closure)
#else
var thrdSlf = pthread_t()
var attr = pthread_attr_t()
pthread_attr_init(&attr)
pthread_attr_setdetachstate(&attr, Int32(PTHREAD_CREATE_DETACHED))
let holderObject = IsThisRequired(closure: closure)
let pthreadFunc: ThreadFunction = {
p in
let unleakyObject = Unmanaged<IsThisRequired>.fromOpaque(COpaquePointer(p)).takeRetainedValue()
unleakyObject.closure()
return nil
}
let leakyObject = UnsafeMutablePointer<Void>(Unmanaged.passRetained(holderObject).toOpaque())
pthread_create(&thrdSlf, &attr, pthreadFunc, leakyObject)
#endif
}
/// Call the cloasure on a new thread given the thread queue.
/// Note that only concurrent queues are supported.
public static func dispatchBlock(queue: ThreadQueue, closure: ThreadClosure) {
#if USE_LIBDISPATCH
dispatch_async(queue, closure)
#else
Threading.dispatchBlock(closure)
#endif
}
// public static func createSerialQueue(named: String) -> ThreadQueue {
//#if USE_LIBDISPATCH
// return dispatch_queue_create(named, DISPATCH_QUEUE_SERIAL)
//#else
// return Threading.createConcurrentQueue(named) // whoops!
//#endif
// }
/// Create a concurrent queue.
/// This is only here for parity with GCD and as of yet has no usefulness when using pthreads.
public static func createConcurrentQueue(named: String) -> ThreadQueue {
#if USE_LIBDISPATCH
return dispatch_queue_create(named, DISPATCH_QUEUE_CONCURRENT)
#else
return 1
#endif
}
/// Call the provided closure on the current thread, but only if it has not been called before.
/// This is useful for ensuring that initialization code is only called once in a multi-threaded process.
/// Upon returning from `Threading.once` it is guaranteed that the closure has been executed and has completed.
public static func once(inout threadOnce: ThreadOnce, onceFunc: ThreadOnceFunction) {
#if USE_LIBDISPATCH
dispatch_once(&threadOnce, onceFunc)
#else
pthread_once(&threadOnce, onceFunc)
#endif
}
}
| agpl-3.0 | 53c94c99f20efe50905040cea78b2073 | 29.912409 | 142 | 0.698111 | 3.551363 | false | false | false | false |
L3-DANT/findme-app | Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift | 2 | 2025 | //
// OFB.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/03/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Output Feedback (OFB)
//
struct OFBModeEncryptGenerator: BlockModeGenerator {
typealias Element = Array<UInt8>
let options: BlockModeOptions = [.InitializationVectorRequired, .PaddingRequired]
private let iv: Element
private let inputGenerator: AnyGenerator<Element>
private let cipherOperation: CipherOperationOnBlock
private var prevCiphertext: Element?
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Array<UInt8>>) {
self.iv = iv
self.cipherOperation = cipherOperation
self.inputGenerator = inputGenerator
}
mutating func next() -> Element? {
guard let plaintext = inputGenerator.next(),
let ciphertext = cipherOperation(block: prevCiphertext ?? iv)
else {
return nil
}
self.prevCiphertext = ciphertext
return xor(plaintext, ciphertext)
}
}
struct OFBModeDecryptGenerator: BlockModeGenerator {
typealias Element = Array<UInt8>
let options: BlockModeOptions = [.InitializationVectorRequired, .PaddingRequired]
private let iv: Element
private let inputGenerator: AnyGenerator<Element>
private let cipherOperation: CipherOperationOnBlock
private var prevCiphertext: Element?
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Element>) {
self.iv = iv
self.cipherOperation = cipherOperation
self.inputGenerator = inputGenerator
}
mutating func next() -> Element? {
guard let ciphertext = inputGenerator.next(),
let decrypted = cipherOperation(block: self.prevCiphertext ?? iv)
else {
return nil
}
let plaintext = xor(decrypted, ciphertext)
self.prevCiphertext = decrypted
return plaintext
}
} | mit | 8fdd2e00302f99053dec6b7c94cf3504 | 29.681818 | 113 | 0.682806 | 4.972973 | false | false | false | false |
zisko/swift | test/decl/func/dynamic_self.swift | 1 | 10436 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ----------------------------------------------------------------------------
// DynamicSelf is only allowed on the return type of class and
// protocol methods.
func global() -> Self { } // expected-error{{global function cannot return 'Self'}}
func inFunction() {
func local() -> Self { } // expected-error{{local function cannot return 'Self'}}
}
struct S0 {
func f() -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{15-19=S0}}
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{16-20=S0}}
}
enum E0 {
func f() -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{15-19=E0}}
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{16-20=E0}}
}
class C0 {
func f() -> Self { } // okay
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}}
func h(_ ds: Self) -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}}
}
protocol P0 {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P0 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
protocol P1: class {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P1 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
// ----------------------------------------------------------------------------
// The 'self' type of a Self method is based on Self
class C1 {
required init(int i: Int) {}
// Instance methods have a self of type Self.
func f(_ b: Bool) -> Self {
// FIXME: below diagnostic should complain about C1 -> Self conversion
if b { return C1(int: 5) } // expected-error{{cannot convert return expression of type 'C1' to return type 'Self'}}
// One can use `type(of:)` to attempt to construct an object of type Self.
if !b { return type(of: self).init(int: 5) }
// Can't utter Self within the body of a method.
var _: Self = self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{12-16=C1}}
// Okay to return 'self', because it has the appropriate type.
return self // okay
}
// Type methods have a self of type Self.Type.
class func factory(_ b: Bool) -> Self {
// Check directly.
var x: Int = self // expected-error{{cannot convert value of type 'Self.Type' to specified type 'Int'}}
// Can't utter Self within the body of a method.
var c1 = C1(int: 5) as Self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{28-32=C1}}
if b { return self.init(int: 5) }
return Self() // expected-error{{use of unresolved identifier 'Self'}} expected-note {{did you mean 'self'?}}
}
// This used to crash because metatype construction went down a
// different code path that didn't handle DynamicSelfType.
class func badFactory() -> Self {
return self(int: 0)
// expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}}
}
}
// ----------------------------------------------------------------------------
// Using a method with a Self result carries the receiver type.
class X {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceX() -> X { }
}
class Y : X {
func produceY() -> Y { }
}
func testInvokeInstanceMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = x.instance()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = y.instance();
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testInvokeTypeMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = X.factory()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = Y.factory()
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testCurryInstanceMethodSelf() {
// Trivial case: currying on the declaring class.
var produceX = X.produceX
var produceX2 = X.instance
produceX = produceX2
produceX2 = produceX
// Currying on a subclass.
var produceY = Y.produceY
var produceY2 = Y.instance
produceY = produceY2
produceY2 = produceY
}
class GX<T> {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceGX() -> GX { }
}
class GY<T> : GX<[T]> {
func produceGY() -> GY { }
}
func testInvokeInstanceMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = x.instance()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = y.instance();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testInvokeTypeMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = GX<Int>.factory()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = GY<Int>.factory();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testCurryInstanceMethodSelfGeneric() {
// Trivial case: currying on the declaring class.
var produceGX = GX<Int>.produceGX
var produceGX2 = GX<Int>.instance
produceGX = produceGX2
produceGX2 = produceGX
// Currying on a subclass.
var produceGY = GY<Int>.produceGY
var produceGY2 = GY<Int>.instance
produceGY = produceGY2
produceGY2 = produceGY
}
// ----------------------------------------------------------------------------
// Overriding a method with a Self
class Z : Y {
override func instance() -> Self {
}
override class func factory() -> Self {
}
}
func testOverriddenMethodSelfGeneric() {
var z = Z()
var z2 = z.instance();
z = z2
z2 = z
var z3 = Z.factory()
z = z3
z3 = z
}
// ----------------------------------------------------------------------------
// Generic uses of Self methods.
protocol P {
func f() -> Self
}
func testGenericCall<T: P>(_ t: T) {
var t = t
var t2 = t.f()
t2 = t
t = t2
}
// ----------------------------------------------------------------------------
// Existential uses of Self methods.
func testExistentialCall(_ p: P) {
_ = p.f()
}
// ----------------------------------------------------------------------------
// Dynamic lookup of Self methods.
@objc class SomeClass {
@objc func method() -> Self { return self }
}
func testAnyObject(_ ao: AnyObject) {
var ao = ao
var result : AnyObject = ao.method!()
result = ao
ao = result
}
// ----------------------------------------------------------------------------
// Name lookup on Self values
extension Y {
func testInstance() -> Self {
if false { return self.instance() }
return instance()
}
class func testFactory() -> Self {
if false { return self.factory() }
return factory()
}
}
// ----------------------------------------------------------------------------
// Optional Self returns
extension X {
func tryToClone() -> Self? { return nil }
func tryHarderToClone() -> Self! { return nil }
func cloneOrFail() -> Self { return self }
func cloneAsObjectSlice() -> X? { return self }
}
extension Y {
func operationThatOnlyExistsOnY() {}
}
func testOptionalSelf(_ y : Y) {
if let clone = y.tryToClone() {
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneOrFail() { // expected-error {{initializer for conditional binding must have Optional type, not 'Y'}}
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneAsObjectSlice() {
clone.operationThatOnlyExistsOnY() // expected-error {{value of type 'X' has no member 'operationThatOnlyExistsOnY'}}
}
if let clone = y.tryHarderToClone().tryToClone() {
clone.operationThatOnlyExistsOnY();
}
}
// ----------------------------------------------------------------------------
// Conformance lookup on Self
protocol Runcible {
}
extension Runcible {
func runce() {}
}
func wantsRuncible<T : Runcible>(_: T) {}
class Runce : Runcible {
func getRunced() -> Self {
runce()
wantsRuncible(self)
return self
}
}
// ----------------------------------------------------------------------------
// Forming a type with 'Self' in invariant position
struct Generic<T> { init(_: T) {} }
class InvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<InvariantSelf> = a
// expected-error@-1 {{cannot convert value of type 'Generic<Self>' to specified type 'Generic<InvariantSelf>'}}
return self
}
}
// FIXME: This should be allowed
final class FinalInvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<FinalInvariantSelf> = a
// expected-error@-1 {{cannot convert value of type 'Generic<Self>' to specified type 'Generic<FinalInvariantSelf>'}}
return self
}
}
// ----------------------------------------------------------------------------
// Semi-bogus factory init pattern
protocol FactoryPattern {
init(factory: @autoclosure () -> Self)
}
extension FactoryPattern {
init(factory: @autoclosure () -> Self) { self = factory() }
}
class Factory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: Factory(_string: string))
// expected-error@-1 {{incorrect argument label in call (have 'factory:', expected '_string:')}}
// FIXME: Bogus diagnostic
}
}
// Final classes are OK
final class FinalFactory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: FinalFactory(_string: string))
}
}
| apache-2.0 | da0f3ca6ec456d94df3b5f5c11a5ffee | 25.420253 | 164 | 0.580299 | 3.821311 | false | false | false | false |
jarvisluong/ios-retro-calculator | RetroCalculator/CalculatorScreen.swift | 1 | 3887 | //
// CalculatorScreen.swift
// RetroCalculator
//
// Created by Hai Dang Luong on 17/01/2017.
// Copyright © 2017 Hai Dang Luong. All rights reserved.
//
import UIKit
import AVFoundation
class CalculatorScreen: UIViewController {
// Sound effect for the buttons
var btnSound : AVAudioPlayer!
// Display the value to the screen
@IBOutlet weak var outputLabel: UILabel!
// List of operators
enum Operators : String {
case Divide = "/"
case Multiply = "Multiply"
case Subtract = "Subtract"
case Add = "Add"
case Empty = "Empty"
}
var currentOperator = Operators.Empty
// Dump Memory Variable for processing the mathematics operations
var leftValue = ""
var rightValue = ""
var result = ""
var runningValue = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
let audioURL = URL(fileURLWithPath: path!)
// Safety first, if for some reasons the sound can't be played then throw and error
do {
try btnSound = AVAudioPlayer(contentsOf: audioURL)
btnSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
}
@IBAction func numberPressed(_ sender: UIButton) {
playAudio()
runningValue += String(sender.tag)
outputLabel.text = runningValue
}
@IBAction func dividePressed(_ sender: UIButton) {
processOperator(operation: .Divide)
}
@IBAction func multiplyPressed(_ sender: UIButton) {
processOperator(operation: .Multiply)
}
@IBAction func subtractPressed(_ sender: UIButton) {
processOperator(operation: .Subtract)
}
@IBAction func addPressed(_ sender: UIButton) {
processOperator(operation: .Add)
}
@IBAction func equalPressed(_ sender: UIButton) {
processOperator(operation: currentOperator)
}
@IBAction func ClearBtnPressed(_ sender: UIButton) {
playAudio()
leftValue = ""
rightValue = ""
runningValue = ""
currentOperator = Operators.Empty
outputLabel.text = "0"
}
func processOperator(operation: Operators) {
playAudio()
if currentOperator != Operators.Empty {
// This happens when user press an operator but then press another operator
if runningValue != "" {
rightValue = runningValue
runningValue = ""
if currentOperator == Operators.Divide {
result = "\(Double(leftValue)! / Double(rightValue)!)"
} else if currentOperator == Operators.Multiply {
result = "\(Double(leftValue)! * Double(rightValue)!)"
} else if currentOperator == Operators.Subtract {
result = "\(Double(leftValue)! - Double(rightValue)!)"
} else if currentOperator == Operators.Add {
result = "\(Double(leftValue)! + Double(rightValue)!)"
}
leftValue = result
outputLabel.text = result
currentOperator = Operators.Empty
}
} else if leftValue != "" {
// This happens when user has already calculated successfully once and continue calculating
currentOperator = operation
} else {
// This is the first time an operator being pushed
leftValue = runningValue
runningValue = ""
currentOperator = operation
}
}
func playAudio() {
if btnSound.isPlaying {
btnSound.stop()
}
btnSound.play()
}
}
| mpl-2.0 | 9010c67afa65c982138840a165fbf586 | 28.664122 | 99 | 0.568708 | 5.345254 | false | false | false | false |
qiuncheng/study-for-swift | BarrageView/BarrageView/ViewController.swift | 1 | 2864 | //
// ViewController.swift
// BarrageView
//
// Created by yolo on 2017/1/11.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var barrageView: BarrageView!
var barrages = [Barrage]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
barrageView = BarrageView(frame: view.bounds)
barrageView.add(in: view)
let messages = ["我是弹幕,我是弹幕,我是弹幕",
"老周的数学课第老周一讲”",
"猪八戒是哪种性格种性格",
"......",
"。。。。。",
"我是一条弹幕1",
"我是一条弹幕我是一条弹幕2",
"弹幕3",
"弹幕4在这里",
"弹幕5",
"弹6",
"弹幕7",
"弹幕弹幕8弹幕",
"弹幕9",
"我是弹幕,我是弹幕,我是弹幕",
"弹幕view的动画执行,部分代码(BulletView.m)如下:",
"创建弹幕view,对弹幕view的各种位置状态进行监听并做出相对应的处理。",
"哈哈哈哈哈哈哈",
"啦啦啦啦啦",
"😂😂😂😂",
"😰😰😰😰😰",
"......",
"。。。。。",
]
let names = ["qiuncheng",
"程庆春",
"chengqingchun",
"vsccw.com",
"qiuncheng.com"]
for message in messages {
let barrage = Barrage(name: names[messages.count / names.count], avatarUrl: "", message: message)
barrages.append(barrage)
}
let button = UIButton(frame: CGRect(x: 5, y: 500, width: UIScreen.main.bounds.width - 10, height: 50))
button.setTitle("开始", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor = UIColor.red
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(beginAnimation(_:)), for: .touchUpInside)
view.addSubview(button)
}
@IBAction func beginAnimation(_ sender: Any) {
barrageView.addNewBarrages(barrages: barrages)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 4aa8e166f318b6f0de37fad57540b8ba | 32.026316 | 110 | 0.461753 | 4.087948 | false | false | false | false |
hejunbinlan/BFKit-Swift | Source/Extensions/Foundation/Dictionary+BFKit.swift | 3 | 2434 | //
// Dictionary+BFKit.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Fabrizio Brancati. 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
/// This extension adds some useful functions to NSDictionary
extension Dictionary
{
// MARK: - Instance functions -
/**
Convert self to JSON as String
:returns: Returns the JSON as String or nil if error while parsing
*/
func dictionaryToJSON() -> String
{
return Dictionary.dictionaryToJSON(self as! AnyObject)
}
// MARK: - Class functions -
/**
Convert the given dictionary to JSON as String
:param: dictionary The dictionary to be converted
:returns: Returns the JSON as String or nil if error while parsing
*/
static func dictionaryToJSON(dictionary: AnyObject) -> String
{
var json: NSString
var error: NSError?
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted, error: &error)!
if jsonData == false
{
return "{}"
}
else if error == nil
{
json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
return json as String
}
else
{
return error!.localizedDescription
}
}
}
| mit | 58a2902d8f911d2266a4485e0fdb630f | 32.342466 | 122 | 0.672555 | 4.735409 | false | false | false | false |
apple/swift-nio-http2 | IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_h1_request_response.swift | 1 | 4193 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOEmbedded
import NIOHPACK
import NIOHTTP1
import NIOHTTP2
/// Have two `EmbeddedChannel` objects send and receive data from each other until
/// they make no forward progress.
func interactInMemory(_ first: EmbeddedChannel, _ second: EmbeddedChannel) throws {
var operated: Bool
func readBytesFromChannel(_ channel: EmbeddedChannel) throws -> ByteBuffer? {
return try channel.readOutbound(as: ByteBuffer.self)
}
repeat {
operated = false
first.embeddedEventLoop.run()
if let data = try readBytesFromChannel(first) {
operated = true
try second.writeInbound(data)
}
if let data = try readBytesFromChannel(second) {
operated = true
try first.writeInbound(data)
}
} while operated
}
final class ServerHandler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let data = self.unwrapInboundIn(data)
switch data {
case .head, .body:
// Ignore this
return
case .end:
break
}
// We got .end. Let's send a response.
let head = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok)
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
}
}
final class ClientHandler: ChannelInboundHandler {
typealias InboundIn = HTTPClientResponsePart
typealias OutboundOut = HTTPClientRequestPart
func channelActive(context: ChannelHandlerContext) {
// Send a request.
let head = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .GET, uri: "/", headers: HTTPHeaders([("host", "localhost")]))
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
}
}
func run(identifier: String) {
let loop = EmbeddedEventLoop()
measure(identifier: identifier) {
var sumOfStreamIDs = 0
for _ in 0..<1000 {
let clientChannel = EmbeddedChannel(loop: loop)
let serverChannel = EmbeddedChannel(loop: loop)
let clientMultiplexer = try! clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()
_ = try! serverChannel.configureHTTP2Pipeline(mode: .server) { channel in
return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()])
}.wait()
try! clientChannel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait()
try! serverChannel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait()
let promise = clientChannel.eventLoop.makePromise(of: Channel.self)
clientMultiplexer.createStreamChannel(promise: promise) { channel in
return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), ClientHandler()])
}
clientChannel.embeddedEventLoop.run()
let child = try! promise.futureResult.wait()
let streamID = try! Int(child.getOption(HTTP2StreamChannelOptions.streamID).wait())
sumOfStreamIDs += streamID
try! interactInMemory(clientChannel, serverChannel)
try! child.closeFuture.wait()
try! clientChannel.close().wait()
try! serverChannel.close().wait()
}
return sumOfStreamIDs
}
}
| apache-2.0 | 71e44a8f4236854c58741a1afe499599 | 35.46087 | 141 | 0.637014 | 4.802978 | false | false | false | false |
CH34MKE10/firebase_friendly_chat | ios-starter/swift-starter/FriendlyChatSwift/Constants.swift | 1 | 934 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
struct Constants {
struct NotificationKeys {
static let SignedIn = "onSignInCompleted"
}
struct Segues {
static let SignInToFp = "SignInToFP"
static let FpToSignIn = "FPToSignIn"
}
struct MessageFields {
static let name = "name"
static let text = "text"
static let photoUrl = "photoUrl"
}
} | apache-2.0 | f78deebce086dcf0f74f1ddc2629b190 | 27.333333 | 76 | 0.704497 | 3.92437 | false | false | false | false |
IAskWind/IAWExtensionTool | IAWExtensionTool/IAWExtensionTool/Classes/Tool/IAW_NetTool.swift | 1 | 20139 | //
// IAW_NetTool.swift
// IAWExtensionTool
//
// Created by winston on 17/1/6.
// Copyright © 2017年 winston. All rights reserved.
//
import Foundation
import ObjectMapper
import AlamofireObjectMapper
import MJRefresh
import Alamofire
open class IAW_NetTool{
public static var headers = [
IAW_AccessToken: "\(UserDefaults.standard.string(forKey: IAW_AccessToken) != nil ? UserDefaults.standard.string(forKey: IAW_AccessToken)! : "")"]
public static var accesstoken=UserDefaults.standard.string(forKey: IAW_AccessToken){
didSet{
UserDefaults.standard.setValue(accesstoken, forKey: IAW_AccessToken)
IAW_NetTool.headers = [
IAW_AccessToken: "\(accesstoken != nil ? accesstoken! : "")"]
}
}
//
// //处理下拉刷新 下拉加载 分页显示
// open class func loadDatasByPage<T:Mappable>(_ url:String,params:[String:Any],tableView:UITableView,_ finished:@escaping (_ pageNum:Int,_ datas:[T])->()){
// // let login_name = "test"
//// let url = "\(BASE_URL)api/question/list"
//
// let block:(Int,@escaping(Int)->())->() = {
// (pageNum,pageReturn) in
//// let params = ["pageNum": pageNum
//// ,"name": queryName
//// ,"typeName": queryType] as [String : Any]
//
// Alamofire.request(url, method: .post,parameters: params,headers: self.headers).responseObject{
// (response:DataResponse<IAW_ResponseModels<T>>) in
// self.endRefresh(tableView: tableView)
// if let responseData = response.result.value{
// //token处理
// if IAW_TokenTool.tokenDeal(tokenInvalid: responseData.tokenInvalid){
// return
// }
// let success = responseData.success
// guard success == true else {
// IAW_ProgressHUDTool.showErrorInfo(msg: responseData.msg)
// return
// }
//
// if let data = responseData.data{
// pageReturn(responseData.page!)
// finished(responseData.page!,data)
// }
// }
// }
// }
// pageBlock(tableView: tableView, block: block)
// }
//****************************泛型运用
public typealias Failure = ()->()
public typealias SuccessNoData = ()->()
/// Closure to be executed when progress changes.
public typealias DealTokenInvalid = (Bool)->Bool
//图片上传(多张)
open class func uploadImgs<M:IAW_BaseModel<Any>>(_ url:String,method: HTTPMethod = .post,uploadImages:[UIImage],headers: HTTPHeaders? = nil,loadingTip:String = "",userDefinedTip:Bool = false,finished:@escaping (M)->(),failure:Failure? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !checkNet(){
return
}
var task:IAW_TaskTool.Task?
if !loadingTip.isEmpty{
task = IAW_TaskTool.delay(1) { //1秒后显示
IAW_ProgressHUDTool.show(msg:loadingTip)
}
}
let scale:CGFloat = 0.8
Alamofire.upload(
multipartFormData: { multipartFormData in
for (index,uploadImg) in uploadImages.enumerated(){
let data = uploadImg.jpegData(compressionQuality: scale)
multipartFormData.append(data!, withName:"file", fileName: "file\(index).png", mimeType: "image/*")
}
},
to: url,
method:.post,
headers:headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseObject{
(response:DataResponse<M>) in
if !loadingTip.isEmpty{
IAW_TaskTool.cancel(task) //速度太快的不显示进度条
IAW_ProgressHUDTool.dimiss()
}
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if !userDefinedTip{
IAW_MsgTool.showSuccessInfo(msg: model.getMsg())
}
finished(model)
}
}
case .failure(let encodingError):
IAW_ProgressHUDTool.dimiss()
print(encodingError)
}
}
)
}
// data 返回msg
open class func loadDataStr<M:IAW_BaseModel<Any>>(_ url:String,method: HTTPMethod = .post,params: Parameters? = nil,headers: HTTPHeaders? = nil,loadingTip:String = "",userDefinedTip:Bool = false,finished:@escaping (M)->(),failure:Failure? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !checkNet(){
return
}
var task:IAW_TaskTool.Task?
if !loadingTip.isEmpty{
task = IAW_TaskTool.delay(1) { //1秒后显示
IAW_ProgressHUDTool.show(msg:loadingTip)
}
}
Alamofire.request(url, method: method, parameters: params,headers:headers).responseObject{
(response:DataResponse<M>) in
if !loadingTip.isEmpty{
IAW_TaskTool.cancel(task) //速度太快的不显示进度条
IAW_ProgressHUDTool.dimiss()
}
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if !userDefinedTip{
IAW_MsgTool.showSuccessInfo(msg: model.getMsg())
}
finished(model)
}
}
}
//返回 T 带 failure
open class func loadData<T:Mappable,M:IAW_BaseModel<T>>(_ url:String,method: HTTPMethod = .post,params: Parameters? = nil,headers: HTTPHeaders? = nil,loadingTip:String = "",userDefinedTip:Bool = false,finished:@escaping (DataResponse<M>,T)->(),failure:Failure? = nil,successNoData:SuccessNoData? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !checkNet(){
return
}
var task:IAW_TaskTool.Task?
if !loadingTip.isEmpty{
task = IAW_TaskTool.delay(1) { //1秒后显示
IAW_ProgressHUDTool.show(msg:loadingTip)
}
}
Alamofire.request(url, method: method, parameters: params,headers: headers).responseObject{
(response:DataResponse<M>) in
if !loadingTip.isEmpty{
IAW_TaskTool.cancel(task) //速度太快的不显示进度条
IAW_ProgressHUDTool.dimiss()
}
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if !userDefinedTip{
IAW_MsgTool.showSuccessInfo(msg: model.getMsg())
}
if let data = model.getData(){
finished(response,data)
}else{
successNoData?()
}
}
}
}
//返回 T 不带failure
// open class func loadData<T:Mappable,M:IAW_BaseModel<T>>(_ url:String,method: HTTPMethod = .post,params:[String:Any],loadingTip:String = "",userDefinedTip:Bool = false,finished:@escaping (DataResponse<M>,T)->(),failure:(()->())?,dealTokenInvalid:((Bool)->(Bool))?){
// if !checkNet(){
// return
// }
// var task:IAW_TaskTool.Task?
// if !loadingTip.isEmpty{
// task = IAW_TaskTool.delay(1) { //1秒后显示
// IAW_ProgressHUDTool.show(msg:loadingTip)
// }
// }
//
// Alamofire.request(url, method: method, parameters: params).responseObject{
// (response:DataResponse<M>) in
// if !loadingTip.isEmpty{
// IAW_TaskTool.cancel(task) //速度太快的不显示进度条
// IAW_ProgressHUDTool.dimiss()
// }
//
// if let model = response.result.value{
// if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
// return
// }
// let success = model.isSuccess()
// guard success else {
// failure?()
// IAW_MsgTool.showErrorInfo(msg: model.getMsg())
// return
// }
// if !userDefinedTip{
// IAW_MsgTool.showSuccessInfo(msg: model.getMsg())
// }
// if let data = model.getData(){
// finished(response,data)
// }
// }
// }
//
// }
//返回[T]
open class func loadDatas<T:Mappable,M:IAW_BaseModel<T>>(_ url:String,method: HTTPMethod = .post,params: Parameters? = nil,headers: HTTPHeaders? = nil,loadingTip:String = "",userDefinedTip:Bool = false,finished:@escaping (M,[T])->(),failure:Failure? = nil,successNoData:SuccessNoData? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !checkNet(){
return
}
var task:IAW_TaskTool.Task?
if !loadingTip.isEmpty{
task = IAW_TaskTool.delay(1) { //1秒后显示
IAW_ProgressHUDTool.show(msg:loadingTip)
}
}
Alamofire.request(url, method: method, parameters: params,headers:headers).responseObject{
(response:DataResponse<M>) in
if !loadingTip.isEmpty{
IAW_TaskTool.cancel(task) //速度太快的不显示进度条
IAW_ProgressHUDTool.dimiss()
}
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if !userDefinedTip{
IAW_MsgTool.showSuccessInfo(msg: model.getMsg())
}
if let data = model.getDatas(){
finished(model, data)
}else{
successNoData?()
}
}
}
}
//泛型分页请求
open class func loadDatasByPage<T:Mappable,M:IAW_BaseModel<T>>(_ url:String,method: HTTPMethod = .post,params: Parameters? = nil,headers: HTTPHeaders? = nil,tableView:UITableView,finished:@escaping (_ pageNum:Int,_ datas:[T],M)->(),failure:Failure? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !IAW_NetTool.checkNet(){
return
}
let block:(Int,@escaping(Int)->())->() = {
(pageNum,pageReturn) in
var params_new:Parameters?
if params != nil{
params_new = params
params_new!.updateValue(pageNum, forKey: "page")
}else{
params_new = ["page":pageNum]
}
Alamofire.request(url, method:method,parameters: params_new,headers: headers).responseObject{
(response:DataResponse<M>) in
IAW_NetTool.endRefresh(tableView: tableView)
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if let data = model.getDatas(){
if data.count <= 0 && model.getPage()!>2 {
print("没新数据了")
return
}
pageReturn(model.getPage()!)
finished(model.getPage()!,data,model)
}
}
}
}
pageBlock(tableView: tableView, block: block)
}
open class func loadDatasByPage<T:Mappable,M:IAW_BaseModel<T>>(_ url:String,method: HTTPMethod = .post,params: Parameters? = nil,headers: HTTPHeaders? = nil,collectionView:UICollectionView,finished:@escaping (_ pageNum:Int,_ datas:[T],M)->(),failure:Failure? = nil,dealTokenInvalid:DealTokenInvalid? = nil){
if !IAW_NetTool.checkNet(){
return
}
let block:(Int,@escaping(Int)->())->() = {
(pageNum,pageReturn) in
var params_new:Parameters?
if params != nil{
params_new = params
params_new!.updateValue(pageNum, forKey: "page")
}else{
params_new = ["page":pageNum]
}
Alamofire.request(url, method:method,parameters: params_new,headers: headers).responseObject{
(response:DataResponse<M>) in
IAW_NetTool.endRefresh(collectionView: collectionView)
if let model = response.result.value{
if dealTokenInvalid?(model.isTokenInvalid()) != nil && (dealTokenInvalid?(model.isTokenInvalid()))!{
return
}
let success = model.isSuccess()
guard success else {
failure?()
IAW_MsgTool.showErrorInfo(msg: model.getMsg())
return
}
if let data = model.getDatas(){
if data.count <= 0 && model.getPage()!>2 {
print("没新数据了")
return
}
pageReturn(model.getPage()!)
finished(model.getPage()!,data,model)
}
}
}
}
pageBlock(collectionView: collectionView, block: block)
}
}
//扩展 处理下拉刷新 上拉加载 分页
extension IAW_NetTool{
//处理MJRefresh 终止刷新
open class func endRefresh(tableView:UITableView){
if tableView.mj_header?.isRefreshing ?? true{
tableView.mj_header?.endRefreshing();
}
if tableView.mj_footer?.isRefreshing ?? true{
tableView.mj_footer?.endRefreshing()
}
}
open class func endRefresh(collectionView:UICollectionView){
if collectionView.mj_header?.isRefreshing ?? false{
collectionView.mj_header?.endRefreshing();
}
if collectionView.mj_footer?.isRefreshing ?? false{
collectionView.mj_footer?.endRefreshing()
}
}
//利用MJRefresh 分页
open class func pageBlock(tableView:UITableView,block:@escaping (Int,@escaping(Int)->())->()){
var page = 1
let pageR = {
(pageN:Int) in
page = pageN
}
let blockRefresh = {
block(1,pageR)
print("blockRefresh**********************************\(page)")
}
let blockAdd = {
block(page,pageR)
print("blockAdd**********************************\(page)")
}
if tableView.mj_header == nil{
let header = MJRefreshNormalHeader(refreshingBlock:blockRefresh)
header.lastUpdatedTimeLabel?.isHidden = true
header.isAutomaticallyChangeAlpha = true //根据拖拽比例自动切换透
header.stateLabel?.isHidden = true
tableView.mj_header = header
}else{
tableView.mj_header?.refreshingBlock = blockRefresh
}
if tableView.mj_header?.isRefreshing ?? false{
tableView.mj_header?.endRefreshing()
}
tableView.mj_header?.beginRefreshing()
if tableView.mj_footer == nil{
let footer = MJRefreshAutoNormalFooter(refreshingBlock: blockAdd)
footer.stateLabel?.isHidden = true
footer.isRefreshingTitleHidden = true
tableView.mj_footer = footer
}else{
tableView.mj_footer?.refreshingBlock = blockAdd
}
}
open class func pageBlock(collectionView:UICollectionView,block:@escaping (Int,@escaping(Int)->())->()){
var page = 1
let pageR = {
(pageN:Int) in
page = pageN
}
let blockRefresh = {
block(1,pageR)
print("blockRefresh**********************************\(page)")
}
let blockAdd = {
block(page,pageR)
print("blockAdd**********************************\(page)")
}
if collectionView.mj_header == nil{
let header = MJRefreshNormalHeader(refreshingBlock:blockRefresh)
header.lastUpdatedTimeLabel?.isHidden = true
header.isAutomaticallyChangeAlpha = true //根据拖拽比例自动切换透
header.stateLabel?.isHidden = true
collectionView.mj_header = header
}else{
collectionView.mj_header?.refreshingBlock = blockRefresh
}
if collectionView.mj_header?.isRefreshing ?? false{
collectionView.mj_header?.endRefreshing()
}
collectionView.mj_header?.beginRefreshing()
if collectionView.mj_footer == nil{
let footer = MJRefreshAutoNormalFooter(refreshingBlock: blockAdd)
footer.stateLabel?.isHidden = true
footer.isRefreshingTitleHidden = true
collectionView.mj_footer = footer
}else{
collectionView.mj_footer?.refreshingBlock = blockAdd
}
}
//检测当前网络是否连接
open class func checkNet()->Bool{
let manager = NetworkReachabilityManager()
let isNet = manager?.isReachable
print(isNet as Any)
if !isNet!{
IAW_MsgTool.showWarningInfo(msg: "请检查您的网络是否连接!",seconds: 3)
}
return isNet!
}
}
| mit | 2a7989da42e76cb792e3bd89223d69a3 | 38.97166 | 348 | 0.498278 | 4.883997 | false | false | false | false |
VladislavJevremovic/Atom-Attack | AtomAttack Shared/Sources/Game/Entities/ParticleManager.swift | 1 | 2176 | //
// ParticleManager.swift
// Atom Attack
//
// Copyright © 2015-2021 Vladislav Jevremović. All rights reserved.
//
import SpriteKit
class ParticleManager: Entity {
// MARK: - Entity
let node = SKNode()
// MARK: - Fields
private var timeout = TimeInterval(0)
private(set) var level: Int {
willSet {
updateTimeout(forLevel: newValue)
}
}
private var particles = [Particle]()
var onAddParticle: ((Particle) -> Void)?
var onRemoveParticle: ((Particle) -> Void)?
// MARK: - Lifecycle
init() {
self.level = 0
updateTimeout(forLevel: level)
}
// MARK: - Public Methods
func start() {
stop()
node.run(
addSequence(),
withKey: AnimationKey.addParticles
)
}
func stop() {
node.removeAction(forKey: AnimationKey.addParticles)
particles.forEach {
self.onRemoveParticle?($0)
}
particles.removeAll()
}
func reset() {
stop()
level = 0
start()
}
func advance() {
level += 1
}
func particleWithNode(_ node: SKNode) -> Particle? {
particles.first { $0.node == node }
}
// MARK: - Private Methods
private func addSequence() -> SKAction {
let addAction = SKAction.run {
self.addParticle()
}
let waitAction = SKAction.wait(forDuration: timeout)
let finalSequence = SKAction.repeatForever(SKAction.sequence([addAction, waitAction]))
return finalSequence
}
private func addParticle() {
let particle = Particle()
particles.append(particle)
onAddParticle?(particle)
}
private func timeoutValue(forLevel level: Int) -> Double {
level < 4 ? 2.5 - Double(level) * 0.5 : 0.25
}
private func updateTimeout(forLevel level: Int) {
timeout = timeoutValue(forLevel: level)
}
// MARK: - Entity
func getInitialPosition(sceneBounds: CGRect) -> CGPoint {
CGPoint(
x: sceneBounds.size.width / 2,
y: sceneBounds.size.height / 2
)
}
}
| mit | fcf05f473aceaf597f2b808eaede63e0 | 19.509434 | 94 | 0.564397 | 4.27112 | false | false | false | false |
thetunesquad/thetunesquad-ios | TheTuneSquad/TheTuneSquad/PlaylistViewController.swift | 1 | 1611 | //
// PlaylistViewController.swift
// TheTuneSquad
//
// Created by Christina Lee on 6/7/17.
// Copyright © 2017 Christina Lee. All rights reserved.
//
import UIKit
class PlaylistViewController: UIViewController {
var playlist = [Track]() {
didSet {
self.playlistTableView.reloadData()
}
}
@IBOutlet weak var playlistTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.playlistTableView.dataSource = self
let nib = UINib(nibName: "PlaylistTableViewCell", bundle: nil)
self.playlistTableView.register(nib, forCellReuseIdentifier: PlaylistTableViewCell.identifier)
self.playlistTableView.estimatedRowHeight = 80
self.playlistTableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: UITableViewDelegate UITableViewDataSource
extension PlaylistViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playlist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PlaylistTableViewCell.identifier, for: indexPath) as! PlaylistTableViewCell
let current = self.playlist[indexPath.row]
cell.track = current
return cell
}
}
| mit | 0894145d5bb5ed0089289a3c9728f97d | 28.272727 | 140 | 0.684472 | 5.532646 | false | false | false | false |
Zeacone/ReadilyOrder | EasyMenu/ViewController.swift | 1 | 1025 | //
// ViewController.swift
// EasyMenu
//
// Created by Zeacone on 16/2/26.
// Copyright © 2016年 Zeacone. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor()
let screen_width = UIScreen.mainScreen().bounds.size.width
let screen_height = UIScreen.mainScreen().bounds.size.height
let backimage: UIImageView = UIImageView(frame: CGRectMake(0, 0, screen_width, screen_height))
backimage.contentMode = UIViewContentMode.ScaleAspectFit
backimage.image = OpenCVWrapper.thresholdingWithImage(UIImage(named: "menu.jpg"))
self.view.addSubview(backimage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 78dc29fe51d1b2ee8d9450795e358343 | 29.058824 | 102 | 0.671233 | 4.624434 | false | false | false | false |
JTWang4778/LearningSwiftDemos | 11-循环引用解决/13-协议/NoteView.swift | 1 | 1602 | //
// NoteView.swift
// 11-循环引用解决
//
// Created by 王锦涛 on 2017/5/2.
// Copyright © 2017年 JTWang. All rights reserved.
//
import UIKit
protocol NoteViewDelegate {
func didClickSubmitButton(withContent: String)
}
class NoteView: UIView {
static func noteView() -> NoteView {
return Bundle.main.loadNibNamed("NoteView", owner: self, options: nil)?.last as! NoteView
}
var delegate: NoteViewDelegate?
var submitClosure: ((String) -> Void)?
@IBOutlet weak var textField: UITextField!
@IBAction func didClickSubmit(_ sender: Any) {
guard (self.textField.text != nil) else {
return
}
guard self.textField.text!.characters.count > 0 else {
print("输入为空")
return
}
// delegateasdf()
self.textField.resignFirstResponder()
if self.submitClosure != nil {
self.submitClosure!(self.textField.text!)
}
}
// 通过代理传值
func delegateasdf() {
if self.delegate != nil {
if self.textField.text == nil {
print(self.textField.text!)
}else{
print(self.textField.text!.characters.count)
}
self.delegate!.didClickSubmitButton(withContent:self.textField.text!)
self.textField.text = nil
}else{
print("没有设置代理")
}
}
}
extension Int {
func dictAtInt() -> Int {
return 10
}
}
| mit | 65cb55d47a74c94cf4b14dc547289023 | 20.219178 | 97 | 0.54164 | 4.351124 | false | false | false | false |
alexktchen/CustomSwitchControl | CustomSwitch/AppDelegate.swift | 1 | 6137 | //
// AppDelegate.swift
// CustomSwitch
//
// Created by Alex Chen on 2015/5/13.
// Copyright (c) 2015年 Alex Chen. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Alex-Chen.CustomSwitch" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CustomSwitch", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CustomSwitch.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 394af1fa7cb65ac4a23b7b3a3a0e054b | 54.27027 | 290 | 0.715892 | 5.760563 | false | false | false | false |
AlexBianzd/NiceApp | NiceApp/Classes/Controller/ZDHomeViewController.swift | 1 | 7693 | //
// ZDHomeViewController.swift
// NiceApp
//
// Created by 边振东 on 8/7/16.
// Copyright © 2016 边振东. All rights reserved.
//
import UIKit
enum ZDControllerType {
case common
case forum
}
class ZDHomeViewController: UIViewController {
fileprivate let menuWidth : CGFloat = 300
fileprivate let animationDuration = 0.3
fileprivate var centerNavController : ZDBaseNavigationController!
fileprivate var commonController : ZDNiceCommonViewController?
fileprivate var forumController : ZDNiceForumViewController?
fileprivate var menuController : UIViewController!
fileprivate weak var cover : UIView!
fileprivate var currentController : UIViewController?
var controllerType : ZDControllerType! = .common {
willSet {
self.controllerType = newValue
}
didSet {
if controllerType == .common {
guard !(self.currentController is ZDNiceCommonViewController) else {
self.leftMenuHiddenAnimate()
return
}
self.removeCenterNavController()
if self.commonController == nil {
self.commonController = ZDNiceCommonViewController()
}
self.currentController = commonController
} else if controllerType == .forum {
guard !(self.currentController is ZDNiceForumViewController) else {
self.leftMenuHiddenAnimate()
return
}
self.removeCenterNavController()
if self.forumController == nil {
self.forumController = ZDNiceForumViewController()
}
self.currentController = forumController
}
self.centerNavController = ZDBaseNavigationController(rootViewController:self.currentController!)
self .addCenterNavController()
self.centerNavController!.view.frame.origin.x = self.menuWidth
self.leftMenuHiddenAnimate()
}
}
convenience init(centerNavController : ZDBaseNavigationController,
menuController : UIViewController) {
self.init(nibName:nil,bundle:nil)
self.centerNavController = centerNavController
self.currentController = centerNavController.viewControllers.first
self.menuController = menuController
self.addmenuController()
self.addCenterNavController()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UI_COLOR_DEFAULT
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(ZDHomeViewController.leftMenuShowAnimate), name: NotifyShowMenu, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ZDHomeViewController.leftMenuHiddenAnimate), name: NotifyHideMenu, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ZDHomeViewController.leftMenuSetupBackColor(notify:)), name: NotifyColor, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ZDHomeViewController.leftMenuSetupCenterView(notify:)), name: NotifyCenter, object: nil)
self.view.bringSubview(toFront: self.centerNavController.view)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
private func addCenterNavController () {
self.currentController!.view.frame = self.view.frame
self.view.addSubview(self.centerNavController!.view)
self.addChildViewController(self.centerNavController!)
self.addCover()
}
private func removeCenterNavController () {
self.currentController!.removeFromParentViewController()
self.centerNavController.view.removeFromSuperview()
self.centerNavController.removeFromParentViewController()
self.centerNavController = nil
}
private func addmenuController () {
self.menuController.view.frame = CGRect.init(x: 0, y: 0, width: menuWidth, height: kSCREEN_HEIGHT)
self.menuController.view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.view.addSubview(self.menuController.view)
self.addChildViewController(self.menuController)
let leftPan : UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ZDHomeViewController.leftMenuDidDrag(pan:)))
self.menuController.view.addGestureRecognizer(leftPan)
}
private func addCover(){
let cover : UIView = UIView(frame: centerNavController!.view.bounds)
let pan : UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ZDHomeViewController.leftMenuDidDrag(pan:)))
cover.backgroundColor = UIColor.clear
cover.addGestureRecognizer(pan)
self.cover = cover
self.centerNavController!.view.addSubview(cover)
let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ZDHomeViewController.leftMenuHiddenAnimate))
cover.addGestureRecognizer(tap)
self.centerNavController.view.bringSubview(toFront: cover)
self.cover.isHidden = true
}
func leftMenuDidDrag(pan : UIPanGestureRecognizer) {
let point = pan.translation(in: pan.view)
if (pan.state == .cancelled || pan.state == .ended) {
self.leftMenuHiddenAnimate()
} else {
self.centerNavController!.view.frame.origin.x += point.x
pan.setTranslation(CGPoint.init(), in: self.centerNavController.view)
if self.centerNavController!.view.frame.origin.x > menuWidth {
self.centerNavController?.view.frame.origin.x = menuWidth
self.cover.isHidden = false
} else if self.centerNavController!.view.frame.origin.x <= 0 {
self.centerNavController?.view.frame.origin.x = 0
self.cover.isHidden = true
}
}
}
func leftMenuShowAnimate() {
UIView.animate(withDuration: animationDuration, animations: { [unowned self]() -> Void in
self.centerNavController!.view.frame.origin.x = self.menuWidth
self.menuController.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.cover.isHidden = false
})
}
func leftMenuHiddenAnimate() {
UIView.animate(withDuration: animationDuration, animations: { [unowned self]() -> Void in
self.centerNavController!.view.frame.origin.x = 0
self.cover.isHidden = true
}) { (finish) -> Void in
self.menuController.view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}
}
func leftMenuSetupBackColor(notify : NSNotification) {
let bg : String = notify.object as! String
let color = UIColor.colorWithHexString(bg)
UIView.animate(withDuration: animationDuration, animations: { () -> Void in
self.view.backgroundColor = color
self.currentController?.view.backgroundColor = color
self.currentController?.navigationController?.navigationBar.barTintColor = color
self.menuController.view.backgroundColor = color
})
}
func leftMenuSetupCenterView(notify : NSNotification) {
let controllerType : String = notify.object as! String
switch controllerType {
case "发现应用":
UIView.animate(withDuration: animationDuration, animations: { () -> Void in
self.view.backgroundColor = UI_COLOR_DEFAULT
self.menuController.view.backgroundColor = UI_COLOR_DEFAULT
})
self.controllerType = .forum
default:
self.controllerType = .common
}
}
}
| mit | 3d87f2cb0d7310afc16d2aad31669a8d | 35.018779 | 157 | 0.716893 | 4.753408 | false | false | false | false |
sarvex/SwiftRecepies | HomeKit/Adding Rooms to the User’s Home/Adding Rooms to the User’s Home/ListRoomsTableViewController.swift | 1 | 3290 | //
// ListRoomsTableViewController.swift
// Adding Rooms to the User’s Home
//
// Created by Vandad Nahavandipoor on 7/25/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import HomeKit
class ListRoomsTableViewController: UITableViewController, HMHomeDelegate {
var homeManager: HMHomeManager!
var home: HMHome!{
didSet{
home.delegate = self
}
}
struct TableViewValues{
static let identifier = "Cell"
}
let addRoomSegueIdentifier = "addRoom"
func home(home: HMHome, didAddRoom room: HMRoom!) {
println("Added a new room to the home")
}
func home(home: HMHome, didRemoveRoom room: HMRoom!) {
println("A room has been removed from the home")
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return home.rooms.count
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier(
TableViewValues.identifier, forIndexPath: indexPath)
as! UITableViewCell
let room = home.rooms[indexPath.row] as! HMRoom
cell.textLabel!.text = room.name
return cell
}
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete{
let room = home.rooms[indexPath.row] as! HMRoom
home.removeRoom(room, completionHandler: {[weak self]
(error: NSError!) in
let strongSelf = self!
if error != nil{
UIAlertController.showAlertControllerOnHostController(strongSelf,
title: "Error",
message: "An error occurred = \(error)",
buttonTitle: "OK")
} else {
tableView.deleteRowsAtIndexPaths([indexPath],
withRowAnimation: .Automatic)
}
})
}
}
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject!) {
if segue.identifier == addRoomSegueIdentifier{
let controller = segue.destinationViewController
as! AddRoomViewController
controller.homeManager = homeManager
controller.home = home
}
}
}
| isc | 33447f37ac60b650084e42896a325d12 | 27.344828 | 83 | 0.648114 | 4.892857 | false | false | false | false |
ebaker355/IBOutletScanner | src/FileScanner.swift | 1 | 2272 | /*
MIT License
Copyright (c) 2017 DuneParkSoftware, LLC
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 FileScannerError: Error {
case noPath
case fileSystemError(path: String)
}
extension FileScannerError: CustomStringConvertible {
var description: String {
switch self {
case .noPath:
return "No search path specified"
case .fileSystemError(let path):
return "Can't access path: " + String(describing: path)
}
}
}
public struct FileScanner {
typealias FileScannerProcessor = (_ file: URL) throws -> Void
func processFiles(ofTypes fileTypes: [String], inPath path: String, _ processor: FileScannerProcessor) throws {
guard path.count > 0 else {
throw FileScannerError.noPath
}
guard let enumerator = FileManager.default.enumerator(atPath: path) else {
throw FileScannerError.fileSystemError(path: path)
}
let rootURL = URL(fileURLWithPath: path)
while let dir = enumerator.nextObject() as? String {
let fileURL = rootURL.appendingPathComponent(dir)
if fileTypes.contains(fileURL.pathExtension) {
try processor(fileURL)
}
}
}
}
| mit | 26705b1dee02f27ad606ba108b234ae7 | 34.5 | 115 | 0.708187 | 4.773109 | false | false | false | false |
benlangmuir/swift | utils/gen-unicode-data/Sources/GenGraphemeBreakProperty/IndicRules.swift | 10 | 4712 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import GenUtils
func getLinkingConsonant(
from data: String
) -> [ClosedRange<UInt32>] {
var unflattened: [(ClosedRange<UInt32>, String)] = []
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let components = line.split(separator: ";")
// Get the property first because it may be one we don't care about.
let splitProperty = components[1].split(separator: "#")
let filteredProperty = splitProperty[0].filter { !$0.isWhitespace }
// We only care about Linking Consonant who is defined as 'Consonant'.
guard filteredProperty == "Consonant" else {
continue
}
// This rule only applies to the following scripts, so ensure that these
// scalars are from such scripts.
for script in ["Bengali", "Devanagari", "Gujarati", "Oriya", "Telugu", "Malayalam"] {
guard line.contains(script.uppercased()) else {
continue
}
break
}
let scalars: ClosedRange<UInt32>
let filteredScalars = components[0].filter { !$0.isWhitespace }
// If we have . appear, it means we have a legitimate range. Otherwise,
// it's a singular scalar.
if filteredScalars.contains(".") {
let range = filteredScalars.split(separator: ".")
scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!
} else {
let scalar = UInt32(filteredScalars, radix: 16)!
scalars = scalar ... scalar
}
unflattened.append((scalars, "Consonant"))
}
return flatten(unflattened).map { $0.0 }
}
func emitLinkingConsonant(
_ data: [ClosedRange<UInt32>],
into result: inout String
) {
// 64 bit arrays * 8 bytes = .512 KB
var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)
let chunkSize = 0x110000 / 64 / 64
var chunks: [Int] = []
for i in 0 ..< 64 * 64 {
let lower = i * chunkSize
let upper = lower + chunkSize - 1
let idx = i / 64
let bit = i % 64
for scalar in lower ... upper {
if data.contains(where: { $0.contains(UInt32(scalar)) }) {
chunks.append(i)
bitArrays[idx][bit] = true
break
}
}
}
// Remove the trailing 0s. Currently this reduces quick look size down to
// 96 bytes from 512 bytes.
var reducedBA = Array(bitArrays.reversed())
reducedBA = Array(reducedBA.drop {
$0.words == [0x0]
})
bitArrays = reducedBA.reversed()
// Keep a record of every rank for all the bitarrays.
var ranks: [UInt16] = []
// Record our quick look ranks.
var lastRank: UInt16 = 0
for (i, _) in bitArrays.enumerated() {
guard i != 0 else {
ranks.append(0)
continue
}
var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)
rank += lastRank
ranks.append(rank)
lastRank = rank
}
// Insert our quick look size at the beginning.
var size = BitArray(size: 64)
size.words = [UInt64(bitArrays.count)]
bitArrays.insert(size, at: 0)
for chunk in chunks {
var chunkBA = BitArray(size: chunkSize)
let lower = chunk * chunkSize
let upper = lower + chunkSize
for scalar in lower ..< upper {
if data.contains(where: { $0.contains(UInt32(scalar)) }) {
chunkBA[scalar % chunkSize] = true
}
}
// Append our chunk bit array's rank.
var lastRank: UInt16 = 0
for (i, _) in chunkBA.words.enumerated() {
guard i != 0 else {
ranks.append(0)
continue
}
var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)
rank += lastRank
ranks.append(rank)
lastRank = rank
}
bitArrays += chunkBA.words.map {
var ba = BitArray(size: 64)
ba.words = [$0]
return ba
}
}
emitCollection(
ranks,
name: "_swift_stdlib_linkingConsonant_ranks",
into: &result
)
emitCollection(
bitArrays,
name: "_swift_stdlib_linkingConsonant",
type: "__swift_uint64_t",
into: &result
) {
assert($0.words.count == 1)
return "0x\(String($0.words[0], radix: 16, uppercase: true))"
}
}
| apache-2.0 | 9726562ab4dbafc2bc24216412ffaf5b | 25.324022 | 89 | 0.584465 | 3.946399 | false | false | false | false |
erkie/ApiModel | Source/Object+JSONDictionary.swift | 1 | 2643 | import Foundation
import RealmSwift
func camelizedString(_ string: String) -> String {
var items: [String] = string.components(separatedBy: "_")
var camelCase = items.remove(at: 0)
for item: String in items {
camelCase += item.capitalized
}
return camelCase
}
func updateRealmObjectFromDictionaryWithMapping(_ realmObject: Object, data: [String:Any], mapping: JSONMapping, originRealm: Realm?) {
for (var key, value) in data {
key = camelizedString(key)
if let transform = mapping[key] {
var optionalValue: AnyObject? = value as AnyObject?
if (value as AnyObject).isKind(of: NSNull.self) {
optionalValue = nil
}
let transformedValue = transform.perform(optionalValue, realm: originRealm)
if let primaryKey = type(of: realmObject).primaryKey(),
let modelsPrimaryKey = convertToApiId(realmObject[primaryKey] as AnyObject?),
let responsePrimaryKey = convertToApiId(transformedValue), key == primaryKey && !modelsPrimaryKey.isEmpty
{
if modelsPrimaryKey == responsePrimaryKey {
continue
} else {
print("APIMODEL WARNING: Api responded with different ID than stored. Changing this crashes Realm. Skipping (Tried to change \(modelsPrimaryKey) to \(responsePrimaryKey))")
continue
}
}
realmObject[key] = transformedValue
}
}
}
extension Object {
public func updateFromForm(_ data: NSDictionary) {
let mapping = type(of: (self as! ApiModel)).fromJSONMapping()
updateFromDictionaryWithMapping(data as! [String:AnyObject], mapping: mapping)
}
// We need to pass in JSONMapping manually because of problems in Swift
// It's impossible to cast Objects to "Object that conforms to ApiModel" currently...
public func updateFromForm(_ data: NSDictionary, mapping: JSONMapping) {
updateFromDictionaryWithMapping(data as! [String:AnyObject], mapping: mapping)
}
public func updateFromDictionary(_ data: [String:Any]) {
let mapping = type(of: (self as! ApiModel)).fromJSONMapping()
updateRealmObjectFromDictionaryWithMapping(self, data: data, mapping: mapping, originRealm: realm)
}
public func updateFromDictionaryWithMapping(_ data: [String:AnyObject], mapping: JSONMapping) {
updateRealmObjectFromDictionaryWithMapping(self, data: data, mapping: mapping, originRealm: realm)
}
}
| mit | 8178ef2b2d6d02a14eb324b12eec4c88 | 40.952381 | 192 | 0.639803 | 5.102317 | false | false | false | false |
ashfurrow/Moya | Tests/MoyaTests/Single+MoyaSpec.swift | 1 | 25988 | import Quick
import Moya
import RxSwift
import Nimble
import Foundation
final class SingleMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes closed range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes closed range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let single = Response(statusCode: 304, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("knows how to filter individual status code") {
let data = Data()
let single = Response(statusCode: 42, data: data).asSingle()
var called = false
_ = single.filter(statusCode: 42).subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let single = Response(statusCode: 43, data: data).asSingle()
var errored = false
_ = single.filter(statusCode: 42).subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .error:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testImage
guard let data = image.asJPEGRepresentation(0.75) else {
fatalError("Failed creating Data from Image")
}
let single = Response(statusCode: 200, data: data).asSingle()
var size: CGSize?
_ = single.mapImage().subscribe(onSuccess: { image in
size = image.size
})
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapImage().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedJSON: [String: String]?
_ = single.mapJSON().subscribe(onSuccess: { json in
if let json = json as? [String: String] {
receivedJSON = json
}
})
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
guard let data = json.data(using: .utf8) else {
fatalError("Failed creating Data from JSON String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapJSON().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
guard let data = string.data(using: .utf8) else {
fatalError("Failed creating Data from String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString().subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("maps data representing a string at a key path to a string") {
let string = "You have the rights to the remains of a silent attorney."
let json = ["words_to_live_by": string]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString(atKeyPath: "words_to_live_by").subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapString().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .error(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("object mapping") {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let json: [String: Any] = [
"title": "Hello, Moya!",
"createdAt": "1995-01-14T12:34:56"
]
it("maps data representing a json to a decodable object") {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to an array of decodable objects") {
let jsonArray = [json, json, json]
guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, using: decoder).subscribe(onSuccess: { objects in
receivedObjects = objects
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 3
expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"]
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
context("when using key path mapping") {
it("maps data representing a json to a decodable object") {
let json: [String: Any] = ["issue": json] // nested json
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, atKeyPath: "issue", using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to a decodable object (#1311)") {
let json: [String: Any] = ["issues": [json]] // nested json array
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, atKeyPath: "issues", using: decoder).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title) == "Hello, Moya!"
expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
it("map Int data to an Int value") {
let json: [String: Any] = ["count": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var count: Int?
_ = observable.map(Int.self, atKeyPath: "count", using: decoder).subscribe(onSuccess: { value in
count = value
})
expect(count).notTo(beNil())
expect(count) == 1
}
it("map Bool data to a Bool value") {
let json: [String: Any] = ["isNew": true]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).notTo(beNil())
expect(isNew) == true
}
it("map String data to a String value") {
let json: [String: Any] = ["description": "Something interesting"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var description: String?
_ = observable.map(String.self, atKeyPath: "description", using: decoder).subscribe(onSuccess: { value in
description = value
})
expect(description).notTo(beNil())
expect(description) == "Something interesting"
}
it("map String data to a URL value") {
let json: [String: Any] = ["url": "http://www.example.com/test"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var url: URL?
_ = observable.map(URL.self, atKeyPath: "url", using: decoder).subscribe(onSuccess: { value in
url = value
})
expect(url).notTo(beNil())
expect(url) == URL(string: "http://www.example.com/test")
}
it("shouldn't map Int data to a Bool value") {
let json: [String: Any] = ["isNew": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).to(beNil())
}
it("shouldn't map String data to an Int value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: Int?
_ = observable.map(Int.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map Array<String> data to an String value") {
let json: [String: Any] = ["test": ["123", "456"]]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: String?
_ = observable.map(String.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map String data to an Array<String> value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: [String]?
_ = observable.map([String].self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
}
it("ignores invalid data") {
var json = json
json["createdAt"] = "Hahaha" // invalid date string
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: Error?
_ = single.map(Issue.self, using: decoder).subscribe { event in
switch event {
case .success:
fail("success called for invalid data")
case .error(let error):
receivedError = error
}
}
if case let MoyaError.objectMapping(nestedError, _)? = receivedError {
expect(nestedError).to(beAKindOf(DecodingError.self))
} else {
fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>")
}
}
}
}
}
| mit | 3fa13bf024c7aa15815c5357dd9e709f | 43.348123 | 150 | 0.495344 | 5.690388 | false | false | false | false |
904388172/-TV | DouYuTV/DouYuTV/Classes/Home/View/RecommendCycleView.swift | 1 | 4814 | //
// RecommendCycleView.swift
// DouYuTV
//
// Created by GS on 2017/10/24.
// Copyright © 2017年 Demo. All rights reserved.
//
//无限轮播
import UIKit
private let kCycleCellID = "kCycleCellID"
class RecommendCycleView: UIView {
//定时器
var cycleTimer : Timer?
//定义属性
var cycleModels: [CycleModel]? {
didSet {
//1.刷新collectionView
collectionView.reloadData()
//2.设置pageController个数(没有值的话设为0)
pageControl.numberOfPages = cycleModels?.count ?? 0
// 3.默认滚动到中间某一个位置
let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
//4.添加定时器(防止出问题,先移除在添加)
removeCycleTimer()
addCycleTimer()
}
}
//MARK: - 控件属性
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
//设置控件不随着父空间拉伸而拉伸
autoresizingMask = UIViewAutoresizing.flexibleRightMargin
//注册cell(代码方式注册)
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCycleCellID)
//xib方式注册
collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID)
}
override func layoutSubviews() {
//设置collectiView的layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// layout.itemSize = collectionView.bounds.size(不能这样写否则设置轮播的时候会出问题)
layout.itemSize = CGSize(width: kScreenW, height: kScreenW * 3 / 8)
// 行间距
layout.minimumLineSpacing = 0
//item之间的间距
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
}
}
//MARK: - 提供一个快速创建view的类方法
extension RecommendCycleView {
class func recommendCycleView() -> RecommendCycleView {
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
//MARK: - 遵守uicollectionView的数据源协议
extension RecommendCycleView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0 ) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell
cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count]
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.green
return cell
}
}
//MARK: - 遵守uicollectionView的代理协议
extension RecommendCycleView: UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//获取滚动的偏移量(滚动超过一半就改变pageControl)
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
//计算pageControl的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
//MARK: - 对定时器的操作方法
extension RecommendCycleView {
private func addCycleTimer() {
cycleTimer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .commonModes)
}
private func removeCycleTimer() {
cycleTimer?.invalidate() //从运行循环中移除
cycleTimer = nil
}
@objc func scrollToNext() {
//获取滚动的偏移量
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
//滚动到该位置
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
| mit | 29125ab001b44bf928a96d66d871d213 | 31.536765 | 129 | 0.662599 | 5.09206 | false | false | false | false |
volodg/iAsync.cache | Sources/CacheAdapter/CacheAdapter.swift | 1 | 1799 | //
// CacheAdapter.swift
// iAsync_cache
//
// Created by Vladimir Gorbenko on 05.08.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_utils
import iAsync_restkit
import struct iAsync_reactiveKit.AsyncStream
import func iAsync_reactiveKit.asyncStreamWithJob
import enum ReactiveKit.Result
public typealias CacheFactory = () -> CacheDB
public class NoCacheDataError : SilentError {
init(key: String) {
let description = "no cached data for key: \(key)"
super.init(description: description)
}
}
open class CacheAdapter : AsyncRestKitCache {
private let cacheFactory : CacheFactory
private let cacheQueueName: String
public init(cacheFactory: @escaping CacheFactory, cacheQueueName: String) {
self.cacheQueueName = cacheQueueName
self.cacheFactory = cacheFactory
}
public func loaderToSet(data: Data, forKey key: String) -> AsyncStream<Void, Any, ErrorWithContext> {
return asyncStreamWithJob(cacheQueueName, job: { _ -> Result<Void, ErrorWithContext> in
self.cacheFactory().set(data: data, forKey:key)
return .success(())
})
}
public func cachedDataStreamFor(key: String) -> AsyncStream<(date: Date, data: Data), Any, ErrorWithContext> {
return asyncStreamWithJob(cacheQueueName, job: { _ -> Result<(date: Date, data: Data), ErrorWithContext> in
let result = self.cacheFactory().dataAndLastUpdateDateFor(key: key)
if let result = result {
return .success((date: result.1, data: result.0))
}
let contextError = ErrorWithContext(utilsError: NoCacheDataError(key: key), context: #function)
return .failure(contextError)
})
}
}
| mit | d874e2f545b2c43b83f31bcd80a3a508 | 28 | 115 | 0.676307 | 4.230588 | false | false | false | false |
fawkes32/swiftCourse | HTTPPrueba/HTTPPrueba/ViewController.swift | 1 | 1876 | //
// ViewController.swift
// HTTPPrueba
//
// Created by Daniel Marquez on 6/25/15.
// Copyright (c) 2015 Tec de Monterrey. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var request:HTTPTask!
@IBOutlet weak var texto: UITextField!
@IBOutlet weak var lblRespuesta: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initHTTP()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
@IBAction func probarServer(sender: AnyObject) {
callService()
}
func initHTTP(){
self.request = HTTPTask()
self.request.requestSerializer = JSONRequestSerializer()
self.request.responseSerializer = JSONResponseSerializer()
}
func callService(){
var nombre = texto.text!
nombre = nombre.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
var metodo = "http://desarrollo.gservicio.com:8080/cursoswift/services.php/saluda/" + nombre
self.request.GET(metodo,
parameters: nil,
completionHandler: {(response: HTTPResponse) in self.onRespuesta(response)})
}
func onRespuesta( response: HTTPResponse){
if let respuesta = response.responseObject as? Dictionary<String,AnyObject>{
NSOperationQueue.mainQueue().addOperationWithBlock{
var respuestaServer: String = respuesta["mensaje"]! as! String
self.lblRespuesta.text = respuestaServer
}
}
}
}
| mit | c4ec305deab1147ec08ddc26978ecd23 | 25.055556 | 106 | 0.629531 | 4.898172 | false | false | false | false |
ixx1232/Getting-Started-swift | GettingStartedSwift/GettingStartedSwift/泛型.playground/Contents.swift | 1 | 2326 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// 在尖括号里写一个名字来创建一个泛型函数或者类型
//func repeat<ItemType>(item: ItemType, times:Int) -> [ItemType] {
// var result = [ItemType]()
// for i in 0..<times {
// result.append(item)
// }
// return result
//}
//repeat("knock", 4)
// 你也可以创建泛型类 枚举和结构体
// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
// 在类型名后面使用 where 来制定对类型的需求, 比如, 限定类型实现某一个协议, 限定两个类型是相同的, 或者限定某个类必须有一个特定的父类
func anyCommonElements<T, U where T: SequenceType, U:SequenceType, T.Generator.Element:Equatable,T.Generator.Element == U.Generator.Element>(lhs:T, rhs:U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], rhs: [3])
// 练习: 修改 anyCommonElements 函数来创建一个函数, 返回一个数组, 内容是两个序列的共有元素
func anyCommonElements1 <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs:U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements1([1, 2, 3], rhs: [3])
func whichCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Array<T.Generator.Element> {
var toReturn = Array<T.Generator.Element>()
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
toReturn.append(lhsItem)
}
}
}
return toReturn
}
whichCommonElements([1, 2, 3], rhs: [3, 2])
// 简单起见, 你可以忽略 where, 只在冒号后面写协议或者类名. <T:Equatable> 和 <T where T:Equatable>是等价的
| mit | 5b11e56b7e854bde9db13b6568bca4d7 | 27.055556 | 195 | 0.621782 | 3.273906 | false | false | false | false |
bitrise-io/sample-apps-ios-xcode7 | BitriseXcode7Sample/MasterViewController.swift | 2 | 9221 | //
// MasterViewController.swift
// BitriseXcode7Sample
//
// Created by Viktor Benei on 9/16/15.
// Copyright © 2015 Bitrise. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
cell.textLabel!.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit | 8ed01305eb2aec79a85f651ebe3463a3 | 45.1 | 360 | 0.689046 | 6.297814 | false | false | false | false |
BumwooPark/RXBattleGround | Pods/Carte/Sources/Carte/Carte.swift | 1 | 2623 | //
// Carte.swift
// Carte
//
// Created by Suyeol Jeon on 06/06/2017.
//
import Foundation
public class Carte {
public static var infoDictionary: [String: Any]? = Bundle.main.infoDictionary {
didSet {
self._items = nil
}
}
private static var _items: [CarteItem]? = nil
public static var items: [CarteItem] {
if let items = self._items {
return items
}
let items = Carte.appendingCarte(to: Carte.items(from: Carte.infoDictionary) ?? [])
self._items = items
return items
}
static func items(from infoDictionary: [String: Any]?) -> [CarteItem]? {
return (infoDictionary?["Carte"] as? [[String: Any]])?
.flatMap { dict -> CarteItem? in
guard let name = dict["name"] as? String else { return nil }
var item = CarteItem(name: name)
item.licenseText = (dict["text"] as? String)
.flatMap { Data(base64Encoded: $0) }
.flatMap { String(data: $0, encoding: .utf8) }
return item
}
.sorted { $0.name < $1.name }
}
static func appendingCarte(to items: [CarteItem]) -> [CarteItem] {
guard items.lazy.filter({ $0.name == "Carte" }).first == nil else { return items }
var item = CarteItem(name: "Carte")
item.licenseText = [
"The MIT License (MIT)",
"",
"Copyright (c) 2015 Suyeol Jeon (xoul.kr)",
"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.",
].joined(separator: "\n")
return (items + [item]).sorted { $0.name < $1.name }
}
}
| mit | 71c881e54e4b7f1ad1c1a5fc2570702d | 38.149254 | 88 | 0.64125 | 3.974242 | false | false | false | false |
ChaselAn/CodeLibrary | codeLibrary/codeLibrary/ACShadeNavigationBar/ACNavigationBar+Ex.swift | 1 | 1561 | //
// UINavigationBar+Ex.swift
// lucencyNav
//
// Created by ancheng on 16/8/19.
// Copyright © 2016年 ac. All rights reserved.
//
import UIKit
private var key: String = "navigationView"
extension UINavigationBar{
var navigationView: UIView? {
get {
return objc_getAssociatedObject(self, &key) as? UIView
}
set {
objc_setAssociatedObject(self , &key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// 设置背景色
func customMyBackgroundColor(_ color: UIColor) {
if navigationView != nil {
navigationView?.backgroundColor = color
} else {
setBackgroundImage(UIImage(), for: UIBarMetrics.default)
shadowImage = UIImage()// 隐藏navigationBar下面的那条黑线
let navView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: -20), size: CGSize(width: UIScreen.main.bounds.size.width, height: bounds.height + 20)))
navView.isUserInteractionEnabled = false
insertSubview(navView, at: 0)
navView.backgroundColor = color
navigationView = navView
}
}
// 设置透明度
func customMyBackgroundColorAlpha(_ alpha: CGFloat) {
guard let navigationView = navigationView else {
return
}
navigationView.backgroundColor = navigationView.backgroundColor?.withAlphaComponent(alpha)
}
/**
解决push进入下一页的bug
*/
func resetNavBar() {
setBackgroundImage(nil , for: UIBarMetrics.default)
navigationView?.removeFromSuperview()
navigationView = nil
}
}
| mit | 8d00042d3b4755d64e56da413e72ccb7 | 24.491525 | 154 | 0.677527 | 4.410557 | false | false | false | false |
rmclea21/Flappy-Santa | FlappyBird/GameViewController.swift | 1 | 1933 | //
// GameViewController.swift
// FlappyBird
//
// Created by pmst on 15/10/4.
// Copyright (c) 2015年 pmst. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// 1.对view进行父类向子类的变形,结果是一个可选类型 因此需要解包
if let skView = self.view as? SKView{
// 倘若skView中没有场景Scene,需要重新创建创建一个
if skView.scene == nil{
/*== 创建场景代码 ==*/
// 2.获得高宽比例
let aspectRatio = skView.bounds.size.height / skView.bounds.size.width
// 3.new一个场景实例 这里注意场景的width始终为320 至于高是通过width * aspectRatio获得
let scene = GameScene(size:CGSizeMake(320, 320 * aspectRatio),gameState:.MainMenu)
// 4.设置一些调试参数
skView.showsFPS = false // 显示帧数
skView.showsNodeCount = false // 显示当前场景下节点个数
skView.showsPhysics = true // 显示物理体
skView.ignoresSiblingOrder = true // 忽略节点添加顺序
// 5.设置场景呈现模式
scene.scaleMode = .AspectFill
// 6.呈现场景
skView.presentScene(scene)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | a42d75c41e477616041b327a26685000 | 28.350877 | 98 | 0.531978 | 4.647222 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/SpeechToTextV1/WebSockets/SpeechToTextEncoder.swift | 1 | 18959 | /**
* (C) Copyright IBM Corp. 2016, 2021.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#if os(Linux)
#else
import Foundation
import AudioToolbox
#if canImport(Clibogg)
import Clibogg
#endif
#if canImport(Clibopus)
import Clibopus
#endif
internal class SpeechToTextEncoder {
// This implementation uses the libopus and libogg libraries to encode and encapsulate audio.
// For more information about these libraries, refer to their online documentation.
// (The opus-tools source code was also helpful to verify the implementation.)
// swiftlint:disable:next type_name
private typealias opus_encoder = OpaquePointer
private var stream: ogg_stream_state // state of the ogg stream
private var encoder: opus_encoder // encoder to convert pcm to opus
private var granulePosition: Int64 // total number of encoded pcm samples in the stream
private var packetNumber: Int64 // total number of packets encoded in the stream
private let frameSize: Int32 // number of pcm frames to encode in an opus frame (20ms)
private let maxFrameSize: Int32 = 3832 // maximum size of an opus frame
private let opusRate: Int32 // desired sample rate of the opus audio
private let pcmBytesPerFrame: UInt32 // bytes per frame in the pcm audio
private var pcmCache = Data() // cache for pcm audio that is too short to encode
private var oggCache = Data() // cache for ogg stream
convenience init(format: AudioStreamBasicDescription, opusRate: Int32, application: Application) throws {
try self.init(
pcmRate: Int32(format.mSampleRate),
pcmChannels: Int32(format.mChannelsPerFrame),
pcmBytesPerFrame: format.mBytesPerFrame,
opusRate: opusRate,
application: application
)
}
init(pcmRate: Int32, pcmChannels: Int32, pcmBytesPerFrame: UInt32, opusRate: Int32, application: Application) throws {
// avoid resampling
guard pcmRate == opusRate else {
print("Resampling is not supported. Please ensure that the PCM and Opus sample rates match.")
throw OggError.internalError
}
// set properties
self.granulePosition = 0
self.packetNumber = 0
self.frameSize = Int32(960 / (48000 / opusRate))
self.opusRate = opusRate
self.pcmBytesPerFrame = pcmBytesPerFrame
self.pcmCache = Data()
// create status to capture errors
var status = Int32(0)
// initialize ogg stream
stream = ogg_stream_state()
let serial = Int32(bitPattern: arc4random())
status = ogg_stream_init(&stream, serial)
guard status == 0 else {
throw OggError.internalError
}
// initialize opus encoder
encoder = opus_encoder_create(opusRate, pcmChannels, application.rawValue, &status)
guard let error = OpusError(rawValue: status) else { throw OpusError.internalError }
guard error == .okay else { throw error }
// add opus headers to ogg stream
try addOpusHeader(channels: UInt8(pcmChannels), rate: UInt32(pcmRate))
try addOpusCommentHeader()
}
deinit {
// ogg_stream_destroy(&stream)
opus_encoder_destroy(encoder)
}
private func addOpusHeader(channels: UInt8, rate: UInt32) throws {
// construct opus header
let header = Header(
outputChannels: channels,
preskip: 0,
inputSampleRate: rate,
outputGain: 0,
channelMappingFamily: .rtp
)
// convert header to a data buffer
let headerData = header.toData()
let packetData = UnsafeMutablePointer<UInt8>.allocate(capacity: headerData.count)
headerData.copyBytes(to: packetData, count: headerData.count)
// construct ogg packet with header
var packet = ogg_packet()
packet.packet = packetData
packet.bytes = headerData.count
packet.b_o_s = 1
packet.e_o_s = 0
packet.granulepos = granulePosition
packet.packetno = Int64(packetNumber)
packetNumber += 1
// add packet to ogg stream
let status = ogg_stream_packetin(&stream, &packet)
guard status == 0 else {
throw OggError.internalError
}
// deallocate header data buffer
packetData.deallocate()
// assemble pages and add to ogg cache
assemblePages(flush: true)
}
private func addOpusCommentHeader() throws {
// construct opus comment header
let header = CommentHeader()
let headerData = header.toData()
let packetData = UnsafeMutablePointer<UInt8>.allocate(capacity: headerData.count)
headerData.copyBytes(to: packetData, count: headerData.count)
// construct ogg packet with comment header
var packet = ogg_packet()
packet.packet = packetData
packet.bytes = headerData.count
packet.b_o_s = 0
packet.e_o_s = 0
packet.granulepos = granulePosition
packet.packetno = Int64(packetNumber)
packetNumber += 1
// add packet to ogg stream
let status = ogg_stream_packetin(&stream, &packet)
guard status == 0 else {
throw OggError.internalError
}
// deallocate header data buffer
packetData.deallocate()
// assemble pages and add to ogg cache
assemblePages(flush: true)
}
internal func encode(pcm: AudioQueueBuffer) throws {
let pcmData = pcm.mAudioData.assumingMemoryBound(to: Int16.self)
try encode(pcm: pcmData, count: Int(pcm.mAudioDataByteSize))
}
internal func encode(pcm: Data) throws {
try pcm.withUnsafeBytes { (bytes: UnsafePointer<Int16>) in
try encode(pcm: bytes, count: pcm.count)
}
// try encode(pcm: pcm.bytes, bytes: pcm.length)
}
internal func encode(pcm: UnsafePointer<Int16>, count: Int) throws {
// ensure we have complete pcm frames
guard UInt32(count) % pcmBytesPerFrame == 0 else {
throw OpusError.internalError
}
// construct audio buffers
var pcm = UnsafeMutablePointer<Int16>(mutating: pcm)
var opus = [UInt8](repeating: 0, count: Int(maxFrameSize))
var count = count
// encode cache, if necessary
try encodeCache(pcm: &pcm, bytes: &count)
// encode complete frames
while count >= Int(frameSize) * Int(pcmBytesPerFrame) {
// encode an opus frame
let numBytes = opus_encode(encoder, pcm, frameSize, &opus, maxFrameSize)
guard numBytes >= 0 else {
throw OpusError.internalError
}
// construct ogg packet with opus frame
var packet = ogg_packet()
granulePosition += Int64(frameSize * 48000 / opusRate)
packet.packet = UnsafeMutablePointer<UInt8>(mutating: opus)
packet.bytes = Int(numBytes)
packet.b_o_s = 0
packet.e_o_s = 0
packet.granulepos = granulePosition
packet.packetno = Int64(packetNumber)
packetNumber += 1
// add packet to ogg stream
let status = ogg_stream_packetin(&stream, &packet)
guard status == 0 else {
throw OggError.internalError
}
// advance pcm buffer
let bytesEncoded = Int(frameSize) * Int(pcmBytesPerFrame)
pcm = pcm.advanced(by: bytesEncoded / MemoryLayout<Int16>.stride)
count -= bytesEncoded
}
// cache remaining pcm data
pcm.withMemoryRebound(to: UInt8.self, capacity: count) { data in
pcmCache.append(data, count: count)
}
}
private func encodeCache(pcm: inout UnsafeMutablePointer<Int16>, bytes: inout Int) throws {
// ensure there is cached data
guard pcmCache.count > 0 else {
return
}
// ensure we can add enough pcm data for a complete frame
guard pcmCache.count + bytes >= Int(frameSize) * Int(pcmBytesPerFrame) else {
return
}
// append pcm data to create a complete frame
let toAppend = Int(frameSize) * Int(pcmBytesPerFrame) - pcmCache.count
pcm.withMemoryRebound(to: UInt8.self, capacity: toAppend) { data in
pcmCache.append(data, count: toAppend)
}
// advance pcm buffer (modifies the inout arguments)
pcm = pcm.advanced(by: toAppend / MemoryLayout<Int16>.stride)
bytes -= toAppend
// encode an opus frame
var opus = [UInt8](repeating: 0, count: Int(maxFrameSize))
var numBytes: opus_int32 = 0
try pcmCache.withUnsafeBytes { (cache: UnsafePointer<Int16>) in
numBytes = opus_encode(encoder, cache, frameSize, &opus, maxFrameSize)
guard numBytes >= 0 else {
throw OpusError.internalError
}
}
// construct ogg packet with opus frame
var packet = ogg_packet()
granulePosition += Int64(frameSize * 48000 / opusRate)
packet.packet = UnsafeMutablePointer<UInt8>(mutating: opus)
packet.bytes = Int(numBytes)
packet.b_o_s = 0
packet.e_o_s = 0
packet.granulepos = granulePosition
packet.packetno = Int64(packetNumber)
packetNumber += 1
// add packet to ogg stream
let status = ogg_stream_packetin(&stream, &packet)
guard status == 0 else {
throw OggError.internalError
}
// reset cache
pcmCache = Data()
}
internal func bitstream(flush: Bool = false, fillBytes: Int32? = nil) -> Data {
assemblePages(flush: flush, fillBytes: fillBytes)
let bitstream = oggCache
oggCache = Data()
return bitstream
}
internal func endstream(fillBytes: Int32? = nil) throws -> Data {
// compute granule position using cache
let pcmFrames = pcmCache.count / Int(pcmBytesPerFrame)
granulePosition += Int64(pcmFrames * 48000 / Int(opusRate))
// add padding to cache to construct complete frame
let toAppend = Int(frameSize) * Int(pcmBytesPerFrame) - pcmCache.count
let padding = [UInt8](repeating: 0, count: toAppend)
pcmCache.append(padding, count: toAppend)
// encode an opus frame
var opus = [UInt8](repeating: 0, count: Int(maxFrameSize))
var numBytes: opus_int32 = 0
try pcmCache.withUnsafeBytes { (cache: UnsafePointer<Int16>) in
numBytes = opus_encode(encoder, cache, frameSize, &opus, maxFrameSize)
guard numBytes >= 0 else {
throw OpusError.internalError
}
}
// construct ogg packet with opus frame
var packet = ogg_packet()
packet.packet = UnsafeMutablePointer<UInt8>(mutating: opus)
packet.bytes = Int(numBytes)
packet.b_o_s = 0
packet.e_o_s = 1
packet.granulepos = granulePosition
packet.packetno = Int64(packetNumber)
packetNumber += 1
// add packet to ogg stream
let status = ogg_stream_packetin(&stream, &packet)
guard status == 0 else {
throw OggError.internalError
}
return bitstream(flush: true)
}
private func assemblePages(flush: Bool = false, fillBytes: Int32? = nil) {
var page = ogg_page()
var status = Int32(1)
// assemble pages until there is insufficient data to fill a page
while true {
// assemble accumulated packets into an ogg page
switch (flush, fillBytes) {
case (true, .some(let fillBytes)): status = ogg_stream_flush_fill(&stream, &page, fillBytes)
case (true, .none): status = ogg_stream_flush(&stream, &page)
case (false, .some(let fillBytes)): status = ogg_stream_pageout_fill(&stream, &page, fillBytes)
case (false, .none): status = ogg_stream_pageout(&stream, &page)
}
// break when all packet data has been accumulated into pages
guard status != 0 else {
return
}
// add ogg page to cache
oggCache.append(page.header, count: page.header_len)
oggCache.append(page.body, count: page.body_len)
}
}
}
// MARK: - Header
private class Header {
private(set) var magicSignature: [UInt8]
private(set) var version: UInt8
private(set) var outputChannels: UInt8
private(set) var preskip: UInt16
private(set) var inputSampleRate: UInt32
private(set) var outputGain: Int16
private(set) var channelMappingFamily: ChannelMappingFamily
init(outputChannels: UInt8, preskip: UInt16, inputSampleRate: UInt32, outputGain: Int16, channelMappingFamily: ChannelMappingFamily) {
self.magicSignature = [ 0x4f, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64 ] // "OpusHead"
self.version = 1 // must always be `1` for this version of the encapsulation specification
self.outputChannels = outputChannels
self.preskip = preskip
self.inputSampleRate = inputSampleRate
self.outputGain = outputGain
self.channelMappingFamily = channelMappingFamily
}
func toData() -> Data {
var data = Data()
data.append(magicSignature, count: magicSignature.count)
withUnsafePointer(to: &version) { ptr in data.append(ptr, count: MemoryLayout<UInt8>.size) }
withUnsafePointer(to: &outputChannels) { ptr in data.append(ptr, count: MemoryLayout<UInt8>.size) }
withUnsafePointer(to: &preskip) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt16>.size) }}
withUnsafePointer(to: &inputSampleRate) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt32>.size) }}
withUnsafePointer(to: &outputGain) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt16>.size) }}
withUnsafePointer(to: &channelMappingFamily) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<ChannelMappingFamily>.size) }}
return data
}
}
// MARK: - Comment Header
private class CommentHeader {
private(set) var magicSignature: [UInt8]
private(set) var vendorStringLength: UInt32
private(set) var vendorString: String
private(set) var userCommentListLength: UInt32
private(set) var userComments: [Comment]
init() {
magicSignature = [ 0x4f, 0x70, 0x75, 0x73, 0x54, 0x61, 0x67, 0x73 ] // "OpusTags"
vendorString = String(validatingUTF8: opus_get_version_string())!
vendorStringLength = UInt32(vendorString.count)
userComments = [Comment(tag: "ENCODER", value: "IBM Mobile Innovation Lab")]
userCommentListLength = UInt32(userComments.count)
}
func toData() -> Data {
var data = Data()
data.append(magicSignature, count: magicSignature.count)
withUnsafePointer(to: &vendorStringLength) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt32>.size) }}
data.append(vendorString.data(using: String.Encoding.utf8)!)
withUnsafePointer(to: &userCommentListLength) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt32>.size) }}
for comment in userComments {
data.append(comment.toData())
}
return data
}
}
// MARK: - Comment
private class Comment {
private(set) var length: UInt32
private(set) var comment: String
fileprivate init(tag: String, value: String) {
comment = "\(tag)=\(value)"
length = UInt32(comment.count)
}
fileprivate func toData() -> Data {
var data = Data()
withUnsafePointer(to: &length) { ptr in ptr.withMemoryRebound(to: UInt8.self, capacity: 1) { ptr in data.append(ptr, count: MemoryLayout<UInt32>.size) }}
data.append(comment.data(using: String.Encoding.utf8)!)
return data
}
}
// MARK: - ChannelMappingFamily
private enum ChannelMappingFamily: UInt8 {
case rtp = 0
case vorbis = 1
case undefined = 255
}
// MARK: - Application
internal enum Application {
case voip
case audio
case lowDelay
var rawValue: Int32 {
switch self {
case .voip: return OPUS_APPLICATION_VOIP
case .audio: return OPUS_APPLICATION_AUDIO
case .lowDelay: return OPUS_APPLICATION_RESTRICTED_LOWDELAY
}
}
init?(rawValue: Int32) {
switch rawValue {
case OPUS_APPLICATION_VOIP: self = .voip
case OPUS_APPLICATION_AUDIO: self = .audio
case OPUS_APPLICATION_RESTRICTED_LOWDELAY: self = .lowDelay
default: return nil
}
}
}
// MARK: - OpusError
internal enum OpusError: Error {
case okay
case badArgument
case bufferTooSmall
case internalError
case invalidPacket
case unimplemented
case invalidState
case allocationFailure
var rawValue: Int32 {
switch self {
case .okay: return OPUS_OK
case .badArgument: return OPUS_BAD_ARG
case .bufferTooSmall: return OPUS_BUFFER_TOO_SMALL
case .internalError: return OPUS_INTERNAL_ERROR
case .invalidPacket: return OPUS_INVALID_PACKET
case .unimplemented: return OPUS_UNIMPLEMENTED
case .invalidState: return OPUS_INVALID_STATE
case .allocationFailure: return OPUS_ALLOC_FAIL
}
}
init?(rawValue: Int32) {
switch rawValue {
case OPUS_OK: self = .okay
case OPUS_BAD_ARG: self = .badArgument
case OPUS_BUFFER_TOO_SMALL: self = .bufferTooSmall
case OPUS_INTERNAL_ERROR: self = .internalError
case OPUS_INVALID_PACKET: self = .invalidPacket
case OPUS_UNIMPLEMENTED: self = .unimplemented
case OPUS_INVALID_STATE: self = .invalidState
case OPUS_ALLOC_FAIL: self = .allocationFailure
default: return nil
}
}
}
// MARK: - OggError
internal enum OggError: Error {
case outOfSync
case internalError
}
#endif
| apache-2.0 | 362b570ba3d3b1794c5458720502888a | 35.885214 | 189 | 0.63669 | 4.176911 | false | false | false | false |
wangzhibiao/EZDrawer | EasyDrawer/EasyDrawer/Classes/EZRootViewController.swift | 1 | 11993 | //
// EZRootViewController.swift
// EasyDrawer
//
// Created by 王小帅 on 2017/2/15.
// Copyright © 2017年 王小帅. All rights reserved.
//
import UIKit
/// 抽屉菜单点根控制器
class EZRootViewController: UIViewController {
// MARK: - 各个自控制器属性
/// 中间主控制器
private var mainVC:UIViewController?
/// 左侧控制器
private var leftVC:UIViewController?
/// 右侧控制器
private var rightVC:UIViewController?
/// 互动手势
private var panGest:UIPanGestureRecognizer?
/// 主页的遮罩button 用来监听点击返回的手势
private var maskButton:UIButton?
// 滑动菜单停靠比例
var scale:CGFloat = 0.0
// MARK: - 初始化方法
init(mainVC: UIViewController?, leftVC: UIViewController?, rightVC:UIViewController?) {
super.init(nibName: nil, bundle: nil)
// 赋值属性
self.mainVC = mainVC
// 判断是否有赋值属性
if leftVC == nil && rightVC == nil {
// 没有设置抽屉 那么只显示主页视图控制器
view.addSubview((mainVC?.view)!)
addChildViewController(mainVC!)
return
}
// 赋值属性
self.leftVC = leftVC
self.rightVC = rightVC
// 设置抽屉位置
if let left = leftVC {
// 初始位置
var frame = left.view.frame
frame = CGRect(x: -frame.width, y: 0, width: frame.width, height: frame.height)
left.view.frame = frame
// 加入视图同时将视图的控制器添加进来
view.addSubview(left.view)
addChildViewController(left)
}
if let right = rightVC {
// 初始位置
var frame = right.view.frame
frame = CGRect(x: frame.width, y: 0, width: frame.width, height: frame.height)
right.view.frame = frame
// 加入视图同时将视图的控制器添加进来
view.addSubview(right.view)
addChildViewController(right)
}
// 加入主视图
view.addSubview((mainVC?.view)!)
addChildViewController(mainVC!)
// 设置滑动手势
let panGest = UIPanGestureRecognizer(target: self, action: #selector(reconizerHandle(recognizer:)))
panGest.minimumNumberOfTouches = 1
panGest.maximumNumberOfTouches = 1
self.mainVC?.view.addGestureRecognizer(panGest)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - 视图移动属性
// 初始位置
var startX:CGFloat = 0.0
var startY:CGFloat = 0.0
// 左边是图中心点
var leftCenter:CGPoint = CGPoint.zero
// 右侧视图中心点
var rightCenter:CGPoint = CGPoint.zero
// 主页中心点
var mainCenter:CGPoint = CGPoint.zero
// MARK: - 打开/关闭 抽屉
/// 打开左侧菜单
func openLeftMenu() {
// 左侧视图的中心点
leftCenter = self.leftVC?.view.center ?? CGPoint.zero
// 主页中心点
mainCenter = self.mainVC?.view.center ?? CGPoint.zero
// 偏移量
let delatX:CGFloat = SCREEN_WIDTH * self.scale
// 动画设置
UIView.animate(withDuration: 0.2,
animations: {
// 分别对主页和菜单页做位移
self.mainVC?.view.center = CGPoint(x: (self.mainCenter.x + delatX),
y: self.mainCenter.y)
self.leftVC?.view.center = CGPoint(x: (self.leftCenter.x + delatX),
y: self.leftCenter.y)
}) { (bool) in
// 动画完成 添加遮罩
self.addMainMask()
}
}
// 打开右侧抽屉
func openRightMenu() {
// 左侧视图的中心点
rightCenter = self.rightVC?.view.center ?? CGPoint.zero
// 主页中心点
mainCenter = self.mainVC?.view.center ?? CGPoint.zero
// 偏移量
let delatX:CGFloat = -SCREEN_WIDTH * self.scale
// 动画设置
UIView.animate(withDuration: 0.2,
animations: {
// 分别对主页和菜单页做位移
self.mainVC?.view.center = CGPoint(x: (self.mainCenter.x + delatX),
y: self.mainCenter.y)
self.rightVC?.view.center = CGPoint(x: (self.rightCenter.x + delatX),
y: self.rightCenter.y)
}) { (bool) in
// 动画完成 添加遮罩
self.addMainMask()
}
}
/// 关闭菜单
func closeMenu() {
// 原始中心点
let orgCenter = CGPoint(x: CGFloat(SCREEN_WIDTH * 0.5),
y: CGFloat(SCREEN_HEIGHT * 0.5))
// 动画设置
UIView.animate(withDuration: 0.2,
animations: {
// 分别对主页和菜单页做位移
self.mainVC?.view.center = CGPoint(x: orgCenter.x,
y: orgCenter.y)
// 复位左右抽屉
self.leftVC?.view.center = CGPoint(x: orgCenter.x - SCREEN_WIDTH,
y: orgCenter.y)
self.rightVC?.view.center = CGPoint(x: orgCenter.x + SCREEN_WIDTH,
y: orgCenter.y)
}) { (bool) in
// 动画完成 移除遮罩
self.removeMainMask()
}
}
// MARK: - 加入/移除/点击 主页遮罩
func addMainMask() {
let frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
maskButton = UIButton(frame: frame)
maskButton?.addTarget(self, action: #selector(maskBtnClick(btn:)), for: .touchUpInside)
self.mainVC?.view.addSubview(maskButton!)
}
/// 移除主页遮罩
func removeMainMask() {
guard let _ = maskButton else {
return
}
maskButton?.removeFromSuperview()
maskButton = nil
}
/// 遮罩按钮点击
func maskBtnClick(btn: UIButton) {
closeMenu()
}
// MARK: - 手势移动监听方法
func reconizerHandle(recognizer: UIPanGestureRecognizer) {
// 主视图和左右侧视图 拖动监听
let targatView = self.mainVC?.view
let leftView = self.leftVC?.view
let rightView = self.rightVC?.view
// 获取被拖动的view在当前view中的坐标点
let transPoint = recognizer.translation(in: recognizer.view)
// 对当前状态进行判断对不同状态做处理比如判断拖动位置并加入动画处理
if recognizer.state == UIGestureRecognizerState.began {
// 如果事件刚刚开始 那么记录下起始点
startX = targatView?.center.x ?? 0
startY = targatView?.center.y ?? 0
if let left = leftView {
leftCenter = left.center
}
if let right = rightView {
rightCenter = right.center
}
}
// 事件进行时
if recognizer.state == UIGestureRecognizerState.changed {
var delatX:CGFloat = startX + transPoint.x
// 因为不能在Y轴拖动 所以y 永远是0
let delatY:CGFloat = startY
// 左侧是图的中心偏移
var changeX:CGFloat = delatX - startX
// 限制拖拽最小的拖拽
if leftView == nil {
// 判断位置 加入动画
if delatX > SCREEN_WIDTH * 0.5 {
delatX = SCREEN_WIDTH * 0.5
}
}
if rightView == nil {
// 判断位置 加入动画
if delatX < SCREEN_WIDTH * 0.5 {
delatX = SCREEN_WIDTH * 0.5
}
}
// 限制最大拖拽范围
if delatX <= -SCREEN_WIDTH * (self.scale - 0.5) {
delatX = -SCREEN_WIDTH * (self.scale - 0.5)
// 当到达限制的时候 偏移也要限制
changeX = delatX - startX
}else if delatX >= SCREEN_WIDTH * (self.scale + 0.5) {
delatX = SCREEN_WIDTH * (self.scale + 0.5)
// 当到达限制的时候 偏移也要限制
changeX = delatX - startX
}
// 偏移
targatView?.center = CGPoint(x: delatX, y: delatY)
leftView?.center = CGPoint(x: leftCenter.x + changeX, y: leftCenter.y)
rightView?.center = CGPoint(x: rightCenter.x + changeX, y: rightCenter.y)
}
// 如果用户取消或者停止拖拽 要做判断 确认视图的位置
if recognizer.state == UIGestureRecognizerState.ended || recognizer.state == UIGestureRecognizerState.cancelled {
// 当前拖坏控制器中点x
var endX:CGFloat = (targatView?.center.x)!
// 判断位置 做动画悬停
if endX < SCREEN_WIDTH * 0.5 {// 左侧停靠
if ((SCREEN_WIDTH * 0.5) - endX) <= (SCREEN_WIDTH * self.scale * 0.1) {
// 拖动小于停靠比例宽度的十分之一 就回到原位
endX = SCREEN_WIDTH * 0.5
// 移除遮罩
removeMainMask()
}else {
// 大于的话 就停在屏幕宽度的三分之二处
endX = -SCREEN_WIDTH * (self.scale - 0.5)
// 加入遮罩
addMainMask()
}
}else { // 右侧停靠
if (endX - (SCREEN_WIDTH * 0.5)) <= (SCREEN_WIDTH * self.scale * 0.1) {
// 拖动小于停靠比例宽度的十分之一 就回到原位
endX = SCREEN_WIDTH * 0.5
// 移除遮罩
removeMainMask()
}else {
// 大于的话 就停在屏幕宽度的三分之二处
endX = SCREEN_WIDTH * (self.scale + 0.5)
// 加入遮罩
addMainMask()
}
}
// 动画停留
UIView.animate(withDuration: 0.2, animations: {
// 设置主页视图
targatView?.center = CGPoint(x: endX, y: self.startY)
// 设置抽屉
leftView?.center = CGPoint(x: self.leftCenter.x + endX - self.startX, y: self.leftCenter.y)
rightView?.center = CGPoint(x: self.rightCenter.x + endX - self.startX, y: self.rightCenter.y)
})
}
}
}
| mit | cbbbde3a3840bf999867e8ebaf6490a2 | 29.2849 | 121 | 0.451834 | 4.418121 | false | false | false | false |
sammyd/iOS8-SplitView | MultiLevelSplit/MasterViewController.swift | 1 | 2723 | //
// MasterViewController.swift
// MultiLevelSplit
//
// Copyright 2015 Sam Davies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class MasterViewController: UITableViewController {
var children: [Hierarchy<Student>]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail",
let detailContainer = segue.destinationViewController as? UINavigationController,
let detailVC = detailContainer.topViewController as? DetailViewController {
let selectedIndexPath = tableView.indexPathForSelectedRow()!
switch children[selectedIndexPath.row] {
case let .Leaf(leaf):
detailVC.student = leaf.unbox
case .Node:
break
}
}
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
let selectedIndexPath = tableView.indexPathForSelectedRow()!
switch children[selectedIndexPath.row] {
case .Leaf:
return true
case .Node:
return false
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return children.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let child = children[indexPath.row]
cell.textLabel?.text = child.description
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch children[indexPath.row] {
case let .Node(name, kids):
let newVC = storyboard?.instantiateViewControllerWithIdentifier("MasterVC") as! MasterViewController
newVC.children = kids
newVC.title = name
showViewController(newVC, sender: self)
default:
break
}
}
}
| apache-2.0 | 80f6655e4962fe4140e66329ca304425 | 30.662791 | 116 | 0.720529 | 4.978062 | false | false | false | false |
kosicki123/eidolon | Kiosk/Bid Fulfillment/ConfirmYourBidPINViewController.swift | 1 | 5574 | import UIKit
import Moya
import ReactiveCocoa
public class ConfirmYourBidPINViewController: UIViewController {
dynamic var pin = ""
@IBOutlet public var keypadContainer: KeypadContainerView!
@IBOutlet public var pinTextField: TextField!
@IBOutlet public var confirmButton: Button!
@IBOutlet public var bidDetailsPreviewView: BidDetailsPreviewView!
public lazy var keypadSignal: RACSignal! = self.keypadContainer.keypad?.keypadSignal
public lazy var clearSignal: RACSignal! = self.keypadContainer.keypad?.rightSignal
public lazy var deleteSignal: RACSignal! = self.keypadContainer.keypad?.leftSignal
public lazy var provider: ReactiveMoyaProvider<ArtsyAPI> = Provider.sharedProvider
public class func instantiateFromStoryboard() -> ConfirmYourBidPINViewController {
return UIStoryboard.fulfillment().viewControllerWithID(.ConfirmYourBidPIN) as ConfirmYourBidPINViewController
}
override public func viewDidLoad() {
super.viewDidLoad()
let keypad = self.keypadContainer!.keypad!
let pinIsZeroSignal = RACObserve(self, "pin").map { (countElements($0 as String) != 4) }
for button in [keypad.rightButton, keypad.leftButton] {
RAC(button, "enabled") <~ pinIsZeroSignal.not()
}
keypadSignal.subscribeNext(addDigitToPIN)
deleteSignal.subscribeNext(deleteDigitFromPIN)
clearSignal.subscribeNext(clearPIN)
RAC(pinTextField, "text") <~ RACObserve(self, "pin")
RAC(fulfillmentNav().bidDetails, "bidderPIN") <~ RACObserve(self, "pin")
bidDetailsPreviewView.bidDetails = fulfillmentNav().bidDetails
/// verify if we can connect with number & pin
confirmButton.rac_command = RACCommand(enabled: pinIsZeroSignal.not()) { [weak self] _ in
if (self == nil) { return RACSignal.empty() }
let phone = self!.fulfillmentNav().bidDetails.newUser.phoneNumber
let endpoint: ArtsyAPI = ArtsyAPI.Me
let testProvider = self!.providerForPIN(self!.pin, number:phone!)
return testProvider.request(endpoint, method:.GET, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().doNext { _ in
self?.fulfillmentNav().loggedInProvider = testProvider
return
}.then {
self?.fulfillmentNav().updateUserCredentials() ?? RACSignal.empty()
}.then {
self?.checkForCreditCard() ?? RACSignal.empty()
}.doNext { (cards) in
if (self == nil) { return }
if countElements(cards as [Card]) > 0 {
self?.performSegue(.PINConfirmedhasCard)
} else {
self?.performSegue(.ArtsyUserviaPINHasNotRegisteredCard)
}
}.doError({ [weak self] (error) -> Void in
self?.showAuthenticationError()
return
})
}
}
@IBAction func forgotPINTapped(sender: AnyObject) {
let auctionID = fulfillmentNav().auctionID
let number = fulfillmentNav().bidDetails.newUser.phoneNumber ?? ""
let endpoint: ArtsyAPI = ArtsyAPI.LostPINNotification(auctionID: auctionID, number: number)
let alertController = UIAlertController(title: "Forgot PIN", message: "We have sent your bidder details to your device.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Back", style: .Cancel) { (_) in }
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true) {}
XAppRequest(endpoint, provider: Provider.sharedProvider, method: .PUT, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().subscribeNext { (_) -> Void in
println("sent")
}
}
public func providerForPIN(pin:String, number:String) -> ReactiveMoyaProvider<ArtsyAPI> {
let newEndpointsClosure = { (target: ArtsyAPI, method: Moya.Method, parameters: [String: AnyObject]) -> Endpoint<ArtsyAPI> in
var endpoint: Endpoint<ArtsyAPI> = Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, target.sampleData), method: method, parameters: parameters)
let auctionID = self.fulfillmentNav().auctionID
return endpoint.endpointByAddingParameters(["auction_pin": pin, "number": number, "sale_id": auctionID])
}
return ReactiveMoyaProvider(endpointsClosure: newEndpointsClosure, endpointResolver: endpointResolver(), stubResponses: APIKeys.sharedKeys.stubResponses)
}
func showAuthenticationError() {
confirmButton.flashError("Wrong PIN")
pinTextField.flashForError()
pinTextField.text = ""
pin = ""
}
func checkForCreditCard() -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.MyCreditCards
let authProvider = self.fulfillmentNav().loggedInProvider!
return authProvider.request(endpoint, method:.GET, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Card.self)
}
}
private extension ConfirmYourBidPINViewController {
func addDigitToPIN(input:AnyObject!) -> Void {
self.pin = "\(self.pin)\(input)"
}
func deleteDigitFromPIN(input:AnyObject!) -> Void {
self.pin = dropLast(self.pin)
}
func clearPIN(input:AnyObject!) -> Void {
self.pin = ""
}
@IBAction func dev_loggedInTapped(sender: AnyObject) {
self.performSegue(.PINConfirmedhasCard)
}
} | mit | 68567e74dafea0e01d1846e92e55c47a | 39.107914 | 179 | 0.671152 | 5.067273 | false | false | false | false |
ZhengShouDong/CloudPacker | Sources/CloudPacker/Libraries/CryptoSwift/BatchedCollection.swift | 1 | 2409 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
struct BatchedCollectionIndex<Base: Collection> {
let range: Range<Base.Index>
}
extension BatchedCollectionIndex: Comparable {
static func ==<Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
return lhs.range.lowerBound == rhs.range.lowerBound
}
static func < <Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
return lhs.range.lowerBound < rhs.range.lowerBound
}
}
protocol BatchedCollectionType: Collection {
associatedtype Base: Collection
}
struct BatchedCollection<Base: Collection>: Collection {
let base: Base
let size: Base.IndexDistance
typealias Index = BatchedCollectionIndex<Base>
private func nextBreak(after idx: Base.Index) -> Base.Index {
return base.index(idx, offsetBy: size, limitedBy: base.endIndex)
?? base.endIndex
}
var startIndex: Index {
return Index(range: base.startIndex..<nextBreak(after: base.startIndex))
}
var endIndex: Index {
return Index(range: base.endIndex..<base.endIndex)
}
func index(after idx: Index) -> Index {
return Index(range: idx.range.upperBound..<nextBreak(after: idx.range.upperBound))
}
subscript(idx: Index) -> Base.SubSequence {
return base[idx.range]
}
}
extension Collection {
func batched(by size: IndexDistance) -> BatchedCollection<Self> {
return BatchedCollection(base: self, size: size)
}
}
| apache-2.0 | d50bb76276769cf45f5d6b0faad0c7ab | 36.625 | 217 | 0.716362 | 4.307692 | false | false | false | false |
siggb/MarvelUniverse | marvel-universe/Sources/Utils/ColorsMap.swift | 1 | 683 | //
// ColorsMap.swift
// marvel-universe
//
// Created by Sibagatov Ildar on 10/1/16.
// Copyright © 2016 Sibagatov Ildar. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hexRGB: Int, alpha: CGFloat = 1) {
let rgb = (
CGFloat((hexRGB & 0xFF0000) >> 16) / 255,
CGFloat((hexRGB & 0xFF00) >> 8) / 255,
CGFloat(hexRGB & 0xFF) / 255
)
self.init(red: rgb.0, green: rgb.1, blue: rgb.2, alpha: alpha)
}
}
struct ColorsMap {
static let redColor = UIColor(hexRGB: 0xf0141e)
static let lightGrayColor = UIColor(hexRGB: 0xe9e9e9)
static let grayColor = UIColor(hexRGB: 0x858585)
}
| mit | 5b920651b595ac36d08a36e7e43fccfc | 25.230769 | 70 | 0.61437 | 3.058296 | false | false | false | false |
liuguya/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/UIButton+Util.swift | 1 | 1015 | //
// UIButton+Util.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/15.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
extension UIButton{
class func createButton(title:String?,bgImageName:String?,selectBgImageName:String?,target:AnyObject?,action:Selector)->UIButton{
let btn = UIButton(type: .Custom)
if let btntitle = title{
btn.setTitle(btntitle, forState: .Normal)
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
if let btnbgImageName = bgImageName{
btn.setBackgroundImage(UIImage(named: btnbgImageName), forState: .Normal)
}
if let btnselectBgImageName = selectBgImageName{
btn.setImage(UIImage(named: btnselectBgImageName), forState: .Selected)
}
if let btnTarget = target{
btn.addTarget(btnTarget, action: action, forControlEvents: .TouchUpInside)
}
return btn
}
}
| mit | a0bdbdff629a46591d4ad51159cb4cd4 | 28.647059 | 133 | 0.623016 | 4.48 | false | false | false | false |
rizumita/TransitionOperator | TransitionOperatorSample/TransitionOperations.swift | 1 | 727 | //
// Transitions.swift
// TransitionOperator
//
// Created by 和泉田 領一 on 2016/02/25.
// Copyright © 2016年 CAPH TECH. All rights reserved.
//
import Foundation
import TransitionOperator
var storyboardReferenceDestinationTransitionOperator: TransitionOperatorType = TransitionOperator { (segue: TransitionExecutorSegue, source: Any, destination: DestinationViewController) in
destination.text = "Storyboard Reference"
}
var actionDestinationTransitionOperator: TransitionOperatorType = TransitionOperator { (segue: TransitionExecutorSegue, source: Any, destination: DestinationViewController) in
if let text = segue.transitionPayload?.payloadValue as? String {
destination.text = text
}
}
| mit | 0a4922c0bda6b5abf8edf8b9aa02f517 | 34.7 | 188 | 0.784314 | 4.791946 | false | false | false | false |
jcfausto/transit-app | TransitApp/TransitAppTests/TransitAppTests.swift | 1 | 6357 | //
// TransitAppTests.swift
// TransitAppTests
//
// Created by Julio Cesar Fausto on 23/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import XCTest
//To decode json to models
import Unbox
//To test polylines
import CoreLocation
import Polyline
@testable import TransitApp
class TransitAppTests: XCTestCase {
var dataPath: String!
override func setUp() {
super.setUp()
self.dataPath = NSBundle.mainBundle().pathForResource("data", ofType: "json")
}
override func tearDown() {
super.tearDown()
}
/**
Test if the JSON that serves as data is being accessible
*/
func testCanLoadData() {
XCTAssertNotNil(NSData(contentsOfFile: self.dataPath))
}
/**
Test if the decoding with Unbox is working properly
with the application models.
*/
func testCanDecodeDataFromJsonWithUnbox(){
if let data = NSData(contentsOfFile: self.dataPath) {
if let routes: Routes? = Unbox(data) {
XCTAssertNotNil(routes)
} else {
XCTFail("Error while decoding JSON to Models")
}
}
}
/**
Testing the NSInterval+Extension created to provide a
string representation of an inveval in minutes.
*/
func testCanGetTimeIntervalInStringFormatMinutes(){
let interval: NSTimeInterval = 6000
XCTAssertEqual(interval.stringValueInMinutes, "40 min")
}
/**
Testing if google maps SKD could be initialized properly
*/
func testCanInitializeGoogleMapsSdkWhenApiKeyIsProvided(){
if let key = ApiKeysHelper.sharedInstance.getGoogleMapsSdkApiKey() {
if !key.isEmpty {
let gmapsSdk = GoogleMapsSDKInitializer()
gmapsSdk.doSetup()
XCTAssertTrue(gmapsSdk.state)
}
} else {
XCTAssertTrue(true)
}
}
func testFailToInitializeGoogleMapsSdkWhenApiKeyIsNotProvided(){
if let key = ApiKeysHelper.sharedInstance.getGoogleMapsSdkApiKey() {
if key.isEmpty {
let gmapsSdk = GoogleMapsSDKInitializer()
gmapsSdk.doSetup()
XCTAssertFalse(gmapsSdk.state)
}
} else {
XCTAssertFalse(false)
}
}
/**
Testing Polylines decoding with 6 digit precision
Polyline with 9 points for testing:
Points:
- 0: 52.528187, 13.410404
- 1: 52.522074, 13.413595
- 2: 52.517229, 13.412454
- 3: 52.512006, 13.408768
- 4: 52.511305, 13.40235
- 5: 52.513363, 13.395347
- 6: 52.512168, 13.389711
- 7: 52.511521, 13.383796
- 8: 52.509067, 13.37798
*/
func testCanDecodePolyline(){
let polyline = Polyline(encodedPolyline: "elr_I_fzpAfe@_Sf]dFr_@~UjCbg@yKvj@lFfb@`C|c@hNjc@")
let coordinates: [CLLocationCoordinate2D]? = polyline.coordinates
let decodedLocations: [CLLocation]? = polyline.locations
XCTAssertNotNil(decodedLocations)
XCTAssertNotNil(coordinates)
XCTAssertEqual(coordinates!.count, 9)
if let decodedLocations = decodedLocations {
let initialLocation = decodedLocations[0]
//There are some issues with precision. due to this, the expected value will be rounded to 5 digits precision.
XCTAssertEqual(initialLocation.coordinate.latitude, 52.52819)
XCTAssertEqual(initialLocation.coordinate.longitude, 13.4104)
}else {
XCTFail("Locations were not decoded properly")
}
//XCTAssertEqual(coordinateOne.latitude, 52.528187)
}
/**
Tests the SVGIconCache object
*/
func testCanStoreSVGDataToSVGCache() {
let svgUrl = "https://d3m2tfu2xpiope.cloudfront.net/vehicles/walking.svg"
let expectation = expectationWithDescription("testCanStoreSVGDataToSVGCache")
if let url = NSURL(string: svgUrl) {
let resourceName = url.lastPathComponent
let request = NSURLRequest(URL: url)
let downloadTask = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if let svgData = data as NSData? {
let cache = SVGIconCache()
cache.saveSVG(svgData, fileName: resourceName!)
let cachedData = cache.retrieveSVG(resourceName!)
if let cachedData = cachedData {
let equalData = svgData.isEqualToData(cachedData)
XCTAssertTrue(equalData)
} else {
XCTFail("It was not possible to use the SVG cache properly")
}
}
expectation.fulfill()
}
downloadTask.resume()
} else {
XCTFail("Error trying to convert the SVG url")
}
waitForExpectationsWithTimeout(10.0, handler:nil)
}
/**
Teste the data provider that currently only loads data from json
*/
func testCandSearchForRoutes(){
let dataProvider = DataProvider()
let routes = dataProvider.searchForRoutes()
XCTAssertNotNil(routes)
}
/**
Test the NSDate+Extension
*/
func testCanGetStringValueWithHourAndMinuteFromNSDate() {
let date = NSDate(datetimeString: "2015-04-17T13:56:00+02:00")
let hoursAndMinutes = date.stringValueWithHourAndMinute
//Value in local timezone
XCTAssertEqual(hoursAndMinutes, "8:56")
}
/**
Test the UIColor+Extension
*/
func testCanCreateUIColorFromDifferentHexStrings() {
let color3 = UIColor(hexString: "#FFF")
XCTAssertNotNil(color3)
let color6 = UIColor(hexString: "#FFFFFF")
XCTAssertNotNil(color6)
let color8 = UIColor(hexString: "#FFFFFF00")
XCTAssertNotNil(color8)
let colorDefault = UIColor(hexString: "#FFFFFFFFFF")
XCTAssertNotNil(colorDefault)
}
}
| mit | 7aac9e2b85d28c20ffee09d32efb77c7 | 29.854369 | 122 | 0.587162 | 4.844512 | false | true | false | false |
auth0/Lock.iOS-OSX | Lock/PasswordlessInteractor.swift | 2 | 7110 | // PasswordlessInteractor.swift
//
// Copyright (c) 2017 Auth0 (http://auth0.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
import UIKit
import Auth0
struct PasswordlessInteractor: PasswordlessAuthenticatable, Loggable {
let connection: PasswordlessConnection
let authentication: Authentication
let dispatcher: Dispatcher
private var user: PasswordlessUser
let options: Options
let passwordlessActivity: PasswordlessUserActivity
let emailValidator: InputValidator = EmailValidator()
let codeValidator: InputValidator = OneTimePasswordValidator()
let phoneValidator: InputValidator = PhoneValidator()
var identifier: String? { return self.user.email }
var validIdentifier: Bool { return self.user.validEmail }
var code: String?
var validCode: Bool = false
var countryCode: CountryCode? {
get { return self.user.countryCode }
set { self.user.countryCode = newValue }
}
init(connection: PasswordlessConnection, authentication: Authentication, dispatcher: Dispatcher, user: PasswordlessUser, options: Options, passwordlessActivity: PasswordlessUserActivity) {
self.authentication = authentication
self.dispatcher = dispatcher
self.user = user
self.options = options
self.passwordlessActivity = passwordlessActivity
self.connection = connection
}
func request(_ connection: String, callback: @escaping (PasswordlessAuthenticatableError?) -> Void) {
guard var identifier = self.identifier, self.validIdentifier else { return callback(.nonValidInput) }
let passwordlessType = self.options.passwordlessMethod == .code ? PasswordlessType.Code : PasswordlessType.iOSLink
var authenticator: Request<Void, AuthenticationError>
if self.connection.strategy == "email" {
authenticator = self.authentication.startPasswordless(email: identifier, type: passwordlessType, connection: connection, parameters: self.options.parameters)
} else {
guard let countryCode = self.countryCode else { return callback(.nonValidInput) }
identifier = countryCode.phoneCode + identifier
authenticator = self.authentication.startPasswordless(phoneNumber: identifier, type: passwordlessType, connection: connection)
}
authenticator.start {
switch $0 {
case .success:
callback(nil)
self.dispatcher.dispatch(result: .passwordless(identifier))
if passwordlessType == .iOSLink {
self.passwordlessActivity.store(PasswordlessLinkTransaction(connection: connection, options: self.options, identifier: identifier, authentication: self.authentication, dispatcher: self.dispatcher))
}
case .failure(let cause as AuthenticationError) where cause.code == "bad.connection":
callback(.noSignup)
self.dispatcher.dispatch(result: .error(PasswordlessAuthenticatableError.noSignup))
case .failure:
callback(.codeNotSent)
return self.dispatcher.dispatch(result: .error(PasswordlessAuthenticatableError.codeNotSent))
}
}
}
func login(_ connection: String, callback: @escaping (CredentialAuthError?) -> Void) {
guard let code = self.code, self.validCode, var identifier = self.identifier, self.validIdentifier
else { return callback(.nonValidInput) }
if let countryCode = self.countryCode {
identifier = countryCode.phoneCode + identifier
}
var request: Request<Credentials, AuthenticationError>
if !options.oidcConformant {
request = CredentialAuth(oidc: false, realm: connection, authentication: authentication)
.request(withIdentifier: identifier, password: code, options: options)
} else if connection == "email" {
request = authentication.login(email: identifier,
code: code,
audience: options.audience,
scope: options.scope,
parameters: options.parameters)
} else {
request = authentication.login(phoneNumber: identifier,
code: code,
audience: options.audience,
scope: options.scope,
parameters: options.parameters)
}
request.start { result in
self.handle(identifier: identifier, result: result, callback: callback)
}
}
mutating func update(_ type: InputField.InputType, value: String?) throws {
let error: Error?
switch type {
case .email:
error = self.update(email: value)
case .oneTimePassword:
error = self.update(code: value)
case .phone:
error = self.update(phone: value)
default:
error = InputValidationError.mustNotBeEmpty
}
if let error = error { throw error }
}
private mutating func update(email: String?) -> Error? {
self.user.email = email?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let error = self.emailValidator.validate(email)
self.user.validEmail = error == nil
return error
}
private mutating func update(code: String?) -> Error? {
self.code = code?.trimmingCharacters(in: CharacterSet.whitespaces)
let error = self.codeValidator.validate(code)
self.validCode = error == nil
return error
}
private mutating func update(phone: String?) -> Error? {
self.user.email = phone?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let error = self.phoneValidator.validate(phone)
self.user.validEmail = error == nil
return error
}
}
| mit | b92ff8216d76fe56faa1c112a1c46150 | 44.576923 | 217 | 0.655837 | 5.243363 | false | false | false | false |
foresterre/mal | swift3/Sources/step3_env/main.swift | 15 | 3561 | import Foundation
// read
func READ(_ str: String) throws -> MalVal {
return try read_str(str)
}
// eval
func eval_ast(_ ast: MalVal, _ env: Env) throws -> MalVal {
switch ast {
case MalVal.MalSymbol:
return try env.get(ast)
case MalVal.MalList(let lst, _):
return list(try lst.map { try EVAL($0, env) })
case MalVal.MalVector(let lst, _):
return vector(try lst.map { try EVAL($0, env) })
case MalVal.MalHashMap(let dict, _):
var new_dict = Dictionary<String,MalVal>()
for (k,v) in dict { new_dict[k] = try EVAL(v, env) }
return hash_map(new_dict)
default:
return ast
}
}
func EVAL(_ ast: MalVal, _ env: Env) throws -> MalVal {
switch ast {
case MalVal.MalList(let lst, _): if lst.count == 0 { return ast }
default: return try eval_ast(ast, env)
}
switch ast {
case MalVal.MalList(let lst, _):
switch lst[0] {
case MalVal.MalSymbol("def!"):
return try env.set(lst[1], try EVAL(lst[2], env))
case MalVal.MalSymbol("let*"):
let let_env = try Env(env)
var binds = Array<MalVal>()
switch lst[1] {
case MalVal.MalList(let l, _): binds = l
case MalVal.MalVector(let l, _): binds = l
default:
throw MalError.General(msg: "Invalid let* bindings")
}
var idx = binds.startIndex
while idx < binds.endIndex {
let v = try EVAL(binds[binds.index(after: idx)], let_env)
try let_env.set(binds[idx], v)
idx = binds.index(idx, offsetBy: 2)
}
return try EVAL(lst[2], let_env)
default:
switch try eval_ast(ast, env) {
case MalVal.MalList(let elst, _):
switch elst[0] {
case MalVal.MalFunc(let fn,_,_,_,_,_):
let args = Array(elst[1..<elst.count])
return try fn(args)
default:
throw MalError.General(msg: "Cannot apply on '\(elst[0])'")
}
default: throw MalError.General(msg: "Invalid apply")
}
}
default:
throw MalError.General(msg: "Invalid apply")
}
}
// print
func PRINT(_ exp: MalVal) -> String {
return pr_str(exp, true)
}
// repl
func rep(_ str:String) throws -> String {
return PRINT(try EVAL(try READ(str), repl_env))
}
func IntOp(_ op: (Int, Int) -> Int, _ a: MalVal, _ b: MalVal) throws -> MalVal {
switch (a, b) {
case (MalVal.MalInt(let i1), MalVal.MalInt(let i2)):
return MalVal.MalInt(op(i1, i2))
default:
throw MalError.General(msg: "Invalid IntOp call")
}
}
var repl_env: Env = try Env()
try repl_env.set(MalVal.MalSymbol("+"),
malfunc({ try IntOp({ $0 + $1}, $0[0], $0[1]) }))
try repl_env.set(MalVal.MalSymbol("-"),
malfunc({ try IntOp({ $0 - $1}, $0[0], $0[1]) }))
try repl_env.set(MalVal.MalSymbol("*"),
malfunc({ try IntOp({ $0 * $1}, $0[0], $0[1]) }))
try repl_env.set(MalVal.MalSymbol("/"),
malfunc({ try IntOp({ $0 / $1}, $0[0], $0[1]) }))
while true {
print("user> ", terminator: "")
let line = readLine(strippingNewline: true)
if line == nil { break }
if line == "" { continue }
do {
print(try rep(line!))
} catch (MalError.Reader(let msg)) {
print("Error: \(msg)")
} catch (MalError.General(let msg)) {
print("Error: \(msg)")
}
}
| mpl-2.0 | 4011209ddb12aa8a96b6bca8ae52bd09 | 29.965217 | 80 | 0.523168 | 3.59334 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/ToolKit/JSToolKit/JSUIKit/UIScreen+Size.swift | 1 | 3687 | //
// JSScreen.swift
// LoveYou
//
// Created by WengHengcong on 2016/11/11.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import UIKit
//设计稿全部以iPhone 5尺寸设计
func designBy3_5Inch(_ x: CGFloat) -> CGFloat {
let scale = ( (UIScreen.width) / CGFloat(320.0) )
let result = scale * x
return result
}
//设计稿全部以iPhone 6尺寸设计
func designBy4_7Inch(_ x: CGFloat) -> CGFloat {
let scale = ( (UIScreen.width) / CGFloat(375.0) )
let result = scale * x
return result
}
//设计稿全部以iPhone 6 Plus尺寸设计
func designBy5_5Inch(_ x: CGFloat) -> CGFloat {
let scale = ( (UIScreen.width) / CGFloat(414.0) )
let result = scale * x
return result
}
//设计稿全部以iPhone X尺寸设计
func designBy5_8Inch(_ x: CGFloat) -> CGFloat {
let scale = ( (UIScreen.width) / CGFloat(375) )
let result = scale * x
return result
}
extension UIScreen {
public enum Size: Int {
case unknownSize = 0
//Watch
case screen1_32Inch //272*340
case screen1_5Inch //312*390
//iPhone
case screen3_5Inch //320*480
case screen4_0Inch //320*568
case screen4_7Inch //375*667
case screen5_5Inch //414*736
case screen5_8Inch //375*812
//iPad
case screen7_9Inch //768*1024
case screen9_7Inch //768*1024
case screen10_5Incn //834*1112
case screen12_9Inch //1024*1366
}
static public func sizeByInch() -> Size {
let w: Double = Double(UIScreen.main.bounds.width)
let h: Double = Double(UIScreen.main.bounds.height)
let screenHeight: Double = max(w, h)
switch screenHeight {
case 480:
return Size.screen3_5Inch
case 568:
return Size.screen4_0Inch
case 667:
return Size.screen4_7Inch
case 736:
return Size.screen5_5Inch
case 812:
return Size.screen5_8Inch
case 1024:
switch UIDevice.modelReadable() {
case .iPadMini, .iPadMini2, .iPadMini3, .iPadMini4:
return Size.screen7_9Inch
default:
return Size.screen9_7Inch
}
case 1366:
return Size.screen12_9Inch
default:
return Size.unknownSize
}
}
// MARK: properties
/// 屏幕scale(避免与scale冲突)
static let screenScale = UIScreen.scale()
/// 是否是retina屏幕
static let isRetina = UIScreen.scale() > 1.0
/// 屏幕bound(去掉s,避免与bounds冲突)
static let bound = UIScreen.bounds()
/// 屏幕Size
static let size = UIScreen.bound.size
/// 屏幕width
static let width = UIScreen.size.width
/// 屏幕height
static let height = UIScreen.size.height
/// 返回屏幕bounds
///
/// - Returns: <#return value description#>
public static func bounds() -> CGRect {
return UIScreen.main.bounds
}
/// 返回屏幕scale
///
/// - Returns: <#return value description#>
public static func scale() -> CGFloat {
return UIScreen.main.scale
}
// MAEK: size compare
static public func isEqual(_ size: Size) -> Bool {
return size == UIScreen.sizeByInch() ? true : false
}
static public func isLargerThan(_ size: Size) -> Bool {
return size.rawValue < UIScreen.sizeByInch().rawValue ? true : false
}
static public func isSmallerThan(_ size: Size) -> Bool {
return size.rawValue > UIScreen.sizeByInch().rawValue ? true : false
}
}
| mit | bb02b8bf76369fa30b3348bf89aed9fc | 25.133333 | 76 | 0.585034 | 3.765208 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.LockPhysicalControls.swift | 1 | 2087 | import Foundation
public extension AnyCharacteristic {
static func lockPhysicalControls(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Lock Physical Controls",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.lockPhysicalControls(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func lockPhysicalControls(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Lock Physical Controls",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt8> {
GenericCharacteristic<UInt8>(
type: .lockPhysicalControls,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | d570ff616632e905fe3c07b8dd302f1c | 33.213115 | 75 | 0.582655 | 5.32398 | false | false | false | false |
SemperIdem/SwiftMarkdownParser | Example/MarkdownParseKit/ViewController.swift | 1 | 1297 | //
// ViewController.swift
// iOSExamples
//
// Created by Semper_Idem on 16/3/21.
// Copyright © 2016年 星夜暮晨. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var webLabel: UILabel!
@IBOutlet weak var switchControl: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let destination = segue.destinationViewController as? WebViewController else { return }
destination.text = textView.text
destination.isWKView = switchControl.on
}
// MARK: Actions
@IBAction func actionSwitch(sender: UISwitch) {
if sender.on {
webLabel.text = "WKWebView"
} else {
webLabel.text = "UIWebView"
}
}
@IBAction func actionButton(sender: UIButton) {
performSegueWithIdentifier("ShowDetailSegue", sender: self)
}
}
| mit | ec61108245e5a1b1c3fd00d49abe96bf | 26.361702 | 101 | 0.654743 | 4.762963 | false | false | false | false |
xivol/MCS-V3-Mobile | assignments/task1/Durak.playground/Sources/Deck.swift | 1 | 254 | import Foundation
public enum Suit: String {
case spades = "♠️"
case hearts = "♥️"
case diamonds = "♦️"
case clubs = "♣️"
}
public enum Rank: Int {
case six = 6, seven,
eight, nine, ten, jack, queen, king, ace
}
| mit | f28d06537c95c15cb2e7cb1d1ca7fc93 | 17.307692 | 44 | 0.567227 | 3.173333 | false | false | false | false |
MadAppGang/refresher | Refresher/ConnectionLostExtension.swift | 1 | 1912 | //
// ConnectionLostExtension.swift
// Pods
//
// Created by Ievgen Rudenko on 21/10/15.
//
//
import Foundation
import ReachabilitySwift
private let сonnectionLostTag = 1326
private let ConnectionLostViewDefaultHeight: CGFloat = 24
extension UIScrollView {
// View on top that shows "connection lost"
public var сonnectionLostView: ConnectionLostView? {
get {
let theView = viewWithTag(сonnectionLostTag) as? ConnectionLostView
return theView
}
}
// If you want to connection lost functionality to your UIScrollView just call this method and pass action closure you want to execute when Reachabikity changed. If you want to stop showing reachability view you must do that manually calling hideReachabilityView methods on your scroll view
public func addReachability(action:(newStatus: Reachability.NetworkStatus) -> ()) {
let frame = CGRectMake(0, -ConnectionLostViewDefaultHeight, self.frame.size.width, ConnectionLostViewDefaultHeight)
let defaultView = ConnectionLostDefaultSubview(frame: frame)
let reachabilityView = ConnectionLostView(view:defaultView, action:action)
reachabilityView.tag = сonnectionLostTag
reachabilityView.hidden = true
addSubview(reachabilityView)
}
public func addReachabilityView(view:UIView, action:(newStatus: Reachability.NetworkStatus) -> ()) {
let reachabilityView = ConnectionLostView(view:view, action:action)
reachabilityView.tag = сonnectionLostTag
reachabilityView.hidden = true
addSubview(reachabilityView)
}
// Manually start pull to refresh
public func showReachabilityView() {
сonnectionLostView?.becomeUnreachable()
}
// Manually stop pull to refresh
public func hideReachabilityView() {
сonnectionLostView?.becomeReachable()
}
} | mit | 01f4bde6b5885308672feb18a20bbcb2 | 33.654545 | 294 | 0.717585 | 4.774436 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Effects/Filters/Roland TB-303 Filter/AKRolandTB303Filter.swift | 1 | 6226 | //
// AKRolandTB303Filter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Emulation of the Roland TB-303 filter
///
open class AKRolandTB303Filter: AKNode, AKToggleable, AKComponent, AKInput {
public typealias AKAudioUnitType = AKRolandTB303FilterAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(effect: "tb3f")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var cutoffFrequencyParameter: AUParameter?
fileprivate var resonanceParameter: AUParameter?
fileprivate var distortionParameter: AUParameter?
fileprivate var resonanceAsymmetryParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Cutoff frequency. (in Hertz)
@objc open dynamic var cutoffFrequency: Double = 500 {
willSet {
if cutoffFrequency != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing,
/// analogue synths generally allow resonances to be above 1.
@objc open dynamic var resonance: Double = 0.5 {
willSet {
if resonance != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
resonanceParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.resonance = Float(newValue)
}
}
}
}
/// Distortion. Value is typically 2.0; deviation from this can cause stability issues.
@objc open dynamic var distortion: Double = 2.0 {
willSet {
if distortion != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
distortionParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.distortion = Float(newValue)
}
}
}
}
/// Asymmetry of resonance. Value is between 0-1
@objc open dynamic var resonanceAsymmetry: Double = 0.5 {
willSet {
if resonanceAsymmetry != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
resonanceAsymmetryParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.resonanceAsymmetry = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff frequency. (in Hertz)
/// - resonance: Resonance, generally < 1, but not limited to it.
/// Higher than 1 resonance values might cause aliasing,
/// analogue synths generally allow resonances to be above 1.
/// - distortion: Distortion. Value is typically 2.0; deviation from this can cause stability issues.
/// - resonanceAsymmetry: Asymmetry of resonance. Value is between 0-1
///
@objc public init(
_ input: AKNode? = nil,
cutoffFrequency: Double = 500,
resonance: Double = 0.5,
distortion: Double = 2.0,
resonanceAsymmetry: Double = 0.5) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
self.distortion = distortion
self.resonanceAsymmetry = resonanceAsymmetry
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
input?.connect(to: self!)
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
cutoffFrequencyParameter = tree["cutoffFrequency"]
resonanceParameter = tree["resonance"]
distortionParameter = tree["distortion"]
resonanceAsymmetryParameter = tree["resonanceAsymmetry"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.cutoffFrequency = Float(cutoffFrequency)
internalAU?.resonance = Float(resonance)
internalAU?.distortion = Float(distortion)
internalAU?.resonanceAsymmetry = Float(resonanceAsymmetry)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | e01c27f80071c10df100de289610d3b4 | 35.403509 | 109 | 0.592129 | 5.320513 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/ZMClientMessage+LinkPreview.swift | 1 | 8947 | //
// Wire
// Copyright (C) 2016 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 WireLinkPreview
extension ZMClientMessage {
public static let linkPreviewImageDownloadNotification = NSNotification.Name(rawValue: "ZMClientMessageLinkPreviewImageDownloadNotificationName")
public var linkPreviewState: ZMLinkPreviewState {
get {
let key = #keyPath(ZMClientMessage.linkPreviewState)
self.willAccessValue(forKey: key)
let raw = (self.primitiveValue(forKey: key) as? NSNumber) ?? 0
self.didAccessValue(forKey: key)
return ZMLinkPreviewState(rawValue: raw.int16Value)!
}
set {
let key = #keyPath(ZMClientMessage.linkPreviewState)
self.willChangeValue(forKey: key)
self.setPrimitiveValue(newValue.rawValue, forKey: key)
self.didChangeValue(forKey: key)
if newValue != .done {
self.setLocallyModifiedKeys(Set([key]))
}
}
}
public var linkPreview: LinkMetadata? {
guard let linkPreview = self.firstZMLinkPreview else { return nil }
if case .tweet? = linkPreview.metaData {
return TwitterStatusMetadata(protocolBuffer: linkPreview)
} else {
let metadata = ArticleMetadata(protocolBuffer: linkPreview)
guard !metadata.isBlacklisted else { return nil }
return metadata
}
}
/// Returns the first link attachment that we need to embed in the UI.
public var mainLinkAttachment: LinkAttachment? {
return linkAttachments?.first
}
var firstZMLinkPreview: LinkPreview? {
return self.underlyingMessage?.linkPreviews.first
}
static func keyPathsForValuesAffectingLinkPreview() -> Set<String> {
return Set([#keyPath(ZMClientMessage.dataSet), #keyPath(ZMClientMessage.dataSet) + ".data"])
}
public func requestLinkPreviewImageDownload() {
guard !self.objectID.isTemporaryID,
self.linkPreview != nil,
let moc = self.managedObjectContext,
let linkPreview = self.firstZMLinkPreview else { return }
guard linkPreview.image.uploaded.hasAssetID, !hasDownloadedImage() else { return }
NotificationInContext(name: ZMClientMessage.linkPreviewImageDownloadNotification, context: moc.notificationContext, object: self.objectID).post()
}
public func fetchLinkPreviewImageData(with queue: DispatchQueue, completionHandler: @escaping (_ imageData: Data?) -> Void) {
guard let cache = managedObjectContext?.zm_fileAssetCache else { return }
let originalKey = FileAssetCache.cacheKeyForAsset(self, format: .original)
let mediumKey = FileAssetCache.cacheKeyForAsset(self, format: .medium)
queue.async {
completionHandler([mediumKey, originalKey].lazy.compactMap({ $0 }).compactMap({ cache.assetData($0) }).first)
}
}
@nonobjc func applyLinkPreviewUpdate(_ updatedMessage: GenericMessage, from updateEvent: ZMUpdateEvent) {
guard
let nonce = self.nonce,
let senderUUID = updateEvent.senderUUID,
let originalText = underlyingMessage?.textData,
let updatedText = updatedMessage.textData,
senderUUID == sender?.remoteIdentifier,
originalText.content == updatedText.content
else {
return
}
let timeout = deletionTimeout > 0 ? deletionTimeout : nil
let message = GenericMessage(content: originalText.updateLinkPreview(from: updatedText), nonce: nonce, expiresAfterTimeInterval: timeout)
do {
try setUnderlyingMessage(message)
} catch {
assertionFailure("Failed to set generic message: \(error.localizedDescription)")
}
}
}
extension ZMClientMessage: ZMImageOwner {
@objc public func imageData(for format: ZMImageFormat) -> Data? {
return self.managedObjectContext?.zm_fileAssetCache.assetData(self, format: format, encrypted: false)
}
// The image formats that this @c ZMImageOwner wants preprocessed. Order of formats determines order in which data is preprocessed
@objc public func requiredImageFormats() -> NSOrderedSet {
if let genericMessage = self.underlyingMessage, genericMessage.linkPreviews.count > 0 {
return NSOrderedSet(array: [ZMImageFormat.medium.rawValue])
}
return NSOrderedSet()
}
@objc public func originalImageData() -> Data? {
return self.managedObjectContext?.zm_fileAssetCache.assetData(self, format: .original, encrypted: false)
}
@objc public func originalImageSize() -> CGSize {
guard let originalImageData = self.originalImageData() else { return CGSize.zero }
return ZMImagePreprocessor.sizeOfPrerotatedImage(with: originalImageData)
}
@objc public func processingDidFinish() {
self.linkPreviewState = .processed
guard let moc = self.managedObjectContext else { return }
moc.zm_fileAssetCache.deleteAssetData(self, format: .original, encrypted: false)
moc.enqueueDelayedSave()
}
@objc public var linkPreviewImageData: Data? {
return self.managedObjectContext?.zm_fileAssetCache.assetData(self, format: .original, encrypted: false)
?? self.managedObjectContext?.zm_fileAssetCache.assetData(self, format: .medium, encrypted: false)
}
public var linkPreviewHasImage: Bool {
guard let linkPreview = self.firstZMLinkPreview else { return false }
return linkPreview.hasImage
}
@objc public var linkPreviewImageCacheKey: String? {
return self.nonce?.uuidString
}
@objc public func setImageData(_ imageData: Data, for format: ZMImageFormat, properties: ZMIImageProperties?) {
guard let moc = self.managedObjectContext,
var linkPreview = self.firstZMLinkPreview,
format == .medium else {
return
}
moc.zm_fileAssetCache.storeAssetData(self, format: format, encrypted: false, data: imageData)
guard let keys = moc.zm_fileAssetCache.encryptImageAndComputeSHA256Digest(self, format: format) else { return }
let imageMetaData = WireProtos.Asset.ImageMetaData(width: Int32(properties?.size.width ?? 0), height: Int32(properties?.size.height ?? 0))
let original = WireProtos.Asset.Original(withSize: UInt64(imageData.count), mimeType: properties?.mimeType ?? "", name: nil, imageMetaData: imageMetaData)
linkPreview.update(withOtrKey: keys.otrKey, sha256: keys.sha256!, original: original)
if let genericMessage = self.underlyingMessage, let textMessageData = textMessageData {
let text = Text.with {
$0.content = textMessageData.messageText ?? ""
$0.mentions = textMessageData.mentions.compactMap { WireProtos.Mention.createMention($0) }
$0.linkPreview = [linkPreview]
}
let messageUpdate: MessageCapable
guard
let content = genericMessage.content,
let nonce = nonce else {
return
}
switch content {
case .text:
messageUpdate = text
case .ephemeral(let data):
switch data.content {
case .text?:
messageUpdate = Ephemeral(content: text, expiresAfter: deletionTimeout)
default:
return
}
case .edited:
guard let replacingMessageID = UUID(uuidString: genericMessage.edited.replacingMessageID) else {
return
}
messageUpdate = MessageEdit(replacingMessageID: replacingMessageID, text: text)
default:
return
}
do {
let genericMessage = GenericMessage(content: messageUpdate, nonce: nonce)
try setUnderlyingMessage(genericMessage)
} catch {
Logging.messageProcessing.warn("Failed to link preview image data. Reason: \(error.localizedDescription)")
return
}
}
moc.enqueueDelayedSave()
}
}
| gpl-3.0 | 52c152e62f7c19a1df704e311513427f | 40.230415 | 162 | 0.655862 | 4.956787 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/User/ZMUser+Predicates.swift | 1 | 3696 | ////
// Wire
// Copyright (C) 2019 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 WireUtilities
extension ZMUser {
/// Retrieves all users (excluding bots), having ZMConnectionStatusAccepted connection statuses.
@objc static var predicateForConnectedNonBotUsers: NSPredicate {
return predicateForUsers(withSearch: "", connectionStatuses: [ZMConnectionStatus.accepted.rawValue])
}
/// Retrieves connected users with name or handle matching search string
///
/// - Parameter query: search string
/// - Returns: predicate having search query and ZMConnectionStatusAccepted connection statuses
@objc(predicateForConnectedUsersWithSearchString:)
public static func predicateForConnectedUsers(withSearch query: String) -> NSPredicate {
return predicateForUsers(withSearch: query, connectionStatuses: [ZMConnectionStatus.accepted.rawValue])
}
/// Retrieves all users with name or handle matching search string
///
/// - Parameter query: search string
/// - Returns: predicate having search query
public static func predicateForAllUsers(withSearch query: String) -> NSPredicate {
return predicateForUsers(withSearch: query, connectionStatuses: nil)
}
/// Retrieves users with name or handle matching search string, having one of given connection statuses
///
/// - Parameters:
/// - query: search string
/// - connectionStatuses: an array of connections status of the users. E.g. for connected users it is [ZMConnectionStatus.accepted.rawValue]
/// - Returns: predicate having search query and supplied connection statuses
@objc(predicateForUsersWithSearchString:connectionStatusInArray:)
public static func predicateForUsers(withSearch query: String, connectionStatuses: [Int16]? ) -> NSPredicate {
var allPredicates = [[NSPredicate]]()
if let statuses = connectionStatuses {
allPredicates.append([predicateForUsers(withConnectionStatuses: statuses)])
}
if !query.isEmpty {
let namePredicate = NSPredicate(formatDictionary: [#keyPath(ZMUser.normalizedName): "%K MATCHES %@"], matchingSearch: query)
let handlePredicate = NSPredicate(format: "%K BEGINSWITH %@", #keyPath(ZMUser.handle), query.strippingLeadingAtSign())
allPredicates.append([namePredicate, handlePredicate].compactMap {$0})
}
let orPredicates = allPredicates.map { NSCompoundPredicate(orPredicateWithSubpredicates: $0) }
return NSCompoundPredicate(andPredicateWithSubpredicates: orPredicates)
}
@objc(predicateForUsersWithConnectionStatusInArray:)
public static func predicateForUsers(withConnectionStatuses connectionStatuses: [Int16]) -> NSPredicate {
return NSPredicate(format: "(%K IN (%@))", #keyPath(ZMUser.connection.status), connectionStatuses)
}
public static func predicateForUsersToUpdateRichProfile() -> NSPredicate {
return NSPredicate(format: "(%K == YES)", #keyPath(ZMUser.needsRichProfileUpdate))
}
}
| gpl-3.0 | dd07502f380578f8121ff9de67e8f368 | 46.384615 | 146 | 0.730249 | 4.994595 | false | false | false | false |
drinkapoint/DrinkPoint-iOS | DrinkPoint/Pods/FacebookShare/Sources/Share/Views/ShareButton.swift | 1 | 2978 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import FBSDKShareKit
/**
A button for sharing content.
*/
public class ShareButton<C: ContentProtocol>: UIView {
private var sdkShareButton: FBSDKShareButton
/// The content to share.
public var content: C? = nil {
didSet {
sdkShareButton.shareContent = content.flatMap(ContentBridger.bridgeToObjC)
}
}
/**
Create a new ShareButton with a given frame and content.
- parameter frame: The frame to initialize with.
- parameter content: The content to share.
*/
public init(frame: CGRect? = nil, content: C? = nil) {
let sdkShareButton = FBSDKShareButton()
let frame = frame ?? sdkShareButton.bounds
self.sdkShareButton = sdkShareButton
self.content = content
super.init(frame: frame)
addSubview(sdkShareButton)
}
/**
Performs logic for laying out subviews.
*/
public override func layoutSubviews() {
super.layoutSubviews()
sdkShareButton.frame = CGRect(origin: .zero, size: bounds.size)
}
/**
Resizes and moves the receiver view so it just encloses its subviews.
*/
public override func sizeToFit() {
bounds.size = sizeThatFits(CGSize(width: CGFloat.max, height: CGFloat.max))
}
/**
Asks the view to calculate and return the size that best fits the specified size.
- parameter size: A new size that fits the receiver’s subviews.
- returns: A new size that fits the receiver’s subviews.
*/
public override func sizeThatFits(size: CGSize) -> CGSize {
return sdkShareButton.sizeThatFits(size)
}
/**
Returns the natural size for the receiving view, considering only properties of the view itself.
- returns: A size indicating the natural size for the receiving view based on its intrinsic properties.
*/
public override func intrinsicContentSize() -> CGSize {
return sdkShareButton.intrinsicContentSize()
}
}
| mit | 7dd6ba528ed4600a22c09280b5fabbfb | 33.183908 | 106 | 0.729321 | 4.526636 | false | false | false | false |
simplymadeapps/SMASaveSystem | Source/SMASaveSystem.swift | 1 | 10244 | //
// SMASaveSystem.swift
//
// Created by Bill Burgess on 1/11/16.
// Copyright © 2016 Simply Made Apps. All rights reserved.
//
import Foundation
import CryptoSwift
struct SMASaveSystemConstants {
static let Encryption: Bool = true
static let EncryptionKey = "secret0key000000"
static let IV = "0123456789012345"
static let Logging: Bool = true
}
struct SMASaveSystemOS {
var value: UInt32
init(_ val: UInt32) { value = val }
}
let SMASaveSystemOSNone = SMASaveSystemOS(0)
let SMASaveSystemOSMacOSX = SMASaveSystemOS(1)
let SMASaveSystemOSIOS = SMASaveSystemOS(2)
public class SMASaveSystem: NSObject {
// MARK: Helper
internal class func appName() -> String? {
let bundlePath = NSBundle.mainBundle().bundleURL.lastPathComponent
return (bundlePath as NSString!).lastPathComponent.lowercaseString
}
internal class func os() -> SMASaveSystemOS {
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
return SMASaveSystemOSIOS
#elseif TARGET_OS_MAC || TARGET_OS_OSX
return SMASaveSystemOSMacOSX
#else
return SMASaveSystemOSIOS
#endif
}
internal class func filePathEncryption(encryption: Bool) -> String? {
let os = self.os()
let fileExt = encryption ? ".abssen" : ".abss"
let fileName = self.appName()! + fileExt
if os.value == SMASaveSystemOSIOS.value {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let path = (documentsDirectory as NSString!).stringByAppendingPathComponent(fileName)
return path
} else if os.value == SMASaveSystemOSMacOSX.value {
let fileManager = NSFileManager.defaultManager()
var folderPath = "~/Library/Application Support/" + self.appName()! + "/"
folderPath = (folderPath as NSString!).stringByExpandingTildeInPath
if fileManager.fileExistsAtPath(folderPath) == false {
do {
try fileManager.createDirectoryAtPath(folderPath, withIntermediateDirectories: false, attributes: nil)
} catch {
print(error)
}
}
return (folderPath as NSString!).stringByAppendingPathComponent(fileName)
}
return nil
}
internal class func loadDictionaryEncryption(encryption: Bool) -> NSMutableDictionary? {
let binaryFile = NSData(contentsOfFile: self.filePathEncryption(encryption)!)
if binaryFile == nil {
return nil
}
var dictionary: NSMutableDictionary
if encryption == true {
let decryptedData = self.decryptData(binaryFile!)
dictionary = NSKeyedUnarchiver.unarchiveObjectWithData(decryptedData!) as! NSMutableDictionary
} else {
dictionary = NSKeyedUnarchiver.unarchiveObjectWithData(binaryFile!) as! NSMutableDictionary
}
return dictionary
}
// MARK: Objects
// MARK: NSData
public class func saveData(data: NSData?, key: String!, encryption: Bool) {
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(self.filePathEncryption(encryption)!)
var tempDic: NSMutableDictionary?
if fileExists == true {
tempDic = self.loadDictionaryEncryption(encryption)!
} else {
tempDic = NSMutableDictionary()
}
tempDic?.setObject(data!, forKey: key)
let dicData = NSKeyedArchiver.archivedDataWithRootObject(tempDic!)
if encryption == true {
let encryptedData = self.encryptData(dicData)
let options: NSDataWritingOptions = .DataWritingAtomic
try! encryptedData?.writeToFile(self.filePathEncryption(encryption)!, options: options)
} else {
try! dicData.writeToFile(self.filePathEncryption(encryption)!, options: .DataWritingAtomic)
}
}
public class func saveData(data: NSData?, key: String!) {
self.saveData(data, key: key, encryption: SMASaveSystemConstants.Encryption)
}
public class func removeData(key: String!, encryption: Bool) {
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(self.filePathEncryption(encryption)!)
let tempDic: NSMutableDictionary?
if fileExists == true {
tempDic = self.loadDictionaryEncryption(encryption)!
} else {
tempDic = NSMutableDictionary()
}
tempDic?.removeObjectForKey(key)
let dicData = NSKeyedArchiver.archivedDataWithRootObject(tempDic!)
if encryption == true {
let encryptedData = self.encryptData(dicData)
do {
try encryptedData?.writeToFile(self.filePathEncryption(encryption)!, options: .DataWritingAtomic)
} catch {
print("SMASaveSystem Error Removing Data: \(key) : \(error)")
}
} else {
do {
try dicData.writeToFile(self.filePathEncryption(encryption)!, options: .DataWritingAtomic)
} catch {
print("SMASaveSystem Error Removing Data: \(key) : \(error)")
}
}
}
public class func removeData(key: String!) {
self.removeData(key, encryption: SMASaveSystemConstants.Encryption)
}
public class func data(key: String!, encryption: Bool) -> NSData? {
let tempDic = self.loadDictionaryEncryption(encryption)
if let data = tempDic?.objectForKey(key) {
return data as? NSData
} else {
if SMASaveSystemConstants.Logging == true {
print("SMASaveSystem ERROR: data(key: \(key)) does not exist!")
}
return nil
}
}
public class func data(key: String!) -> NSData? {
return self.data(key, encryption: SMASaveSystemConstants.Encryption)
}
// MARK: NSObject
public class func saveObject(object: AnyObject, key: String!) {
let data = NSKeyedArchiver.archivedDataWithRootObject(object)
self.saveData(data, key: key)
}
public class func object(key: String!) -> AnyObject? {
//return self.object(key)
if let data = self.data(key) {
if let object = NSKeyedUnarchiver.unarchiveObjectWithData(data) {
return object
} else {
if SMASaveSystemConstants.Logging == true {
print("SMASaveSystem ERROR: object(key: \(key) does not exist!")
}
}
}
return nil
}
// MARK: String
public class func saveString(string: String!, key: String!) {
self.saveObject(string, key: key)
}
public class func string(key: String!) -> String? {
return self.object(key) as? String
}
// MARK: NSNumber
public class func saveNumber(number: NSNumber!, key: String!) {
self.saveObject(number, key: key)
}
public class func number(key: String!) -> NSNumber? {
return self.object(key) as? NSNumber
}
// MARK: NSDate
public class func saveDate(date: NSDate!, key: String!) {
self.saveObject(date, key: key)
}
public class func date(key: String!) -> NSDate? {
return self.object(key) as? NSDate
}
// MARK: Primitives
// MARK: NSInteger
public class func saveInteger(integer: NSInteger!, key: String!) {
self.saveObject(NSNumber(integer: integer), key: key)
}
public class func integer(key: String!) -> NSInteger? {
return self.object(key) as? NSInteger
}
// MARK: CGFloat
public class func saveFloat(float: Float!, key: String!) {
self.saveObject(NSNumber(float: float), key: key)
}
public class func float(key: String!) -> Float? {
return self.object(key) as? Float
}
// MARK: Bool
public class func saveBool(bool: Bool, key: String!) {
self.saveObject(NSNumber(bool: bool), key: key)
}
public class func bool(key: String!) -> Bool? {
return self.object(key) as? Bool
}
// MARK: Logging
public class func logSavedValues() {
self.logSavedValues(SMASaveSystemConstants.Encryption)
}
public class func logSavedValues(encryption: Bool) {
let baseLogMessage = encryption ? "SMASaveSystem: logSavedValues (Encrypted)" : "SMASaveSystem: logSavedValues"
if let tempDic = self.loadDictionaryEncryption(encryption) {
print("\(baseLogMessage) -> START LOG")
tempDic.enumerateKeysAndObjectsUsingBlock {
(key, value, pointer) in
let valueString = NSKeyedUnarchiver.unarchiveObjectWithData(value as! NSData)
print("\(baseLogMessage) -> Key: \(key) -> \(valueString)")
}
print("\(baseLogMessage) -> END LOG")
} else {
print("\(baseLogMessage) -> NO DATA SAVED")
return
}
}
// MARK: Cleanup
public class func truncate() {
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(self.filePathEncryption(SMASaveSystemConstants.Encryption)!)
print("Data file successfully removed")
} catch {
let fileExt = SMASaveSystemConstants.Encryption ? ".abssen" : ".abss"
let fileName = self.appName()! + fileExt
print("Could not delete file: \(fileName)")
}
}
// MARK: Encryption Helpers
class func encryptData(data: NSData) -> NSData? {
let encrypted = try! data.encrypt(AES(key: SMASaveSystemConstants.EncryptionKey, iv: SMASaveSystemConstants.IV))
return encrypted
}
class func decryptData(data: NSData) -> NSData? {
let decrypted = try! data.decrypt(AES(key: SMASaveSystemConstants.EncryptionKey, iv: SMASaveSystemConstants.IV))
return decrypted
}
}
| mit | ffb6ae7ef1582ec0854e18660a2b0763 | 34.442907 | 122 | 0.610368 | 4.843026 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Lifting/ScriptWriter.swift | 1 | 2971 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
struct ScriptWriter {
/// How many spaces to use per indention level.
public let indent: Int
/// The current script code.
var code = ""
/// The current number of spaces to use for indention.
private var currentIndention: Int = 0
/// Whether to include comments in the output.
/// Comment removal is best effort and will currently generally only remove comments if the comment is the only content of the line.
private let stripComments: Bool
/// Whether to include line numbers in the output.
private let includeLineNumbers: Bool
/// Current line, used when including line numbers in the output.
private var curLine = 0
public init (stripComments: Bool = false, includeLineNumbers: Bool = false, indent: Int = 4) {
self.indent = indent
self.stripComments = stripComments
self.includeLineNumbers = includeLineNumbers
}
/// Emit one line of code.
mutating func emit<S: StringProtocol>(_ line: S) {
assert(!line.contains("\n"))
curLine += 1
if includeLineNumbers { code += "\(String(format: "%3i", curLine)). " }
code += String(repeating: " ", count: currentIndention) + line + "\n"
}
/// Emit an expression statement.
mutating func emit(_ expr: Expression) {
emit(expr.text + ";")
}
/// Emit a comment.
mutating func emitComment(_ comment: String) {
guard !stripComments else { return }
for line in comment.split(separator: "\n") {
emit("// " + line)
}
}
/// Emit one or more lines of code.
mutating func emitBlock(_ block: String) {
for line in block.split(separator: "\n") {
if stripComments {
let trimmedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedLine.hasPrefix("//") || (trimmedLine.hasPrefix("/*") && trimmedLine.hasSuffix("*/")) {
continue
}
}
emit(line)
}
}
/// Increase the indention level of the following code by one.
mutating func increaseIndentionLevel() {
currentIndention += self.indent
}
/// Decrease the indention level of the following code by one.
mutating func decreaseIndentionLevel() {
currentIndention -= self.indent
assert(currentIndention >= 0)
}
}
| apache-2.0 | 5a4c87526dd4c1dd27da25a067393638 | 33.546512 | 136 | 0.638842 | 4.542813 | false | false | false | false |
meteochu/Alamofire | Tests/DownloadTests.swift | 130 | 18195 | //
// DownloadTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
class DownloadInitializationTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
func testDownloadClassMethodWithMethodURLAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class DownloadResponseTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
let cachesURL: NSURL = {
let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
return cachesURL
}()
var randomCachesFileURL: NSURL {
return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
}
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "https://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(
directory: searchPathDirectory,
domain: searchPathDomain
)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
do {
let contents = try fileManager.contentsOfDirectoryAtURL(
directory,
includingPropertiesForKeys: nil,
options: .SkipsHiddenFiles
)
#if os(iOS) || os(tvOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(
file.lastPathComponent ?? "",
"\(suggestedFilename)",
"filename should be \(suggestedFilename)"
)
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
do {
try fileManager.removeItemAtURL(file)
} catch {
XCTFail("file manager should remove item at URL: \(file)")
}
} else {
XCTFail("file should not be nil")
}
} catch {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "https://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (
completedUnitCount: download.progress.completedUnitCount,
totalUnitCount: download.progress.totalUnitCount
)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
do {
try fileManager.removeItemAtURL(fileURL)
} catch {
XCTFail("file manager should remove item at URL: \(fileURL)")
}
}
func testDownloadRequestWithParameters() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let parameters = ["foo": "bar"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
args = JSON["args"] as? [String: String]
{
XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
} else {
XCTFail("args parameter in JSON should not be nil")
}
}
func testDownloadRequestWithHeaders() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, headers: headers, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
headers = JSON["headers"] as? [String: String]
{
XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
} else {
XCTFail("headers parameter in JSON should not be nil")
}
}
}
// MARK: -
class DownloadResumeDataTestCase: BaseTestCase {
let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
let destination: Request.DownloadFileDestination = {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
}()
func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNil(download.resumeData, "resume data should be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
if let
responseData = data as? NSData,
resumeData = download.resumeData
{
XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
} else {
XCTFail("response data or resume data was unexpectedly nil")
}
}
func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var response: Response<AnyObject, NSError>?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
XCTAssertNotNil(response.result.error, "result error should not be nil")
} else {
XCTFail("response should not be nil")
}
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
}
}
| mit | de58a40f86a640d6e8c30aebb8d37fc2 | 38.468547 | 126 | 0.642374 | 5.854247 | false | false | false | false |
AshuMishra/iAppStreetDemo | iAppStreet App/Delegate/AppDelegate.swift | 1 | 5883 | //
// AppDelegate.swift
// iAppStreet App
//
// Created by Ashutosh Mishra on 18/07/15.
// Copyright (c) 2015 Ashutosh Mishra. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "ashumishra224.iAppStreet_App" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("iAppStreet_App", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("iAppStreet_App.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 0c8dc344c1677530369a6ef5e16f43e2 | 52.481818 | 287 | 0.749788 | 5.247993 | false | false | false | false |
teroxik/open-muvr | ios/Lift/Device/This/ThisDevice.swift | 5 | 2168 | import Foundation
///
/// Driver for this device (iPhone / iPod with accelerometer, GPS, and all HealthKit data)
///
class ThisDevice : NSObject, Device {
internal struct Info {
static let id = NSUUID(UUIDString: "00000000-0000-0000-0000-000000000001")!
static let deviceInfo: DeviceInfo = {
return DeviceInfo.ConnectedDeviceInfo(id: id, type: "this", name: UIDevice.currentDevice().name, description: UIDevice.currentDevice().localizedModel)
}()
static let deviceInfoDetail: DeviceInfo.Detail = {
return DeviceInfo.Detail(address: "(This device)".localized(), hardwareVersion: UIDevice.currentDevice().model, osVersion: UIDevice.currentDevice().systemVersion)
}()
}
// MARK: Device implementation
func peek(onDone: DeviceInfo -> Void) {
onDone(Info.deviceInfo)
}
func connect(deviceDelegate: DeviceDelegate, deviceSessionDelegate: DeviceSessionDelegate, onDone: ConnectedDevice -> Void) {
onDone(ThisConnectedDevice(deviceDelegate: deviceDelegate, deviceSessionDelegate: deviceSessionDelegate))
}
}
///
/// Driver for this device (iPhone / iPod with accelerometer, GPS, and all HealthKit data)
///
class ThisConnectedDevice : ThisDevice, ConnectedDevice {
var deviceDelegate: DeviceDelegate!
var deviceSessionDelegate: DeviceSessionDelegate!
var currentDeviceSession: ThisDeviceSession?
required init(deviceDelegate: DeviceDelegate, deviceSessionDelegate: DeviceSessionDelegate) {
self.deviceDelegate = deviceDelegate
self.deviceSessionDelegate = deviceSessionDelegate
super.init()
}
// MARK: ConnectedDevice implementation
func start() {
deviceDelegate.deviceGotDeviceInfo(Info.id, deviceInfo: Info.deviceInfo)
deviceDelegate.deviceGotDeviceInfoDetail(Info.id, detail: Info.deviceInfoDetail)
deviceDelegate.deviceAppLaunched(Info.id)
currentDeviceSession?.stop()
currentDeviceSession = ThisDeviceSession(deviceSessionDelegate: deviceSessionDelegate)
}
func stop() {
currentDeviceSession?.stop()
}
}
| apache-2.0 | d1aacc222c4d00193f29f50a60f68e21 | 37.035088 | 174 | 0.708948 | 5.065421 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/UIKit/TKStyleManager+UIKit.swift | 1 | 2049 | //
// TKStyleManager+UIKit.swift
// TripKit-iOS
//
// Created by Adrian Schönig on 1/2/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
// MARK: - Default Styles
extension TKStyleManager {
@objc(addDefaultShadow:)
public static func addDefaultShadow(to view: UIView) {
view.layer.shadowOpacity = 0.2
view.layer.shadowOffset = .init(width: 0, height: 0)
view.layer.shadowRadius = 1
}
@objc(addDefaultOutline:)
public static func addDefaultOutline(to view: UIView) {
view.layer.borderColor = UIColor.tkSeparator.cgColor
view.layer.borderWidth = 0.5
}
@objc(styleSearchBar:includingBackground:)
public static func style(_ searchBar: UISearchBar, includingBackground: Bool = false) {
style(searchBar, includingBackground: includingBackground, styler: { _ in })
}
@objc(styleSearchBar:includingBackground:styler:)
public static func style(_ searchBar: UISearchBar, includingBackground: Bool, styler: (UITextField) -> Void) {
searchBar.backgroundImage = includingBackground
? UIImage.backgroundNavSecondary
: UIImage() // blank
style(searchBar) { textField in
textField.clearButtonMode = .whileEditing
textField.font = customFont(forTextStyle: .subheadline)
textField.textColor = .tkLabelPrimary
textField.backgroundColor = .tkBackground
styler(textField)
}
}
@objc(styleSearchBar:styler:)
public static func style(_ searchBar: UISearchBar, styler: (UITextField) -> Void) {
if #available(iOS 13.0, *) {
styler(searchBar.searchTextField)
} else {
if let textField = searchBar.subviews.compactMap( { $0 as? UITextField } ).first {
styler(textField)
} else if let textField = searchBar.subviews.first?.subviews.compactMap( { $0 as? UITextField } ).first {
// look one-level deep
styler(textField)
} else {
assertionFailure("Couldn't locate text field")
}
}
}
}
#endif
| apache-2.0 | 01d52c3404d9a09fdb6f6320039f8e6f | 26.662162 | 112 | 0.676111 | 4.238095 | false | false | false | false |
mohamede1945/quran-ios | VFoundation/QProgress.swift | 2 | 2670 | //
// QProgress.swift
// Quran
//
// Created by Mohamed Afifi on 4/21/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import Foundation
public protocol QProgressListener: class {
func onProgressUpdated(to progress: Double)
}
open class BlockQProgressListener: QProgressListener {
private let body: (Double) -> Void
public init(_ body: @escaping (Double) -> Void) {
self.body = body
}
open func onProgressUpdated(to progress: Double) {
body(progress)
}
}
open class QProgress: NSObject, QProgressListener {
private var children: [QProgress: Double] = [:]
open let progressListeners = WeakSet<QProgressListener>()
open var totalUnitCount: Double {
didSet { notifyProgressChanged() }
}
open var completedUnitCount: Double = 0 {
didSet { notifyProgressChanged() }
}
private func notifyProgressChanged() {
let progress = self.progress
for listener in progressListeners {
listener.onProgressUpdated(to: progress)
}
}
open var progress: Double {
return Double(completedUnitCount) / Double(totalUnitCount)
}
public init(totalUnitCount: Double) {
self.totalUnitCount = totalUnitCount
}
open func add(child: QProgress, withPendingUnitCount inUnitCount: Double) {
children[child] = inUnitCount
child.progressListeners.insert(self)
}
open func remove(child: QProgress) {
children[child] = nil
child.progressListeners.remove(self)
}
private func childProgressChanged() {
var completedUnitCount: Double = 0
for (child, pendingUnitCount) in children {
completedUnitCount += child.progress * pendingUnitCount
}
self.completedUnitCount = completedUnitCount
}
open func onProgressUpdated(to progress: Double) {
var completedUnitCount: Double = 0
for (child, pendingUnitCount) in children {
completedUnitCount += child.progress * pendingUnitCount
}
self.completedUnitCount = completedUnitCount
}
}
| gpl-3.0 | 46c44c86ea3a7ec2aba5eaee4061606a | 28.666667 | 79 | 0.676779 | 4.603448 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Models/Notifications/NotificationRange.swift | 1 | 3463 | import Foundation
// MARK: - NotificationRange Entity
//
class NotificationRange {
/// Kind of the current Range
///
let kind: Kind
/// Text Range Associated!
///
let range: NSRange
/// Resource URL, if any.
///
fileprivate(set) var url: URL?
/// Comment ID, if any.
///
fileprivate(set) var commentID: NSNumber?
/// Post ID, if any.
///
fileprivate(set) var postID: NSNumber?
/// Site ID, if any.
///
fileprivate(set) var siteID: NSNumber?
/// User ID, if any.
///
fileprivate(set) var userID: NSNumber?
/// String Payload, if any.
///
fileprivate(set) var value: String?
/// Designated Initializer
///
init?(dictionary: [String: AnyObject]) {
guard let type = dictionary[RangeKeys.RawType] as? String, let indices = dictionary[RangeKeys.Indices] as? [Int],
let start = indices.first, let end = indices.last else {
return nil
}
kind = Kind(rawValue: type) ?? .Site
range = NSMakeRange(start, end - start)
siteID = dictionary[RangeKeys.SiteId] as? NSNumber
if let rawURL = dictionary[RangeKeys.URL] as? String {
url = URL(string: rawURL)
}
// SORRY: << Let me stress this. Sorry, i'm 1000% against Duck Typing.
// ======
// `id` is coupled with the `kind`. Which, in turn, is also duck typed.
//
// type = comment => id = comment_id
// type = user => id = user_id
// type = post => id = post_id
// type = site => id = site_id
//
switch kind {
case .Comment:
commentID = dictionary[RangeKeys.Id] as? NSNumber
postID = dictionary[RangeKeys.PostId] as? NSNumber
case .Noticon:
value = dictionary[RangeKeys.Value] as? String
case .Post:
postID = dictionary[RangeKeys.Id] as? NSNumber
case .Site:
siteID = dictionary[RangeKeys.Id] as? NSNumber
case .User:
userID = dictionary[RangeKeys.Id] as? NSNumber
default:
break
}
}
}
// MARK: - NotificationRange Parsers
//
extension NotificationRange {
/// Parses NotificationRange instances, given an array of raw ranges.
///
class func rangesFromArray(_ ranges: [[String: AnyObject]]?) -> [NotificationRange] {
let parsed = ranges?.flatMap {
return NotificationRange(dictionary: $0)
}
return parsed ?? []
}
}
// MARK: - NotificationRange Types
//
extension NotificationRange {
/// Known kinds of Range
///
enum Kind: String {
case User = "user"
case Post = "post"
case Comment = "comment"
case Stats = "stat"
case Follow = "follow"
case Blockquote = "blockquote"
case Noticon = "noticon"
case Site = "site"
case Match = "match"
}
/// Parsing Keys
///
fileprivate enum RangeKeys {
static let RawType = "type"
static let URL = "url"
static let Indices = "indices"
static let Id = "id"
static let Value = "value"
static let SiteId = "site_id"
static let PostId = "post_id"
}
}
| gpl-2.0 | 61db7269aacf08a5434cfd9c43701bd7 | 26.054688 | 121 | 0.525845 | 4.361461 | false | false | false | false |
justeat/JustPeek | JustPeek/Classes/PeekController.swift | 1 | 1700 | //
// PeekController.swift
// JustPeek
//
// Copyright 2016 Just Eat Holdings Ltd.
//
import UIKit
private extension UIDevice {
var isSimulator: Bool {
get {
return TARGET_OS_SIMULATOR != 0
}
}
}
private extension UIView {
var hasNativeForceTouchEnabled: Bool {
get {
guard !UIDevice.current.isSimulator else { return false }
if #available(iOS 9.0, *) {
return traitCollection.forceTouchCapability == .available
} else {
return false
}
}
}
}
internal protocol PeekHandler {
func register(viewController vc: UIViewController, forPeekingWithDelegate delegate: PeekingDelegate, sourceView: UIView)
}
@objc(JEPeekingDelegate) public protocol PeekingDelegate {
func peekContext(_ context: PeekContext, viewControllerForPeekingAt location: CGPoint) -> UIViewController?
func peekContext(_ context: PeekContext, commit viewController: UIViewController)
}
@objc(JEPeekController) @objcMembers open class PeekController: NSObject {
fileprivate var peekHandler: PeekHandler?
fileprivate var sourceViewController: UIViewController?
open func register(viewController v: UIViewController, forPeekingWithDelegate d: PeekingDelegate, sourceView: UIView) {
if #available(iOS 9.0, *) {
peekHandler = sourceView.hasNativeForceTouchEnabled ? PeekNativeHandler() : PeekReplacementHandler()
} else {
peekHandler = PeekReplacementHandler()
}
peekHandler?.register(viewController: v, forPeekingWithDelegate: d, sourceView: sourceView)
}
}
| apache-2.0 | ddc9225a42dabd31741f2e946ac87d97 | 26.419355 | 124 | 0.664118 | 4.97076 | false | false | false | false |
osrufung/TouchVisualizer | Example/Example/ViewController.swift | 1 | 2947 | //
// ViewController.swift
// Example
//
// Created by MORITA NAOKI on 2015/05/06.
// Copyright (c) 2015年 molabo. All rights reserved.
//
import UIKit
import TouchVisualizer
class ViewController: UITableViewController {
// MARK: - Life Cycle
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PushToDetail" {
let viewController = segue.destinationViewController as! DetailViewController
if let cell = sender as? UITableViewCell {
viewController.text = cell.detailTextLabel?.text
}
}
}
// MARK: - TableView DataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = "Smooth scrolling!"
cell.detailTextLabel?.text = "\(indexPath.row)"
return cell
}
// MARK: - Actions
@IBAction func rightBarButtonItemTapped(sender: AnyObject) {
let alertAction = UIAlertAction(title: "Show Alert", style: .Default, handler:
{ [unowned self] (alertAction) -> Void in
let controller = UIAlertController(
title: "Alert",
message: "Even when alert shows, your tap is visible.",
preferredStyle: .Alert
)
controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(controller, animated: true, completion: nil)
}
)
var startOrStopTitle = "Start Visualizer"
if Visualizer.isEnabled() {
startOrStopTitle = "Stop Visualizer"
}
let startOrStopAction = UIAlertAction(title: startOrStopTitle, style: .Default, handler:
{ [unowned self] (alertAction) -> Void in
if Visualizer.isEnabled() {
Visualizer.stop()
self.navigationItem.leftBarButtonItem?.enabled = false
} else {
Visualizer.start()
self.navigationItem.leftBarButtonItem?.enabled = true
}
}
)
let controller = UIAlertController(
title: "ActionSheet",
message: "Even when action sheet shows, your tap is visible.",
preferredStyle: .ActionSheet
)
controller.addAction(alertAction)
controller.addAction(startOrStopAction)
controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(controller, animated: true, completion: nil)
}
}
| mit | 70da9fa5df5692ef7c6a4e3006a406b7 | 36.278481 | 118 | 0.604414 | 5.40367 | false | false | false | false |
dominicpr/SSASideMenu | SSASideMenu/SSASideMenu.swift | 2 | 44875 | //
// SSASideMenu.swift
// SSASideMenuExample
//
// Created by Sebastian Andersen on 06/10/14.
// Copyright (c) 2015 Sebastian Andersen. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
var sideMenuViewController: SSASideMenu? {
get {
return getSideViewController(self)
}
}
private func getSideViewController(viewController: UIViewController) -> SSASideMenu? {
if let parent = viewController.parentViewController {
if parent is SSASideMenu {
return parent as? SSASideMenu
}else {
return getSideViewController(parent)
}
}
return nil
}
@IBAction func presentLeftMenuViewController() {
sideMenuViewController?._presentLeftMenuViewController()
}
@IBAction func presentRightMenuViewController() {
sideMenuViewController?._presentRightMenuViewController()
}
}
@objc protocol SSASideMenuDelegate {
optional func sideMenuDidRecognizePanGesture(sideMenu: SSASideMenu, recongnizer: UIPanGestureRecognizer)
optional func sideMenuWillShowMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuDidShowMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuWillHideMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
optional func sideMenuDidHideMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController)
}
class SSASideMenu: UIViewController, UIGestureRecognizerDelegate {
enum SSASideMenuPanDirection: Int {
case Edge = 0
case EveryWhere = 1
}
enum SSASideMenuType: Int {
case Scale = 0
case Slip = 1
}
enum SSAStatusBarStyle: Int {
case Hidden = 0
case Black = 1
case Light = 2
}
private enum SSASideMenuSide: Int {
case Left = 0
case Right = 1
}
struct ContentViewShadow {
var enabled: Bool = true
var color: UIColor = UIColor.blackColor()
var offset: CGSize = CGSizeZero
var opacity: Float = 0.4
var radius: Float = 8.0
init(enabled: Bool = true, color: UIColor = UIColor.blackColor(), offset: CGSize = CGSizeZero, opacity: Float = 0.4, radius: Float = 8.0) {
self.enabled = false
self.color = color
self.offset = offset
self.opacity = opacity
self.radius = radius
}
}
struct MenuViewEffect {
var fade: Bool = true
var scale: Bool = true
var scaleBackground: Bool = true
var parallaxEnabled: Bool = true
var bouncesHorizontally: Bool = true
var statusBarStyle: SSAStatusBarStyle = .Black
init(fade: Bool = true, scale: Bool = true, scaleBackground: Bool = true, parallaxEnabled: Bool = true, bouncesHorizontally: Bool = true, statusBarStyle: SSAStatusBarStyle = .Black) {
self.fade = fade
self.scale = scale
self.scaleBackground = scaleBackground
self.parallaxEnabled = parallaxEnabled
self.bouncesHorizontally = bouncesHorizontally
self.statusBarStyle = statusBarStyle
}
}
struct ContentViewEffect {
var alpha: Float = 1.0
var scale: Float = 0.7
var landscapeOffsetX: Float = 30
var portraitOffsetX: Float = 30
var minParallaxContentRelativeValue: Float = -25.0
var maxParallaxContentRelativeValue: Float = 25.0
var interactivePopGestureRecognizerEnabled: Bool = true
init(alpha: Float = 1.0, scale: Float = 0.7, landscapeOffsetX: Float = 30, portraitOffsetX: Float = 30, minParallaxContentRelativeValue: Float = -25.0, maxParallaxContentRelativeValue: Float = 25.0, interactivePopGestureRecognizerEnabled: Bool = true) {
self.alpha = alpha
self.scale = scale
self.landscapeOffsetX = landscapeOffsetX
self.portraitOffsetX = portraitOffsetX
self.minParallaxContentRelativeValue = minParallaxContentRelativeValue
self.maxParallaxContentRelativeValue = maxParallaxContentRelativeValue
self.interactivePopGestureRecognizerEnabled = interactivePopGestureRecognizerEnabled
}
}
struct SideMenuOptions {
var animationDuration: Float = 0.35
var panGestureEnabled: Bool = true
var panDirection: SSASideMenuPanDirection = .Edge
var type: SSASideMenuType = .Scale
var panMinimumOpenThreshold: UInt = 60
var menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.5, 1.5)
var backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7)
var endAllEditing: Bool = false
init(animationDuration: Float = 0.35, panGestureEnabled: Bool = true, panDirection: SSASideMenuPanDirection = .Edge, panMinimumOpenThreshold: UInt = 60, menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.5, 1.5), backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7), endAllEditing: Bool = false) {
self.animationDuration = animationDuration
self.panGestureEnabled = panGestureEnabled
self.panDirection = panDirection
self.panMinimumOpenThreshold = panMinimumOpenThreshold
self.menuViewControllerTransformation = menuViewControllerTransformation
self.backgroundTransformation = backgroundTransformation
self.endAllEditing = endAllEditing
}
}
func configure(configuration: MenuViewEffect) {
fadeMenuView = configuration.fade
scaleMenuView = configuration.scale
scaleBackgroundImageView = configuration.scaleBackground
parallaxEnabled = configuration.parallaxEnabled
bouncesHorizontally = configuration.bouncesHorizontally
}
func configure(configuration: ContentViewShadow) {
contentViewShadowEnabled = configuration.enabled
contentViewShadowColor = configuration.color
contentViewShadowOffset = configuration.offset
contentViewShadowOpacity = configuration.opacity
contentViewShadowRadius = configuration.radius
}
func configure(configuration: ContentViewEffect) {
contentViewScaleValue = configuration.scale
contentViewFadeOutAlpha = configuration.alpha
contentViewInLandscapeOffsetCenterX = configuration.landscapeOffsetX
contentViewInPortraitOffsetCenterX = configuration.portraitOffsetX
parallaxContentMinimumRelativeValue = configuration.minParallaxContentRelativeValue
parallaxContentMaximumRelativeValue = configuration.maxParallaxContentRelativeValue
}
func configure(configuration: SideMenuOptions) {
animationDuration = configuration.animationDuration
panGestureEnabled = configuration.panGestureEnabled
panDirection = configuration.panDirection
type = configuration.type
panMinimumOpenThreshold = configuration.panMinimumOpenThreshold
menuViewControllerTransformation = configuration.menuViewControllerTransformation
backgroundTransformation = configuration.backgroundTransformation
endAllEditing = configuration.endAllEditing
}
// MARK : Storyboard Support
@IBInspectable var contentViewStoryboardID: String?
@IBInspectable var leftMenuViewStoryboardID: String?
@IBInspectable var rightMenuViewStoryboardID: String?
// MARK : Private Properties: MenuView & BackgroundImageView
@IBInspectable var fadeMenuView: Bool = true
@IBInspectable var scaleMenuView: Bool = true
@IBInspectable var scaleBackgroundImageView: Bool = true
@IBInspectable var parallaxEnabled: Bool = true
@IBInspectable var bouncesHorizontally: Bool = true
// MARK : Public Properties: MenuView
@IBInspectable var statusBarStyle: SSAStatusBarStyle = .Black
// MARK : Private Properties: ContentView
@IBInspectable var contentViewScaleValue: Float = 0.7
@IBInspectable var contentViewFadeOutAlpha: Float = 1.0
@IBInspectable var contentViewInLandscapeOffsetCenterX: Float = 30.0
@IBInspectable var contentViewInPortraitOffsetCenterX: Float = 30.0
@IBInspectable var parallaxContentMinimumRelativeValue: Float = -25.0
@IBInspectable var parallaxContentMaximumRelativeValue: Float = 25.0
// MARK : Public Properties: ContentView
@IBInspectable var interactivePopGestureRecognizerEnabled: Bool = true
@IBInspectable var endAllEditing: Bool = false
// MARK : Private Properties: Shadow for ContentView
@IBInspectable var contentViewShadowEnabled: Bool = true
@IBInspectable var contentViewShadowColor: UIColor = UIColor.blackColor()
@IBInspectable var contentViewShadowOffset: CGSize = CGSizeZero
@IBInspectable var contentViewShadowOpacity: Float = 0.4
@IBInspectable var contentViewShadowRadius: Float = 8.0
// MARK : Public Properties: SideMenu
@IBInspectable var animationDuration: Float = 0.35
@IBInspectable var panGestureEnabled: Bool = true
@IBInspectable var panDirection: SSASideMenuPanDirection = .Edge
@IBInspectable var type: SSASideMenuType = .Scale
@IBInspectable var panMinimumOpenThreshold: UInt = 60
@IBInspectable var menuViewControllerTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.5, 1.5)
@IBInspectable var backgroundTransformation: CGAffineTransform = CGAffineTransformMakeScale(1.7, 1.7)
// MARK : Internal Private Properties
weak var delegate: SSASideMenuDelegate?
private var visible: Bool = false
private var leftMenuVisible: Bool = false
private var rightMenuVisible: Bool = false
private var originalPoint: CGPoint = CGPoint()
private var didNotifyDelegate: Bool = false
private let iOS8: Bool = kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber_iOS_7_1
private let menuViewContainer: UIView = UIView()
private let contentViewContainer: UIView = UIView()
private let contentButton: UIButton = UIButton()
private let backgroundImageView: UIImageView = UIImageView()
// MARK : Public Properties
@IBInspectable var backgroundImage: UIImage? {
willSet {
if let bckImage = newValue {
backgroundImageView.image = bckImage
}
}
}
var contentViewController: UIViewController? {
willSet {
setupViewController(contentViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupContentViewShadow()
if visible {
setupContentViewControllerMotionEffects()
}
}
}
var leftMenuViewController: UIViewController? {
willSet {
setupViewController(menuViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupMenuViewControllerMotionEffects()
view.bringSubviewToFront(contentViewContainer)
}
}
var rightMenuViewController: UIViewController? {
willSet {
setupViewController(menuViewContainer, targetViewController: newValue)
}
didSet {
if let controller = oldValue {
hideViewController(controller)
}
setupMenuViewControllerMotionEffects()
view.bringSubviewToFront(contentViewContainer)
}
}
// MARK : Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience init(contentViewController: UIViewController, leftMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.leftMenuViewController = leftMenuViewController
}
convenience init(contentViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.rightMenuViewController = rightMenuViewController
}
convenience init(contentViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.contentViewController = contentViewController
self.leftMenuViewController = leftMenuViewController
self.rightMenuViewController = rightMenuViewController
}
//MARK : Present / Hide Menu ViewControllers
func _presentLeftMenuViewController() {
presentMenuViewContainerWithMenuViewController(leftMenuViewController)
showLeftMenuViewController()
}
func _presentRightMenuViewController() {
presentMenuViewContainerWithMenuViewController(rightMenuViewController)
showRightMenuViewController()
}
func hideMenuViewController() {
hideMenuViewController(true)
}
private func showRightMenuViewController() {
if let viewController = rightMenuViewController {
showMenuViewController(.Right, menuViewController: viewController)
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: {[unowned self] () -> Void in
self.animateMenuViewController(.Right)
self.menuViewContainer.alpha = 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
}, completion: {[unowned self] (Bool) -> Void in
self.animateMenuViewControllerCompletion(.Right, menuViewController: viewController)
})
statusBarNeedsAppearanceUpdate()
}
}
private func showLeftMenuViewController() {
if let viewController = leftMenuViewController {
showMenuViewController(.Left, menuViewController: viewController)
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: {[unowned self] () -> Void in
self.animateMenuViewController(.Left)
self.menuViewContainer.alpha = 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
}, completion: {[unowned self] (Bool) -> Void in
self.animateMenuViewControllerCompletion(.Left, menuViewController: viewController)
})
statusBarNeedsAppearanceUpdate()
}
}
private func showMenuViewController(side: SSASideMenuSide, menuViewController: UIViewController) {
menuViewController.view.hidden = false
switch side {
case .Left:
leftMenuViewController?.beginAppearanceTransition(true, animated: true)
rightMenuViewController?.view.hidden = true
case .Right:
rightMenuViewController?.beginAppearanceTransition(true, animated: true)
leftMenuViewController?.view.hidden = true
}
if endAllEditing {
view.window?.endEditing(true)
}else {
setupUserInteractionForContentButtonAndTargetViewControllerView(true, targetViewControllerViewInteractive: false)
}
setupContentButton()
setupContentViewShadow()
resetContentViewScale()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
private func animateMenuViewController(side: SSASideMenuSide) {
if type == .Scale {
contentViewContainer.transform = CGAffineTransformMakeScale(CGFloat(contentViewScaleValue), CGFloat(contentViewScaleValue))
} else {
contentViewContainer.transform = CGAffineTransformIdentity
}
if side == .Left {
let centerXLandscape = CGFloat(contentViewInLandscapeOffsetCenterX) + (iOS8 ? CGFloat(CGRectGetWidth(view.frame)) : CGFloat(CGRectGetHeight(view.frame)))
let centerXPortrait = CGFloat(contentViewInPortraitOffsetCenterX) + CGFloat(CGRectGetWidth(view.frame))
let centerX = UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) ? centerXLandscape : centerXPortrait
contentViewContainer.center = CGPointMake(centerX, contentViewContainer.center.y)
} else {
let centerXLandscape = -CGFloat(self.contentViewInLandscapeOffsetCenterX)
let centerXPortrait = CGFloat(-self.contentViewInPortraitOffsetCenterX)
let centerX = UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) ? centerXLandscape : centerXPortrait
contentViewContainer.center = CGPointMake(centerX, contentViewContainer.center.y)
}
menuViewContainer.transform = CGAffineTransformIdentity
if scaleBackgroundImageView {
if let backgroundImage = backgroundImage {
backgroundImageView.transform = CGAffineTransformIdentity
}
}
}
private func animateMenuViewControllerCompletion(side: SSASideMenuSide, menuViewController: UIViewController) {
if !visible {
self.delegate?.sideMenuDidShowMenuViewController?(self, menuViewController: menuViewController)
}
visible = true
switch side {
case .Left:
leftMenuViewController?.endAppearanceTransition()
leftMenuVisible = true
case .Right:
if contentViewContainer.frame.size.width == view.bounds.size.width &&
contentViewContainer.frame.size.height == view.bounds.size.height &&
contentViewContainer.frame.origin.x == 0 &&
contentViewContainer.frame.origin.y == 0 {
visible = false
}
rightMenuVisible = visible
rightMenuViewController?.endAppearanceTransition()
}
UIApplication.sharedApplication().endIgnoringInteractionEvents()
setupContentViewControllerMotionEffects()
}
private func presentMenuViewContainerWithMenuViewController(menuViewController: UIViewController?) {
menuViewContainer.transform = CGAffineTransformIdentity
menuViewContainer.frame = view.bounds
if scaleBackgroundImageView {
if backgroundImage != nil {
backgroundImageView.transform = CGAffineTransformIdentity
backgroundImageView.frame = view.bounds
backgroundImageView.transform = backgroundTransformation
}
}
if scaleMenuView {
menuViewContainer.transform = menuViewControllerTransformation
}
menuViewContainer.alpha = fadeMenuView ? 0 : 1
if let viewController = menuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
}
private func hideMenuViewController(animated: Bool) {
let isRightMenuVisible: Bool = rightMenuVisible
let visibleMenuViewController: UIViewController? = isRightMenuVisible ? rightMenuViewController : leftMenuViewController
visibleMenuViewController?.beginAppearanceTransition(true, animated: true)
if isRightMenuVisible, let viewController = rightMenuViewController {
delegate?.sideMenuWillHideMenuViewController?(self, menuViewController: viewController)
}
if !isRightMenuVisible, let viewController = leftMenuViewController {
delegate?.sideMenuWillHideMenuViewController?(self, menuViewController: viewController)
}
if !endAllEditing {
setupUserInteractionForContentButtonAndTargetViewControllerView(false, targetViewControllerViewInteractive: true)
}
visible = false
leftMenuVisible = false
rightMenuVisible = false
contentButton.removeFromSuperview()
let animationsClosure: () -> () = {[unowned self] () -> () in
self.contentViewContainer.transform = CGAffineTransformIdentity
self.contentViewContainer.frame = self.view.bounds
if self.scaleMenuView {
self.menuViewContainer.transform = self.menuViewControllerTransformation
}
self.menuViewContainer.alpha = self.fadeMenuView ? 0 : 1
self.contentViewContainer.alpha = CGFloat(self.contentViewFadeOutAlpha)
if self.scaleBackgroundImageView {
if self.backgroundImage != nil {
self.backgroundImageView.transform = self.backgroundTransformation
}
}
if self.parallaxEnabled {
self.removeMotionEffects(self.contentViewContainer)
}
}
let completionClosure: () -> () = {[unowned self] () -> () in
visibleMenuViewController?.endAppearanceTransition()
if isRightMenuVisible, let viewController = self.rightMenuViewController {
self.delegate?.sideMenuDidHideMenuViewController?(self, menuViewController: viewController)
}
if !isRightMenuVisible, let viewController = self.leftMenuViewController {
self.delegate?.sideMenuDidHideMenuViewController?(self, menuViewController: viewController)
}
}
if animated {
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in
animationsClosure()
}, completion: { (Bool) -> Void in
completionClosure()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
})
}else {
animationsClosure()
completionClosure()
}
statusBarNeedsAppearanceUpdate()
}
// MARK : ViewController life cycle
override func awakeFromNib() {
if iOS8 {
if let cntentViewStoryboardID = contentViewStoryboardID {
contentViewController = storyboard?.instantiateViewControllerWithIdentifier(cntentViewStoryboardID)
}
if let lftViewStoryboardID = leftMenuViewStoryboardID {
leftMenuViewController = storyboard?.instantiateViewControllerWithIdentifier(lftViewStoryboardID)
}
if let rghtViewStoryboardID = rightMenuViewStoryboardID {
rightMenuViewController = storyboard?.instantiateViewControllerWithIdentifier(rghtViewStoryboardID)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
menuViewContainer.frame = view.bounds;
menuViewContainer.autoresizingMask = [.FlexibleWidth, .FlexibleHeight];
menuViewContainer.alpha = fadeMenuView ? 0 : 1
contentViewContainer.frame = view.bounds
contentViewContainer.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
setupViewController(contentViewContainer, targetViewController: contentViewController)
setupViewController(menuViewContainer, targetViewController: leftMenuViewController)
setupViewController(menuViewContainer, targetViewController: rightMenuViewController)
if panGestureEnabled {
view.multipleTouchEnabled = false
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"))
panGestureRecognizer.delegate = self
view.addGestureRecognizer(panGestureRecognizer)
}
if let image = backgroundImage {
if scaleBackgroundImageView {
backgroundImageView.transform = backgroundTransformation
}
backgroundImageView.frame = view.bounds
backgroundImageView.contentMode = .ScaleAspectFill;
backgroundImageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight];
view.addSubview(backgroundImageView)
}
view.addSubview(menuViewContainer)
view.addSubview(contentViewContainer)
setupMenuViewControllerMotionEffects()
setupContentViewShadow()
}
// MARK : Setup
private func setupViewController(targetView: UIView, targetViewController: UIViewController?) {
if let viewController = targetViewController {
addChildViewController(viewController)
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func hideViewController(targetViewController: UIViewController) {
targetViewController.willMoveToParentViewController(nil)
targetViewController.view.removeFromSuperview()
targetViewController.removeFromParentViewController()
}
// MARK : Layout
private func setupContentButton() {
if let contentButtonSuperView = contentButton.superview {
return
} else {
contentButton.addTarget(self, action: Selector("hideMenuViewController"), forControlEvents:.TouchUpInside)
contentButton.autoresizingMask = .None
contentButton.frame = contentViewContainer.bounds
contentButton.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
contentButton.tag = 101
contentViewContainer.addSubview(contentButton)
}
}
private func statusBarNeedsAppearanceUpdate() {
if self.respondsToSelector(Selector("setNeedsStatusBarAppearanceUpdate")) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()
})
}
}
private func setupContentViewShadow() {
if contentViewShadowEnabled {
let layer: CALayer = contentViewContainer.layer
let path: UIBezierPath = UIBezierPath(rect: layer.bounds)
layer.shadowPath = path.CGPath
layer.shadowColor = contentViewShadowColor.CGColor
layer.shadowOffset = contentViewShadowOffset
layer.shadowOpacity = contentViewShadowOpacity
layer.shadowRadius = CGFloat(contentViewShadowRadius)
}
}
//MARK : Helper Functions
private func resetContentViewScale() {
let t: CGAffineTransform = contentViewContainer.transform
let scale: CGFloat = sqrt(t.a * t.a + t.c * t.c)
let frame: CGRect = contentViewContainer.frame
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.transform = CGAffineTransformMakeScale(scale, scale)
contentViewContainer.frame = frame
}
private func setupUserInteractionForContentButtonAndTargetViewControllerView(contentButtonInteractive: Bool, targetViewControllerViewInteractive: Bool) {
if let viewController = contentViewController {
for view in viewController.view.subviews {
if view.tag == 101 {
view.userInteractionEnabled = contentButtonInteractive
}else {
view.userInteractionEnabled = targetViewControllerViewInteractive
}
}
}
}
// MARK : Motion Effects (Private)
private func removeMotionEffects(targetView: UIView) {
let targetViewMotionEffects = targetView.motionEffects
for effect in targetViewMotionEffects {
targetView.removeMotionEffect(effect)
}
}
private func setupMenuViewControllerMotionEffects() {
if parallaxEnabled {
removeMotionEffects(menuViewContainer)
// We need to refer to self in closures!
UIView.animateWithDuration(0.2, animations: { [unowned self] () -> Void in
let interpolationHorizontal: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
let interpolationVertical: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
self.menuViewContainer.addMotionEffect(interpolationHorizontal)
self.menuViewContainer.addMotionEffect(interpolationVertical)
})
}
}
private func setupContentViewControllerMotionEffects() {
if parallaxEnabled {
removeMotionEffects(contentViewContainer)
// We need to refer to self in closures!
UIView.animateWithDuration(0.2, animations: { [unowned self] () -> Void in
let interpolationHorizontal: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
let interpolationVertical: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
interpolationHorizontal.minimumRelativeValue = self.parallaxContentMinimumRelativeValue
interpolationHorizontal.maximumRelativeValue = self.parallaxContentMaximumRelativeValue
self.contentViewContainer.addMotionEffect(interpolationHorizontal)
self.contentViewContainer.addMotionEffect(interpolationVertical)
})
}
}
// MARK : View Controller Rotation handler
override func shouldAutorotate() -> Bool {
if let cntViewController = contentViewController {
return cntViewController.shouldAutorotate()
}
return false
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if visible {
menuViewContainer.bounds = view.bounds
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
if type == .Scale {
contentViewContainer.transform = CGAffineTransformMakeScale(CGFloat(contentViewScaleValue), CGFloat(contentViewScaleValue))
} else {
contentViewContainer.transform = CGAffineTransformIdentity
}
var center: CGPoint
if leftMenuVisible {
let centerXLandscape = CGFloat(contentViewInLandscapeOffsetCenterX) + (iOS8 ? CGFloat(CGRectGetWidth(view.frame)) : CGFloat(CGRectGetHeight(view.frame)))
let centerXPortrait = CGFloat(contentViewInPortraitOffsetCenterX) + CGFloat(CGRectGetWidth(view.frame))
let centerX = UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) ? centerXLandscape : centerXPortrait
center = CGPointMake(centerX, contentViewContainer.center.y)
} else {
let centerXLandscape = -CGFloat(self.contentViewInLandscapeOffsetCenterX)
let centerXPortrait = CGFloat(-self.contentViewInPortraitOffsetCenterX)
let centerX = UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) ? centerXLandscape : centerXPortrait
center = CGPointMake(centerX, contentViewContainer.center.y)
}
contentViewContainer.center = center
}
setupContentViewShadow()
}
// MARK : Status Bar Appearance Management
override func preferredStatusBarStyle() -> UIStatusBarStyle {
var style: UIStatusBarStyle
switch statusBarStyle {
case .Hidden:
style = .Default
case .Black:
style = .Default
case .Light:
style = .LightContent
}
if visible || contentViewContainer.frame.origin.y <= 0, let cntViewController = contentViewController {
style = cntViewController.preferredStatusBarStyle()
}
return style
}
override func prefersStatusBarHidden() -> Bool {
var statusBarHidden: Bool
switch statusBarStyle {
case .Hidden:
statusBarHidden = true
default:
statusBarHidden = false
}
if visible || contentViewContainer.frame.origin.y <= 0, let cntViewController = contentViewController {
statusBarHidden = cntViewController.prefersStatusBarHidden()
}
return statusBarHidden
}
override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
var statusBarAnimation: UIStatusBarAnimation = .None
if let cntViewController = contentViewController, leftMenuViewController = leftMenuViewController {
statusBarAnimation = visible ? leftMenuViewController.preferredStatusBarUpdateAnimation() : cntViewController.preferredStatusBarUpdateAnimation()
if contentViewContainer.frame.origin.y > 10 {
statusBarAnimation = leftMenuViewController.preferredStatusBarUpdateAnimation()
} else {
statusBarAnimation = cntViewController.preferredStatusBarUpdateAnimation()
}
}
if let cntViewController = contentViewController, rghtMenuViewController = rightMenuViewController {
statusBarAnimation = visible ? rghtMenuViewController.preferredStatusBarUpdateAnimation() : cntViewController.preferredStatusBarUpdateAnimation()
if contentViewContainer.frame.origin.y > 10 {
statusBarAnimation = rghtMenuViewController.preferredStatusBarUpdateAnimation()
} else {
statusBarAnimation = cntViewController.preferredStatusBarUpdateAnimation()
}
}
return statusBarAnimation
}
// MARK : UIGestureRecognizer Delegate (Private)
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if interactivePopGestureRecognizerEnabled,
let viewController = contentViewController as? UINavigationController
where viewController.viewControllers.count > 1 && viewController.interactivePopGestureRecognizer!.enabled {
return false
}
if gestureRecognizer is UIPanGestureRecognizer && !visible {
switch panDirection {
case .EveryWhere:
return true
case .Edge:
let point = touch.locationInView(gestureRecognizer.view)
if point.x < 20.0 || point.x > view.frame.size.width - 20.0 { return true }
else { return false }
}
}
return true
}
func panGestureRecognized(recognizer: UIPanGestureRecognizer) {
delegate?.sideMenuDidRecognizePanGesture?(self, recongnizer: recognizer)
if !panGestureEnabled {
return
}
var point: CGPoint = recognizer.translationInView(view)
if recognizer.state == .Began {
setupContentViewShadow()
originalPoint = CGPointMake(contentViewContainer.center.x - CGRectGetWidth(contentViewContainer.bounds) / 2.0,
contentViewContainer.center.y - CGRectGetHeight(contentViewContainer.bounds) / 2.0)
menuViewContainer.transform = CGAffineTransformIdentity
if (scaleBackgroundImageView) {
backgroundImageView.transform = CGAffineTransformIdentity
backgroundImageView.frame = view.bounds
}
menuViewContainer.frame = view.bounds
setupContentButton()
if endAllEditing {
view.window?.endEditing(true)
}else {
setupUserInteractionForContentButtonAndTargetViewControllerView(true, targetViewControllerViewInteractive: false)
}
didNotifyDelegate = false
}
if recognizer.state == .Changed {
var delta: CGFloat = 0.0
if visible {
delta = originalPoint.x != 0 ? (point.x + originalPoint.x) / originalPoint.x : 0
} else {
delta = point.x / view.frame.size.width
}
delta = min(fabs(delta), 1.6)
var contentViewScale: CGFloat = type == .Scale ? 1 - ((1 - CGFloat(contentViewScaleValue)) * delta) : 1
var backgroundViewScale: CGFloat = backgroundTransformation.a - ((backgroundTransformation.a - 1) * delta)
var menuViewScale: CGFloat = menuViewControllerTransformation.a - ((menuViewControllerTransformation.a - 1) * delta)
if !bouncesHorizontally {
contentViewScale = max(contentViewScale, CGFloat(contentViewScaleValue))
backgroundViewScale = max(backgroundViewScale, 1.0)
menuViewScale = max(menuViewScale, 1.0)
}
menuViewContainer.alpha = fadeMenuView ? delta : 0
contentViewContainer.alpha = 1 - (1 - CGFloat(contentViewFadeOutAlpha)) * delta
if scaleBackgroundImageView {
backgroundImageView.transform = CGAffineTransformMakeScale(backgroundViewScale, backgroundViewScale)
}
if scaleMenuView {
menuViewContainer.transform = CGAffineTransformMakeScale(menuViewScale, menuViewScale)
}
if scaleBackgroundImageView && backgroundViewScale < 1 {
backgroundImageView.transform = CGAffineTransformIdentity
}
if bouncesHorizontally && visible {
if contentViewContainer.frame.origin.x > contentViewContainer.frame.size.width / 2.0 {
point.x = min(0.0, point.x)
}
if contentViewContainer.frame.origin.x < -(contentViewContainer.frame.size.width / 2.0) {
point.x = max(0.0, point.x)
}
}
// Limit size
if point.x < 0 {
point.x = max(point.x, -UIScreen.mainScreen().bounds.size.height)
} else {
point.x = min(point.x, UIScreen.mainScreen().bounds.size.height)
}
recognizer.setTranslation(point, inView: view)
if !didNotifyDelegate {
if point.x > 0 && !visible, let viewController = leftMenuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
if point.x < 0 && !visible, let viewController = rightMenuViewController {
delegate?.sideMenuWillShowMenuViewController?(self, menuViewController: viewController)
}
didNotifyDelegate = true
}
if contentViewScale > 1 {
let oppositeScale: CGFloat = (1 - (contentViewScale - 1))
contentViewContainer.transform = CGAffineTransformMakeScale(oppositeScale, oppositeScale)
contentViewContainer.transform = CGAffineTransformTranslate(contentViewContainer.transform, point.x, 0)
} else {
contentViewContainer.transform = CGAffineTransformMakeScale(contentViewScale, contentViewScale)
contentViewContainer.transform = CGAffineTransformTranslate(contentViewContainer.transform, point.x, 0)
}
leftMenuViewController?.view.hidden = contentViewContainer.frame.origin.x < 0
rightMenuViewController?.view.hidden = contentViewContainer.frame.origin.x > 0
if leftMenuViewController == nil && contentViewContainer.frame.origin.x > 0 {
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
visible = false
leftMenuVisible = false
} else if self.rightMenuViewController == nil && contentViewContainer.frame.origin.x < 0 {
contentViewContainer.transform = CGAffineTransformIdentity
contentViewContainer.frame = view.bounds
visible = false
rightMenuVisible = false
}
statusBarNeedsAppearanceUpdate()
}
if recognizer.state == .Ended {
didNotifyDelegate = false
if panMinimumOpenThreshold > 0 &&
contentViewContainer.frame.origin.x < 0 &&
contentViewContainer.frame.origin.x > -CGFloat(panMinimumOpenThreshold) ||
contentViewContainer.frame.origin.x > 0 &&
contentViewContainer.frame.origin.x < CGFloat(panMinimumOpenThreshold) {
hideMenuViewController()
}
else if contentViewContainer.frame.origin.x == 0 {
hideMenuViewController(false)
}
else if recognizer.velocityInView(view).x > 0 {
if contentViewContainer.frame.origin.x < 0 {
hideMenuViewController()
} else if leftMenuViewController != nil {
showLeftMenuViewController()
}
}
else {
if contentViewContainer.frame.origin.x < 20 && rightMenuViewController != nil{
showRightMenuViewController()
} else {
hideMenuViewController()
}
}
}
}
}
| mit | fc8991f40c259a15f09205aec879a81e | 39.10277 | 367 | 0.634474 | 6.566433 | false | false | false | false |
CM-Studio/NotLonely-iOS | NotLonely-iOS/ViewController/Find/FindViewController.swift | 1 | 1532 | //
// FindViewController.swift
// NotLonely-iOS
//
// Created by plusub on 3/24/16.
// Copyright © 2016 cm. All rights reserved.
//
import UIKit
class FindViewController: BaseViewController {
var overlay: UIView!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension FindViewController: UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("InterestPeopleCell", forIndexPath: indexPath)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("InterestCircleCell", forIndexPath: indexPath)
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 6
} else {
return 4
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
} | mit | 96d8a62169a7505208e37a526c1753ca | 27.37037 | 113 | 0.653821 | 5.608059 | false | false | false | false |
edulpn/rxmoyatest | RxMoyaTest/RxMoyaTest/RepositoryEntity.swift | 1 | 5727 | //
// RepositoryEntity.swift
// RxMoyaTest
//
// Created by Eduardo Pinto on 8/25/17.
// Copyright © 2017 Eduardo Pinto. All rights reserved.
//
import Foundation
import ObjectMapper
struct RepositoryEntity: ImmutableMappable {
let id: Int
let name: String
let fullName: String
let owner: UserEntity
let isPrivate: Bool
let htmlURL: String
let isFork: Bool
let URL: String
let createdAt: String
// let forksURL: String
// let keysURL: String
// let collaboratorsURL: String
// let teamsURL: String
// let hooksURL: String
// let issueEventsURL: String
// let eventsURL: String
// let assigneesURL: String
// let branchesURL: String
// let tagsURL: String
// let blobsURL: String
// let gitTagsURL: String
// let gitRefsURL: String
// let treesURL: String
// let statusesURL: String
// let languagesURL: String
// let stargazersURL: String
// let contributorsURL: String
// let subscribersURL: String
// let subscriptionURL: String
// let commitsURL: String
// let gitCommitsURL: String
// let commentsURL: String
// let issueCommentURL: String
// let contentsURL: String
// let compareURL: String
// let mergesURL: String
// let archiveURL: String
// let downloadsURL: String
// let issuesURL: String
// let pullsURL: String
// let milestonesURL: String
// let notificationsURL: String
// let labelsURL: String
// let releasesURL: String
// let deploymentsURL: String
// let updatedAt: String
// let pushedAt: String
// let gitURL: String
// let sshURL: String
// let cloneURL: String
// let svnURL: String
// let homepage: String
// let size: Int
// let stargazersCount: Int
// let watchersCount: Int
// let language: String
// let hasIssues: Bool
// let hasProjects: Bool
// let hasDownloads: Bool
// let hasWiki: Bool
// let hasPages: Bool
// let forksCount: Int
// let mirrorURL: String
// let openIssuesCount: Int
// let openIssuesCount: Int
// let watchersCount: Int
// let defaultBranch: String
// let description: String
init(map: Map) throws {
id = try map.value("id")
name = try map.value("name")
fullName = try map.value("full_name")
owner = try map.value("owner")
isPrivate = try map.value("private")
htmlURL = try map.value("html_url")
isFork = try map.value("fork")
URL = try map.value("url")
createdAt = try map.value("created_at")
// forksURL = try map.value("forks_url")
// keysURL = try map.value("keys_url")
// collaboratorsURL = try map.value("collaborators_url")
// teamsURL = try map.value("teams_url")
// hooksURL = try map.value("hooks_url")
// issueEventsURL = try map.value("issue_events_url")
// eventsURL = try map.value("events_url")
// assigneesURL = try map.value("assignees_url")
// branchesURL = try map.value("branches_url")
// tagsURL = try map.value("tags_url")
// blobsURL = try map.value("blobs_url")
// gitTagsURL = try map.value("git_tags_url")
// gitRefsURL = try map.value("git_refs_url")
// treesURL = try map.value("trees_url")
// statusesURL = try map.value("statuses_url")
// languagesURL = try map.value("languages_url")
// stargazersURL = try map.value("stargazers_url")
// contributorsURL = try map.value("contributors_url")
// subscribersURL = try map.value("subscribers_url")
// subscriptionURL = try map.value("subscription_url")
// commitsURL = try map.value("commits_url")
// gitCommitsURL = try map.value("git_commits_url")
// commentsURL = try map.value("comments_url")
// issueCommentURL = try map.value("issue_comment_url")
// contentsURL = try map.value("contents_url")
// compareURL = try map.value("compare_url")
// mergesURL = try map.value("merges_url")
// archiveURL = try map.value("archive_url")
// downloadsURL = try map.value("downloads_url")
// issuesURL = try map.value("issues_url")
// pullsURL = try map.value("pulls_url")
// milestonesURL = try map.value("milestones_url")
// notificationsURL = try map.value("notifications_url")
// labelsURL = try map.value("labels_url")
// releasesURL = try map.value("releases_url")
// deploymentsURL = try map.value("deployments_url")
// createdAt = try map.value("created_at")
// updatedAt = try map.value("updated_at")
// pushedAt = try map.value("pushed_at")
// gitURL = try map.value("git_url")
// sshURL = try map.value("ssh_url")
// cloneURL = try map.value("clone_url")
// svnURL = try map.value("svn_url")
// size = try map.value("size")
// stargazersCount = try map.value("stargazers_count")
// watchersCount = try map.value("watchers_count")
// hasIssues = try map.value("has_issues")
// hasProjects = try map.value("has_projects")
// hasDownloads = try map.value("has_downloads")
// hasWiki = try map.value("has_wiki")
// hasPages = try map.value("has_pages")
// forksCount = try map.value("forks_count")
// openIssuesCount = try map.value("open_issues_count")
// openIssuesCount = try map.value("open_issues")
// watchersCount = try map.value("watchers")
// defaultBranch = try map.value("default_branch")
// description = try map.value("description")
// language = try map.value("language")
// mirrorURL = try map.value("mirror_url")
// homepage = try map.value("homepage")
}
}
| mit | b50d6f521db9186409fff4520197882c | 36.424837 | 63 | 0.620503 | 3.585473 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Revolution Tool CL/structs/SmallStructTables.swift | 1 | 4455 | //
// SmallStructTables.swift
// GoD Tool
//
// Created by Stars Momodu on 03/05/2021.
//
import Foundation
let iconsStruct = GoDStruct(name: "Pokemon Icons", format: [
.word(name: "Male Face ID", description: "", type: .fsysFileIdentifier(fsysName: "menu_face")),
.word(name: "Male Body ID", description: "", type: .fsysFileIdentifier(fsysName: "menu_pokemon")),
.word(name: "Female Face ID", description: "", type: .fsysFileIdentifier(fsysName: "menu_face")),
.word(name: "female Body ID", description: "", type: .fsysFileIdentifier(fsysName: "menu_pokemon"))
])
let iconsTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 6 : 0, "common"), properties: iconsStruct, documentByIndex: false)
let pokemonFacesStruct = GoDStruct(name: "Pokemon Faces", format: [
.word(name: "Species", description: "", type: .pokemonID),
.short(name: "Icons Index", description: "", type: .indexOfEntryInTable(table: iconsTable, nameProperty: nil)),
.bitMask(name: "Forms", description: "Divide by 2 for form count, last bit is unknown but seems set for NFE pokemon?", length: .short, values: [
(name: "Form Count", type: .uint, numberOfBits: 15, firstBitIndexLittleEndian: 1, mod: nil, div: nil, scale: nil),
(name: "Has an Evolution", type: .bool, numberOfBits: 1, firstBitIndexLittleEndian: 0, mod: nil, div: nil, scale: nil),
]),
])
let pokemonFacesTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 5 : 22, "common"), properties: pokemonFacesStruct) { (index, entry) -> String? in
if let species: Int = entry.get("Species") {
return XGPokemon.index(species).name.unformattedString
}
return nil
}
let pokemonBodiesStruct = GoDStruct(name: "Pokemon Bodies", format: [
.word(name: "Species", description: "", type: .pokemonID),
.short(name: "Icons Index", description: "", type: .indexOfEntryInTable(table: iconsTable, nameProperty: nil)),
.short(name: "Forms Count", description: "", type: .uint),
.array(name: "Unknowns", description: "", property:
.byte(name: "", description: "", type: .uintHex), count: 4)
])
let pokemonBodiesTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 5 : 22, "common"), properties: pokemonBodiesStruct) { (index, entry) -> String? in
if let species: Int = entry.get("Species") {
return XGPokemon.index(species).name.unformattedString
}
return nil
}
let pokecouponShopStruct = GoDStruct(name: "Pokecoupon Rewards", format: [
.short(name: "Coupon Price (in thousands)", description: "Multiply this by 1000 to get the price", type: .int),
.short(name: "Pokemon or Item ID", description: "Meaning depends on the 'Is Pokemon' flag", type: .uintHex),
.short(name: "Name ID", description: "", type: .msgID(file: nil)),
.short(name: "Description ID", description: "", type: .msgID(file: nil)),
.short(name: "Unknown ID", description: "", type: .uintHex),
.bitArray(name: "Flags", description: "", bitFieldNames: ["Is Pokemon"])
])
let pokecouponShopTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 8 : 2, "common"), properties: pokecouponShopStruct)
let experienceStruct = GoDStruct(name: "Experience Table", format: [
.word(name: "Experience For Level 0", description: "", type: .uint),
.array(name: "Experience For Level", description: "", property:
.word(name: "", description: "", type: .uint), count: 100),
])
let experienceTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 11 : 5, "common"), properties: experienceStruct) { (index, data) -> String? in
return XGExpRate(rawValue: index)?.string ?? "Experience Rate \(index)"
}
let tmsStruct = GoDStruct(name: "TMs", format: [
.short(name: "Move", description: "", type: .moveID),
.byte(name: "Chance for random selection", description: "0 means never selected for random moves on npc mons", type: .uint)
])
let tmsTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 30 : 29, "common"), properties: tmsStruct) { (index, data) -> String? in
if let move: Int = data.get("Move") {
return XGMoves.index(move).name.unformattedString
}
return nil
}
let trainerTitlesStruct = GoDStruct(name: "Trainer Titles", format: [
.short(name: "Name", description: "", type: .msgID(file: nil)),
.array(name: "Quotes", description: "", property: .short(name: "Quote", description: "", type: .msgID(file: nil)), count: 6)
])
let trainerTitlesTable = CommonStructTable(file: .indexAndFsysName(region == .JP ? 22 : 28, "common"), properties: trainerTitlesStruct)
| gpl-2.0 | 7d6b4d9cecc280e65b81da8d592ee681 | 52.035714 | 165 | 0.700561 | 3.30735 | false | false | false | false |
huonw/swift | test/stdlib/TestProgress.swift | 39 | 2709 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if FOUNDATION_XCTEST
import XCTest
class TestProgressSuper : XCTestCase { }
#else
import StdlibUnittest
class TestProgressSuper { }
#endif
class TestProgress : TestProgressSuper {
func testUserInfoConveniences() {
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let p = Progress(parent:nil, userInfo: nil)
expectNil(p.userInfo[.throughputKey])
expectNil(p.throughput)
p.throughput = 50
expectEqual(p.throughput, 50)
expectNotNil(p.userInfo[.throughputKey])
expectNil(p.userInfo[.estimatedTimeRemainingKey])
expectNil(p.estimatedTimeRemaining)
p.estimatedTimeRemaining = 100
expectEqual(p.estimatedTimeRemaining, 100)
expectNotNil(p.userInfo[.estimatedTimeRemainingKey])
expectNil(p.userInfo[.fileTotalCountKey])
expectNil(p.fileTotalCount)
p.fileTotalCount = 42
expectEqual(p.fileTotalCount, 42)
expectNotNil(p.userInfo[.fileTotalCountKey])
expectNil(p.userInfo[.fileCompletedCountKey])
expectNil(p.fileCompletedCount)
p.fileCompletedCount = 24
expectEqual(p.fileCompletedCount, 24)
expectNotNil(p.userInfo[.fileCompletedCountKey])
}
}
func testPerformAsCurrent() {
if #available(OSX 10.11, iOS 8.0, *) {
// This test can be enabled once <rdar://problem/31867347> is in the SDK
/*
let p = Progress.discreteProgress(totalUnitCount: 10)
let r = p.performAsCurrent(withPendingUnitCount: 10) {
expectNotNil(Progress.current())
return 42
}
expectEqual(r, 42)
expectEqual(p.completedUnitCount, 10)
expectNil(Progress.current())
*/
}
}
}
#if !FOUNDATION_XCTEST
let ProgressTests = TestSuite("TestProgress")
ProgressTests.test("testUserInfoConveniences") { TestProgress().testUserInfoConveniences() }
ProgressTests.test("testPerformAsCurrent") { TestProgress().testPerformAsCurrent() }
runAllTests()
#endif
| apache-2.0 | 6d3998ed40be3110097f7cd573807bb2 | 34.644737 | 92 | 0.613511 | 4.736014 | false | true | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/CompLayers/PreCompositionLayer.swift | 1 | 3336 | //
// PreCompositionLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import Foundation
import QuartzCore
final class PreCompositionLayer: CompositionLayer {
let frameRate: CGFloat
let remappingNode: NodeProperty<Vector1D>?
fileprivate var animationLayers: [CompositionLayer]
init(precomp: PreCompLayerModel,
asset: PrecompAsset,
layerImageProvider: LayerImageProvider,
textProvider: AnimationTextProvider,
assetLibrary: AssetLibrary?,
frameRate: CGFloat) {
self.animationLayers = []
if let keyframes = precomp.timeRemapping?.keyframes {
self.remappingNode = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframes))
} else {
self.remappingNode = nil
}
self.frameRate = frameRate
super.init(layer: precomp, size: CGSize(width: precomp.width, height: precomp.height))
masksToBounds = true
bounds = CGRect(origin: .zero, size: CGSize(width: precomp.width, height: precomp.height))
let layers = asset.layers.initializeCompositionLayers(assetLibrary: assetLibrary, layerImageProvider: layerImageProvider, textProvider: textProvider, frameRate: frameRate)
var imageLayers = [ImageCompositionLayer]()
var mattedLayer: CompositionLayer? = nil
for layer in layers.reversed() {
layer.bounds = bounds
animationLayers.append(layer)
if let imageLayer = layer as? ImageCompositionLayer {
imageLayers.append(imageLayer)
}
if let matte = mattedLayer {
/// The previous layer requires this layer to be its matte
matte.matteLayer = layer
mattedLayer = nil
continue
}
if let matte = layer.matteType,
(matte == .add || matte == .invert) {
/// We have a layer that requires a matte.
mattedLayer = layer
}
contentsLayer.addSublayer(layer)
}
self.childKeypaths.append(contentsOf: layers)
layerImageProvider.addImageLayers(imageLayers)
}
override init(layer: Any) {
/// Used for creating shadow model layers. Read More here: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
guard let layer = layer as? PreCompositionLayer else {
fatalError("init(layer:) Wrong Layer Class")
}
self.frameRate = layer.frameRate
self.remappingNode = nil
self.animationLayers = []
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) {
let localFrame: CGFloat
if let remappingNode = remappingNode {
remappingNode.update(frame: frame)
localFrame = remappingNode.value.cgFloatValue * frameRate
} else {
localFrame = (frame - startFrame) / timeStretch
}
animationLayers.forEach( { $0.displayWithFrame(frame: localFrame, forceUpdates: forceUpdates) })
}
override var keypathProperties: [String : AnyNodeProperty] {
guard let remappingNode = remappingNode else {
return super.keypathProperties
}
return ["Time Remap" : remappingNode]
}
override func updateRenderScale() {
super.updateRenderScale()
animationLayers.forEach( { $0.renderScale = renderScale } )
}
}
| mit | 2d52bac681afc70b7b68733bf8dc9d8d | 31.38835 | 175 | 0.690647 | 4.502024 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournalTests/WrappedModels/NoteTest.swift | 1 | 1814 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
@testable import third_party_sciencejournal_ios_ScienceJournalProtos
class NoteTest: XCTestCase {
func testNoteCopying() {
let proto = GSJLabel()
proto.timestampMs = 123456
let textValue = GSJTextLabelValue()
textValue.text = "foo text"
proto.protoData = textValue.data()!
let note = Note(proto: proto)
let copy = note.copy()
XCTAssertTrue(note.ID == copy.ID)
XCTAssertFalse(note === copy)
XCTAssertEqual(note.timestamp, copy.timestamp)
XCTAssertEqual(note.proto.protoData, copy.proto.protoData)
XCTAssertEqual(123456, note.timestamp)
}
func testNoteCopyingWithNewID() {
let proto = GSJLabel()
proto.timestampMs = 123456
let textValue = GSJTextLabelValue()
textValue.text = "foo text"
proto.protoData = textValue.data()!
let note = Note(proto: proto)
let copy = note.copyWithNewID()
XCTAssertFalse(note.ID == copy.ID)
XCTAssertFalse(note === copy)
XCTAssertEqual(note.timestamp, copy.timestamp)
XCTAssertEqual(note.proto.protoData, copy.proto.protoData)
XCTAssertEqual(123456, note.timestamp)
}
}
| apache-2.0 | 44864ef11544fd162ef3e640b7648af4 | 32.592593 | 76 | 0.720507 | 4.040089 | false | true | false | false |
tensorflow/examples | lite/examples/gesture_classification/ios/GestureClassification/Views/CurvedView.swift | 1 | 1082 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class CurvedView: UIView {
let cornerRadius: CGFloat = 24.0
override func layoutSubviews() {
super.layoutSubviews()
setCornerMask()
}
func setCornerMask() {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
self.layer.mask = shapeLayer
}
}
| apache-2.0 | f8bc7d8b573180643ed8ceeff154cd9e | 30.823529 | 159 | 0.733826 | 4.345382 | false | false | false | false |
MORZorg/i3DAudio | sources/iOS_src/i3DAudio/SourceScene.swift | 1 | 3356 | //
// GameScene.swift
// i3DAudio
//
// Created by Maurizio Zucchelli on 13/07/14.
// Copyright (c) 2014 MORZorg. All rights reserved.
//
import SpriteKit
extension CGPoint {
func bearingTowards(point: CGPoint) -> CGFloat {
return atan2(point.y - y, point.x - x)
}
}
class SourceScene: SKScene {
var shownPerspective: String?
var headNodeHandler: HeadNodeHandler?
var headTouch: AnyObject?
var sourceNodeHandler: SourceNodeHandler?
var sourceTouch: AnyObject?
override func didMoveToView(view: SKView) {
let headNode = self.childNodeWithName("head")!
let sourceNode = self.childNodeWithName("source")!
switch shownPerspective {
case let perspective where perspective == "top":
headNodeHandler = TopHeadNodeHandler(node: headNode)
sourceNodeHandler = TopSourceNodeHandler(node: sourceNode)
case let perspective where perspective == "front":
headNodeHandler = FrontHeadNodeHandler(node: headNode)
sourceNodeHandler = FrontSourceNodeHandler(node: sourceNode)
case let perspective where perspective == "side":
headNodeHandler = SideHeadNodeHandler(node: headNode)
sourceNodeHandler = SideSourceNodeHandler(node: sourceNode)
default:
headNodeHandler = HeadNodeHandler(node: headNode)
sourceNodeHandler = SourceNodeHandler(node: sourceNode)
}
headNode.runAction(SKAction.setTexture(headNodeHandler!.getTexture()!))
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in touches {
if sourceNodeHandler?.node == nodeAtPoint(touch.locationInNode(self)) {
sourceTouch = touch
}
else if headNodeHandler?.node == nodeAtPoint(touch.locationInNode(self)) {
headTouch = touch
}
}
if headTouch == nil {
sourceTouch = touches.anyObject()
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch moves */
if let location = sourceTouch?.locationInNode(self) {
sourceNodeHandler?.changePosition(location)
}
if let location = headTouch?.locationInNode(self) {
headNodeHandler?.changeRotation(headNodeHandler!.node.position.bearingTowards(location))
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch ends */
touchesMoved(touches, withEvent: event)
headTouch = nil
sourceTouch = nil
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if let sourceHandler = sourceNodeHandler {
if let headHandler = headNodeHandler {
sourceHandler.updatePosition()
headHandler.updateRotation()
if sourceHandler.hasChanged {
sourceHandler.node.zRotation = sourceHandler.node.position.bearingTowards(headHandler.node.position)
sourceHandler.hasChanged = false
}
}
}
}
}
| gpl-2.0 | 7dc9c084f984070945666aa147cbf44c | 33.958333 | 120 | 0.618594 | 4.870827 | false | false | false | false |
Alexiuce/Tip-for-day | Tip for Day Demo/Core Image Demo/ViewController.swift | 1 | 3309 | //
// ViewController.swift
// Core Image Demo
//
// Created by alexiuce on 2017/6/20.
// Copyright © 2017年 com.Alexiuce. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var finalImageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let img = UIImage(named: "58")!
imageView.image = img
handleImage(img)
}
}
func Max8(_ x : uint) -> uint{
return ((x) & 0xff)
}
func R(_ x : uint) -> uint{
return Max8(x)
}
func G(_ x : uint) -> uint{
return Max8((x) >> 8)
}
func B(_ x: uint) -> uint{
return Max8((x) >> 16)
}
extension ViewController{
fileprivate func handleImage(_ targetImage : UIImage){
guard let inputImage = targetImage.cgImage else {return} // UIImage -> CGImage
let imgWidth = inputImage.width
let imgHeight = inputImage.height
let bytesPerPixel = 4 // 每像素用4个字节(32位 表示 RGBA的颜色空间)
let bitPerCompent = 8 // RGBA中每个部分用 8 个bit
let bytesPerRow = bytesPerPixel * imgWidth // 每行的字节数
var pixels = calloc(imgHeight * imgWidth, MemoryLayout<uint>.size) // 申请内存空间,尺寸为图片的size,单个单元的大小为UInt(也就是32)位
let colorSpace = CGColorSpaceCreateDeviceRGB() // 创建RGB颜色空间
let bmpAlpha = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue // 设置位图的alpha通道信息
let context = CGContext(data: pixels, width: imgWidth, height: imgHeight, bitsPerComponent: bitPerCompent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bmpAlpha) // 创建绘图上下文
context?.draw(inputImage, in: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight)) // 绘制图片到指定图形上下文中的区域
// 遍历图片像素
for _ in 0 ..< imgWidth {
for _ in 0 ..< imgHeight {
let pix = pixels!.assumingMemoryBound(to: uint.self) // 声明指针的内存布局,与定义时要保持一直(参见51行)
// let pixValue = pix.pointee // 获取指针内存中的数据
/* Core Image 中的颜色空间是ABGR: 即 透明度 蓝色 绿色 红色,如下图
00000000 | 00000000 | 00000000 | 0000000
| <-透明度-> |<- 蓝色 ->|<- 绿色 ->| <- 红色 ->|
*/
// pix.pointee = pix.pointee & 0xff0000ff // 只保留红色
pix.pointee = pix.pointee & 0xff00ff00 // 只保留绿色
// pix.pointee = pix.pointee & 0xffff0000 // 只保留蓝色
// print((R(pixValue) + G(pixValue) + B(pixValue)) / 3,terminator:" ")
pixels = pixels?.advanced(by:MemoryLayout<uint>.size) // 移动指针到下个位置
}
}
let newCGImage = context!.makeImage()! // 从图形上下文中获取图片
let newImage = UIImage(cgImage: newCGImage) // CGImage -> UIImage
finalImageView.image = newImage // 显示图片(CPU执行处理)
}
}
| mit | 0405a476cfb86c0382ea48eb9145d472 | 35.518987 | 193 | 0.588908 | 3.689258 | false | false | false | false |
yangligeryang/codepath | labs/DetailViewDemo/DetailViewDemo/PhotoViewController.swift | 1 | 1288 | //
// PhotoViewController.swift
// DetailViewDemo
//
// Created by Yang Yang on 11/15/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController {
var selectedImageView: UIImageView!
var detailZoomTransition: DetailZoomTransition!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
detailZoomTransition = DetailZoomTransition()
detailZoomTransition.duration = 1
let detailViewController = segue.destination as! DetailViewController
detailViewController.modalPresentationStyle = .custom
detailViewController.transitioningDelegate = detailZoomTransition
detailViewController.image = selectedImageView.image
}
@IBAction func didTapImage(_ sender: UITapGestureRecognizer) {
selectedImageView = sender.view as! UIImageView
performSegue(withIdentifier: "detailSegue", sender: nil)
}
}
| apache-2.0 | 1b8c76194c60037c8445159bac4d681c | 29.642857 | 80 | 0.698524 | 5.745536 | false | false | false | false |
hovansuit/FoodAndFitness | FoodAndFitness/Controllers/UserFoodsDetail/UserFoodsDetailController.swift | 1 | 8742 | //
// UserFoodsDetailController.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/16/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import SwiftUtils
final class UserFoodsDetailController: BaseViewController {
@IBOutlet fileprivate(set) weak var tableView: TableView!
var viewModel: UserFoodsDetailViewModel!
override var isNavigationBarHidden: Bool {
return true
}
enum Sections: Int {
case userFoods
case information
case suggestion
static var count: Int {
return self.suggestion.hashValue + 1
}
var title: String {
switch self {
case .userFoods:
return Strings.empty
case .information:
return Strings.informationNutrion
case .suggestion:
return Strings.suggestionNutrion
}
}
var heightForHeader: CGFloat {
switch self {
case .userFoods:
return 224
default:
return 70
}
}
}
enum InformationRows: Int {
case calories
case protein
case carbs
case fat
static var count: Int {
return self.fat.rawValue + 1
}
var title: String {
switch self {
case .calories:
return Strings.calories
case .protein:
return Strings.protein
case .carbs:
return Strings.carbs
case .fat:
return Strings.fat
}
}
}
override func setupUI() {
super.setupUI()
title = viewModel.activity.title
configureTableView()
configureViewModel()
}
private func configureTableView() {
tableView.register(AddUserFoodCell.self)
tableView.register(UserFoodCell.self)
tableView.register(InfomationNutritionCell.self)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
private func configureViewModel() {
viewModel.delegate = self
}
}
// MARK: - UserFoodsDetailViewModelDelegate
extension UserFoodsDetailController: UserFoodsDetailViewModelDelegate {
func viewModel(_ viewModel: UserFoodsDetailViewModel, needsPerformAction action: UserFoodsDetailViewModel.Action) {
switch action {
case .userFoodChanged:
tableView.reloadData()
}
}
}
// MARK: - UITableViewDataSource
extension UserFoodsDetailController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userFoods:
return viewModel.userFoods.count + 1
case .information:
return InformationRows.count
case .suggestion:
return viewModel.suggestFoods.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userFoods:
switch indexPath.row {
case 0:
let cell = tableView.dequeue(AddUserFoodCell.self)
cell.data = viewModel.dataForAddButton()
cell.delegate = self
return cell
default:
let cell = tableView.dequeue(UserFoodCell.self)
cell.accessoryType = .none
cell.data = viewModel.dataForUserFood(at: indexPath.row - 1)
return cell
}
case .information:
guard let rows = InformationRows(rawValue: indexPath.row) else {
fatalError(Strings.Errors.enumError)
}
let cell = tableView.dequeue(InfomationNutritionCell.self)
cell.data = viewModel.dataForInformationNutrition(at: rows)
return cell
case .suggestion:
let cell = tableView.dequeue(UserFoodCell.self)
cell.accessoryType = .disclosureIndicator
cell.data = viewModel.dataForSuggestFood(at: indexPath.row)
return cell
}
}
}
// MARK: - UITableViewDelegate
extension UserFoodsDetailController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userFoods: break
case .information: break
case .suggestion:
let foods = viewModel.suggestFoods
guard indexPath.row >= 0, indexPath.row < foods.count else { break }
let foodDetailController = FoodDetailController()
foodDetailController.viewModel = FoodDetailViewModel(food: foods[indexPath.row], activity: viewModel.activity)
navigationController?.pushViewController(foodDetailController, animated: true)
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userFoods:
return true
case .information, .suggestion:
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
viewModel.delete(at: indexPath.row - 1, completion: { (result) in
switch result {
case .success(_):
tableView.deleteRows(at: [indexPath], with: .automatic)
case .failure(let error):
error.show()
}
})
default: break
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
return sections.heightForHeader
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
if sections == .userFoods && indexPath.row == 0 { return 60 }
return 55
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
if sections == .userFoods && viewModel.userFoods.isEmpty {
return .leastNormalMagnitude
} else {
return 10
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userFoods:
let headerView: MealHeaderView = MealHeaderView.loadNib()
headerView.delegate = self
headerView.data = viewModel.dataForHeaderView()
return headerView
default:
let headerView: TitleCell = TitleCell.loadNib()
headerView.data = TitleCell.Data(title: sections.title)
return headerView.contentView
}
}
}
// MARK: - MealHeaderViewDelegate
extension UserFoodsDetailController: MealHeaderViewDelegate {
func view(_ view: MealHeaderView, needsPerformAction action: MealHeaderView.Action) {
back(view.backButton)
}
}
// MARK: - AddUserFoodCellDelegate
extension UserFoodsDetailController: AddUserFoodCellDelegate {
func cell(_ cell: AddUserFoodCell, needsPerformAction action: AddUserFoodCell.Action) {
switch action {
case .add:
let addActivityController = AddActivityController()
addActivityController.viewModel = AddActivityViewModel(activity: viewModel.activity)
navigationController?.pushViewController(addActivityController, animated: true)
}
}
}
| mit | f0cc907ed7bc5dfd4e9c54647a083812 | 31.737828 | 127 | 0.612859 | 5.362577 | false | false | false | false |
drmohundro/Quick | Examples/Scenester/Scenester/Commit+Network.swift | 1 | 2189 | //
// Commit+Network.swift
// Scenester
//
// Created by Brian Ivan Gesiak on 6/10/14.
// Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved.
//
import Foundation
extension Commit {
public static func latestCommit(repo: String,
success: (commit: Commit) -> (), failure: (error: NSError) -> ()) {
let endpoint = "https://api.github.com/repos/\(repo)/commits"
let request = NSURLRequest(URL: NSURL(string: endpoint))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(),
completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) in
if error {
failure(error: error)
return
}
var jsonError : NSError?
let json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.fromRaw(0)!, error: &jsonError)
if jsonError.hasValue {
failure(error: jsonError!)
return
}
if let commits = json as? [NSDictionary] {
if commits.count == 0 {
failure(error: self.commitError(CommitErrorCode.NoCommits))
} else {
let latest = commits[0]
if let message = latest.valueForKeyPath("commit.message") as? String {
if let author = latest.valueForKeyPath("author.login") as? String {
let commit = Commit(message: message, author: author)
success(commit: commit)
return
}
}
failure(error: self.commitError(CommitErrorCode.InvalidCommit))
}
} else {
failure(error: self.commitError(CommitErrorCode.InvalidResponse))
}
})
}
}
| mit | 7fda0889d232dcc965d160792bf68de5 | 40.301887 | 99 | 0.47556 | 5.791005 | false | true | false | false |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Classes/Repository/RequestFactory.swift | 1 | 7335 | //
// RequestFactory.swift
// NStackSDK
//
// Created by Dominik Hadl on 25/09/2018.
// Copyright © 2018 Nodes ApS. All rights reserved.
//
import Foundation
public struct RequestFactory {
public var baseUrl: String
public var route: Routes
public init(baseUrl: String, route: Routes) {
self.baseUrl = baseUrl
self.route = route
}
public var path: String {
switch self.route {
case .identifyCustomer: return baseUrl + "/track/v2/projects/\(projectToken)/customers"
case .customEvent: return baseUrl + "/track/v2/projects/\(projectToken)/customers/events"
case .customerRecommendation: return baseUrl + "/data/v2/projects/\(projectToken)/customers/attributes"
case .customerAttributes: return baseUrl + "/data/v2/\(projectToken)/customers/attributes"
case .customerEvents: return baseUrl + "/data/v2/projects/\(projectToken)/customers/events"
case .banners: return baseUrl + "/data/v2/projects/\(projectToken)/configuration/banners"
case .personalization:
return baseUrl + "/data/v2/projects/\(projectToken)/customers/personalisation/show-banners"
}
}
public var method: HTTPMethod { return .post }
}
extension RequestFactory {
func prepareRequest(authorization: Authorization,
parameters: RequestParametersType? = nil,
customerIds: [String: JSONValue]? = nil) -> URLRequest {
var request = URLRequest(url: URL(string: path)!)
// Create the basic request
request.httpMethod = method.rawValue
request.addValue(Constants.Repository.contentType,
forHTTPHeaderField: Constants.Repository.headerContentType)
request.addValue(Constants.Repository.contentType,
forHTTPHeaderField: Constants.Repository.headerAccept)
// Add authorization if it was provided
switch authorization {
case .none: break
case .basic(let secret):
request.addValue("Basic \(secret)",
forHTTPHeaderField: Constants.Repository.headerAuthorization)
}
// Add parameters as request body in JSON format, if we have any
if let parameters = parameters?.requestParameters {
var params = parameters
// Add customer ids if separate
if let customerIds = customerIds {
params["customer_ids"] = customerIds.mapValues({ $0.jsonConvertible })
}
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
} catch {
Exponea.logger.log(.error,
message: "Failed to serialise request body into JSON: \(error.localizedDescription)")
Exponea.logger.log(.verbose, message: "Request parameters: \(params)")
}
}
// Log request if necessary
if Exponea.logger.logLevel == .verbose {
Exponea.logger.log(.verbose, message: "Created request: \n\(request.description)")
}
return request
}
typealias CompletionHandler = ((Data?, URLResponse?, Error?) -> Void)
func handler<T: ErrorInitialisable>(with completion: @escaping ((EmptyResult<T>) -> Void)) -> CompletionHandler {
return { (data, response, error) in
self.process(response, data: data, error: error, resultAction: { (result) in
switch result {
case .success:
DispatchQueue.main.async {
completion(.success)
}
case .failure(let error):
DispatchQueue.main.async {
let error = T.create(from: error)
completion(.failure(error))
}
}
})
}
}
func handler<T: Decodable>(with completion: @escaping ((Result<T>) -> Void)) -> CompletionHandler {
return { (data, response, error) in
self.process(response, data: data, error: error, resultAction: { (result) in
switch result {
case .success(let data):
do {
let object = try JSONDecoder().decode(T.self, from: data)
DispatchQueue.main.async {
completion(.success(object))
}
} catch {
DispatchQueue.main.async {
completion(.failure(error))
}
}
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
}
})
}
}
func process(_ response: URLResponse?, data: Data?, error: Error?,
resultAction: @escaping ((Result<Data>) -> Void)) {
// Check if we have any response at all
guard let response = response else {
DispatchQueue.main.async {
resultAction(.failure(RepositoryError.connectionError))
}
return
}
// Log response if needed
if Exponea.logger.logLevel == .verbose {
Exponea.logger.log(.verbose, message: """
Response received:
\(response.description(with: data, error: error))
""")
}
// Make sure we got the correct response type
guard let httpResponse = response as? HTTPURLResponse else {
DispatchQueue.main.async {
resultAction(.failure(RepositoryError.invalidResponse(response)))
}
return
}
if let error = error {
//handle server errors
switch httpResponse.statusCode {
case 500..<600:
resultAction(.failure(RepositoryError.serverError(nil)))
default:
resultAction(.failure(error))
}
} else if let data = data {
let decoder = JSONDecoder()
// Switch on status code
switch httpResponse.statusCode {
case 400, 405..<500:
let text = String(data: data, encoding: .utf8)
resultAction(.failure(RepositoryError.missingData(text ?? httpResponse.description)))
case 401:
let response = try? decoder.decode(ErrorResponse.self, from: data)
resultAction(.failure(RepositoryError.notAuthorized(response)))
case 404:
let errorResponse = try? decoder.decode(MultipleErrorResponse.self, from: data)
resultAction(.failure(RepositoryError.urlNotFound(errorResponse)))
case 500...Int.max:
let errorResponse = try? decoder.decode(MultipleErrorResponse.self, from: data)
resultAction(.failure(RepositoryError.serverError(errorResponse)))
default:
// We assume all other status code are a success
resultAction(.success(data))
}
} else {
resultAction(.failure(RepositoryError.invalidResponse(response)))
}
}
}
| mit | a7e46e1b805b8d3cca224b3a8c54899d | 39.076503 | 120 | 0.560676 | 5.287671 | false | false | false | false |
brave/browser-ios | Client/Frontend/Browser/LoginsHelper.swift | 1 | 9494 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
import WebKit
import Deferred
import SwiftyJSON
private let log = Logger.browserLogger
class LoginsHelper: BrowserHelper {
fileprivate let profile: Profile
weak var browser: Browser?
var snackBar: SnackBar?
// Exposed for mocking purposes
var logins: BrowserLogins {
return profile.logins
}
required init(browser: Browser, profile: Profile) {
self.browser = browser
self.profile = profile
if let path = Bundle.main.path(forResource: "LoginsHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
static func scriptMessageHandlerName() -> String? {
return "loginsManagerMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard var res = message.body as? [String: Any] else { return }
guard let type = res["type"] as? String else { return }
// We don't use the WKWebView's URL since the page can spoof the URL by using document.location
// right before requesting login data. See bug 1194567 for more context.
if let url = message.frameInfo.request.url {
// Since responses go to the main frame, make sure we only listen for main frame requests
// to avoid XSS attacks.
if message.frameInfo.isMainFrame && type == "request" {
res["username"] = ""
res["password"] = ""
if let login = Login.fromScript(url, script: res),
let requestId = res["requestId"] as? String {
requestLogins(login, requestId: requestId)
}
} else if type == "submit" {
if self.profile.prefs.boolForKey("saveLogins") ?? true {
if let login = Login.fromScript(url, script: res) {
setCredentials(login)
}
}
}
}
}
class func replace(_ base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in keys.enumerated() {
let replace = replacements[index]
let range = string.range(of: key,
options: NSString.CompareOptions.literal,
range: nil,
locale: nil)!
string.replaceSubrange(range, with: replace)
let nsRange = NSMakeRange(string.characters.distance(from: string.startIndex, to: range.lowerBound),
replace.characters.count)
ranges.append(nsRange)
}
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)
attributes[NSAttributedStringKey.foregroundColor] = UIColor.darkGray
let attr = NSMutableAttributedString(string: string, attributes: attributes)
let font: UIFont = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
for (_, range) in ranges.enumerated() {
attr.addAttribute(NSAttributedStringKey.font, value: font, range: range)
}
return attr
}
func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
return profile.logins.getLoginsForProtectionSpace(protectionSpace)
}
func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success {
return profile.logins.updateLoginByGUID(guid, new: new, significant: significant)
}
func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success {
return profile.logins.removeLoginsWithGUIDs(guids)
}
func setCredentials(_ login: LoginData) {
if login.password.isEmpty {
log.debug("Empty password")
return
}
succeed().upon() { _ in // move off main
self.profile.logins
.getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username)
.uponQueue(DispatchQueue.main) { res in
if let data = res.successValue {
log.debug("Found \(data.count) logins.")
for saved in data {
if let saved = saved {
if saved.password == login.password {
self.profile.logins.addUseOfLoginByGUID(saved.guid)
return
}
self.promptUpdateFromLogin(login: saved, toLogin: login)
return
}
}
}
self.promptSave(login)
}
}
}
fileprivate func promptSave(_ login: LoginData) {
guard login.isValid.isSuccess else {
return
}
let promptMessage: NSAttributedString
if let username = login.username {
let promptStringFormat = Strings.Save_login_for_template
promptMessage = NSAttributedString(string: String(format: promptStringFormat, username, login.hostname))
} else {
let promptStringFormat = Strings.Save_password_for_template
promptMessage = NSAttributedString(string: String(format: promptStringFormat, login.hostname))
}
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "key"),
buttons: [
SnackButton(title: Strings.DontSave, accessibilityIdentifier: "", callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
}),
SnackButton(title: Strings.SaveLogin, accessibilityIdentifier: "", callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
succeed().upon { _ in // move off main thread
self.profile.logins.addLogin(login)
}
})
])
browser?.addSnackbar(snackBar!)
}
fileprivate func promptUpdateFromLogin(login old: LoginData, toLogin new: LoginData) {
guard new.isValid.isSuccess else {
return
}
let guid = old.guid
let formatted: String
if let username = new.username {
let promptStringFormat = Strings.Update_login_for_template
formatted = String(format: promptStringFormat, username, new.hostname)
} else {
let promptStringFormat = Strings.Update_password_for_template
formatted = String(format: promptStringFormat, new.hostname)
}
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "key"),
buttons: [
SnackButton(title: Strings.DontSave, accessibilityIdentifier: "", callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
}),
SnackButton(title: Strings.Update, accessibilityIdentifier: "", callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.updateLoginByGUID(guid, new: new,
significant: new.isSignificantlyDifferentFrom(old))
})
])
browser?.addSnackbar(snackBar!)
}
fileprivate func requestLogins(_ login: LoginData, requestId: String) {
succeed().upon() { _ in // move off main thread
getApp().profile?.logins.getLoginsForProtectionSpace(login.protectionSpace).uponQueue(DispatchQueue.main) { res in
var jsonObj = [String: Any]()
if let cursor = res.successValue {
log.debug("Found \(cursor.count) logins.")
jsonObj["requestId"] = requestId
jsonObj["name"] = "RemoteLogins:loginsFound"
jsonObj["logins"] = cursor.map { $0!.toDict() }
}
let json = JSON(jsonObj)
let src = "window.__firefox__.logins.inject(\(json.rawString() ?? ""))"
self.browser?.webView?.evaluateJavaScript(src, completionHandler: nil)
}
}
}
}
| mpl-2.0 | 1745b710573583861a512e0ee57ca602 | 39.922414 | 184 | 0.582473 | 5.36991 | false | false | false | false |
simplepanda/SimpleSQL | Sources/SSConnectionEncoding.swift | 1 | 2558 | //
// Part of SimpleSQL
// https://github.com/simplepanda/SimpleSQL
//
// Created by Dylan Neild - July 2016
// [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MySQL
extension SSConnection {
// Get information about the server we're connected to.
//
public func getCharacterSet() -> SSCharacterEncoding {
return SSUtils.translateCharacterString(chars: mysql_character_set_name(mysql))
}
/**
Get a string in the connection centric character set, as a Data object.
- Parameters:
- from: The string to encode into data.
- Returns: A Data object, representing the original string as encoded data.
*/
public func stringToConnectionEncoding(_ from: String) -> Data? {
return from.data(using: getCharacterSet().getPlatformEncoding(), allowLossyConversion: false)
}
/**
SQL Escape a String using the current connection character encoding
- Parameters:
- from: The String to escape
- Returns: The String, escaped and encoded into the connecton character encoding.
*/
public func escapeString(_ from: String) -> String? {
guard let encoded = stringToConnectionEncoding(from) else {
return nil
}
let sourceLength = encoded.count
let targetLength = (sourceLength * 2) + 1
let buffer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>.allocate(capacity: targetLength)
let conversionSize = encoded.withUnsafeBytes { (ptr: UnsafePointer<Int8>) -> UInt in
return mysql_real_escape_string(mysql, buffer, ptr, UInt(sourceLength))
}
guard conversionSize >= 0 else {
return nil
}
let r = SSUtils.encodingDataToString(chars: buffer, characterSet: getCharacterSet())
buffer.deallocate(capacity: targetLength)
return r
}
}
| apache-2.0 | db7520e81efed20bffb25312bd2d643f | 32.220779 | 109 | 0.648944 | 4.693578 | false | false | false | false |
darina/omim | iphone/Chart/Chart/Views/ChartPreviewView.swift | 5 | 7877 | import UIKit
protocol ChartPreviewViewDelegate: AnyObject {
func chartPreviewView(_ view: ChartPreviewView, didChangeMinX minX: Int, maxX: Int)
}
class TintView: UIView {
let maskLayer = CAShapeLayer()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
maskLayer.fillRule = .evenOdd
layer.mask = maskLayer
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func updateViewport(_ viewport: CGRect) {
let cornersMask = UIBezierPath(roundedRect: bounds, cornerRadius: 5)
let rectMask = UIBezierPath(rect: viewport.insetBy(dx: 11, dy: 1))
let result = UIBezierPath()
result.append(cornersMask)
result.append(rectMask)
result.usesEvenOddFillRule = true
maskLayer.path = result.cgPath
}
}
class ViewPortView: ExpandedTouchView {
let maskLayer = CAShapeLayer()
var tintView: TintView?
override init(frame: CGRect = .zero) {
super.init(frame: frame)
maskLayer.fillRule = .evenOdd
layer.mask = maskLayer
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override var frame: CGRect {
didSet {
maskLayer.path = makeMaskPath().cgPath
tintView?.updateViewport(convert(bounds, to: tintView))
}
}
func makeMaskPath() -> UIBezierPath {
let cornersMask = UIBezierPath(roundedRect: bounds, cornerRadius: 5)
let rectMask = UIBezierPath(rect: bounds.insetBy(dx: 11, dy: 1))
let result = UIBezierPath()
result.append(cornersMask)
result.append(rectMask)
result.usesEvenOddFillRule = true
return result
}
}
class ChartPreviewView: ExpandedTouchView {
let previewContainerView = UIView()
let viewPortView = ViewPortView()
let leftBoundView = UIView()
let rightBoundView = UIView()
let tintView = TintView()
var previewViews: [ChartLineView] = []
var selectorColor: UIColor = UIColor.white {
didSet {
viewPortView.backgroundColor = selectorColor
}
}
var selectorTintColor: UIColor = UIColor.clear {
didSet {
tintView.backgroundColor = selectorTintColor
}
}
var minX = 0
var maxX = 0
weak var delegate: ChartPreviewViewDelegate?
override var frame: CGRect {
didSet {
if chartData != nil {
updateViewPort()
}
}
}
var chartData: ChartPresentationData! {
didSet {
previewViews.forEach { $0.removeFromSuperview() }
previewViews.removeAll()
for i in (0..<chartData.linesCount).reversed() {
let line = chartData.lineAt(i)
let v = ChartLineView()
v.isPreview = true
v.chartLine = line
v.frame = previewContainerView.bounds
v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
previewContainerView.addSubview(v)
previewViews.insert(v, at: 0)
}
previewViews.forEach { $0.setY(min: chartData.lower, max: chartData.upper) }
let count = chartData.pointsCount - 1
minX = 0
maxX = count
updateViewPort()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
previewContainerView.translatesAutoresizingMaskIntoConstraints = false
previewContainerView.layer.cornerRadius = 5
previewContainerView.clipsToBounds = true
addSubview(previewContainerView)
let t = previewContainerView.topAnchor.constraint(equalTo: topAnchor)
let b = previewContainerView.bottomAnchor.constraint(equalTo: bottomAnchor)
t.priority = .defaultHigh
b.priority = .defaultHigh
t.constant = 1
b.constant = -1
NSLayoutConstraint.activate([
previewContainerView.leftAnchor.constraint(equalTo: leftAnchor),
previewContainerView.rightAnchor.constraint(equalTo: rightAnchor),
t,
b])
tintView.frame = bounds
tintView.backgroundColor = selectorTintColor
tintView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(tintView)
viewPortView.tintView = tintView
viewPortView.backgroundColor = selectorColor
viewPortView.translatesAutoresizingMaskIntoConstraints = false
addSubview(viewPortView)
viewPortView.addSubview(leftBoundView)
viewPortView.addSubview(rightBoundView)
let pan = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:)))
viewPortView.addGestureRecognizer(pan)
let leftPan = UIPanGestureRecognizer(target: self, action: #selector(onLeftPan(_:)))
let rightPan = UIPanGestureRecognizer(target: self, action: #selector(onRightPan(_:)))
leftBoundView.addGestureRecognizer(leftPan)
rightBoundView.addGestureRecognizer(rightPan)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
@objc func onPan(_ sender: UIPanGestureRecognizer) {
if sender.state != .changed { return }
let p = sender.translation(in: viewPortView)
let count = chartData.labels.count - 1
let x = Int((viewPortView.frame.minX + p.x) / bounds.width * CGFloat(count))
let dx = maxX - minX
let mx = x + dx
if x > 0 && mx < count {
viewPortView.frame = viewPortView.frame.offsetBy(dx: p.x, dy: 0)
sender.setTranslation(CGPoint(x: 0, y: 0), in: viewPortView)
if x != minX {
minX = x
maxX = mx
delegate?.chartPreviewView(self, didChangeMinX: minX, maxX: maxX)
}
} else if minX > 0 && x <= 0 {
setX(min: 0, max: dx)
} else if maxX < count && mx >= count {
setX(min: count - dx, max: count)
}
}
@objc func onLeftPan(_ sender: UIPanGestureRecognizer) {
if sender.state != .changed { return }
let p = sender.translation(in: leftBoundView)
let count = chartData.labels.count - 1
let x = Int((viewPortView.frame.minX + p.x) / bounds.width * CGFloat(count))
if x > 0 && x < maxX && maxX - x >= count / 10 {
var f = viewPortView.frame
f = CGRect(x: f.minX + p.x, y: f.minY, width: f.width - p.x, height: f.height)
viewPortView.frame = f
rightBoundView.frame = CGRect(x: viewPortView.bounds.width - 14, y: 0, width: 44, height: viewPortView.bounds.height)
sender.setTranslation(CGPoint(x: 0, y: 0), in: leftBoundView)
if x != minX {
minX = x
delegate?.chartPreviewView(self, didChangeMinX: minX, maxX: maxX)
}
} else if x <= 0 && minX > 0 {
setX(min: 0, max: maxX)
}
}
@objc func onRightPan(_ sender: UIPanGestureRecognizer) {
if sender.state != .changed { return }
let p = sender.translation(in: viewPortView)
let count = chartData.labels.count - 1
let x = Int((viewPortView.frame.maxX + p.x) / bounds.width * CGFloat(count))
if x > minX && x < count && x - minX >= count / 10 {
var f = viewPortView.frame
f = CGRect(x: f.minX, y: f.minY, width: f.width + p.x, height: f.height)
viewPortView.frame = f
rightBoundView.frame = CGRect(x: viewPortView.bounds.width - 14, y: 0, width: 44, height: viewPortView.bounds.height)
sender.setTranslation(CGPoint(x: 0, y: 0), in: rightBoundView)
if x != maxX {
maxX = x
delegate?.chartPreviewView(self, didChangeMinX: minX, maxX: maxX)
}
} else if x >= count && maxX < count {
setX(min: minX, max: count)
}
}
func setX(min: Int, max: Int) {
assert(min < max)
minX = min
maxX = max
updateViewPort()
delegate?.chartPreviewView(self, didChangeMinX: minX, maxX: maxX)
}
func updateViewPort() {
let count = CGFloat(chartData.labels.count - 1)
viewPortView.frame = CGRect(x: CGFloat(minX) / count * bounds.width,
y: bounds.minY,
width: CGFloat(maxX - minX) / count * bounds.width,
height: bounds.height)
leftBoundView.frame = CGRect(x: -30, y: 0, width: 44, height: viewPortView.bounds.height)
rightBoundView.frame = CGRect(x: viewPortView.bounds.width - 14, y: 0, width: 44, height: viewPortView.bounds.height)
}
}
| apache-2.0 | a4f425edb35f0c44c5f98cf3080487dd | 31.020325 | 123 | 0.659261 | 3.992397 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/XCTest/XCTest.swift | 1 | 43902 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import XCTest // Clang module
import CoreGraphics
import _SwiftXCTestOverlayShims
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(_ expected: Bool, _ condition: String, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCase()
_XCTPreformattedFailureHandler(test, expected, file.description, line, condition, message())
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(_ assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArg...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case success
case failedWithError(error: Error)
case failedWithException(className: String, name: String, reason: String)
case failedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception or error,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(_ block: () throws -> Void) -> _XCTThrowableBlockResult {
var blockErrorOptional: Error?
let d = _XCTRunThrowableBlockBridge({
do {
try block()
} catch {
blockErrorOptional = error
}
})
if let blockError = blockErrorOptional {
return .failedWithError(error: blockError)
} else if d.count > 0 {
let t: String = d["type"]!
if t == "objc" {
return .failedWithException(
className: d["className"]!,
name: d["name"]!,
reason: d["reason"]!)
} else {
return .failedWithUnknownException
}
} else {
return .success
}
}
// --- Supported Assertions ---
public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`nil`
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssert(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(expression, message, file: file, line: line)
}
public func XCTAssertTrue(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`true`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertFalse(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`false`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional != expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional == expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equalWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqualWithAccuracy")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqualWithAccuracy")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.greaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.greaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.lessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.lessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Error) -> Void = { _ in }) -> Void {
// evaluate expression exactly once
var caughtErrorOptional: Error?
let result = _XCTRunThrowableBlock {
do {
_ = try expression()
} catch {
caughtErrorOptional = error
}
}
switch result {
case .success:
if let caughtError = caughtErrorOptional {
errorHandler(caughtError)
} else {
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message, file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrow(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrow
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
| apache-2.0 | e460d70eb7131a9d0d853d0e715fac1b | 40.300094 | 267 | 0.707325 | 4.345012 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Utils/CLDCryptoUtils.swift | 1 | 8959 | //
// CLDCryptoUtils.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.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
import CommonCrypto
public func cloudinarySignParamsUsingSecret(_ paramsToSign: [String : Any],cloudinaryApiSecret: String) -> String {
var paramsArr: [String] = []
let sortedKeys = paramsToSign.keys.sorted(){$0 < $1} // sort by dictionary keys
for key in sortedKeys {
if let value = paramsToSign[key] {
var paramValue: String?
if value is [String] {
if let valueArr: [String] = value as? [String] , valueArr.count > 0 {
paramValue = valueArr.joined(separator: ",")
}
else {continue}
}
else if let valueStr = cldParamValueAsString(value: value) {
paramValue = valueStr
}
if let paramValue = paramValue {
let encodedParam = [key, paramValue]
paramsArr.append(encodedParam.joined(separator: "="))
}
}
}
let toSign = paramsArr.joined(separator: "&")
return toSign.sha1_base8(cloudinaryApiSecret)
}
internal extension String {
func sha1_base8(_ secret: String?) -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
let ctx = UnsafeMutablePointer<CC_SHA1_CTX>.allocate(capacity: 1)
CC_SHA1_Init(ctx)
_ = data.withUnsafeBytes { buffer in
CC_SHA1_Update(ctx, buffer.baseAddress!, CC_LONG(data.count))
}
if let secret = secret {
let secretData = secret.data(using: String.Encoding.utf8)!
_ = secretData.withUnsafeBytes { buffer in
CC_SHA1_Update(ctx, buffer.baseAddress!, CC_LONG(secretData.count))
}
}
CC_SHA1_Final(&digest, ctx)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
func sha1_base64() -> String {
return sha_base64(type: .sha1)
}
func sha256_base64() -> String {
return sha_base64(type: .sha256)
}
fileprivate func sha_base64(type: shaBase64Type) -> String {
var digest = [UInt8](repeating: 0, count:type.count)
type.hash(string: self, digest: &digest)
let data = Data(bytes: digest, count: MemoryLayout<UInt8>.size * digest.count)
let base64 = data.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let encoded = base64.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "=", with: "")
return encoded
}
fileprivate enum shaBase64Type {
case sha1
case sha256
var count: Int {
get {
switch self {
case .sha1 : return Int(CC_SHA1_DIGEST_LENGTH)
case .sha256: return Int(CC_SHA256_DIGEST_LENGTH)
}
}
}
func hash(string: String, digest: UnsafeMutablePointer<UInt8>!) {
let cStr = NSString(string: string).utf8String
switch self {
case .sha1 : CC_SHA1(cStr, CC_LONG(strlen(cStr!)), digest)
case .sha256: CC_SHA256(cStr, CC_LONG(strlen(cStr!)), digest)
}
}
}
func toCRC32() -> UInt32 {
return crc32(self)
}
func cld_md5() -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
if let data = self.data(using: String.Encoding.utf8) {
_ = data.withUnsafeBytes { buffer in
CC_MD5(buffer.baseAddress!, CC_LONG(buffer.count), &digest)
}
}
var digestHex = ""
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
}
private func crc32(_ string: String) -> UInt32 {
let crcTable:[UInt32] = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d]
guard let data = string.data(using: String.Encoding.utf8)
else {
return 0
}
var crc:UInt32 = 0xffffffff
var buffer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)
for _ in 1...data.count {
crc = (crc >> 8) ^ crcTable[Int((crc ^ UInt32(buffer.pointee)) & 0xff)]
buffer += 1
}
return crc ^ 0xffffffff
}
| mit | d74efce8592b3da554276ede0b3478ce | 45.180412 | 124 | 0.659672 | 2.677525 | false | false | false | false |
Benkracker/RESTeasy | SampleProject/RestEasy/URLParametersBuilder.swift | 2 | 814 | //
// URLParametersBuilder.swift
//
// Created by Kracker, Ben on 5/20/16.
// Copyright © 2016 Ben Kracker. All rights reserved.
//
import Foundation
class URLParametersBuilder {
func URLFormattedStringFromDictionary(dictionary: [String : AnyObject]) -> String {
let urlStrings = URLArrayFromDictionary(dictionary)
let urlString = "?" + urlStrings.joinWithSeparator("&")
return urlString
}
private func URLArrayFromDictionary(dictionary: [String : AnyObject]) -> [String] {
var urlArray: [String] = []
for (key, value) in dictionary {
if let condition: String = key + "=" + (value as! String) {
urlArray.append(condition)
}
}
return urlArray
}
} | mit | ab1de2b45dd50ca077cd7ea190c7fb72 | 24.4375 | 87 | 0.584256 | 4.699422 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftLearning/SwiftLearning/Learning/类/自定义类/属性/PersonWithProperty.swift | 1 | 4881 | //
// PersonWithProperty.swift
// JSwiftLearnMore
//
// Created by apple on 17/3/8.
// Copyright © 2017年 BP. All rights reserved.
//
import UIKit
// MARK: - 属性
/*
Swift中的属性分为两种:存储属性(用于类、结构体)和计算属性(用于类、结构体、枚举),并且在Swift中并不强调成员变量的概念。 无论从概念上还是定义方式上来看存储属性更像其他语言中的成员变量,但是不同的是可以控制读写操作、通过属性监视器来属性的变化以及快速实现懒加载功能
*/
class Account {
var balance:Double=0.0
/*
计算属性并不直接存储一个值,而是提供getter来获取一个值,或者利用setter来间接设置其他属性;
lazy属性必须有初始值,必须是变量不能是常量(因为常量在构造完成之前就已经确定了值);
在构造方法之前存储属性必须有值,无论是变量属性(var修饰)还是常量属性(let修饰)这个值既可以在属性创建时指定也可以在构造方法内指定
上面的例子中不难区分存储属性和计算属性,计算属性通常会有一个setter、getter方法,如果要监视一个计算属性的变化在setter方法中即可办到(因为在setter方法中可以newValue或者自定义参数名),但是如果是存储属性就无法通过监视属性的变化过程了,因为在存储属性中是无法定义setter方法的。不过Swift为我们提供了另外两个方法来监视属性的变化那就是willSet和didSet,通常称之为“属性监视器”或“属性观察器”
*/
var balanceCount:Double=0.0{
willSet{
self.balance=2.0
//注意newValue可以使用自定义值,并且在属性监视器内部调用属性不会引起监视器循环调用,注意此时修改balance的值没有用
print("Account.balance willSet,newValue=\(newValue),value=\(self.balance)")
}
didSet{
self.balance=3.0
//注意oldValue可以使用自定义值,并且在属性监视器内部调用属性不会引起监视器循环调用,注意此时修改balance的值将作为最终结果
print("Account.balance didSet,oldValue=\(oldValue),value=\(self.balance)")
}
}
/*
和setter方法中的newValue一样,默认情况下载willSet和didSet中会有一个newValue和oldValue参数表示要设置的新值和已经被修改过的旧值(当然参数名同样可以自定义);
存储属性的默认值设置不会引起属性监视器的调用(另外在构造方法中赋值也不会引起属性监视器调用),只有在外部设置存储属性才会引起属性监视器调用;
存储属性的属性监视器willSet、didSet内可以直接访问属性,但是在计算属性的get、set方法中不能直接访问计算属性,否则会引起循环调用;
在didSet中可以修改属性的值,这个值将作为最终值(在willSet中无法修改);
*/
}
class PersonWithProperty: NSObject {
//firstName、lastName、age是存储属性
var firstName:String
var lastName:String
let age:Int
//fullName是一个计算属性,并且由于只定义了get方法,所以是一个只读属性
//如果fullName只有get则是一个只读属性,只读属性可以简写如下:
var fullName:String{
return firstName + "." + lastName
}
//若需要修改,需要以下方法
var fullNameCanWrite:String{
get{
return firstName + "." + lastName
}
set{
var array = ["hello","world"]
if array.count == 2 {
firstName=array[0]
lastName=array[1]
}
}
// set方法中的newValue表示即将赋的新值,可以自己设置set中的newValue变量,如下:
// set(myValue){
// }
}
//属性的懒加载,第一次访问才会计算初始值,在Swift中懒加载的属性不一定就是对象类型,也可以是基本类型
lazy var account = Account()
//构造器方法,注意如果不编写构造方法默认会自动创建一个无参构造方法
//需要加上age,因为age未赋默认值,若要去除,初始化时需要改成var age:Int=0
init(firstName:String,lastName:String,age:Int){
self.firstName=firstName
self.lastName=lastName
self.age=age
}
//类型属性
static var skin:Array<String>{
return ["yellow","white","black"];
}
//定义方法
func showMessage(){
print("name=\(fullName),age=\(age)")
}
//通过final声明,子类无法重写
final func sayHello(){
print("hello world.")
}
}
| apache-2.0 | 37e55c543310ce6acf9d1b2def7bebb1 | 26.943396 | 225 | 0.658677 | 2.861836 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/RACExample/RACTableViewVC.swift | 1 | 2720 | //
// RACTableViewVC.swift
// iOSExample
//
// Created by iCrany on 2018/8/4.
// Copyright © 2018年 iCrany. All rights reserved.
//
import Foundation
class RACTableViewVC: UIViewController {
struct Constant {
static let kDemo1: String = "RAC bind example"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Network Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
}
private func prepareDataSource() {
self.dataSource.append(Constant.kDemo1)
}
}
extension RACTableViewVC: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kDemo1:
let vc: HttpHeaderExampleVC = HttpHeaderExampleVC()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
extension RACTableViewVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
| mit | 3385baea18e4321ecc6d546d445472eb | 28.215054 | 132 | 0.660655 | 4.877917 | false | false | false | false |
notjosh/Dynamically | Dynamically/EffectGravityViewController.swift | 1 | 1764 | //
// EffectGravityViewController.swift
// Dynamically
//
// Created by joshua may on 5/11/2014.
// Copyright (c) 2014 notjosh, inc. All rights reserved.
//
import UIKit
class EffectGravityViewController: UIViewController {
var animator: UIDynamicAnimator?
var collisionBehaviour: UICollisionBehavior?
var gravityBehaviour: UIGravityBehavior?
override func viewDidLoad() {
super.viewDidLoad()
animator = UIDynamicAnimator(referenceView: view)
gravityBehaviour = UIGravityBehavior()
animator?.addBehavior(gravityBehaviour)
collisionBehaviour = UICollisionBehavior()
collisionBehaviour?.translatesReferenceBoundsIntoBoundary = true
animator?.addBehavior(collisionBehaviour)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tap:"))
}
func tap(gr: UIGestureRecognizer) {
if UIGestureRecognizerState.Ended != gr.state {
return
}
let dimension: Int = Int(arc4random_uniform(40)) + 20
let subview = UIView()
subview.layer.cornerRadius = CGFloat(dimension) / 2
subview.backgroundColor = UIColor.redColor()
subview.userInteractionEnabled = false
subview.layer.borderColor = UIColor.blackColor().CGColor
subview.layer.borderWidth = 1
// OR:
// let subview = UISwitch()
subview.frame = CGRect(
x: Int(gr.locationInView(view).x) - dimension/2,
y: Int(gr.locationInView(view).y) - dimension/2,
width: dimension,
height: dimension
)
view.addSubview(subview)
collisionBehaviour?.addItem(subview)
gravityBehaviour?.addItem(subview)
}
}
| mit | 97048cff2c4ab10e61e4128a3390b08a | 28.4 | 87 | 0.652494 | 5.025641 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/Class/FirstVC/Controllers/FirstViewController.swift | 1 | 21730 | //
// FirstViewController.swift
// MyTools
//
// Created by zhangk on 17/3/23.
// Copyright © 2017年 zhangk. All rights reserved.
//
//
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
import UIKit
class FirstViewController: TableViewBaseController {
var actionArray = NSMutableArray()
//有导航栏时会失效
//要在viewDidLoad 中setNeedsStatusBarAppearanceUpdate()
//Info.plist 中添加 View controller-based status bar appearance : YES
//使用BearNavigationViewController
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
var label:UILabel{
let l = ZKTools.createLabel(CGRect(x: 0, y: 64, width: 100, height: 40), title: "label", textAlignment: nil, font: nil, textColor: UIColor.red)
return l
}
override func viewDidLoad() {
super.viewDidLoad()
// setNeedsStatusBarAppearanceUpdate()
//navigationController?.navigationBar.isTranslucent=false
automaticallyAdjustsScrollViewInsets=false
NotificationCenter.default.addObserver(self, selector: #selector(changeNetWorking(n:)), name: NSNotification.Name(kNetworkReachabilityChangedNotification), object: nil)
//fixItem 用于消除左(右)边空隙,要不然按钮顶不到最前面
let fixItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixItem.width = -10
let netItem = UIBarButtonItem(title: "网络", style: .done, target: nil, action: nil)
navigationItem.rightBarButtonItems = [fixItem,netItem]
navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
// let target = navigationController?.interactivePopGestureRecognizer?.delegate
// let pan = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:")))
// pan.delegate = self
// view.addGestureRecognizer(pan)
// navigationController?.interactivePopGestureRecognizer?.isEnabled = false
//view.addSubview(label)
creatADView()
downloadVaporHost()
//createSubViews()
createTableView(frame: CGRect(x: 0, y: 64, w: kScreenWidth, h: kScreenHeight-64-44), style: .plain, separatorStyle: .none)
tableView?.delegate = self
tableView?.dataSource = self
dataArray = ["全屏返回测试","缓存大小","下载界面","WebView","选择图片","多种字体","获取手机验证码","二维码生成","二维码扫描","轮播图","监听照片库变化","视频截图","SIM信息","刮刮卡","Gallery画廊效果(左右滑动浏览图片)","WMPageController","GPS","FaceBook Twitter 分享","Youtube 分享","Ping","视图抖动"]
actionArray = ["goBackVCBtnAction","cacheClick","downloadVCAction","webViewAction","albumBtnAction","clickUIFontVC","getPhoneCode","EFQRCode","QRCodeScan","cycleClick","photoLibraryDidChange","videoShotClick","simInfoClick","scratchClick","galleryClick","WMPageControllerClick","GPSClick","ShareClick","youTubeClick","ppsPingClick","viewShakeClick"]
// navigationController?.setNavigationBarHidden(true, animated: false)
//去空格
let str = " adf aase werwer wr w wer wr qw r w"
print(str)
let str1 = str.replacingOccurrences(of: " ", with: "")
print(str1)
let arr = ["aa","cc","bb"]
let b = arr.sorted { (a, b) -> Bool in
return a < b
}
print(b)
let des:NSString = "123"
let dese = des.encrypt()
print(dese as Any)
changeNavBackGroundColor(leftColor: "efaf0f", rightColor: "acdd00")
}
@objc private func changeNetWorking(n:NSNotification){
if (n.object is NetworkReachabilityManager.NetworkReachabilityStatus){
let reach = n.object as! NetworkReachabilityManager.NetworkReachabilityStatus
var status = ""
switch reach {
case .unknown:
status = "未知的"
case .notReachable:
status = "不可用"
case .reachable(.wwan):
status = "移动网络"
case .reachable(.ethernetOrWiFi):
status = "WiFi"
}
let fixItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixItem.width = -10
let netItem = UIBarButtonItem(title: status, style: .done, target: nil, action: nil)
navigationItem.rightBarButtonItems = [fixItem,netItem]
}
}
private func delay(delay:Double,closure:@escaping ()->()){
DispatchQueue.main.asyncAfter(deadline: .now()+delay, execute: closure)
}
private func createSubViews(){
let btn = ZKTools.createButton(CGRect.init(x: 0, y: 114, width: 80, height: 30), title: "清空缓存", imageName: nil, bgImageName: nil, target: self, action: #selector(cacheClick))
view.addSubview(btn)
let goBackVCBtn = UIButton(type: .system)
view.addSubview(goBackVCBtn)
goBackVCBtn.setTitle("全屏返回测试", for: .normal)
goBackVCBtn.addTarget(self, action: #selector(goBackVCBtnAction), for: .touchUpInside)
goBackVCBtn.snp.makeConstraints {
[weak self]
(make) in
make.top.equalTo(btn.snp.bottom)
make.left.equalTo((self?.view.snp.left)!)
make.height.equalTo(20)
}
let downloadVCBtn = UIButton(type: .system)
view.addSubview(downloadVCBtn)
downloadVCBtn.snp.makeConstraints {
[weak self]
(make) in
make.top.equalTo(goBackVCBtn.snp.bottom)
make.left.equalTo((self?.view.snp.left)!)
make.height.equalTo(20)
}
downloadVCBtn.setTitle("下载界面", for: .normal)
downloadVCBtn.addTarget(self, action: #selector(downloadVCAction), for: .touchUpInside)
let webViewBtn = UIButton(type: .system)
view.addSubview(webViewBtn)
webViewBtn.snp.makeConstraints {
[weak self]
(make) in
make.top.equalTo(downloadVCBtn.snp.bottom)
make.left.equalTo((self?.view.snp.left)!)
make.height.equalTo(20)
}
webViewBtn.setTitle("WebView", for: .normal)
webViewBtn.addTarget(self, action: #selector(webViewAction), for: .touchUpInside)
let albumBtn = UIButton(type: .system)
view.addSubview(albumBtn)
albumBtn.setTitle("选择图片", for: .normal)
albumBtn.addTarget(self, action: #selector(albumBtnAction), for: .touchUpInside)
albumBtn.snp.makeConstraints {
[weak self]
(make) in
make.top.equalTo(webViewBtn.snp.bottom)
make.left.equalTo((self?.view.snp.left)!)
make.height.equalTo(20)
}
albumBtn.uxy_ignoreEvent=false
albumBtn.uxy_acceptEventInterval=2
let accEventBtn = UIButton(type: .system)
view.addSubview(accEventBtn)
accEventBtn.snp.makeConstraints {
[weak self]
(make) in
make.left.equalTo((self?.view.snp.left)!)
make.top.equalTo(albumBtn.snp.bottom)
make.height.equalTo(30)
}
accEventBtn.uxy_acceptEventInterval=2
accEventBtn.addTarget(self, action: #selector(accEventBtnAction), for: .touchUpInside)
accEventBtn.setTitle("SwiftRuntime", for: .normal)
}
@objc private func accEventBtnAction(){
print("aaaa")
}
@objc fileprivate func albumBtnAction(){
// let style = UIApplication.shared.statusBarStyle
// if style == UIStatusBarStyle.default{
// UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
// }else{
// UIApplication.shared.setStatusBarStyle(.default, animated: true)
// }
// delay(delay: 1) {
// // let alert = UIAlertView(title: "测试", message: "测试", delegate: nil, cancelButtonTitle: "取消")
// // alert.show()
// let aalert = UIAlertController(title: "测试2", message: "测试2", preferredStyle: .alert)
// let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
// aalert.addAction(cancelAction)
// aalert.show()
// }
let alert = LGAlertView(progressViewAndTitle: "测试", message: "测试", style: .alert, progressLabelText: "测试", buttonTitles: ["确定"], cancelButtonTitle: "取消", destructiveButtonTitle: nil)
alert.isCancelOnTouch = true
updateProgressWithAlertView(alertView: alert)
alert.show(animated: false, completionHandler: nil)
}
private func updateProgressWithAlertView(alertView:LGAlertView){
delay(delay: 0.02) {
[weak self] in
if(alertView.progress >= 1.0){
alertView.dismiss()
}else{
var progress = alertView.progress+0.001
if (progress > 1.0){
progress = 1.0
}
alertView.setProgress(progress, progressLabelText: NSString(format: "%.0f %%", progress*100) as String)
self?.updateProgressWithAlertView(alertView: alertView)
}
}
}
@objc fileprivate func webViewAction(){
let webVc = WebViewController()
hidesBottomBarWhenPushed=true
navigationController?.pushViewController(webVc, animated: true)
hidesBottomBarWhenPushed=false
}
@objc fileprivate func downloadVCAction(){
let downloadVC = DownloadTaskViewController()
hidesBottomBarWhenPushed=true
navigationController?.pushViewController(downloadVC, animated: true)
hidesBottomBarWhenPushed=false
}
@objc fileprivate func goBackVCBtnAction(){
let backVC = BackViewController()
backVC.delegate = self
navigationController?.pushViewController(backVC, animated: true)
}
@objc fileprivate func cacheClick(){
// let flag = ADView.clear()
// if flag {
// ZKTools.alertViewCtroller(vc: self, title: "提示", message: "清除缓存成功", cancelActionTitle: nil, sureActionTitle: "确定", action: nil)
// }
//tableView回到第一行
//tableView?.scrollToRow(at: IndexPath.init(row: 0, section: 0), at: .bottom, animated: true)
let size = CacheTool.cacheSize
ZKTools.alertViewCtroller(vc: self, title: "提示", message: size, cancelActionTitle: nil, sureActionTitle: "确定", action: nil)
}
@objc fileprivate func clickUIFontVC(){
let vc = UIFontViewController()
hidesBottomBarWhenPushed=true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed=false
}
@objc fileprivate func getPhoneCode(){
let vc = PhoneCodeViewController()
//导航栏消失
vc.modalTransitionStyle = .partialCurl
hidesBottomBarWhenPushed = true
present(vc, animated: true, completion: nil)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func EFQRCode(){
let vc = EFQRCodeViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func QRCodeScan(){
let vc = SwiftScanViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@available(iOS 8.2, *)
@objc fileprivate func cycleClick(){
let vc = CycleViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func photoLibraryDidChange() {
//监听照片库变化
let vc = PhotoLibraryDidChangeViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func videoShotClick(){
let vc = VideoShotViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func simInfoClick(){
let vc = SIMInfoViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func scratchClick(){
let vc = ScratchViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func galleryClick(){
let vc = GalleryViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func WMPageControllerClick(){
let vc = WMPageTestViewController.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func GPSClick(){
let vc = GPSViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func ShareClick(){
let vc = ShareViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func youTubeClick(){
let vc = YouTubeViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func ppsPingClick(){
let vc = PingViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
@objc fileprivate func viewShakeClick(){
let vc = ViewShakeViewController()
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
hidesBottomBarWhenPushed = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
download()
//Info.plist 中添加 View controller-based status bar appearance : NO
//UIApplication.shared.setStatusBarStyle(.default, animated: animated)
// UIApplication.shared.statusBarStyle = .default
navigationController?.setNavigationBarHidden(false, animated: animated)
// navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// navigationController?.setNavigationBarHidden(false, animated: animated)
// navigationController?.navigationBar.isHidden = false
}
private func creatADView(){
let kADModel = kUserDefaults.data(forKey: "ADModel")
var model = ADModel()
if kADModel == nil{
model.adImageUrl = "https://www.uilucky.com/AppData/images/WechatIMG1.jpeg"
model.adUrl = "https://uilucky.com/"
}else{
model = ADModel.parseJson(kADModel!)
}
let adView = ADView(frame: self.view.frame, imagedUrl: (model.adImageUrl)!, ad: (model.adUrl)!) {
[weak self]
(adUrl) in
let adVC = ADViewController()
adVC.adUrl = adUrl
adVC.hidesBottomBarWhenPushed = true
self?.navigationController?.pushViewController(adVC, animated: true)
}
adView.showTime = 5
adView.show()
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(kNetworkReachabilityChangedNotification), object: nil)
}
private func download(){
let download = ZKDownloader()
download.delegate = self
download.getWithUrl(kADUrl)
download.type=1
}
private func downloadVaporHost(){
let downloadVapor = ZKDownloader()
downloadVapor.delegate = self
downloadVapor.getWithUrl(kVaporHost+"?name="+kDeviceName)
downloadVapor.type=2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - ZKDownloaderDelegate
extension FirstViewController:ZKDownloaderDelegate{
func downloader(_ download: ZKDownloader, didFailWithError error: NSError) {
print(error)
}
func downloader(_ download: ZKDownloader, didFinishWithData data: Data?) {
if download.type == 1 {
//print(ZKTools.stringWithData(data: data!))
kUserDefaults.set(data!, forKey: "ADModel")
kUserDefaults.synchronize()
}else if download.type == 2{
if let da = data{
let model = VaporHostModel.parseJson(data: da)
print(model.message as Any)
print(ZKTools.stringWithData(data: da))
}
}
}
}
extension FirstViewController:BackViewControllerDelegate{
func backTest(str: String) {
print(str)
}
}
// MARK: - TableViewDelegate
extension FirstViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ID = "FirstViewControllerID"
var cell = tableView.dequeueReusableCell(withIdentifier: ID)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ID)
}
cell?.selectionStyle = .none
cell?.textLabel?.text = dataArray[indexPath.row] as? String
return cell!
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animate(withDuration: 0.25) {
cell.layer.transform = CATransform3DMakeScale(1, 1, 1)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//取消选中状态
tableView.deselectRow(at: indexPath, animated: true)
if(actionArray.count<=indexPath.row){
return
}
let action = NSSelectorFromString(actionArray[indexPath.row] as! String)
if responds(to: action )==true{
perform(action)
}
/*switch indexPath.row {
case 0:
goBackVCBtnAction()
break
case 1:
cacheClick()
break
case 2:
downloadVCAction()
case 3:
webViewAction()
case 4:
albumBtnAction()
case 5:
clickUIFontVC()
case 6:
getPhoneCode()
//fallthrough穿透case
//fallthrough
case 7:
EFQRCode()
case 8:
QRCodeScan()
case 9:
if #available(iOS 8.2, *) {
cycleClick()
}
case 10:
photoLibraryDidChange()
case 11:
videoShotClick()
default:
print("fallthrough")
break
}*/
}
}
extension FirstViewController:UIGestureRecognizerDelegate{
//是否允许手势
// func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
//
// if(gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer){
// //只有二级以及以下的页面允许手势返回
// return (self.navigationController?.viewControllers.count)! > 1
// }
// return true
// }
// func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// if(childViewControllers.count == 1){
// return false
// }
// return true
// }
}
| mit | 0ac0e6cc6b50fece4004727100b4cf0d | 38.621269 | 357 | 0.60517 | 4.816738 | false | false | false | false |
danpratt/On-the-Map | OTM Playground.playground/Contents.swift | 1 | 1788 | //: Playground - noun: a place where people can play
import UIKit
import MapKit
import CoreLocation
import PlaygroundSupport
// this line tells the Playground to execute indefinitely
PlaygroundPage.current.needsIndefiniteExecution = true
//var str = "Hello, playground"
//
//print("{\"udacity\": {\"username\": \"[email protected]\", \"password\": \"********\"}}")
//
//let url = "https://parse.udacity.com/parse/classes/StudentLocation?where={\"uniqueKey\":\"1234\"}"
//let escapedURL:String! = url.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
//
//print(escapedURL)
//let request = MKLocalSearchRequest()
//request.naturalLanguageQuery = "Berlin, Germany"
//
//let search = MKLocalSearch(request: request)
//
//search.start { (response, error) in
//
//
// if error != nil {
// print("Error \(error.debugDescription)")
// } else {
// for item in response!.mapItems {
// print(item.name ?? "No Item")
// print(item.placemark.coordinate)
// }
// }
//}
//
//CLGeocoder().geocodeAddressString("Seattle, WA") { (placemark, error) in
// print(placemark ?? "Can't find it")
//}
//
//let url = "http://www.apple.com"
//print(url)
//let httpURL = url.substring(to: url.index(url.startIndex, offsetBy: 7))
//var myArray = ["World", "My", "Name", "is", "Daniel"]
//myArray.insert("Hello", at: 0)
//let request = NSMutableURLRequest(url: URL(string: "http://quotes.rest/qod.json?category=life")!)
//request.httpMethod = "GET"
//let session = URLSession.shared
//let task = session.dataTask(with: request as URLRequest) { data, response, error in
// if error != nil { // Handle error...
// return
// }
// print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
//}
//task.resume()
| mit | 44c3cbb8e1a7ef66049a9d0db9338a71 | 27.380952 | 100 | 0.651007 | 3.612121 | false | false | false | false |
RizanHa/RHImgPicker | RHImgPicker/Classes/Views/Cells/PhotoCell.swift | 1 | 8315 | // The MIT License (MIT)
//
// Copyright (c) 2016 Rizan Hamza
//
// 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.
//
// PhotoCell.swift
// Pods
//
// Created by rizan on 26/08/2016.
//
//
import UIKit
import Photos
/**
The photo cell.
*/
class PhotoCell: UICollectionViewCell {
class var IDENTIFIER: String {
return "PhotoCell_IDENTIFIER"
}
//MARK: - Setup
var imageView: UIImageView = UIImageView()
var selectionOverlayView: UIView = UIView()
var selectionView: SelectionView = SelectionView()
override init(frame: CGRect) {
super.init(frame: frame)
self.imageView.contentMode = .scaleAspectFill
self.selectionView.backgroundColor = UIColor.clear
self.selectionOverlayView.backgroundColor = RHSettings.sharedInstance.selectionHighlightColor
self.selectionOverlayView.alpha = 0.0
self.clipsToBounds = true
self.imageView.clipsToBounds = true
self.selectionOverlayView.clipsToBounds = true
self.selectionView.clipsToBounds = true
self.addSubview(imageView)
self.addSubview(selectionOverlayView)
self.addSubview(selectionView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
func layoutCell() {
let frame : CGRect = self.frame
let sizeSelectionViewXY = self.frame.size.height*0.35
self.imageView.frame = CGRect(x: 0,
y: 0,
width: frame.size.width,
height: frame.size.height)
self.selectionOverlayView.frame = CGRect(x: 0,
y: 0,
width: frame.size.width,
height: frame.size.height)
self.selectionView.frame = CGRect(x: frame.size.width - sizeSelectionViewXY*1.15,
y: frame.size.height - sizeSelectionViewXY*1.15 ,
width: sizeSelectionViewXY ,
height: sizeSelectionViewXY )
}
//MARK: -
func updata(_ index : Int) {
self.selectionString = String(index)
}
weak var asset: PHAsset?
var selectionString: String {
get {
return selectionView.selectionString
}
set {
selectionView.selectionString = newValue
}
}
override var isSelected: Bool {
get {
return super.isSelected
}
set {
let hasChanged = isSelected != newValue
super.isSelected = newValue
if UIView.areAnimationsEnabled && hasChanged {
UIView.animate(withDuration: TimeInterval(0.1), animations: { () -> Void in
// Set alpha for views
self.updateAlpha(newValue)
// Scale all views down a little
self.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}, completion: { (finished: Bool) -> Void in
UIView.animate(withDuration: TimeInterval(0.1), animations: { () -> Void in
// And then scale them back upp again to give a bounce effect
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
})
} else {
updateAlpha(newValue)
}
}
}
fileprivate func updateAlpha(_ selected: Bool) {
if selected == true {
self.selectionView.alpha = 1.0
self.selectionOverlayView.alpha = 0.3
} else {
self.selectionView.alpha = 0.0
self.selectionOverlayView.alpha = 0.0
}
}
}
/**
Used as an overlay on selected cells
*/
@IBDesignable final class SelectionView: UIView {
//MARK: - SelectionView
var selectionString: String = "" {
didSet {
if selectionString != oldValue {
setNeedsDisplay()
}
}
}
override func draw(_ rect: CGRect) {
let settings: RHImgPickerSettings = RHSettings.sharedInstance
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
//// Shadow Declarations
let shadow2Offset = CGSize(width: 0.1, height: -0.1);
let shadow2BlurRadius: CGFloat = 2.5;
//// Frames
let checkmarkFrame = bounds;
//// Subframes
let group = CGRect(x: checkmarkFrame.minX + 3, y: checkmarkFrame.minY + 3, width: checkmarkFrame.width - 6, height: checkmarkFrame.height - 6)
//// CheckedOval Drawing
let checkedOvalPath = UIBezierPath(ovalIn: CGRect(x: group.minX + floor(group.width * 0.0 + 0.5), y: group.minY + floor(group.height * 0.0 + 0.5), width: floor(group.width * 1.0 + 0.5) - floor(group.width * 0.0 + 0.5), height: floor(group.height * 1.0 + 0.5) - floor(group.height * 0.0 + 0.5)))
context?.saveGState()
context?.setShadow(offset: shadow2Offset, blur: shadow2BlurRadius, color: settings.selectionShadowColor.cgColor)
settings.selectionFillColor.setFill()
checkedOvalPath.fill()
context?.restoreGState()
settings.selectionStrokeColor.setStroke()
checkedOvalPath.lineWidth = 1
checkedOvalPath.stroke()
context?.setFillColor(UIColor.white.cgColor)
//// Check mark for single assets
if (settings.maxNumberOfSelections == 1) {
context?.setStrokeColor(UIColor.white.cgColor)
let pixelSize = rect.size.height / 8
let offsetX = pixelSize*1.5
let offsetY = pixelSize*1.0
let checkPath = UIBezierPath()
checkPath.move(to: CGPoint(x: offsetX + 1*pixelSize, y: offsetY + 3*pixelSize))
checkPath.addLine(to: CGPoint(x: offsetX + 2*pixelSize, y: offsetY + 4*pixelSize))
checkPath.addLine(to: CGPoint(x: offsetX + 4*pixelSize, y: offsetY + 2*pixelSize))
checkPath.lineWidth = pixelSize*1.25
checkPath.stroke()
return;
}
//// Bezier Drawing (Picture Number)
let size = selectionString.size(attributes: settings.selectionTextAttributes)
selectionString.draw(in: CGRect(x: checkmarkFrame.midX - size.width / 2.0,
y: checkmarkFrame.midY - size.height / 2.0,
width: size.width,
height: size.height), withAttributes: settings.selectionTextAttributes)
}
}
| mit | 189a3a6337cd8259f234010d43bf44c7 | 29.796296 | 302 | 0.55923 | 5.116923 | false | false | false | false |
zisko/swift | test/IRGen/osx-targets.swift | 9 | 424 | // RUN: %swift %s -emit-ir | %FileCheck %s
// RUN: %swift -target x86_64-apple-macosx10.12 %s -emit-ir | %FileCheck -check-prefix=CHECK-SPECIFIC %s
// RUN: %swift -target x86_64-apple-darwin16 %s -emit-ir | %FileCheck -check-prefix=CHECK-SPECIFIC %s
// REQUIRES: OS=macosx
// CHECK: target triple = "x86_64-apple-macosx10.
// CHECK-SPECIFIC: target triple = "x86_64-apple-macosx10.12.0"
public func anchor() {}
anchor()
| apache-2.0 | 7f6569f105bc9ad2ff1672709824c128 | 34.333333 | 104 | 0.688679 | 2.789474 | false | false | false | false |
rnystrom/VectorKit | VectorKit/Vectors.swift | 1 | 975 | //
// Vectors.swift
// ATCSim
//
// Created by Ryan Nystrom on 3/15/15.
// Copyright (c) 2015 Ryan Nystrom. All rights reserved.
//
import Foundation
import Darwin
public typealias Point = (x: Double, y: Double)
public func turnCenterOffset(radius: Double, heading: Double, isLeftTurn: Bool) -> Point {
let adjustment = isLeftTurn ? M_PI : 0.0
let angle = heading + adjustment
let x = radius * cos(angle)
let y = radius * sin(angle)
return (x, y)
}
public func turnCenter(radius: Double, heading: Double, isLeftTurn: Bool, point: Point) -> Point {
let offset = turnCenterOffset(radius, heading, isLeftTurn)
return (offset.x + point.x, offset.y + point.y)
}
public func tangentPoint(center: Point, tangent: Double, radius: Double, isLeftTurn: Bool) -> Point {
let adjustment = (isLeftTurn ? 1.0 : -1.0) * M_PI / 2.0
let theta = tangent + adjustment
let x = cos(theta) * radius
let y = sin(theta) * radius
return (center.x + x, center.y + y)
}
| mit | 9426da7fdccfccef964a1cd4acc51bfa | 28.545455 | 101 | 0.678974 | 3.217822 | false | false | false | false |
SagarSDagdu/SDDownloadManager | SDDownloadManager/Classes/SDDownloadObject.swift | 1 | 2012 | //
// SDDownloadObject.swift
// SDDownloadManager
//
// Created by Sagar Dagdu on 8/4/17.
// Copyright © 2017 Sagar Dagdu. 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 UIKit
class SDDownloadObject: NSObject {
var completionBlock: SDDownloadManager.DownloadCompletionBlock
var progressBlock: SDDownloadManager.DownloadProgressBlock?
let downloadTask: URLSessionDownloadTask
let directoryName: String?
let fileName:String?
init(downloadTask: URLSessionDownloadTask,
progressBlock: SDDownloadManager.DownloadProgressBlock?,
completionBlock: @escaping SDDownloadManager.DownloadCompletionBlock,
fileName: String?,
directoryName: String?) {
self.downloadTask = downloadTask
self.completionBlock = completionBlock
self.progressBlock = progressBlock
self.fileName = fileName
self.directoryName = directoryName
}
}
| mit | b2e906b09bbf7c63361ca265591ab97f | 39.22 | 81 | 0.737941 | 4.857488 | false | false | false | false |
slimane-swift/Hanger | Sources/ClientConnection.swift | 1 | 2725 | //
// Hanger.swift
// Hanger
//
// Created by Yuki Takei on 5/2/16.
//
//
@_exported import C7
@_exported import S4
@_exported import HTTP
@_exported import HTTPParser
@_exported import URI
@_exported import Suv
@_exported import CLibUv
public enum ClientConnectionState {
case Disconnected
case Connected
case Closed
}
public protocol HTTPConnection: AsyncConnection {
var state: ClientConnectionState { get }
}
public final class ClientConnection: HTTPConnection {
var _stream: TCP?
var stream: TCP {
return _stream!
}
public private(set) var state: ClientConnectionState = .Disconnected
public let uri: URI
public init(loop: Loop = Loop.defaultLoop, uri: URI) {
self._stream = TCP(loop: loop)
self.uri = uri
}
public var closed: Bool {
return stream.isClosing()
}
public func open(timingOut deadline: Double = .never, completion: ((Void) throws -> AsyncConnection) -> Void) throws {
stream.connect(host: self.uri.host ?? "0.0.0.0", port: self.uri.port ?? 80) {
if case .Error(let error) = $0 {
completion {
throw error
}
return
}
self.state = .Connected
completion {
self
}
}
}
public func send(_ data: Data, timingOut deadline: Double = .never, completion result: ((Void) throws -> Void) -> Void = { _ in}) {
stream.write(buffer: data.bufferd) { res in
result {
if case .Error(let error) = res {
throw error
}
}
}
}
public func receive(upTo byteCount: Int = 2048 /* ignored */, timingOut deadline: Double = .never, completion result: ((Void) throws -> Data) -> Void) {
stream.read { res in
if case .Data(let buf) = res {
result {
buf.data
}
} else if case .Error(let error) = res {
result {
throw error
}
} else {
result {
throw SuvError.UVError(code: UV_EOF.rawValue)
}
}
}
}
public func close() throws {
if closed {
throw StreamError.closedStream(data: [])
}
stream.close()
self._stream = nil
self.state = .Closed
}
public func unref() {
stream.unref()
}
public func flush(timingOut deadline: Double, completion result: ((Void) throws -> Void) -> Void = {_ in }) {
// noop
}
} | mit | e0a49cdad3be5f09c8329a6672ce1c13 | 24.476636 | 156 | 0.511927 | 4.526578 | false | false | false | false |
FirebaseExtended/crashlytics-migration-ios | Fabric/iOSApp/SecondViewController.swift | 1 | 6966 | //Copyright 2019 Google LLC
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//https://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// SecondViewController.swift
// sample1
//
//
import UIKit
import Crashlytics
class SecondViewController: UIViewController, UITextFieldDelegate {
var activeTextField: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textField: UITextField!
@IBOutlet var tapticButtons: [UIButton]!
@IBOutlet weak var searchTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for button in tapticButtons {
button.layer.cornerRadius = button.frame.size.height/2
}
registerForKeyboardNotifications()
textField.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
deregisterForKeyboardNotification()
}
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func deregisterForKeyboardNotification() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWasShown(notification: NSNotification) {
self.scrollView.isScrollEnabled = true
var userInfo = notification.userInfo!
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize!.height, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
var frameRect: CGRect = self.view.frame
frameRect.size.height -= keyboardSize!.height
if let activeField = self.activeTextField {
let activeOrigin = activeField.frame.origin
if frameRect.contains(activeOrigin) {
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}
@objc func keyboardWillDisappear(notification: NSNotification) {
var userInfo = notification.userInfo!
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -keyboardSize!.height, right: 0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
self.scrollView.isScrollEnabled = false
}
//TextField Delegate
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeTextField = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func searchButtonPressed(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
//Fabric Answers for logSearch
if let searchKeyword = self.textField.text {
Answers.logSearch(withQuery: searchKeyword,
customAttributes: nil)
} else {
Answers.logSearch(withQuery: "All",
customAttributes: nil)
}
}
@IBAction func appleAddToCartButtonPressed(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
//Fabric Answers for logAddToCart
Answers.logAddToCart(withPrice: 1.50,
currency: "USD",
itemName: "Answers Apple",
itemType: "Fruit",
itemId: "sku-100",
customAttributes: nil)
}
@IBAction func pearAddToCartButtonPressed(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
//Fabric Answers for logAddToCart
Answers.logAddToCart(withPrice: 2.50,
currency: "USD",
itemName: "Answers Pear",
itemType: "Fruit",
itemId: "sku-200",
customAttributes: nil)
}
@IBAction func orangeAddToCartButtonPressed(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
//Fabric Answers for logAddToCart
Answers.logAddToCart(withPrice: 1.00,
currency: "USD",
itemName: "Answers Orange",
itemType: "Fruit",
itemId: "sku-300",
customAttributes: nil)
}
@IBAction func purchaseEventBtnPressed(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
//Fabric Answers for logPurchase
Answers.logPurchase(withPrice: 30,
currency: "USD",
success: true,
itemName: "Fruit Basket",
itemType: "Fruits",
itemId: "APO-3",
customAttributes: nil)
}
}
| apache-2.0 | a4d475986b82c07449bbb95df6e5c505 | 34.360406 | 172 | 0.600775 | 5.873524 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.