repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AlbertXYZ/HDCP
|
refs/heads/master
|
HDCP/HDCP/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// HDCP
//
// Created by 徐琰璋 on 16/1/4.
// Copyright © 2016年 batonsoft. All rights reserved.
//
import UIKit
import CoreData
import Alamofire
import RxSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//设置导航栏和标签栏样式
setUpBarStyle();
//ShareSDK 初始化
HDShareSDKManager.initializeShareSDK();
//欢迎导航页面
showWelcome();
//监听网络变化
networkMonitoring();
//缓存参数设置
setCache();
//用户数据初始化
loadUserInfo();
add3DTouch();
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.
HDCoreDataManager.sharedInstance.saveContext()
}
// MARK: - 欢迎界面
func showWelcome() {
/**
* 判断欢迎界面是否已经执行
*/
let userDefault = UserDefaults.standard
let appVersion: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
if (userDefault.string(forKey: Constants.HDAppVersion)) == nil {
//第一次进入
userDefault.setValue(appVersion, forKey: Constants.HDAppVersion)
userDefault.synchronize()
self.window?.rootViewController = WelcomeController()
} else {
//版本升级后,根据版本号来判断是否进入
let version: String = (userDefault.string(forKey: Constants.HDAppVersion))!
if ( appVersion == version) {
// UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
self.window?.rootViewController = MainViewController()
} else {
userDefault.setValue(appVersion, forKey: Constants.HDAppVersion)
userDefault.synchronize()
self.window?.rootViewController = WelcomeController()
}
}
}
// MARK: - 设置导航栏和标签栏样式
func setUpBarStyle() {
/**
* 导航栏样式
*/
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "Heiti SC", size: 18.0)!]
UINavigationBar.appearance().barTintColor = Constants.HDMainColor
// UINavigationBar.appearance().barTintColor = CoreUtils.HDColor(245, g: 161, b: 0, a: 1)
/**
* 状态栏字体设置白色
*/
// UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
/**
* 底部TabBar的颜色
*/
UITabBar.appearance().shadowImage = UIImage()
UITabBar.appearance().tintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0)
UITabBar.appearance().backgroundColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0)
UITabBar.appearance().barTintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0)
// UITabBar.appearance().selectedImageTintColor = UIColor.clearColor()
/**
* 底部TabBar字体正常状态颜色
*/
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainTextColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.normal)
/**
* 底部TabBar字体选择状态颜色
*/
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.selected)
}
// MARK: - 网络监听
func networkMonitoring() {
// let reachability: Reachability
// do {
// reachability = try Reachability.reachabilityForInternetConnection()
// } catch {
// print("Unable to create Reachability")
// return
// }
//
//
// reachability.whenReachable = { reachability in
// // this is called on a background thread, but UI updates must
// // be on the main thread, like this:
// dispatch_async(dispatch_get_main_queue()) {
// if reachability.isReachableViaWiFi() {
// print("Reachable via WiFi")
// } else {
// print("Reachable via Cellular")
// }
// }
// }
// reachability.whenUnreachable = { reachability in
// // this is called on a background thread, but UI updates must
// // be on the main thread, like this:
// dispatch_async(dispatch_get_main_queue()) {
// print("Not reachable")
// }
// }
//
// do {
// try reachability.startNotifier()
// } catch {
// print("Unable to start notifier")
// }
}
// MARK: - 缓存参数设置
func setCache() {
//是否将图片缓存到内存
// SDImageCache.shared().shouldCacheImagesInMemory = true
// //缓存将保留5天
// SDImageCache.shared().maxCacheAge = 5*24*60*60
// //缓存最大占有内存100MB
// SDImageCache.shared().maxCacheSize = UInt(1024*1024*100)
}
// MARK: - 初始化当前登录用户数据
func loadUserInfo() {
//判断用户是否已登录
let defaults = UserDefaults.standard
let sign = defaults.object(forKey: Constants.HDSign)
if let _ = sign {
//初始化用户数据
HDUserInfoManager.shareInstance.load()
}
}
// MARK: - 添加3DTouch功能
func add3DTouch() {
if (UIDevice().systemVersion as NSString).doubleValue > 8.0 {
let ggShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_04");
let dtShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_on_02");
let myShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_05");
let ggShortcutItem = UIApplicationShortcutItem(type: "TAB_GG", localizedTitle: "逛逛", localizedSubtitle: "", icon: ggShortcutIcon, userInfo: nil);
let dtShortcutItem = UIApplicationShortcutItem(type: "TAB_DT", localizedTitle: "动态", localizedSubtitle: "", icon: dtShortcutIcon, userInfo: nil);
let myShortcutItem = UIApplicationShortcutItem(type: "TAB_CENTER", localizedTitle: "个人中心", localizedSubtitle: "", icon: myShortcutIcon, userInfo: nil);
UIApplication.shared.shortcutItems = [ggShortcutItem, dtShortcutItem, myShortcutItem];
}
}
// MARK: - 3DTouch事件处理
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if shortcutItem.type == "TAB_GG" {
let userDefualt = UserDefaults.standard;
userDefualt.set("1", forKey: Constants.HDPushIndex)
userDefualt.synchronize()
self.window?.rootViewController = MainViewController()
}
if shortcutItem.type == "TAB_DT" {
let userDefualt = UserDefaults.standard;
userDefualt.set("3", forKey: Constants.HDPushIndex)
userDefualt.synchronize()
self.window?.rootViewController = MainViewController()
}
if shortcutItem.type == "TAB_CENTER" {
let userDefualt = UserDefaults.standard;
userDefualt.set("4", forKey: Constants.HDPushIndex)
userDefualt.synchronize()
self.window?.rootViewController = MainViewController()
}
}
}
|
bb4b1d2719ba507487bda0ac25d73d21
| 35.952381 | 285 | 0.644652 | false | false | false | false |
mikker/Dispatcher
|
refs/heads/master
|
Dispatcher.swift
|
mit
|
1
|
public class Dispatcher {
public typealias Callback = Any? -> Void
public var tokenGenerator: TokenStream.Generator = TokenStream(prefix: "ID_").generate()
var callbacks: [String: Callback] = [:]
var isPending: [String: (Bool)] = [:]
var isHandled: [String: (Bool)] = [:]
var isDispatching: Bool = false
var pendingPayload: Any?
public init() {}
// Public
public func register(callback: Callback) -> String {
if let id = tokenGenerator.next() {
callbacks[id] = callback
return id
}
preconditionFailure("Dispatcher.register(...): Failed to generate token for registration.")
}
public func unregister(id: String) {
precondition(callbacks.keys.contains(id),
"Dispatcher.unregister(...): `\(id)` does not map to a registered callback.")
callbacks.removeValueForKey(id)
}
public func waitFor(ids: [String]) {
precondition(isDispatching, "Dispatcher.waitFor(...): Must be invoked while dispatching.")
for id in ids {
if (isPending[id]!) {
precondition(isHandled[id] != nil, "Dispatcher.waitFor(...): Circular dependency detected while waiting for `\(id)`.")
continue
}
invokeCallback(id)
}
}
public func dispatch(payload: Any?) {
precondition(!isDispatching, "Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.")
startDispatching(payload)
defer { stopDispatching() }
for id in callbacks.keys {
if isPending[id]! {
continue
}
invokeCallback(id)
}
}
// Private
private func invokeCallback(id: String) {
isPending[id] = true
callbacks[id]!(pendingPayload)
isHandled[id] = true
}
private func startDispatching(payload: Any?) {
for id in callbacks.keys {
isPending[id] = false
isHandled[id] = false
}
pendingPayload = payload
isDispatching = true
}
private func stopDispatching() {
pendingPayload = nil
isDispatching = false
}
}
// TokenStream
extension Dispatcher {
public struct TokenStream {
let prefix: String
}
}
extension Dispatcher.TokenStream: CollectionType {
public typealias Index = Int
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int.max }
public subscript(index: Int) -> String {
get { return "\(prefix)\(index)" }
}
public func generate() -> IndexingGenerator<Dispatcher.TokenStream> {
return IndexingGenerator(self)
}
}
|
b87c1d8af8daa69c4b21db187881ec4e
| 26.77 | 134 | 0.57889 | false | false | false | false |
306244907/Weibo
|
refs/heads/master
|
JLSina/JLSina/Classes/View(视图和控制器)/Compose撰写微博/JLComposeViewController.swift
|
mit
|
1
|
//
// JLComposeViewController.swift
// JLSina
//
// Created by 盘赢 on 2017/12/5.
// Copyright © 2017年 JinLong. All rights reserved.
//
import UIKit
import SVProgressHUD
//撰写微博控制器
/*
加载视图控制器的时候,如果XIB和控制器重名,默认的构造函数会优先加载XIB
*/
class JLComposeViewController: UIViewController {
///文本编辑视图
@IBOutlet weak var textView: JLComposeTextView!
///底部工具栏
@IBOutlet weak var toolBar: UIToolbar!
///发布按钮
@IBOutlet var sendButton: UIButton!
//标题标签 - 换行热键 option + 回车
///逐行选中文本并且设置属性
///如果要想调整行间距,增加空行,设置空行的字体,lineHeight
@IBOutlet var titleLabel: UILabel!
///工具栏底部约束
@IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
///表情输入视图
lazy var emoticonView = CZEmoticonInputView.inputView { [weak self](emoticon) in
//FIXME: -
self?.textView.insertEmoticon(em: emoticon)
}
//MARK: - 视图生命周期
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
//监听键盘通知 - UIWindow.h
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardChanged),
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//激活键盘
textView.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//关闭键盘
textView.resignFirstResponder()
}
//MARK: - 键盘监听
@objc private func keyboardChanged(n: Notification) {
// print(n.userInfo)
//1,目标rect
guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else {
return
}
//2,设置底部约束的高度
let offset = view.bounds.height - rect.origin.y
//3,更新底部约束
toolBarBottomCons.constant = offset
//动画更新约束
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
@objc private func close() {
dismiss(animated: true, completion: nil)
}
//MARK: - 监听方法
//发布微博
@IBAction func postStatus() {
//1,获取发送给服务器的表情微博文字
let text = textView.emtionText + "www.epermarket.com"
//2,发布微博, 想法带图片的,只需设置图片有没有就行
//FIXME: - 临时测试发布带图片的微博
let image: UIImage? = nil //UIImage(named: "icon_small_kangaroo_loading_1")
JLNetworkManager.shared.postStatus(text: text , image:image ) { (result, isSuccess) in
// print(result)
//修改指示器样式
SVProgressHUD.setDefaultStyle(.dark)
let message = isSuccess ? "发布成功" : "网络不给力"
SVProgressHUD.showInfo(withStatus: message)
//如果成功,延迟一段时间关闭当前窗口
//FIXME: 反向判断。!
if !isSuccess {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
//恢复样式
SVProgressHUD.setDefaultStyle(.light)
self.close()
}
}
}
}
///切换表情键盘
@objc private func emoticonKeyboard () {
//textView.inputView 就是文本框的输入视图
//如果使用系统默认的键盘,输入视图为 nil
//1,测试键盘视图 - 视图的宽度可以随便,就是屏幕的宽度,
// let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 253))
// keyboardView.backgroundColor = UIColor.blue
//2,设置键盘视图
textView.inputView = (textView.inputView == nil) ? emoticonView : nil
//3,!!!刷新键盘视图
textView.reloadInputViews()
}
}
//MARK: - UITextViewDelegate
/*
通知: 一对多, 只要有注册的监听者,在注销监听之前,都可以接收到通知
代理: 一对一,最后设置的代理对象有效!
苹果日常开发中,代理监听方式是最多的!
- 代理是发生事件时,直接让代理执行协议方法
代理的效率更高
直接的反向传值
- 通知是发生事件时,将通知发给通知中心,通知中心再‘广播’通知
通知相对要低一些
如果层次嵌套的非常深,可以使用通知传值
*/
extension JLComposeViewController: UITextViewDelegate {
/// 文本视图文字变化
func textViewDidChange(_ textView: UITextView) {
sendButton.isEnabled = textView.hasText
}
}
private extension JLComposeViewController {
func setupUI() {
view.backgroundColor = UIColor.white
setupNavtionBar()
setupToolBar()
}
///设置工具栏
func setupToolBar() {
let itemSettings = [
["imageName": "compose_toolbar_picture"],
["imageName": "compose_mentionbutton_background"],
["imageName": "compose_trendbutton_background"],
["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
["imageName": "compose_add_background"]
]
//遍历数组
var items = [UIBarButtonItem]()
for s in itemSettings {
guard let imageName = s["imageName"] else {
continue
}
let image = UIImage(named: imageName)
let imageHL = UIImage(named: imageName + "_highlighted")
let btn = UIButton()
btn.setImage(image, for: [])
btn.setImage(imageHL, for: .highlighted)
btn.sizeToFit()
//判断actionName
if let actionName = s["actionName"] {
//给按钮添加监听方法
btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
}
//追加按钮
items .append(UIBarButtonItem(customView: btn))
//追加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
}
// 删除末尾弹簧
items.removeLast()
toolBar.items = items
}
//设置导航栏
func setupNavtionBar() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
//设置发布按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
//设置标题视图
navigationItem.titleView = titleLabel
sendButton.isEnabled = false
}
}
|
6ffe1de426a3eb4ddccc3a6ecca6b39f
| 26.869565 | 115 | 0.557878 | false | false | false | false |
LesCoureurs/Coulomb
|
refs/heads/master
|
Courir/Pods/Coulomb/NetworkLib/CoulombNetwork.swift
|
mit
|
2
|
//
// CoulombNetwork.swift
// Coulomb
//
// Created by Ian Ngiaw on 3/14/16.
// Copyright © 2016 nus.cs3217.group5. All rights reserved.
//
import MultipeerConnectivity
import UIKit
public protocol CoulombNetworkDelegate: class {
func foundHostsChanged(foundHosts: [MCPeerID])
func invitationToConnectReceived(peer: MCPeerID, handleInvitation: (Bool) -> Void)
func connectedPeersInSessionChanged(peers: [MCPeerID])
func connectedToPeer(peer: MCPeerID)
func connectingToPeer(peer: MCPeerID)
func disconnectedFromSession(peer: MCPeerID)
func handleDataPacket(data: NSData, peerID: MCPeerID)
}
public class CoulombNetwork: NSObject {
// MARK: Public settings
/// Toggle on/off to print DLog messages to console
public var debugMode = false
public var autoAcceptGuests = true
public var maxNumPeerInRoom = 4
// MARK: Private settings
static let defaultTimeout: NSTimeInterval = 7
private var serviceAdvertiser: MCNearbyServiceAdvertiser?
private var serviceBrowser: MCNearbyServiceBrowser?
private var foundHosts = [MCPeerID]()
private let myPeerId: MCPeerID
private var host: MCPeerID?
private let serviceType: String
public weak var delegate: CoulombNetworkDelegate?
private lazy var session: MCSession = {
let session = MCSession(peer: self.myPeerId, securityIdentity: nil,
encryptionPreference: .Required)
session.delegate = self
return session
}()
public init(serviceType: String, myPeerId: MCPeerID) {
self.serviceType = serviceType
self.myPeerId = myPeerId
}
deinit {
stopAdvertisingHost()
stopSearchingForHosts()
session.disconnect()
}
// MARK: Methods for host
/// Start advertising.
/// Assign advertiser delegate
public func startAdvertisingHost() {
stopSearchingForHosts()
self.host = myPeerId
serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId,
discoveryInfo: ["peerType": "host"], serviceType: serviceType)
self.serviceAdvertiser?.delegate = self
self.serviceAdvertiser?.startAdvertisingPeer()
}
/// Stop advertising.
/// Unassign advertiser delegate
public func stopAdvertisingHost() {
serviceAdvertiser?.stopAdvertisingPeer()
serviceAdvertiser?.delegate = nil
}
// MARK: Methods for guest
/// Start looking for discoverable hosts
public func startSearchingForHosts() {
self.host = nil
serviceBrowser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: serviceType)
serviceBrowser?.delegate = self
foundHosts = []
serviceBrowser?.startBrowsingForPeers()
}
/// Stop looking for hosts
public func stopSearchingForHosts() {
serviceBrowser?.stopBrowsingForPeers()
}
/// Send inivitation to connect to a host
public func connectToHost(host: MCPeerID, context: NSData? = nil, timeout: NSTimeInterval = defaultTimeout) {
guard foundHosts.contains(host) else {
return
}
DLog("%@", "connect to host: \(host)")
serviceBrowser?.invitePeer(host, toSession: session, withContext: context, timeout: timeout)
// If the session is still without host, assign a new one
if self.host == nil {
self.host = host
}
}
/// Get the list of discovered hosts
public func getFoundHosts() -> [MCPeerID] {
return foundHosts
}
// MARK: Methods for session
/// Called when deliberately disconnect.
/// Disconnect from current session, browse for another host
public func disconnect() {
session.disconnect()
host = nil
DLog("%@", "disconnected from \(session.hashValue)")
}
/// Send data to every peer in session
public func sendData(data: NSData, mode: MCSessionSendDataMode) -> Bool {
do {
try session.sendData(data, toPeers: session.connectedPeers, withMode: mode)
} catch {
return false
}
return true
}
/// Return my peer ID
public func getMyPeerID() -> MCPeerID {
return myPeerId
}
/// Debug mode
private func DLog(message: String, _ function: String) {
if debugMode {
NSLog(message, function)
}
}
}
extension CoulombNetwork: MCNearbyServiceAdvertiserDelegate {
/// Invitation is received from guest
public func advertiser(advertiser: MCNearbyServiceAdvertiser,
didReceiveInvitationFromPeer peerID: MCPeerID,
withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) {
DLog("%@", "didReceiveInvitationFromPeer \(peerID)")
let acceptGuest = {
(accepted: Bool) -> Void in
invitationHandler(accepted, self.session)
}
if autoAcceptGuests {
acceptGuest(true)
} else {
delegate?.invitationToConnectReceived(peerID, handleInvitation: acceptGuest)
}
}
}
extension CoulombNetwork: MCNearbyServiceBrowserDelegate {
/// Peer is found in browser
public func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID,
withDiscoveryInfo info: [String : String]?) {
DLog("%@", "foundPeer: \(peerID)")
guard let discoveryInfo = info else {
return
}
guard discoveryInfo["peerType"] == "host" else {
return
}
foundHosts.append(peerID)
delegate?.foundHostsChanged(foundHosts)
}
/// Peer is lost in browser
public func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
guard foundHosts.contains(peerID) else {
return
}
DLog("%@", "lostPeer: \(peerID)")
let index = foundHosts.indexOf(peerID)!
foundHosts.removeAtIndex(index)
delegate?.foundHostsChanged(foundHosts)
}
}
extension CoulombNetwork: MCSessionDelegate {
// Handles MCSessionState changes: NotConnected, Connecting and Connected.
public func session(session: MCSession, peer peerID: MCPeerID,
didChangeState state: MCSessionState) {
DLog("%@", "peer \(peerID) didChangeState: \(state.stringValue())")
if state != .Connecting {
if state == .Connected {
DLog("%@", "connected to \(session.hashValue)")
// If currently a guest, stop looking for host
stopSearchingForHosts()
if self.host == peerID {
if session.connectedPeers.count >= maxNumPeerInRoom {
disconnect()
return
} else {
// Pass to delegate
delegate?.connectedToPeer(peerID)
}
}
} else {
DLog("%@", "not connected to \(session.hashValue)")
// If self is disconnected from current host
if self.host == peerID {
DLog("%@", "disconnected from host")
session.disconnect()
delegate?.disconnectedFromSession(peerID)
return
}
}
// If self did not disconnect deliberately
if self.host != nil {
delegate?.connectedPeersInSessionChanged(session.connectedPeers)
}
} else {
delegate?.connectingToPeer(peerID)
}
}
// Handles incomming NSData
public func session(session: MCSession, didReceiveData data: NSData,
fromPeer peerID: MCPeerID) {
delegate?.handleDataPacket(data, peerID: peerID)
}
// Handles incoming NSInputStream
public func session(session: MCSession, didReceiveStream stream: NSInputStream,
withName streamName: String, fromPeer peerID: MCPeerID) {
}
// Handles finish receiving resource
public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
}
// Handles start receiving resource
public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
}
}
// MARK: For Dlog messages
extension MCSessionState {
func stringValue() -> String {
switch(self) {
case .NotConnected: return "NotConnected"
case .Connecting: return "Connecting"
case .Connected: return "Connected"
}
}
}
|
1ed04bcc17584d7f9917441043dd5bff
| 32.507353 | 133 | 0.600132 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Plans/PlansLoadingIndicatorView.swift
|
gpl-2.0
|
2
|
import UIKit
import WordPressShared
// Circle View is 100x100 pixels
private struct Config {
// Icon images are 256 pixels high
struct Scale {
static let free: CGFloat = 0.25
static let premium: CGFloat = 0.35
static let business: CGFloat = 0.3
}
// Distance from view center
struct OffsetX {
static let free: CGFloat = -20
static let premium: CGFloat = 0
static let business: CGFloat = 20
}
// Final vertical offset from the center
struct OffsetY {
static let free: CGFloat = 30
static let premium: CGFloat = 12
static let business: CGFloat = 25
}
// Initial vertical offset from bottom of the circle view's bounding box
struct InitialOffsetY {
static let free: CGFloat = 0
static let premium: CGFloat = 0
static let business: CGFloat = 0
}
// The total duration of the animations, measured in seconds
struct Duration {
// Make this larger than 1 to slow down all animations
static let durationScale: TimeInterval = 1.2
static let free: TimeInterval = 1.4
static let premium: TimeInterval = 1
static let business: TimeInterval = 1.2
}
// The amount of time (measured in seconds) to wait before beginning the animations
struct Delay {
static let initial: TimeInterval = 0.3
static let free: TimeInterval = 0.35
static let premium: TimeInterval = 0.0
static let business: TimeInterval = 0.2
}
// The damping ratio for the spring animation as it approaches its quiescent state.
// To smoothly decelerate the animation without oscillation, use a value of 1. Employ a damping ratio closer to zero to increase oscillation.
struct SpringDamping {
static let free: CGFloat = 0.5
static let premium: CGFloat = 0.65
static let business: CGFloat = 0.5
}
// The initial spring velocity. For smooth start to the animation, match this value to the view’s velocity as it was prior to attachment.
// A value of 1 corresponds to the total animation distance traversed in one second. For example, if the total animation distance is 200 points and you want the start of the animation to match a view velocity of 100 pt/s, use a value of 0.5.
struct InitialSpringVelocity {
static let free: CGFloat = 0.1
static let premium: CGFloat = 0.01
static let business: CGFloat = 0.1
}
struct DefaultSize {
static let width: CGFloat = 100
static let height: CGFloat = 100
}
}
// ===========================================================================
private extension CGRect {
init(center: CGPoint, size: CGSize) {
self.init()
self.origin = CGPoint(x: center.x - size.width / 2, y: center.y - size.height / 2)
self.size = size
}
}
private extension CGSize {
func scaleBy(_ scale: CGFloat) -> CGSize {
return self.applying(CGAffineTransform(scaleX: scale, y: scale))
}
}
private extension UIView {
var boundsCenter: CGPoint {
return CGPoint(x: bounds.midX, y: bounds.midY)
}
}
class PlansLoadingIndicatorView: UIView {
fileprivate let freeView = UIImageView(image: UIImage(named: "plan-free-loading")!)
fileprivate let premiumView = UIImageView(image: UIImage(named: "plan-premium-loading")!)
fileprivate let businessView = UIImageView(image: UIImage(named: "plan-business-loading")!)
fileprivate let circleView = UIView()
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: Config.DefaultSize.width, height: Config.DefaultSize.height))
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .neutral(.shade5)
circleView.clipsToBounds = true
circleView.addSubview(premiumView)
circleView.addSubview(freeView)
circleView.addSubview(businessView)
addSubview(circleView)
freeView.frame = targetFreeFrame
premiumView.frame = targetPremiumFrame
businessView.frame = targetBusinessFrame
circleView.backgroundColor = UIColor(red: 211/255, green: 222/255, blue: 230/255, alpha: 1)
circleView.layer.cornerRadius = 50
setInitialPositions()
}
fileprivate var targetFreeFrame: CGRect {
let freeCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.free, y: Config.OffsetY.free))
let freeSize = freeView.sizeThatFits(bounds.size).scaleBy(Config.Scale.free)
return CGRect(center: freeCenter, size: freeSize)
}
fileprivate var targetPremiumFrame: CGRect {
let premiumCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.premium, y: Config.OffsetY.premium))
let premiumSize = premiumView.sizeThatFits(bounds.size).scaleBy(Config.Scale.premium)
return CGRect(center: premiumCenter, size: premiumSize)
}
fileprivate var targetBusinessFrame: CGRect {
let businessCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.business, y: Config.OffsetY.business))
let businessSize = businessView.sizeThatFits(bounds.size).scaleBy(Config.Scale.business)
return CGRect(center: businessCenter, size: businessSize)
}
fileprivate func setInitialPositions() {
let freeOffset = Config.InitialOffsetY.free + bounds.size.height - targetFreeFrame.origin.y
freeView.transform = CGAffineTransform(translationX: 0, y: freeOffset)
let premiumOffset = Config.InitialOffsetY.premium + bounds.size.height - targetPremiumFrame.origin.y
premiumView.transform = CGAffineTransform(translationX: 0, y: premiumOffset)
let businessOffset = Config.InitialOffsetY.business + bounds.size.height - targetBusinessFrame.origin.y
businessView.transform = CGAffineTransform(translationX: 0, y: businessOffset)
}
override func layoutSubviews() {
super.layoutSubviews()
let size = min(bounds.width, bounds.height)
circleView.frame = CGRect(center: boundsCenter, size: CGSize(width: size, height: size))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
animateAfterDelay(Config.Delay.initial)
}
@objc func animateAfterDelay(_ delay: TimeInterval) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { [weak self] in self?.animate() }
)
}
@objc func animate() {
UIView.performWithoutAnimation {
self.setInitialPositions()
}
UIView.animate(
withDuration: Config.Duration.free * Config.Duration.durationScale,
delay: Config.Delay.free * Config.Duration.durationScale,
usingSpringWithDamping: Config.SpringDamping.free,
initialSpringVelocity: Config.InitialSpringVelocity.free,
options: .curveEaseOut,
animations: { [unowned freeView] in
freeView.transform = CGAffineTransform.identity
})
UIView.animate(
withDuration: Config.Duration.premium * Config.Duration.durationScale,
delay: Config.Delay.premium * Config.Duration.durationScale,
usingSpringWithDamping: Config.SpringDamping.premium,
initialSpringVelocity: Config.InitialSpringVelocity.premium,
options: .curveEaseOut,
animations: { [unowned premiumView] in
premiumView.transform = CGAffineTransform.identity
})
UIView.animate(
withDuration: Config.Duration.business * Config.Duration.durationScale,
delay: Config.Delay.business * Config.Duration.durationScale,
usingSpringWithDamping: Config.SpringDamping.business,
initialSpringVelocity: Config.InitialSpringVelocity.business,
options: .curveEaseOut,
animations: { [unowned businessView] in
businessView.transform = CGAffineTransform.identity
})
}
}
|
f369646a4951eafaffab533211d5ae51
| 39.009615 | 245 | 0.665946 | false | true | false | false |
wireapp/wire-ios-data-model
|
refs/heads/develop
|
Source/Model/AccountStore.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2017 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
private let log = ZMSLog(tag: "Accounts")
/// Persistence layer for `Account` objects.
/// Objects are stored in files named after their identifier like this:
///
/// ```
/// - Root url passed to init
/// - Accounts
/// - 47B3C313-E3FA-4DE4-8DBE-5BBDB6A0A14B
/// - 0F5771BB-2103-4E45-9ED2-E7E6B9D46C0F
/// ```
public final class AccountStore: NSObject {
private static let directoryName = "Accounts"
private let fileManager = FileManager.default
private let directory: URL // The url to the directory in which accounts are stored in
/// Creates a new `AccountStore`.
/// `Account` objects will be stored in a subdirectory of the passed in url.
/// - parameter root: The root url in which the storage will use to store its data
public required init(root: URL) {
directory = root.appendingPathComponent(AccountStore.directoryName)
super.init()
FileManager.default.createAndProtectDirectory(at: directory)
}
// MARK: - Storing and Retrieving
/// Loads all stored accounts.
/// - returns: All accounts stored in this `AccountStore`.
func load() -> Set<Account> {
return Set<Account>(loadURLs().compactMap(Account.load))
}
/// Tries to load a stored account with the given `UUID`.
/// - parameter uuid: The `UUID` of the user the account belongs to.
/// - returns: The `Account` stored for the passed in `UUID`, or `nil` otherwise.
func load(_ uuid: UUID) -> Account? {
return Account.load(from: url(for: uuid))
}
/// Stores an `Account` in the account store.
/// - parameter account: The account which should be saved (or updated).
/// - returns: Whether or not the operation was successful.
@discardableResult func add(_ account: Account) -> Bool {
do {
try account.write(to: url(for: account))
return true
} catch {
log.error("Unable to store account \(account), error: \(error)")
return false
}
}
/// Deletes an `Account` from the account store.
/// - parameter account: The account which should be deleted.
/// - returns: Whether or not the operation was successful.
@discardableResult func remove(_ account: Account) -> Bool {
do {
guard contains(account) else { return false }
try fileManager.removeItem(at: url(for: account))
return true
} catch {
log.error("Unable to delete account \(account), error: \(error)")
return false
}
}
/// Deletes the persistence layer of an `AccountStore` from the file system.
/// Mostly useful for cleaning up after tests or for complete account resets.
/// - parameter root: The root url of the store that should be deleted.
@discardableResult static func delete(at root: URL) -> Bool {
do {
try FileManager.default.removeItem(at: root.appendingPathComponent(directoryName))
return true
} catch {
log.error("Unable to remove all accounts at \(root): \(error)")
return false
}
}
/// Check if an `Account` is already stored in this `AccountStore`.
/// - parameter account: The account which should be deleted.
/// - returns: Whether or not the account is stored in this `AccountStore`.
func contains(_ account: Account) -> Bool {
return fileManager.fileExists(atPath: url(for: account).path)
}
// MARK: - Private Helper
/// Loads the urls to all stored accounts.
/// - returns: The urls to all accounts stored in this `AccountStore`.
private func loadURLs() -> Set<URL> {
do {
let uuidName: (String) -> Bool = { UUID(uuidString: $0) != nil }
let paths = try fileManager.contentsOfDirectory(atPath: directory.path)
return Set<URL>(paths.filter(uuidName).map(directory.appendingPathComponent))
} catch {
log.error("Unable to load accounts from \(directory), error: \(error)")
return []
}
}
/// Create a local url for an `Account` inside this `AccountStore`.
/// - parameter account: The account for which the url should be generated.
/// - returns: The `URL` for the given account.
private func url(for account: Account) -> URL {
return url(for: account.userIdentifier)
}
/// Create a local url for an `Account` with the given `UUID` inside this `AccountStore`.
/// - parameter uuid: The uuid of the user for which the url should be generated.
/// - returns: The `URL` for the given uuid.
private func url(for uuid: UUID) -> URL {
return directory.appendingPathComponent(uuid.uuidString)
}
}
|
5c4231b480c4a51358928541a39379da
| 38.875912 | 94 | 0.646714 | false | false | false | false |
zmian/xcore.swift
|
refs/heads/main
|
Sources/Xcore/Swift/Components/FeatureFlag/Core/FeatureFlag+Providers.swift
|
mit
|
1
|
//
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
// MARK: - Registration
extension FeatureFlag {
/// The registered list of providers.
private static var provider = CompositeFeatureFlagProvider([
ProcessInfoEnvironmentVariablesFeatureFlagProvider()
])
/// Register the given provider if it's not already registered.
///
/// - Note: This method ensures there are no duplicate providers.
public static func register(_ provider: FeatureFlagProvider) {
self.provider.add(provider)
}
}
// MARK: - FeatureFlag.Key Convenience
extension FeatureFlag.Key {
private var currentValue: FeatureFlag.Value? {
FeatureFlag.provider.value(forKey: self)
}
/// Returns the value of the key from registered list of feature flag providers.
///
/// - Returns: The value for the key.
public func value() -> Bool {
currentValue?.get() ?? false
}
/// Returns the value of the key from registered list of feature flag providers.
///
/// - Returns: The value for the key.
public func value<T>() -> T? {
currentValue?.get()
}
/// Returns the value of the key from registered list of feature flag providers.
///
/// - Parameter defaultValue: The value returned if the providers list doesn't
/// contain value.
/// - Returns: The value for the key.
public func value<T>(default defaultValue: @autoclosure () -> T) -> T {
currentValue?.get() ?? defaultValue()
}
/// Returns the value of the key from registered list of feature flag providers.
///
/// - Parameter defaultValue: The value returned if the providers list doesn't
/// contain value.
/// - Returns: The value for the key.
public func value<T>(default defaultValue: @autoclosure () -> T) -> T where T: RawRepresentable, T.RawValue == String {
currentValue?.get() ?? defaultValue()
}
/// Returns the value of the key, decoded from a JSON object, from registered
/// list of feature flag providers.
///
/// - Parameters:
/// - type: The type of the value to decode from the string.
/// - decoder: The decoder used to decode the data. If set to `nil`, it uses
/// ``JSONDecoder`` with `convertFromSnakeCase` key decoding strategy.
/// - Returns: A value of the specified type, if the decoder can parse the data.
public func decodedValue<T>(_ type: T.Type = T.self, decoder: JSONDecoder? = nil) -> T? where T: Decodable {
currentValue?.get(type, decoder: decoder)
}
}
|
1aaeb71156763bc6b35394b9b5a363b0
| 33.813333 | 123 | 0.649177 | false | false | false | false |
mcarter6061/FetchedResultsCoordinator
|
refs/heads/master
|
Example/Tests/CollectionViewTests.swift
|
mit
|
1
|
// Copyright © 2016 Mark Carter. All rights reserved.
import XCTest
import Quick
import Nimble
@testable import FetchedResultsCoordinator
import CoreData
class CollectionViewTests: QuickSpec {
override func spec() {
describe("With a collection view") {
let indexPathZero = NSIndexPath( forRow:0, inSection:0 )
let indexPathOne = NSIndexPath( forRow:1, inSection:0 )
let indexSet = NSMutableIndexSet(index: 5)
var sut: SpyCollectionView!
var changes:ChangeSet!
beforeEach({
sut = SpyCollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
changes = ChangeSet()
})
it("reloads data") {
sut.reloadData()
}
it("applies no changes") {
changes.objectChanges = []
sut.apply(changes)
let expected = CollectionViewInvocation.PerformBatchUpdates
expect(sut.capturedCalls).to(equal([expected]))
}
it("updates table when section inserted") {
changes.insertedSections = indexSet
sut.apply( changes )
let expected = CollectionViewInvocation.InsertSections(indexSet)
expect(sut.capturedCalls).to(contain(expected))
}
it("updates table when section inserted") {
changes.deletedSections = indexSet
sut.apply( changes )
let expected = CollectionViewInvocation.DeleteSections(indexSet)
expect(sut.capturedCalls).to(contain(expected))
}
it("updates table when data inserted") {
changes.objectChanges = [.Insert(indexPathZero)]
sut.apply( changes )
let expected = CollectionViewInvocation.InsertItemssAtIndexPaths(indexPaths:[indexPathZero])
expect(sut.capturedCalls).to(contain(expected))
}
it("updates table when data deleted") {
changes.objectChanges = [.Delete(indexPathZero)]
sut.apply( changes )
let expected = CollectionViewInvocation.DeleteItemssAtIndexPaths(indexPaths:[indexPathZero])
expect(sut.capturedCalls).to(contain(expected))
}
it("updates table when data moved") {
changes.objectChanges = [.Move(from:indexPathZero,to:indexPathOne)]
sut.apply( changes )
let expectedA:CollectionViewInvocation = .DeleteItemssAtIndexPaths(indexPaths:[indexPathZero])
let expectedB:CollectionViewInvocation = .InsertItemssAtIndexPaths(indexPaths:[indexPathOne])
expect(sut.capturedCalls).to(contain(expectedA,expectedB))
}
it("updates table when data updated") {
changes.objectChanges = [.Update(indexPathZero)]
sut.apply( changes )
let expected = CollectionViewInvocation.ReloadItemssAtIndexPaths(indexPaths:[indexPathZero])
expect(sut.capturedCalls).to(contain(expected))
}
it("doesn't update table when cell reloaded") {
changes.objectChanges = [.CellConfigure( {} )]
sut.apply(changes)
let rejected = CollectionViewInvocation.ReloadItemssAtIndexPaths(indexPaths:[indexPathZero])
expect(sut.capturedCalls).toNot(contain(rejected))
}
it("calls reload cell function when cell reloaded") {
var calledReload = false
changes.objectChanges = [.CellConfigure( {calledReload = true} )]
sut.apply(changes)
expect(calledReload).to(beTrue())
}
// TODO: finish porting over tests from tableview objc tests.
}
}
}
|
0044a756e0674d6ebcd73cc4c7391b24
| 38.626168 | 110 | 0.548007 | false | false | false | false |
bengottlieb/ios
|
refs/heads/master
|
FiveCalls/FiveCallsUITests/FiveCallsUITests.swift
|
mit
|
1
|
//
// FiveCallsUITests.swift
// FiveCallsUITests
//
// Created by Ben Scheirman on 2/8/17.
// Copyright © 2017 5calls. All rights reserved.
//
import XCTest
@testable import FiveCalls
class FiveCallsUITests: XCTestCase {
var app: XCUIApplication!
override func setUp() {
super.setUp()
continueAfterFailure = false
app = XCUIApplication()
app.launchEnvironment = ["UI_TESTING" : "1"]
loadJSONFixtures(application: app)
setupSnapshot(app)
app.launch()
}
override func tearDown() {
super.tearDown()
}
func testTakeScreenshots() {
snapshot("0-welcome")
let label = app.staticTexts["Turn your passive participation into active resistance. Facebook likes and Twitter retweets can’t create the change you want to see. Calling your Government on the phone can."]
label.swipeLeft()
snapshot("1-welcome2")
app.buttons["Get Started"].tap()
app.buttons["Set Location"].tap()
app.textFields["Zip or Address"].tap()
app.typeText("77429")
app.buttons["Submit"].tap()
snapshot("2-issues")
app.tables.cells.staticTexts["Defend the Affordable Care Act"].tap()
snapshot("3-issue-detail")
let issueTable = app.tables.element(boundBy: 0)
issueTable.swipeUp()
issueTable.swipeUp()
issueTable.swipeUp()
app.cells.staticTexts["Ted Cruz"].tap()
snapshot("4-call-script")
}
private func loadJSONFixtures(application: XCUIApplication) {
let bundle = Bundle(for: FiveCallsUITests.self)
application.launchEnvironment["GET:/issues"] = bundle.path(forResource: "GET-issues", ofType: "json")
application.launchEnvironment["GET:/report"] = bundle.path(forResource: "GET-report", ofType: "json")
application.launchEnvironment["POST:/report"] = bundle.path(forResource: "POST-report", ofType: "json")
}
}
|
b33da4ac5cca817826af4a63c6fa6775
| 30.625 | 213 | 0.62747 | false | true | false | false |
firebase/friendlypix-ios
|
refs/heads/master
|
FriendlyPix/UIImage+Circle.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2017 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.
//
import SDWebImage
import Firebase
extension UIImage {
var circle: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
//let square = CGSize(width: 36, height: 36)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width / 2
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContext(imageView.bounds.size)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
func resizeImage(_ dimension: CGFloat) -> UIImage {
var width: CGFloat
var height: CGFloat
var newImage: UIImage
let size = self.size
let aspectRatio = size.width / size.height
if aspectRatio > 1 { // Landscape image
width = dimension
height = dimension / aspectRatio
} else { // Portrait image
height = dimension
width = dimension * aspectRatio
}
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
newImage = renderer.image { _ in
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
}
} else {
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
func resizeImage(_ dimension: CGFloat, with quality: CGFloat) -> Data? {
return resizeImage(dimension).jpegData(compressionQuality: quality)
}
static func circleImage(with url: URL, to imageView: UIImageView) {
let urlString = url.absoluteString
let trace = Performance.startTrace(name: "load_profile_pic")
if let image = SDImageCache.shared.imageFromCache(forKey: urlString) {
trace?.incrementMetric("cache", by: 1)
trace?.stop()
imageView.image = image
return
}
SDWebImageDownloader.shared.downloadImage(with: url,
options: .highPriority, progress: nil) { image, _, error, _ in
trace?.incrementMetric("download", by: 1)
trace?.stop()
if let error = error {
print(error)
return
}
if let image = image {
let circleImage = image.circle
SDImageCache.shared.store(circleImage, forKey: urlString, completion: nil)
imageView.image = circleImage
}
}
}
static func circleButton(with url: URL, to button: UIBarButtonItem) {
let urlString = url.absoluteString
let trace = Performance.startTrace(name: "load_profile_pic")
if let image = SDImageCache.shared.imageFromCache(forKey: urlString) {
trace?.incrementMetric("cache", by: 1)
trace?.stop()
button.image = image.resizeImage(36).withRenderingMode(.alwaysOriginal)
return
}
SDWebImageDownloader.shared.downloadImage(with: url, options: .highPriority, progress: nil) { image, _, _, _ in
trace?.incrementMetric("download", by: 1)
trace?.stop()
if let image = image {
let circleImage = image.circle
button.tintColor = .red
SDImageCache.shared.store(circleImage, forKey: urlString, completion: nil)
button.image = circleImage?.resizeImage(36).withRenderingMode(.alwaysOriginal)
}
}
}
}
|
3cbd12a2436c5178aff46974d22c0edc
| 36.101695 | 115 | 0.665372 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
refs/heads/master
|
MobilePeopleDirectory/ServerAsyncCallback.swift
|
gpl-3.0
|
1
|
//
// ServerSyncCallback.swift
// MobilePeopleDirectory
//
// Created by alejandro soto on 2/3/15.
// Copyright (c) 2015 Rivet Logic. All rights reserved.
//
import UIKit
import CoreData
class ServerAsyncCallback:NSObject, LRCallback {
private var _syncable:ServerSyncableProtocol
private var _primaryKey:String
private var _itemsCountKey:String
private var _listKey:String
private var _errorHandler: ((ServerFetchResult!) -> Void)!
var appHelper = AppHelper()
init(syncable:ServerSyncableProtocol, primaryKey:String, itemsCountKey:String, listKey:String, errorHandler: ((ServerFetchResult!) -> Void)!) {
self._syncable = syncable
self._primaryKey = primaryKey
self._itemsCountKey = itemsCountKey
self._listKey = listKey
self._errorHandler = errorHandler
}
func onFailure(error: NSError!) {
switch (error.code) {
//case -1001:
default:
self._errorHandler(ServerFetchResult.ConnectivityIssue)
break;
}
}
func onSuccess(result: AnyObject!) {
var response = result as! NSDictionary
var items = response[self._listKey] as! NSArray
var activeItemsCount = response[self._itemsCountKey] as! NSInteger
println("Items retrieved from server : \(items.count)")
var managedObjectContext = appHelper.getManagedContext()
for item in items {
// checks if item exists
if self._syncable.itemExists(item[self._primaryKey] as! NSInteger) {
var existentItem = self._syncable.getItemById(item[self._primaryKey] as! NSInteger) as NSManagedObject
// update item with latest data
existentItem = self._syncable.fillItem(item as! NSDictionary, managedObject: existentItem)
managedObjectContext!.save(nil)
} else {
self._syncable.addItem(item as! NSDictionary)
}
}
// if items unsynced retrieve entire data from server
if (self._areItemsUnsynced(activeItemsCount)) {
//self._syncable.removeAllItems()
var session = SessionContext.createSessionFromCurrentSession()
var asyncCallback = ServerAsyncCallback(syncable: self._syncable,
primaryKey: self._primaryKey,
itemsCountKey: self._itemsCountKey,
listKey: self._listKey,
errorHandler: self._errorHandler)
session?.callback = asyncCallback
//self._syncable.getServerData(0.0, session: &session!)
}
}
private func _areItemsUnsynced(serverActiveItemsCount:NSInteger) -> Bool {
let storedItemsCount = self._syncable.getItemsCount()
return (storedItemsCount != serverActiveItemsCount)
}
}
|
5ed51f52845a1b1c86c3c117035c4a63
| 37.052632 | 147 | 0.628976 | false | false | false | false |
seongkyu-sim/BaseVCKit
|
refs/heads/master
|
BaseVCKit/Classes/extensions/UILabelExtensions.swift
|
mit
|
1
|
//
// UILabelExtensions.swift
// BaseVCKit
//
// Created by frank on 2015. 11. 10..
// Copyright © 2016년 colavo. All rights reserved.
//
import UIKit
public extension UILabel {
static func configureLabel(color:UIColor, size:CGFloat, weight: UIFont.Weight = UIFont.Weight.regular) -> UILabel {
let label = UILabel()
label.textAlignment = NSTextAlignment.left
label.font = UIFont.systemFont(ofSize: size, weight: weight)
label.textColor = color
label.numberOfLines = 0
return label
}
// MARK: - Attributed
func setAttributedText(fullText: String, highlightText: String, highlightColor: UIColor? = nil, highlightFontWeight: UIFont.Weight? = nil) {
let range = (fullText as NSString).range(of: highlightText)
let attributedString = NSMutableAttributedString(string:fullText)
if let highlightColor = highlightColor { // height color
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: highlightColor , range: range)
}
// set bold
var originFontSize = CGFloat(15)
if let originFont = self.font {
originFontSize = originFont.pointSize
}
var font = UIFont.systemFont(ofSize: originFontSize, weight: UIFont.Weight.medium)
if let highlightFontWeight = highlightFontWeight {
font = UIFont.systemFont(ofSize: originFontSize, weight: highlightFontWeight)
}
attributedString.addAttribute(NSAttributedString.Key.font, value: font , range: range)
self.attributedText = attributedString
}
// MARK: - Strikethrough line
func renderStrikethrough(text:String?, color:UIColor = UIColor.black) {
guard let text = text else {
return
}
let attributedText = NSMutableAttributedString(string: text , attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue, NSAttributedString.Key.strikethroughColor: color])
attributedText.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: NSMakeRange(0, attributedText.length))
self.attributedText = attributedText
}
// MARK: - Ellipse Indecator
func startEllipseAnimate(withText txt: String = "") {
defaultTxt = txt
stopEllipseAnimate()
ellipseTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { timer in
self.ellipseUpdate(loading: true)
}
}
func stopEllipseAnimate() {
if let aTimer = ellipseTimer {
aTimer.invalidate()
ellipseTimer = nil
}
ellipseUpdate(loading: false)
}
private struct AssociatedKeys {
static var ellipseTimerKey = "ellipseTimer"
static var defaultTxtKey = "defaultTxtKey"
}
private var ellipseTimer: Timer? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ellipseTimerKey) as? Timer
}
set {
willChangeValue(forKey: "ellipseTimer")
objc_setAssociatedObject(self, &AssociatedKeys.ellipseTimerKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
didChangeValue(forKey: "ellipseTimer")
}
}
private var defaultTxt: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.defaultTxtKey) as? String
}
set {
if let newValue = newValue {
willChangeValue(forKey: "defaultTxt")
objc_setAssociatedObject(self, &AssociatedKeys.defaultTxtKey, newValue as NSString?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "defaultTxt")
}
}
}
private func ellipseUpdate(loading: Bool) {
guard let defaultTxt = defaultTxt else {
return
}
guard loading else {
self.text = defaultTxt
return
}
if self.text == defaultTxt {
self.text = defaultTxt + "."
}else if self.text == defaultTxt + "." {
self.text = defaultTxt + ".."
}else if self.text == defaultTxt + ".." {
self.text = defaultTxt + "..."
}else {
self.text = defaultTxt
}
}
}
|
0ff6309896e900f156f6d00f7f9d84d5
| 32.695313 | 210 | 0.634593 | false | false | false | false |
kyotaw/ZaifSwift
|
refs/heads/master
|
ZaifSwiftTests/ZaifSwiftTests.swift
|
mit
|
1
|
//
// ZaifSwiftTests.swift
// ZaifSwiftTests
//
// Created by 渡部郷太 on 6/30/16.
// Copyright © 2016 watanabe kyota. All rights reserved.
//
import XCTest
import ZaifSwift
private let api = PrivateApi(apiKey: key_full, secretKey: secret_full)
class ZaifSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testGetInfo() {
// successfully complete
let successExpectation = self.expectation(description: "get_info success")
api.getInfo() { (err, res) in
XCTAssertNil(err, "get_info success. err is nil")
XCTAssertNotNil(res, "get_info success. res is not nil")
successExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// keys has no permission for get_info
let noPermissionExpectation = self.expectation(description: "no permission error")
let api2 = ZaifSwift.PrivateApi(apiKey: key_no_info, secretKey: secret_no_info)
api2.getInfo() { (err, res) in
XCTAssertNotNil(err, "no permission. err is not nil")
switch err!.errorType {
case ZaifSwift.ZSErrorType.INFO_API_NO_PERMISSION:
XCTAssertTrue(true, "no permission exception")
default:
XCTFail()
}
noPermissionExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
//invalid key
let invalidKeyExpectaion = self.expectation(description: "invalid key error")
let key_invalid = "INVALID"
let api6 = PrivateApi(apiKey: key_invalid, secretKey: secret_full)
api6.getInfo() { (err, res) in
XCTAssertNotNil(err, "invalid key. err is not nil")
XCTAssertTrue(true)
/*
switch err!.errorType {
case ZaifSwift.ZSErrorType.INVALID_API_KEY:
XCTAssertTrue(true)
default:
XCTFail()
}
*/
invalidKeyExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
//invalid secret
let invalidSecretExpectaion = self.expectation(description: "invalid secret error")
let secret_invalid = "INVALID"
let api5 = ZaifSwift.PrivateApi(apiKey: key_no_trade, secretKey: secret_invalid)
api5.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZaifSwift.ZSErrorType.INVALID_SIGNATURE:
XCTAssertTrue(true)
default:
XCTFail()
}
invalidSecretExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce exceeds limit
let nonceExceedExpectaion = self.expectation(description: "nonce exceed limit error")
let nonce = SerialNonce(initialValue: IntMax.max)
let _ = try! nonce.getNonce()
let api7 = PrivateApi(apiKey: key_full, secretKey: secret_full, nonce: nonce)
api7.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceExceedExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce out of range
let nonceOutOfRangeExpectaion = self.expectation(description: "nonce out of range error")
let nonce2 = SerialNonce(initialValue: IntMax.max)
let api8 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce2)
api8.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceOutOfRangeExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce not incremented
let nonceNotIncremented = self.expectation(description: "nonce not incremented error")
let nonce3 = SerialNonce(initialValue: 1)
let api9 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce3)
api9.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_NOT_INCREMENTED:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceNotIncremented.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// connection error
/*
let connectionErrorExpectation = self.expectationWithDescription("connection error")
let api5 = PrivateApi(apiKey: key_full, secretKey: secret_full)
api5.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.CONNECTION_ERROR:
XCTAssertTrue(true)
default:
XCTAssertTrue(true)
}
connectionErrorExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(10.0, handler: nil)
*/
}
func testTradeBtcJpy() {
// keys has no permission for trade
let noPermissionExpectation = self.expectation(description: "no permission error")
let api_no_trade = PrivateApi(apiKey: key_no_trade, secretKey: secret_no_trade)
let dummyOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001)
api_no_trade.trade(dummyOrder) { (err, res) in
XCTAssertNotNil(err, "no permission. err is not nil")
switch err!.errorType {
case ZSErrorType.TRADE_API_NO_PERMISSION:
XCTAssertTrue(true, "no permission exception")
default:
XCTFail()
}
noPermissionExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy btc_jpy
let btcJpyExpectation = self.expectation(description: "buy btc_jpy order success")
let btcOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001)
api.trade(btcOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price (border)
let btcJpyExpectation20 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder20 = Trade.Buy.Btc.In.Jpy.createOrder(5, amount: 0.0001)
api.trade(btcOrder20) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation20.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy btc_jpy with limit
let btcJpyExpectation4 = self.expectation(description: "buy btc_jpy order with limit success")
let btcOrder4 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60005)
api.trade(btcOrder4) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation4.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price
let btcJpyExpectation2 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder2 = Trade.Buy.Btc.In.Jpy.createOrder(60001, amount: 0.0001)
api.trade(btcOrder2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (border)
let btcJpyExpectation22 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder22 = Trade.Buy.Btc.In.Jpy.createOrder(4, amount: 0.0001)
api.trade(btcOrder22) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation22.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (minus)
let btcJpyExpectation11 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder11 = Trade.Buy.Btc.In.Jpy.createOrder(-60000, amount: 0.0001)
api.trade(btcOrder11) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation11.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (zero)
let btcJpyExpectation12 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder12 = Trade.Buy.Btc.In.Jpy.createOrder(0, amount: 0.0001)
api.trade(btcOrder12) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation12.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit
let btcJpyExpectation3 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder3 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60002)
api.trade(btcOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit (minus)
let btcJpyExpectation13 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder13 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: -60005)
api.trade(btcOrder13) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation13.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit (zero)
let btcJpyExpectation14 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder14 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 0)
api.trade(btcOrder14) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation14.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount
let btcJpyExpectation5 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder5 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00011)
api.trade(btcOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount (minus)
let btcJpyExpectation15 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder15 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: -0.0001)
api.trade(btcOrder15) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation15.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount (zero)
let btcJpyExpectation16 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder16 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0)
api.trade(btcOrder16) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation16.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell btc_jpy
let btcJpyExpectation6 = self.expectation(description: "sell btc_jpy order success")
let btcOrder6 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001)
api.trade(btcOrder6) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation6.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell btc_jpy with limit
let btcJpyExpectation7 = self.expectation(description: "sell btc_jpy order with limit success")
let btcOrder7 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001, limit: 79995)
api.trade(btcOrder7) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation7.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price
let btcJpyExpectation8 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder8 = Trade.Sell.Btc.For.Jpy.createOrder(79999, amount: 0.0001)
api.trade(btcOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit
let btcJpyExpectation9 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder9 = Trade.Buy.Btc.In.Jpy.createOrder(80000, amount: 0.0001, limit: 79998)
api.trade(btcOrder9) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount
let btcJpyExpectation10 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder10 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00009)
api.trade(btcOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTradeMonaJpy() {
// buy mona_jpy
let monaJpyExpectation = self.expectation(description: "buy mona_jpy order success")
let monaOrder = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1)
api.trade(monaOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price (min)
let monaJpyExpectation60 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder60 = Trade.Buy.Mona.In.Jpy.createOrder(0.1, amount: 1)
api.trade(monaOrder60) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation60.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy mona_jpy with limit
let monaJpyExpectation2 = self.expectation(description: "buy mona_jpy order with limit success")
let monaOrder2 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 4.1)
api.trade(monaOrder2) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation2.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price
let monaJpyExpectation3 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder3 = Trade.Buy.Mona.In.Jpy.createOrder(4.01, amount: 1)
api.trade(monaOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (border)
let monaJpyExpectation34 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder34 = Trade.Buy.Mona.In.Jpy.createOrder(0.09, amount: 1)
api.trade(monaOrder34) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation34.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (minus)
let monaJpyExpectation33 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder33 = Trade.Buy.Mona.In.Jpy.createOrder(-4.0, amount: 1)
api.trade(monaOrder33) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation33.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (zero)
let monaJpyExpectation7 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder7 = Trade.Buy.Mona.In.Jpy.createOrder(0, amount: 1)
api.trade(monaOrder7) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit
let monaJpyExpectation4 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder4 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 3.99)
api.trade(monaOrder4) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit (minus)
let monaJpyExpectation8 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder8 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: -4.1)
api.trade(monaOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit (zero)
let monaJpyExpectation9 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder9 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 0)
api.trade(monaOrder9) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount (minus)
let monaJpyExpectation10 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder10 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: -1)
api.trade(monaOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount (zero)
let monaJpyExpectation5 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder5 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: 0)
api.trade(monaOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell mona_jpy
let monaJpyExpectation11 = self.expectation(description: "sell mona_jpy order success")
let monaOrder11 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1)
api.trade(monaOrder11) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation11.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell mona_jpy with limit
let monaJpyExpectation12 = self.expectation(description: "sell mona_jpy order with limit success")
let monaOrder12 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 5.9)
api.trade(monaOrder12) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation12.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price
let monaJpyExpectation13 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder13 = Trade.Sell.Mona.For.Jpy.createOrder(6.01, amount: 1)
api.trade(monaOrder13) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation13.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit
let monaJpyExpectation14 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder14 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 3.91)
api.trade(monaOrder14) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation14.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount
let monaJpyExpectation15 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder15 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0)
api.trade(monaOrder15) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation15.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTradeMonaBtc() {
// buy mona_btc
let monaBtcExpectation = self.expectation(description: "buy mona_btc order success")
let monaOrder = Trade.Buy.Mona.In.Btc.createOrder(0.00000321, amount: 1)
api.trade(monaOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// buy mona_btc (min)
let monaBtcExpectation22 = self.expectation(description: "buy mona_btc order success")
let monaOrder22 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1)
api.trade(monaOrder22) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation22.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// buy mona_btc with limit
let monaBtcExpectation2 = self.expectation(description: "buy mona_btc order with limit success")
let monaOrder2 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.00010001)
api.trade(monaOrder2) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation2.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_btc invalid price
let monaBtcExpectation3 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder3 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1)
api.trade(monaOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (border)
let monaBtcExpectation44 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder44 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1)
api.trade(monaOrder44) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation44.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (minus)
let monaBtcExpectation4 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder4 = Trade.Buy.Mona.In.Btc.createOrder(-0.00000001, amount: 1)
api.trade(monaOrder4) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (zero)
let monaBtcExpectation5 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder5 = Trade.Buy.Mona.In.Btc.createOrder(0, amount: 1)
api.trade(monaOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit
let monaBtcExpectation6 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder6 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.000000019)
api.trade(monaOrder6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit (minus)
let monaBtcExpectation7 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder7 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: -0.00000002)
api.trade(monaOrder7) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit (zero)
let monaBtcExpectation8 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder8 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0)
api.trade(monaOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount (minus)
let monaBtcExpectation10 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder10 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: -1)
api.trade(monaOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount (zero)
let monaBtcExpectation55 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder55 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 0)
api.trade(monaOrder55) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation55.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell mona_btc
let monaBtcExpectation32 = self.expectation(description: "sell mona_btc order success")
let monaOrder32 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1)
api.trade(monaOrder32) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation32.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell mona_btc with limit
let monaBtcExpectation19 = self.expectation(description: "sell mona_btc order with limit success")
let monaOrder19 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 5.9)
api.trade(monaOrder19) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation19.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_btc invalid price
let monaBtcExpectation40 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder40 = Trade.Sell.Mona.For.Btc.createOrder(0.000000019, amount: 1)
api.trade(monaOrder40) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation40.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit
let monaBtcExpectation64 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder64 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 0.000000009)
api.trade(monaOrder64) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation64.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount
let monaBtcExpectation54 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder54 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0)
api.trade(monaOrder54) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation54.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testHistory() {
// query using 'from' and 'count'. 'from' minus value
let fromQueryExpectation2 = self.expectation(description: "query using 'from' and 'count'")
let query2 = HistoryQuery(from: -1, count: 10)
api.tradeHistory(query2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' zero value
let fromQueryExpectation3 = self.expectation(description: "query using 'from' and 'count'")
let query3 = HistoryQuery(from: 0, count: 10)
api.tradeHistory(query3) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' valid value
let fromQueryExpectation = self.expectation(description: "query using 'from' and 'count'")
let query = HistoryQuery(from: 1, count: 10)
api.tradeHistory(query) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' valid value
let fromQueryExpectation4 = self.expectation(description: "query using 'from' and 'count'")
let query4 = HistoryQuery(from: 10, count: 10)
api.tradeHistory(query4) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' not specified
let fromQueryExpectation41 = self.expectation(description: "query using 'from' and 'count'")
let query41 = HistoryQuery(count: 10)
api.tradeHistory(query41) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation41.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' minus value
let fromQueryExpectation5 = self.expectation(description: "query using 'from' and 'count'")
let query5 = HistoryQuery(from: 0, count: -1)
api.tradeHistory(query5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' zero value
let fromQueryExpectation6 = self.expectation(description: "query using 'from' and 'count'")
let query6 = HistoryQuery(from: 0, count: 0)
api.tradeHistory(query6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' valid value
let fromQueryExpectation7 = self.expectation(description: "query using 'from' and 'count'")
let query7 = HistoryQuery(from: 1, count: 1)
api.tradeHistory(query7) { (err, res) in
//print(res)
XCTAssertNil(err)
XCTAssertEqual(res!["return"].dictionary?.count, 1)
fromQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' valid value
let fromQueryExpectation8 = self.expectation(description: "query using 'from' and 'count'")
let query8 = HistoryQuery(from: 1, count: 2)
api.tradeHistory(query8) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 2)
fromQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' not specified
let fromQueryExpectation9 = self.expectation(description: "query using 'from' and 'count'")
let query9 = HistoryQuery(from: 1, count: 2)
api.tradeHistory(query9) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
fromQueryExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'
let idQueryExpectation = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery = HistoryQuery(fromId: 6915724, endId: 7087911)
api.tradeHistory(idQuery) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 8)
idQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' minus value
let idQueryExpectation2 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery2 = HistoryQuery(fromId: -1, endId: 7087911)
api.tradeHistory(idQuery2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
idQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' 0 value
let idQueryExpectation3 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery3 = HistoryQuery(fromId: 0, endId: 7087911)
api.tradeHistory(idQuery3) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' not specified
let idQueryExpectation4 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery4 = HistoryQuery(endId: 7087911)
api.tradeHistory(idQuery4) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' minus value
let idQueryExpectation5 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery5 = HistoryQuery(fromId: 6915724, endId: -1)
api.tradeHistory(idQuery5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
idQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' zero value
let idQueryExpectation6 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery6 = HistoryQuery(fromId: 6915724, endId: 0)
api.tradeHistory(idQuery6) { (err, res) in
XCTAssertNil(err)
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
idQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' not specified
let idQueryExpectation7 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery7 = HistoryQuery(fromId: 6915724)
api.tradeHistory(idQuery7) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' is greater than 'from_id'
let idQueryExpectation8 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery8 = HistoryQuery(fromId: 7087911 , endId: 6915724)
api.tradeHistory(idQuery8) { (err, res) in
XCTAssertNil(err)
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
idQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'
let sinceQueryExpectation = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery = HistoryQuery(since: 1467014263, end: 1467540926)
api.tradeHistory(sinceQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' minus value
let sinceQueryExpectation2 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery2 = HistoryQuery(since: -1, end: 1467540926)
api.tradeHistory(sinceQuery2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
sinceQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' zero value
let sinceQueryExpectation3 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery3 = HistoryQuery(since: 0, end: 1467540926)
api.tradeHistory(sinceQuery3) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' valid value
let sinceQueryExpectation4 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery4 = HistoryQuery(since: 1, end: 1467540926)
api.tradeHistory(sinceQuery4) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' not spcified
let sinceQueryExpectation5 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery5 = HistoryQuery(end: 1467540926)
api.tradeHistory(sinceQuery5) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' minus value
let sinceQueryExpectation6 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery6 = HistoryQuery(since: 1467014263, end: -1)
api.tradeHistory(sinceQuery6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
sinceQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' zero value
let sinceQueryExpectation7 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery7 = HistoryQuery(since: 1467014263, end: 0)
api.tradeHistory(sinceQuery7) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' valid value
let sinceQueryExpectation8 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery8 = HistoryQuery(since: 1467014263, end: 1)
api.tradeHistory(sinceQuery8) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' not specified
let sinceQueryExpectation9 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery9 = HistoryQuery(since: 1467014263)
api.tradeHistory(sinceQuery9) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' is greater than 'end'
let sinceQueryExpectation10 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery10 = HistoryQuery(since: 1467540926, end: 1467014263)
api.tradeHistory(sinceQuery10) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for btc_jpy. asc order
let btcQueryExpectation = self.expectation(description: "query for btc_jpy")
let btcQuery = HistoryQuery(order: .ASC, currencyPair: .BTC_JPY)
api.tradeHistory(btcQuery) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for btc_jpy. desc order
let btcQueryExpectation2 = self.expectation(description: "query for btc_jpy")
let btcQuery2 = HistoryQuery(order: .DESC, currencyPair: .BTC_JPY)
api.tradeHistory(btcQuery2) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_jpy. asc order
let monaQueryExpectation = self.expectation(description: "query for mona_jpy")
let monaQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_JPY)
api.tradeHistory(monaQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_jpy. desc order
let monaQueryExpectation2 = self.expectation(description: "query for mona_jpy")
let monaQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_JPY)
api.tradeHistory(monaQuery2) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_btc. asc order
let monaBtcQueryExpectation = self.expectation(description: "query for mona_btc")
let monaBtcQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_BTC)
api.tradeHistory(monaBtcQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_btc. desc order
let monaBtcQueryExpectation2 = self.expectation(description: "query for mona_btc")
let monaBtcQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_BTC)
api.tradeHistory(monaBtcQuery2) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testActiveOrders() {
// btc_jpy
let btcExpectation = self.expectation(description: "active orders of btc_jpy")
api.activeOrders(.BTC_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// mona_jpy
let monaExpectation = self.expectation(description: "active orders of mona_jpy")
api.activeOrders(.MONA_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// mona_btc
let monaBtcExpectation = self.expectation(description: "active orders of mona_btc")
api.activeOrders(.MONA_BTC) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemExpectation = self.expectation(description: "active orders of xem_jpy")
api.activeOrders(.XEM_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "xem_jpy")
xemExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// all
let allExpectation = self.expectation(description: "active orders of all")
api.activeOrders() { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
allExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testCancelOrder() {
var orderIds: [String] = []
let allExpectation = self.expectation(description: "active orders of all")
api.activeOrders() { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
for (orderId, _) in res!["return"].dictionaryValue {
orderIds.append(orderId)
}
allExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let cancelExpectation = self.expectation(description: "cancel orders")
var count = orderIds.count
let semaphore = DispatchSemaphore(value: 1)
for orderId in orderIds {
api.cancelOrder(Int(orderId)!) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
var resOrderId = res!["return"].dictionaryValue["order_id"]
XCTAssertEqual(resOrderId?.stringValue, orderId)
semaphore.wait(timeout: DispatchTime.distantFuture)
count -= 1
if count == 0 {
cancelExpectation.fulfill()
}
semaphore.signal()
}
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let invalid = self.expectation(description: "invalid order id")
api.cancelOrder(-1) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let invalid2 = self.expectation(description: "invalid order id")
api.cancelOrder(0) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let invalid3 = self.expectation(description: "invalid order id")
api.cancelOrder(999) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testStream() {
// btc_jpy
let streamExpectation = self.expectation(description: "stream of btc_jpy")
let stream = StreamingApi.stream(.BTC_JPY) { _,_ in
print("opened btc_jpy")
}
var count = 10
stream.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation.fulfill()
stream.onData(callback: nil)
}
}
stream.onError() { (err, _) in
print(err)
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let colseExp = self.expectation(description: "")
stream.close() { (_, res) in
print(res)
colseExp.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
// reopen
let streamExpectationRe = self.expectation(description: "stream of btc_jpy")
stream.open() { (_, _) in
print("reopened")
}
count = 10
stream.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectationRe.fulfill()
stream.onData(callback: nil)
}
}
stream.onError() { (err, _) in
print(err)
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let colseExpRe = self.expectation(description: "")
stream.close() { (_, res) in
print(res)
colseExpRe.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
// mona_jpy
let streamExpectation2 = self.expectation(description: "stream of mona_jpy")
let stream2 = StreamingApi.stream(.MONA_JPY) { _,_ in
print("opened mona_jpy")
}
count = 1
stream2.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation2.fulfill()
stream2.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp2 = self.expectation(description: "")
stream2.onClose() { (_, res) in
print(res)
colseExp2.fulfill()
}
stream2.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
// mona_btc
let streamExpectation3 = self.expectation(description: "stream of mona_btc")
let stream3 = StreamingApi.stream(.MONA_BTC) { _,_ in
print("opened mona_btc")
}
count = 1
stream3.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation3.fulfill()
stream3.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp3 = self.expectation(description: "")
stream3.onClose() { (_, res) in
print(res)
colseExp3.fulfill()
}
stream3.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
// xem_jpy
let streamExpectation4 = self.expectation(description: "stream of xem_jpy")
let stream4 = StreamingApi.stream(.XEM_JPY) { _,_ in
print("opened xem_jpy")
}
count = 1
stream4.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation4.fulfill()
stream4.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp4 = self.expectation(description: "")
stream4.onClose() { (_, res) in
print(res)
colseExp4.fulfill()
}
stream4.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
}
func testLastPrice() {
// btc_jpy
let btcLastPrice = self.expectation(description: "last price of btc_jpy")
PublicApi.lastPrice(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
btcLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaLastPrice = self.expectation(description: "last price of mona_jpy")
PublicApi.lastPrice(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
monaLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcLastPrice = self.expectation(description: "last price for mona_btc")
PublicApi.lastPrice(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
monaBtcLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemLastPrice = self.expectation(description: "last price for xem_jpy")
PublicApi.lastPrice(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
xemLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTicker() {
// btc_jpy
let btcTicker = self.expectation(description: "ticker for btc_jpy")
PublicApi.ticker(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
btcTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaTicker = self.expectation(description: "ticker for mona_jpy")
PublicApi.ticker(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
monaTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcTicker = self.expectation(description: "ticker for mona_btc")
PublicApi.ticker(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
monaBtcTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemTicker = self.expectation(description: "ticker for xem_jpy")
PublicApi.ticker(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
xemTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTrades() {
// btc_jpy
let btcTrades = self.expectation(description: "trades of btc_jpy")
PublicApi.trades(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "btc_jpy")
btcTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaTrades = self.expectation(description: "trades of mona_jpy")
PublicApi.trades(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "mona_jpy")
monaTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcTrades = self.expectation(description: "trades of mona_btc")
PublicApi.trades(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "mona_btc")
monaBtcTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemTrades = self.expectation(description: "trades of xem_jpy")
PublicApi.trades(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "xem_jpy")
xemTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testDepth() {
// btc_jpy
let btcDepth = self.expectation(description: "depth of btc_jpy")
PublicApi.depth(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
btcDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaDepth = self.expectation(description: "depth of mona_jpy")
PublicApi.depth(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
monaDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcDepth = self.expectation(description: "depth of mona_btc")
PublicApi.depth(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
monaBtcDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemDepth = self.expectation(description: "depth of xem_jpy")
PublicApi.depth(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
xemDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testSerialNonce() {
// invalid initial value test
var nonce = SerialNonce(initialValue: -1)
var value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value -1")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value -1, 1 increment")
nonce = SerialNonce(initialValue: 0)
value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value 0")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 0, 1 increment")
// valid initial value test
nonce = SerialNonce(initialValue: 1)
value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value 1")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 1, 1 increment")
nonce = SerialNonce(initialValue: 2)
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 2")
value = try! nonce.getNonce()
XCTAssertEqual(value, "3", "initial value 2, 1 increment")
// max initial value test
nonce = SerialNonce(initialValue: IntMax.max)
value = try! nonce.getNonce()
XCTAssertEqual(value, IntMax.max.description, "initial value max")
XCTAssertThrowsError(try nonce.getNonce()) { (error) in
switch error as! ZSErrorType {
case .NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
}
}
func testTimeNonce() {
let nonce = TimeNonce()
var prev = try! nonce.getNonce()
sleep(1)
var cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second")
prev = cur
sleep(2)
cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second")
prev = cur
var count = 10
while count > 0 {
cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "multiple request in a second")
prev = cur
if Int64(cur) == IntMax.max {
break
}
count -= 1
}
/*
XCTAssertThrowsError(try nonce.getNonce()) { (error) in
switch error as! ZSErrorType {
case .NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
}
*/
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
b271c88fddf3f228cf54f56cced503c1
| 37.443741 | 111 | 0.566348 | false | false | false | false |
barteljan/RocketChatAdapter
|
refs/heads/master
|
Pod/Classes/CommandHandler/SendMessageCommandHandler.swift
|
mit
|
1
|
//
// SendMessageCommandHandler.swift
// Pods
//
// Created by Jan Bartel on 13.03.16.
//
//
import Foundation
import SwiftDDP
import VISPER_CommandBus
public class SendMessageCommandHandler: CommandHandlerProtocol {
let parser : MessageParserProtocol
public init(parser : MessageParserProtocol){
self.parser = parser
}
public func isResponsible(command: Any!) -> Bool {
return command is SendMessageCommandProtocol
}
public func process<T>(command: Any!, completion: ((result: T?, error: ErrorType?) -> Void)?) throws{
let myCommand = command as! SendMessageCommandProtocol
var messageObject : [String : NSObject]
messageObject = [
"rid":myCommand.channelId,
"msg":myCommand.message
]
Meteor.call("sendMessage", params: [messageObject]) { (result, error) -> () in
if error != nil {
completion?(result: nil,error: error)
return
}
if(result == nil){
completion?(result:nil,error: RocketChatAdapterError.RequiredResponseFieldWasEmpty(field: "result",fileName: __FILE__,function: __FUNCTION__,line: __LINE__,column: __COLUMN__))
return
}
print(result)
let messageResult = self.parser.parseMessage(result as! [String:AnyObject])
//completion?(result: (result as! T?), error: nil)
completion?(result:(messageResult.message as! T), error: messageResult.error)
}
}
}
|
c8c711fb6e1f850f98941d022019401b
| 28.333333 | 192 | 0.565789 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th
|
refs/heads/master
|
Chap9_Homepwner/Homepwner/ItemsViewController.swift
|
mit
|
1
|
//
// ItemsViewController.swift
// Homepwner
//
// Created by Joonwon Lee on 7/31/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
class ItemsViewController: UITableViewController {
var itemStore: ItemStore!
override func viewDidLoad() {
super.viewDidLoad()
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height
let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemStore.allItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath)
let item = itemStore.allItems[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = "$\(item.valueInDollars)"
return cell
}
/*
// Override to support conditional editing of the table view.
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 to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
995b90399a19bab06733a8f13f02f752
| 32.91954 | 157 | 0.682481 | false | false | false | false |
soflare/XWebApp
|
refs/heads/master
|
XWebApp/XWAPluginBinding.swift
|
apache-2.0
|
1
|
/*
Copyright 2015 XWebView
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 WebKit
import XWebView
@objc public class XWAPluginBinding {
struct Descriptor {
var pluginID: String
var argument: AnyObject! = nil
var channelName: String! = nil
var mainThread: Bool = false
var lazyBinding: Bool = false
init(pluginID: String, argument: AnyObject! = nil) {
self.pluginID = pluginID
self.argument = argument
}
}
private var bindings = [String: Descriptor]()
private let inventory: XWAPluginInventory
private let pluginQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
public init(inventory: XWAPluginInventory) {
self.inventory = inventory
}
public func addBinding(spec: AnyObject, forNamespace namespace: String) {
if let str = spec as? String where !str.isEmpty {
// simple spec
var descriptor = Descriptor(pluginID: str)
if last(descriptor.pluginID) == "?" {
descriptor.pluginID = dropLast(descriptor.pluginID)
descriptor.lazyBinding = true
}
if last(descriptor.pluginID) == "!" {
descriptor.pluginID = dropLast(descriptor.pluginID)
descriptor.mainThread = true
}
bindings[namespace] = descriptor
} else if let pluginID = spec["Plugin"] as? String {
// full spec
var descriptor = Descriptor(pluginID: pluginID, argument: spec["argument"])
descriptor.channelName = spec["channelName"] as? String
descriptor.mainThread = spec["mainThread"] as? Bool ?? false
descriptor.lazyBinding = spec["lazyBinding"] as? Bool ?? false
bindings[namespace] = descriptor
} else {
println("ERROR: Unknown binding spec for namespace '\(namespace)'")
}
}
public func prebind(webView: WKWebView) {
for (namespace, _) in filter(bindings, { !$0.1.lazyBinding }) {
bind(webView, namespace: namespace)
}
}
func bind(namespace: AnyObject!, argument: AnyObject?, _Promise: XWVScriptObject) {
let scriptObject = objc_getAssociatedObject(self, unsafeAddressOf(XWVScriptObject)) as? XWVScriptObject
if let namespace = namespace as? String, let webView = scriptObject?.channel.webView {
if let obj = bind(webView, namespace: namespace) {
_Promise.callMethod("resolve", withArguments: [obj], resultHandler: nil)
} else {
_Promise.callMethod("reject", withArguments: nil, resultHandler: nil)
}
}
}
private func bind(webView: WKWebView, namespace: String) -> XWVScriptObject? {
if let spec = bindings[namespace], let plugin: AnyClass = inventory[spec.pluginID] {
if let object: AnyObject = instantiateClass(plugin, withArgument: spec.argument) {
let queue = spec.mainThread ? dispatch_get_main_queue() : pluginQueue
let channel = XWVChannel(name: spec.channelName, webView: webView, queue: queue)
return channel.bindPlugin(object, toNamespace: namespace)
}
println("ERROR: Failed to create instance of plugin '\(spec.pluginID)'.")
} else if let spec = bindings[namespace] {
println("ERROR: Plugin '\(spec.pluginID)' not found.")
} else {
println("ERROR: Namespace '\(namespace)' has no binding")
}
return nil
}
private func instantiateClass(cls: AnyClass, withArgument argument: AnyObject?) -> AnyObject? {
//XWAPluginFactory.self // a trick to access static method of protocol
if class_conformsToProtocol(cls, XWAPluginSingleton.self) {
return cls.instance()
} else if class_conformsToProtocol(cls, XWAPluginFactory.self) {
if argument != nil && cls.createInstanceWithArgument != nil {
return cls.createInstanceWithArgument!(argument)
}
return cls.createInstance()
}
var initializer = Selector("initWithArgument:")
var args: [AnyObject]!
if class_respondsToSelector(cls, initializer) {
args = [ argument ?? NSNull() ]
} else {
initializer = Selector("init")
if !class_respondsToSelector(cls, initializer) {
return cls as AnyObject
}
}
return XWVInvocation.construct(cls, initializer: initializer, arguments: args)
}
}
extension XWAPluginBinding {
subscript (namespace: String) -> Descriptor? {
get {
return bindings[namespace]
}
set {
bindings[namespace] = newValue
}
}
}
|
d1a7188f7c30aec4d801e219279e3c24
| 38.746269 | 111 | 0.623733 | false | false | false | false |
davidear/swiftsome
|
refs/heads/master
|
JokeClient-Swift/JokeClient-Swift/Utility/FileUtility.swift
|
mit
|
1
|
//
// FileUtility.swift
// JokeClient-Swift
//
// Created by YANGReal on 14-6-7.
// Copyright (c) 2014年 YANGReal. All rights reserved.
//
import UIKit
class FileUtility: NSObject {
class func cachePath(fileName:String)->String
{
var arr = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
var path = arr[0] as! String
return "\(path)/\(fileName)"
}
class func imageCacheToPath(path:String,image:NSData)->Bool
{
return image.writeToFile(path, atomically: true)
}
class func imageDataFromPath(path:String)->AnyObject
{
var exist = NSFileManager.defaultManager().fileExistsAtPath(path)
if exist
{
//var urlStr = NSURL.fileURLWithPath(path)
var data = NSData(contentsOfFile: path);
//var img:UIImage? = UIImage(data:data!)
//return img ?? NSNull()
var img = UIImage(contentsOfFile: path)
var url:NSURL? = NSURL.fileURLWithPath(path)
var dd = NSFileManager.defaultManager().contentsAtPath(url!.path!)
var jpg = UIImage(data:dd!)
if img != nil {
return img!
} else {
return NSNull()
}
}
return NSNull()
}
}
|
ddd88e60de04f4ee8656198b5d09895e
| 24.181818 | 95 | 0.552347 | false | false | false | false |
Shivol/Swift-CS333
|
refs/heads/master
|
examples/swift/SwiftClasses.playground/Pages/Initializers.xcplaygroundpage/Contents.swift
|
mit
|
3
|
//: ## Initializers
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
//: ****
//: ### Default Initializers
//: Classes and structures will have a default initializer if every stored property is initialized explicitly
struct Point {
var x = 0.0, y = 0.0
}
let zero = Point()
//: Structures also have a memeber-wise initializer
struct Size {
var width = 0, height = 0
}
let square = Size(width: 100, height: 100)
//: Classes don't have a memeber-wise initializer
class Rectangle {
var origin = Point()
var size = Size()
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
}
let rect = Rectangle(origin: zero, size: square)
//: ### Designated and Convenience Initializers
//: Classes have two types of initializers:
//: - designated — fully initializes every property of the class
//: - convenience — covers specific use case of initializetion parameters
extension Rectangle {
// Convenience initializers can be declared in extencions
convenience init(center: Point, size: Size) {
let originX = center.x - Double(size.width) / 2.0
let originY = center.y - Double(size.height) / 2.0
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
//: ### Initializers and Class Heirarchy
//: If no designated initializers are declared, designated initializers of the superclass are inherited
class DefaultTextBox: Rectangle {
var text: String = ""
}
let def = DefaultTextBox(center: zero, size: square)
def.text = "Hello!"
//: Any designated initializer must call superclass initializer
class TextBox: Rectangle {
var text = ""
init(text: String, origin: Point, size: Size) {
self.text = text;
super.init(origin: origin, size: size)
}
}
//: Convenience initializers can not call super class initializer. They must call another initializer from the same class instead
extension TextBox {
convenience init(text: String, center: Point, size: Size) {
let originX = center.x - Double(size.width) / 2
let originY = center.y - Double(size.height) / 2
self.init(text: text, origin: Point(x: originX, y: originY),
size: size)
}
}
//: ### Required Initializers
//: You can require all subclasses to implement a specific initializer
class Polygon {
var points = [Point]()
required init() {}
}
class RegularPolygon: Polygon {
required init() {}
}
class Triangle: Polygon {
required init() {}
}
//: ### Deinitializers
class Star: Polygon {
deinit {
print("I was a Star!")
}
}
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
//: ****
|
b2bbb9696ebd6fc5b90508c4a5c0eecb
| 31.987805 | 129 | 0.663216 | false | false | false | false |
jwfriese/FrequentFlyer
|
refs/heads/master
|
FrequentFlyer/Visuals/UnderlineTextField/UnderlineTextField.swift
|
apache-2.0
|
1
|
import UIKit
class UnderlineTextField: UIView {
private var contentView: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let viewPackage = Bundle.main.loadNibNamed("UnderlineTextField", owner: self, options: nil)
guard let loadedView = viewPackage?.first as? UIView else {
print("Failed to load nib with name 'UnderlineTextField'")
return
}
contentView = loadedView
addSubview(contentView)
contentView.bounds = bounds
autoresizesSubviews = true
autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear
underline?.backgroundColor = Style.Colors.titledTextFieldUnderlineColor
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// Because this view contains the actual text view, explicitly give it a chance
// to claim a touch it otherwise wouldn't.
if let hitTextField = textField?.hitTest(point, with: event) {
return hitTextField
}
return super.hitTest(point, with: event)
}
private weak var cachedTextField: UnderlineTextFieldTextField?
weak var textField: UnderlineTextFieldTextField? {
get {
if cachedTextField != nil { return cachedTextField }
let textField = contentView.subviews.filter { subview in
return subview.isKind(of: UnderlineTextFieldTextField.self)
}.first as? UnderlineTextFieldTextField
cachedTextField = textField
return cachedTextField
}
}
private weak var cachedUnderline: Underline?
private weak var underline: Underline? {
get {
if cachedUnderline != nil { return cachedUnderline }
let underline = contentView.subviews.filter { subview in
return subview.isKind(of: Underline.self)
}.first as? Underline
cachedUnderline = underline
return cachedUnderline
}
}
}
|
da9b2053092debe80e0f9196ee264d32
| 34.469697 | 99 | 0.648441 | false | false | false | false |
XLabKC/Badger
|
refs/heads/master
|
Badger/Badger/TeamCell.swift
|
gpl-2.0
|
1
|
import UIKit
class TeamCell: BorderedCell {
private var hasAwakened = false
private var team: Team?
@IBOutlet weak var teamCircle: TeamCircle!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var arrowImage: UIImageView!
override func awakeFromNib() {
self.hasAwakened = true
self.updateView()
}
func setTeam(team: Team) {
self.team = team
self.updateView()
}
private func updateView() {
if self.hasAwakened {
if let team = self.team {
self.teamCircle.setTeam(team)
self.nameLabel.text = team.name
}
}
}
}
|
76a03ac4240d45e5d5d96cd07dfbdd39
| 21.896552 | 47 | 0.585843 | false | false | false | false |
younata/RSSClient
|
refs/heads/master
|
Tethys/ExplanationView.swift
|
mit
|
1
|
import UIKit
import PureLayout
public final class ExplanationView: UIView {
public var title: String {
get { return self.titleLabel.text ?? "" }
set { self.titleLabel.text = newValue }
}
public var detail: String {
get { return self.detailLabel.text ?? "" }
set { self.detailLabel.text = newValue }
}
private let titleLabel = UILabel(forAutoLayout: ())
private let detailLabel = UILabel(forAutoLayout: ())
public override init(frame: CGRect) {
super.init(frame: frame)
self.titleLabel.textAlignment = .center
self.titleLabel.numberOfLines = 0
self.titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)
self.detailLabel.textAlignment = .center
self.detailLabel.numberOfLines = 0
self.detailLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
self.addSubview(self.titleLabel)
self.addSubview(self.detailLabel)
self.titleLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20),
excludingEdge: .bottom)
self.detailLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 8, bottom: 8, right: 8),
excludingEdge: .top)
self.detailLabel.autoPinEdge(.top, to: .bottom, of: self.titleLabel, withOffset: 8)
self.layer.cornerRadius = 4
self.isAccessibilityElement = true
self.isUserInteractionEnabled = false
self.accessibilityTraits = [.staticText]
self.applyTheme()
}
public required init?(coder aDecoder: NSCoder) { fatalError() }
private func applyTheme() {
self.titleLabel.textColor = Theme.textColor
self.detailLabel.textColor = Theme.textColor
}
}
|
a8b57fd157f53efdec45e3940949bb2f
| 33.037736 | 113 | 0.670177 | false | false | false | false |
sendyhalim/iYomu
|
refs/heads/master
|
Yomu/Screens/MangaList/MangaCollectionViewModel.swift
|
mit
|
1
|
//
// MangaCollectionViewModel.swift
// Yomu
//
// Created by Sendy Halim on 6/16/17.
// Copyright © 2017 Sendy Halim. All rights reserved.
//
import OrderedSet
import class RealmSwift.Realm
import RxCocoa
import RxMoya
import RxSwift
import RxRealm
import Swiftz
struct SelectedIndex {
let previousIndex: Int
let index: Int
}
struct MangaCollectionViewModel {
// MARK: Public
var count: Int {
return _mangas.value.count
}
// MARK: Output
let fetching: Driver<Bool>
let showEmptyDataSetLoading: Driver<Void>
let reload: Driver<Void>
// MARK: Private
fileprivate let _selectedIndex = Variable(SelectedIndex(previousIndex: -1, index: -1))
fileprivate var _fetching = Variable(false)
fileprivate var _mangas: Variable<OrderedSet<MangaViewModel>> = {
let mangas = Database
.queryMangas()
.sorted {
$0.position < $1.position
}
.map(MangaViewModel.init)
return Variable(OrderedSet(elements: mangas))
}()
fileprivate let deletedManga = PublishSubject<MangaViewModel>()
fileprivate let addedManga = PublishSubject<MangaViewModel>()
fileprivate let disposeBag = DisposeBag()
init() {
fetching = _fetching.asDriver()
reload = _mangas
.asDriver()
.map { _ in () }
deletedManga
.map { manga in
return Database.queryMangaRealm(id: manga.id)
}
.subscribe(Realm.rx.delete())
.disposed(by: disposeBag)
addedManga
.map {
MangaRealm.from(manga: $0.manga)
}
.subscribe(Realm.rx.add(update: true))
.disposed(by: disposeBag)
// We want to show empty data set loading view if manga count is 0 and we're in the fetching state
showEmptyDataSetLoading = Driver
.combineLatest(
fetching,
_mangas.asDriver().map { $0.count == 0 }
)
.map {
$0 && $1
}
.filter(identity)
.map { _ in () }
}
subscript(index: Int) -> MangaViewModel {
return _mangas.value[index]
}
func fetch(id: String) -> Disposable {
let api = MangaEdenAPI.mangaDetail(id)
let request = MangaEden.request(api).share()
let newMangaObservable = request
.filterSuccessfulStatusCodes()
.map(Manga.self)
.map {
var manga = $0
manga.id = id
manga.position = self.count
return MangaViewModel(manga: manga)
}
.filter {
return !self._mangas.value.contains($0)
}
.share()
let fetchingDisposable = request
.map(const(false))
.startWith(true)
.asDriver(onErrorJustReturn: false)
.drive(_fetching)
let resultDisposable = newMangaObservable.subscribe(onNext: {
self.addedManga.on(.next($0))
self._mangas.value.append(element: $0)
})
return CompositeDisposable(fetchingDisposable, resultDisposable)
}
func setSelectedIndex(_ index: Int) {
let previous = _selectedIndex.value
let selectedIndex = SelectedIndex(previousIndex: previous.index, index: index)
_selectedIndex.value = selectedIndex
}
func move(fromIndex: Int, toIndex: Int) {
let mangaViewModel = self[fromIndex]
_mangas.value.remove(index: fromIndex)
_mangas.value.insert(element: mangaViewModel, atIndex: toIndex)
updateMangaPositions()
}
func remove(mangaViewModel: MangaViewModel) {
let manga = _mangas.value.remove(element: mangaViewModel)!
deletedManga.on(.next(manga))
updateMangaPositions()
}
private func updateMangaPositions() {
let indexes: [Int] = [Int](0..<self.count)
indexes.forEach {
_mangas.value[$0].update(position: $0)
}
}
}
|
69f6e12b5ddc132f9858276f9f687df1
| 23.513514 | 102 | 0.652977 | false | false | false | false |
pvbaleeiro/movie-aholic
|
refs/heads/master
|
movieaholic/movieaholic/controller/main/ExploreFeedViewController.swift
|
mit
|
1
|
//
// ExploreFeedViewController.swift
// movieaholic
//
// Created by Victor Baleeiro on 23/09/17.
// Copyright © 2017 Victor Baleeiro. All rights reserved.
//
import UIKit
import Foundation
class ExploreFeedViewController: BaseTableController {
//-------------------------------------------------------------------------------------------------------------
// MARK: Propriedades
//-------------------------------------------------------------------------------------------------------------
let cellID = "cellID"
var categories = ["Trending"]
var moviesTrending: NSMutableArray!
var moviesTrendingFiltered = NSMutableArray()
var refreshControl: UIRefreshControl!
var currentSearchText: String! = ""
lazy var tbvMovies: UITableView = {
let view = UITableView()
view.translatesAutoresizingMaskIntoConstraints = false
view.dataSource = self
view.delegate = self
view.register(CategoryTableViewCell.self, forCellReuseIdentifier: self.cellID)
view.rowHeight = 300
view.separatorStyle = .none
view.showsVerticalScrollIndicator = false
view.allowsSelection = false
return view
}()
//-------------------------------------------------------------------------------------------------------------
// MARK: Ciclo de vida
//-------------------------------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
setLayout()
setData()
}
//-------------------------------------------------------------------------------------------------------------
// MARK: Sets
//-------------------------------------------------------------------------------------------------------------
func setLayout() {
//Define layout table view
view.addSubview(tbvMovies)
tbvMovies.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
tbvMovies.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
tbvMovies.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
tbvMovies.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
//Refresh control para a tabela
refreshControl = tbvMovies.addRefreshControl(target: self, action: #selector(doRefresh(_:)))
refreshControl.tintColor = UIColor.primaryColor()
refreshControl.attributedTitle =
NSAttributedString(string: "Buscando dados...",
attributes: [
NSAttributedStringKey.backgroundColor: UIColor.black.withAlphaComponent(0.6),
NSAttributedStringKey.foregroundColor: UIColor.white,
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 25) ])
}
func setData() {
buscaDados(forceUpdate: false)
}
//-------------------------------------------------------------------------------------------------------------
// MARK: Acoes
//-------------------------------------------------------------------------------------------------------------
@objc func doRefresh(_ sender: UIRefreshControl) {
//Busca dados
buscaDados(forceUpdate: true)
UIView.animate(withDuration: 0.1, animations: {
self.view.tintColor = self.view.backgroundColor // store color
self.view.backgroundColor = UIColor.white
}) { (Bool) in
self.view.backgroundColor = self.view.tintColor // restore color
}
}
func buscaDados(forceUpdate: Bool) {
//Buscar os dados
APIMovie.getTrendingMovies(forceUpdate: forceUpdate) {
(response) in
switch response {
case .onSuccess(let trendingMovies as NSMutableArray):
//Obtem resposta e atribui à lista
self.moviesTrending = trendingMovies
self.tbvMovies.reloadData()
self.refreshControl.endRefreshing()
break
case .onError(let erro):
print(erro)
self.refreshControl.endRefreshing()
break
case .onNoConnection():
print("Sem conexão")
self.refreshControl.endRefreshing()
break
default: break
}
}
}
}
//-------------------------------------------------------------------------------------------------------------
// MARK: UITableViewDataSource
//-------------------------------------------------------------------------------------------------------------
extension ExploreFeedViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (moviesTrending != nil) {
return 1
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CategoryTableViewCell
cell.title = categories[indexPath.section]
if (moviesTrendingFiltered.count > 0 || !self.currentSearchText.isEmpty) {
cell.items = moviesTrendingFiltered as! [MovieTrending]
} else {
cell.items = moviesTrending as! [MovieTrending]
}
cell.indexPath = indexPath // needed for dismiss animation
if let parent = parent as? CategoryTableViewCellDelegate {
cell.delegate = parent
}
return cell
}
}
extension ExploreFeedViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filter(searchText: searchBar.text!)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
filter(searchText: searchBar.text!)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
self.currentSearchText = ""
self.moviesTrendingFiltered = NSMutableArray()
self.tbvMovies.reloadData()
}
func filter(searchText: String) {
//Filtrar filmes
self.currentSearchText = searchText
if !self.currentSearchText.isEmpty {
let swiftArray = NSArray(array:moviesTrending) as! Array<MovieTrending>
var swiftArrayFilter: Array<MovieTrending>
swiftArrayFilter = swiftArray.filter { movie in
return (movie.movie?.title?.lowercased().contains(self.currentSearchText.lowercased()))!
}
self.moviesTrendingFiltered = NSMutableArray(array: swiftArrayFilter)
self.tbvMovies.reloadData()
} else {
self.moviesTrendingFiltered = NSMutableArray()
self.tbvMovies.reloadData()
}
}
}
|
4a88c9a72b5c6dd2647f83e150125e5e
| 36.167513 | 115 | 0.513521 | false | false | false | false |
Sidetalker/TapMonkeys
|
refs/heads/master
|
TapMonkeys/TapMonkeys/MonkeyViewController.swift
|
mit
|
1
|
//
// MonkeyViewController.swift
// TapMonkeys
//
// Created by Kevin Sullivan on 5/9/15.
// Copyright (c) 2015 Kevin Sullivan. All rights reserved.
//
import UIKit
class MonkeyViewController: UIViewController {
@IBOutlet weak var dataHeader: DataHeader!
var monkeyTable: MonkeyTableViewController?
var nightMode = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewWillAppear(animated: Bool) {
self.tabBarItem.badgeValue = nil
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("updateHeaders", object: self, userInfo: [
"letters" : 0,
"animated" : true
])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueMonkeyTable" {
monkeyTable = segue.destinationViewController as? MonkeyTableViewController
}
}
func toggleNightMode(nightMode: Bool) {
self.nightMode = nightMode
self.view.backgroundColor = self.nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
self.tabBarController?.tabBar.setNeedsDisplay()
monkeyTable?.toggleNightMode(nightMode)
}
}
class MonkeyTableViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, AnimatedLockDelegate, MonkeyBuyButtonDelegate {
var nightMode = false
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 232
}
func toggleNightMode(nightMode: Bool) {
self.nightMode = nightMode
self.view.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor()
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return count(monkeys) == 0 ? 0 : 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count(monkeys)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let saveData = load(self.tabBarController)
if !saveData.monkeyCollapsed![indexPath.row] {
return monkeys[indexPath.row].unlocked ? UITableViewAutomaticDimension : 232
}
else {
return monkeys[indexPath.row].unlocked ? 60 : 232
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let saveData = load(self.tabBarController)
let index = indexPath.row
if saveData.monkeyCollapsed![index] { return }
let curMonkey = monkeys[index]
if !curMonkey.unlocked {
if let lockView = cell.contentView.viewWithTag(8) as? AnimatedLockView {
// We're good to go I guess
}
else {
let lockView = AnimatedLockView(frame: cell.contentView.frame)
lockView.tag = 8
lockView.index = indexPath.row
lockView.delegate = self
lockView.type = .Monkey
lockView.nightMode = nightMode
lockView.customize(load(self.tabBarController))
cell.contentView.addSubview(lockView)
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let saveData = load(self.tabBarController)
let index = indexPath.row
let curMonkey = monkeys[index]
if !saveData.monkeyCollapsed![index] {
if let
cell = self.tableView.dequeueReusableCellWithIdentifier("cellMonkey") as? UITableViewCell,
pic = cell.viewWithTag(1) as? UIImageView,
name = cell.viewWithTag(2) as? UILabel,
owned = cell.viewWithTag(3) as? UILabel,
frequency = cell.viewWithTag(4) as? UILabel,
total = cell.viewWithTag(5) as? AutoUpdateLabel,
buyButton = cell.viewWithTag(6) as? MonkeyBuyButton,
description = cell.viewWithTag(7) as? UILabel
{
let curPrice = curMonkey.getPrice(1).0
pic.image = UIImage(named: curMonkey.imageName)
pic.alpha = nightMode ? 0.5 : 1.0
buyButton.monkeyIndex = index
buyButton.delegate = self
buyButton.nightMode = nightMode
buyButton.setNeedsDisplay()
total.index = index
total.controller = self.tabBarController as? TabBarController
total.type = .Monkey
name.text = curMonkey.name
description.text = curMonkey.description
owned.text = "Owned: \(curMonkey.count)"
frequency.text = "Letters/sec: \(curMonkey.lettersPerSecondCumulative())"
total.text = "Total Letters: \(curMonkey.totalProduced)"
name.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
description.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
owned.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
frequency.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
total.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
cell.contentView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor()
if let lockView = cell.contentView.viewWithTag(8) as? AnimatedLockView {
lockView.index = index
lockView.type = .Monkey
lockView.customize(load(self.tabBarController))
if curMonkey.unlocked { lockView.removeFromSuperview() }
}
else {
if pic.gestureRecognizers == nil {
let briefHold = UILongPressGestureRecognizer(target: self, action: "heldPic:")
pic.addGestureRecognizer(briefHold)
}
}
return cell
}
}
else {
if let
cell = self.tableView.dequeueReusableCellWithIdentifier("cellMonkeyMini") as? UITableViewCell,
pic = cell.viewWithTag(1) as? UIImageView,
name = cell.viewWithTag(2) as? UILabel
{
pic.image = UIImage(named: curMonkey.imageName)
pic.alpha = nightMode ? 0.5 : 1.0
name.text = curMonkey.name
name.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
cell.contentView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor()
if pic.gestureRecognizers == nil {
let briefHold = UILongPressGestureRecognizer(target: self, action: "heldPic:")
pic.addGestureRecognizer(briefHold)
}
return cell
}
}
return UITableViewCell()
}
func heldPic(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.Began { return }
var saveData = load(self.tabBarController)
let location = sender.locationInView(self.tableView)
let indexPath = tableView.indexPathForRowAtPoint(location)
let index = indexPath!.row
self.tableView.beginUpdates()
saveData.monkeyCollapsed![index] = !saveData.monkeyCollapsed![index]
save(self.tabBarController, saveData)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.endUpdates()
}
func tappedLock(view: AnimatedLockView) {
var saveData = load(self.tabBarController)
let index = view.index
for cost in monkeys[index].unlockCost {
if saveData.incomeCounts![Int(cost.0)] < Int(cost.1) { return }
}
for cost in monkeys[index].unlockCost {
saveData.incomeCounts![Int(cost.0)] -= Int(cost.1)
incomes[Int(cost.0)].count -= Int(cost.1)
}
view.unlock()
saveData.monkeyUnlocks![index] = true
monkeys[index].unlocked = true
if index + 1 <= count(monkeys) - 1 {
var paths = [NSIndexPath]()
self.tableView.beginUpdates()
for i in index + 1...count(monkeys) - 1 {
paths.append(NSIndexPath(forRow: i, inSection: 0))
}
self.tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
}
save(self.tabBarController, saveData)
}
// REFACTOR you wrote this all stupid cause you wanted to move on
func buyTapped(monkeyIndex: Int) {
var saveData = load(self.tabBarController)
var monkey = monkeys[monkeyIndex]
if monkey.canPurchase(1, data: saveData) {
var price = monkey.getPrice(1).0 * -1
saveData = monkey.purchase(1, data: saveData)!
monkeys[monkeyIndex] = monkey
save(self.tabBarController, saveData)
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("updateHeaders", object: self, userInfo: [
"money" : price,
"animated" : false
])
nc.postNotificationName("updateMonkeyProduction", object: self, userInfo: nil)
delay(0.2, {
self.tableView.reloadData()
// self.tableView.beginUpdates()
//
// self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: monkeyIndex, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
//
// self.tableView.endUpdates()
})
}
}
}
protocol MonkeyBuyButtonDelegate {
func buyTapped(monkeyIndex: Int)
}
class MonkeyBuyButton: UIView {
// 0 is 1 only, 1 is 1 | 10, 2 is 1 | 10 | 100
// Like, maybe
var state = 0
var monkeyIndex = -1
var nightMode = false
var delegate: MonkeyBuyButtonDelegate?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
let tap = UILongPressGestureRecognizer(target: self, action: "tappedMe:")
tap.minimumPressDuration = 0.0
self.addGestureRecognizer(tap)
}
override func drawRect(rect: CGRect) {
let price = monkeys[monkeyIndex].getPrice(1).0
let text = currencyFormatter.stringFromNumber(price)!
let color = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
TapStyle.drawBuy(frame: rect, colorBuyBorder: color, colorBuyText: color, buyText: text)
}
func tappedMe(sender: UITapGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
UIView.animateWithDuration(0.15, animations: {
self.transform = CGAffineTransformMakeScale(0.91, 0.91)
})
}
else if sender.state == UIGestureRecognizerState.Ended {
self.delegate?.buyTapped(self.monkeyIndex)
UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}, completion: { (Bool) -> Void in
})
}
}
}
|
40d55b6ae79c9511b409ffa18b15c23f
| 36.504425 | 195 | 0.576025 | false | false | false | false |
jshultz/ios9-swift2-memorable-places
|
refs/heads/master
|
memorable-places/LocationViewController.swift
|
mit
|
1
|
//
// LocationViewController.swift
// memorable-places
//
// Created by Jason Shultz on 10/18/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
import CoreData
class LocationViewController: UIViewController {
var place: Places? = nil
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var streetLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//-- fetch data from CoreData --//
func fetchLocation () {
if place != nil {
titleLabel.text = place?.title
descriptionLabel.text = place?.user_description
streetLabel.text = place?.street
cityLabel.text = place?.locality
stateLabel.text = place?.administrativeArea
}
}
override func viewWillAppear(animated: Bool) {
fetchLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "mapSegue" {
let mapController:MapViewController = segue.destinationViewController as! MapViewController
mapController.place = place
} else if segue.identifier == "editPlace" {
let editController:EditLocationViewController = segue.destinationViewController as! EditLocationViewController
editController.place = place
}
}
}
|
84028309b3fac685bbe8bc3f7d9517b3
| 27.555556 | 122 | 0.651751 | false | false | false | false |
nwdl/the-more-you-know-ios
|
refs/heads/master
|
TheMoreYouKnow/ZeroAutoLayoutViewController.swift
|
mit
|
1
|
//
// ZeroAutoLayoutViewController.swift
// TheMoreYouKnow
//
// Created by Nate Walczak on 5/21/15.
// Copyright (c) 2015 Detroit Labs, LLC. All rights reserved.
//
import UIKit
class ZeroAutoLayoutViewController : UIViewController {
@IBOutlet weak var upperLeftView: UIView!
@IBOutlet weak var upperLeftViewCenterXLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var upperLeftViewCenterYLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var upperRightView: UIView!
@IBOutlet weak var upperRightViewCenterXLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var upperRightViewCenterYLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var bottomViewCenterYLayoutConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// onlyShowUpperViews() // red and green
// onlyShowUpperLeftView() // red
// onlyShowUpperRightView() // green
// onlyShowUpperLeftViewAndBottomView() // red and blue
// onlyShowUpperRightViewAndBottomView() // green and blue
// onlyShowBottomViews() // blue
}
func onlyShowUpperViews() {
upperLeftViewCenterYLayoutConstraint.constant = 0
upperRightViewCenterYLayoutConstraint.constant = 0
bottomView.hidden = true
}
func onlyShowUpperLeftView() {
upperLeftViewCenterXLayoutConstraint.constant = 0
upperLeftViewCenterYLayoutConstraint.constant = 0
upperRightView.hidden = true
bottomView.hidden = true
}
func onlyShowUpperRightView() {
upperLeftView.hidden = true
upperRightViewCenterXLayoutConstraint.constant = 0
upperRightViewCenterYLayoutConstraint.constant = 0
bottomView.hidden = true
}
func onlyShowUpperLeftViewAndBottomView() {
upperLeftViewCenterXLayoutConstraint.constant = 0
upperRightView.hidden = true
}
func onlyShowUpperRightViewAndBottomView() {
upperLeftView.hidden = true
upperRightViewCenterXLayoutConstraint.constant = 0
}
func onlyShowBottomViews() {
upperLeftView.hidden = true
upperRightView.hidden = true
bottomViewCenterYLayoutConstraint.constant = 0
}
}
|
926a168f680bc17b126dd8a623bdbebb
| 31.774648 | 81 | 0.703051 | false | false | false | false |
DuostecDalian/Meijiabang
|
refs/heads/master
|
KickYourAss/KickYourAss/RegisterTextCell.swift
|
mit
|
3
|
//
// RegisterTextCell.swift
// KickYourAss
//
// Created by eagle on 15/1/29.
// Copyright (c) 2015年 宇周. All rights reserved.
//
import UIKit
class RegisterTextCell: UITableViewCell {
@IBOutlet private weak var icyImageView: UIImageView!
@IBOutlet weak var icyTextField: UITextField!
enum RegisterTextCellType: Int{
case PhoneNumber = 0
case Password
case ConfirmPassword
}
var currentType: RegisterTextCellType = .PhoneNumber {
didSet {
switch currentType {
case .PhoneNumber:
icyImageView.image = UIImage(named: "loginUser")
icyTextField.secureTextEntry = false
icyTextField.placeholder = "输入手机号"
icyTextField.keyboardType = UIKeyboardType.NumberPad
case .Password:
icyImageView.image = UIImage(named: "loginPassword")
icyTextField.secureTextEntry = true
icyTextField.placeholder = "输入密码"
icyTextField.keyboardType = UIKeyboardType.ASCIICapable
case .ConfirmPassword:
icyImageView.image = UIImage(named: "loginConfirmPassword")
icyTextField.secureTextEntry = true
icyTextField.placeholder = "确认密码"
icyTextField.keyboardType = UIKeyboardType.ASCIICapable
}
}
}
class var identifier: String {
return "RegisterTextCellIdentifier"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
8b0066b35a28cd507432b122aacc4906
| 29.655172 | 75 | 0.615298 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/People/WPStyleGuide+People.swift
|
gpl-2.0
|
2
|
import Foundation
import WordPressShared
extension WPStyleGuide {
public struct People {
public struct RoleBadge {
// MARK: Metrics
public static let padding = CGFloat(4)
public static let borderWidth = CGFloat(1)
public static let cornerRadius = CGFloat(2)
// MARK: Typography
public static var font: UIFont {
return WPStyleGuide.fontForTextStyle(.caption2)
}
// MARK: Colors
public static let textColor = UIColor.white
}
// MARK: Colors
public static let superAdminColor = WPStyleGuide.fireOrange()
public static let adminColor = WPStyleGuide.darkGrey()
public static let editorColor = WPStyleGuide.darkBlue()
public static let otherRoleColor = WPStyleGuide.wordPressBlue()
}
}
|
3927084c260394c87806a44894da8cc4
| 31.296296 | 71 | 0.620413 | false | false | false | false |
fnazarios/weather-app
|
refs/heads/dev
|
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Map.swift
|
apache-2.0
|
4
|
//
// Map.swift
// Rx
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class MapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType {
typealias ResultType = O.E
typealias Element = SourceType
typealias Parent = Map<SourceType, ResultType>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func performMap(element: SourceType) throws -> ResultType {
abstractMethod()
}
func on(event: Event<SourceType>) {
switch event {
case .Next(let element):
do {
let mappedElement = try performMap(element)
forwardOn(.Next(mappedElement))
}
catch let e {
forwardOn(.Error(e))
dispose()
}
case .Error(let error):
forwardOn(.Error(error))
dispose()
case .Completed:
forwardOn(.Completed)
dispose()
}
}
}
class MapSink1<SourceType, O: ObserverType> : MapSink<SourceType, O> {
typealias ResultType = O.E
override init(parent: Map<SourceType, ResultType>, observer: O) {
super.init(parent: parent, observer: observer)
}
override func performMap(element: SourceType) throws -> ResultType {
return try _parent._selector1!(element)
}
}
class MapSink2<SourceType, O: ObserverType> : MapSink<SourceType, O> {
typealias ResultType = O.E
private var _index = 0
override init(parent: Map<SourceType, ResultType>, observer: O) {
super.init(parent: parent, observer: observer)
}
override func performMap(element: SourceType) throws -> ResultType {
return try _parent._selector2!(element, try incrementChecked(&_index))
}
}
class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Selector1 = (SourceType) throws -> ResultType
typealias Selector2 = (SourceType, Int) throws -> ResultType
private let _source: Observable<SourceType>
private let _selector1: Selector1?
private let _selector2: Selector2?
init(source: Observable<SourceType>, selector: Selector1) {
_source = source
_selector1 = selector
_selector2 = nil
}
init(source: Observable<SourceType>, selector: Selector2) {
_source = source
_selector2 = selector
_selector1 = nil
}
override func run<O: ObserverType where O.E == ResultType>(observer: O) -> Disposable {
if let _ = _selector1 {
let sink = MapSink1(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
}
else {
let sink = MapSink2(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
}
}
}
|
3539407a170ecb4047350184eb5578a4
| 27.271028 | 91 | 0.596892 | false | false | false | false |
hooman/swift
|
refs/heads/main
|
libswift/Sources/SIL/Type.swift
|
apache-2.0
|
3
|
//===--- Type.swift - Value type ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct Type {
var bridged: BridgedType
public var isAddress: Bool { SILType_isAddress(bridged) != 0 }
public var isObject: Bool { !isAddress }
}
|
f7d8cc2239ec837912e6acf8dd11471d
| 34.05 | 80 | 0.590585 | false | false | false | false |
embryoconcepts/TIY-Assignments
|
refs/heads/master
|
37 -- Venue Menu/VenueMenu/VenueMenu/FavoriteVenuesTableViewController.swift
|
cc0-1.0
|
1
|
//
// FavoriteVenuesTableViewController.swift
// VenueMenu
//
// Created by Jennifer Hamilton on 11/25/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
protocol VenueSearchDelegate
{
func venueWasSelected(venue: NSManagedObject)
}
class FavoriteVenuesTableViewController: UITableViewController, VenueSearchDelegate
{
var venues = Array<NSManagedObject>()
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad()
{
super.viewDidLoad()
title = "Favorite Venues"
let fetchRequest = NSFetchRequest(entityName: "Venue")
do {
let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Venue]
venues = fetchResults!
}
catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return venues.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("VenueTableViewCell", forIndexPath: indexPath) as! VenueTableViewCell
let aVenue = venues[indexPath.row]
cell.venueLabel.text = aVenue.valueForKey("name") as? String
// cell.ratingLabel.text = aVenue.valueForKey("rating") as? String
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete
{
let aVenue = venues[indexPath.row]
venues.removeAtIndex(indexPath.row)
managedObjectContext.deleteObject(aVenue)
saveContext()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "ShowSearchModal"
{
let destVC = segue.destinationViewController as! UINavigationController
let modalVC = destVC.viewControllers[0] as! VenueSearchViewController
modalVC.delegate = self
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let venueDetailVC = storyboard?.instantiateViewControllerWithIdentifier("VenueDetailViewController") as! VenueDetailViewController
venueDetailVC.indexRow = indexPath.row
venueDetailVC.venuesForDetailView = venues
navigationController?.pushViewController(venueDetailVC, animated: true)
}
// MARK: - Add Contact Delegate
func venueWasSelected(venue: NSManagedObject)
{
// let aVenue = NSEntityDescription.insertNewObjectForEntityForName("Venue", inManagedObjectContext: managedObjectContext) as! Venue
// let venueEntity = NSEntityDescription.entityForName("Venue", inManagedObjectContext: managedObjectContext)
// let aVenue = NSManagedObject(entity: venueEntity!, insertIntoManagedObjectContext: managedObjectContext)
managedObjectContext.insertObject(venue)
venues.append(venue)
saveContext()
tableView.reloadData()
}
// MARK: - Private functions
private func saveContext()
{
do
{
try managedObjectContext.save()
}
catch
{
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
|
6708df0fae0289e4d9d75cef7ec833d9
| 30.678571 | 157 | 0.670349 | false | false | false | false |
eridbardhaj/Weather
|
refs/heads/master
|
Weather/AppDelegate/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Weather
//
// Created by Erid Bardhaj on 4/27/15.
// Copyright (c) 2015 STRV. All rights reserved.
//
import UIKit
import CoreLocation
import WatchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Get current location
LocationManager.shared.getCurrentLocation()
//Control UIApperance to customise layout
changeLayout()
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:.
}
//MARK: - WatchKit
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!)
{
//Make the call to API
WeatherNetwork.getForecastWeatherByCoordinates(DataManager.shared.m_city_lat, lng: DataManager.shared.m_city_lng, responseHandler:
{
(error, array) -> (Void) in
if error == ErrorType.None
{
var response: NSDictionary = NSDictionary(dictionary: ["response" : array as! AnyObject])
reply(response as [NSObject : AnyObject])
}
else
{
//Handle Error
reply(nil)
}
})
}
//MARK: - Custom Settings
func changeLayout()
{
//Navigation Bar customization
UINavigationBar.appearance().setBackgroundImage(UIImage.new(), forBarMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 18.0)!, NSForegroundColorAttributeName: Constants.Colors.blackColor()]
UINavigationBar.appearance().backItem?.backBarButtonItem?.tintColor = Constants.Colors.lightBlue()
//UIBarButtonItem Attributes
var barAttribs = [NSFontAttributeName : UIFont(name: "ProximaNova-Regular", size: 16.0)!, NSForegroundColorAttributeName: Constants.Colors.lightBlue()]
UIBarButtonItem.appearance().setTitleTextAttributes(barAttribs, forState: UIControlState.Normal)
UIBarButtonItem.appearance().tintColor = Constants.Colors.lightBlue()
//UITabBar Attributes
var tabAttribsNormal = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 10.0)!, NSForegroundColorAttributeName: Constants.Colors.blackColor()]
var tabAttribsSelected = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 10.0)!, NSForegroundColorAttributeName: Constants.Colors.lightBlue(), ]
UITabBarItem.appearance().setTitleTextAttributes(tabAttribsNormal, forState: UIControlState.Normal)
UITabBarItem.appearance().setTitleTextAttributes(tabAttribsSelected, forState: UIControlState.Selected)
//Changing image tint color
UITabBar.appearance().tintColor = Constants.Colors.lightBlue()
UITabBar.appearance().backgroundImage = UIImage()
}
}
|
334fdae360163675cb72249bc85d368e
| 47.76 | 285 | 0.698728 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Managers/Model/AuthSettingsManagerPersistencyExtension.swift
|
mit
|
1
|
//
// AuthSettingsManagerPersistencyExtension.swift
// Rocket.Chat
//
// Created by Rafael Streit on 14/11/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
extension AuthSettingsManager {
static func persistPublicSettings(settings: AuthSettings, realm: Realm? = Realm.current, completion: (MessageCompletionObject<AuthSettings>)? = nil) {
let unmanagedSettings = AuthSettings(value: settings)
shared.internalSettings = unmanagedSettings
realm?.execute({ realm in
// Delete all the AuthSettings objects, since we don't
// support multiple-server per database
realm.delete(realm.objects(AuthSettings.self))
})
realm?.execute({ realm in
realm.add(settings)
if let auth = AuthManager.isAuthenticated(realm: realm) {
auth.settings = settings
realm.add(auth, update: true)
}
})
ServerManager.updateServerInformation(from: unmanagedSettings)
completion?(unmanagedSettings)
}
static func updatePublicSettings(
serverVersion: Version? = nil,
apiHost: URL? = nil,
apiSSLCertificatePath: URL? = nil,
apiSSLCertificatePassword: String = "",
_ auth: Auth?,
completion: (MessageCompletionObject<AuthSettings>)? = nil) {
let api: API?
if let apiHost = apiHost {
if let serverVersion = serverVersion {
api = API(host: apiHost, version: serverVersion)
} else {
api = API(host: apiHost)
}
} else {
api = API.current()
}
if let certificatePathURL = apiSSLCertificatePath {
api?.sslCertificatePath = certificatePathURL
api?.sslCertificatePassword = apiSSLCertificatePassword
}
let realm = Realm.current
let options: APIRequestOptionSet = [.paginated(count: 0, offset: 0)]
api?.fetch(PublicSettingsRequest(), options: options) { response in
switch response {
case .resource(let resource):
guard resource.success else {
completion?(nil)
return
}
persistPublicSettings(settings: resource.authSettings, realm: realm, completion: completion)
case .error(let error):
switch error {
case .version: websocketUpdatePublicSettings(realm, auth, completion: completion)
default: completion?(nil)
}
}
}
}
private static func websocketUpdatePublicSettings(_ realm: Realm?, _ auth: Auth?, completion: (MessageCompletionObject<AuthSettings>)? = nil) {
let object = [
"msg": "method",
"method": "public-settings/get"
] as [String: Any]
SocketManager.send(object) { (response) in
guard !response.isError() else {
completion?(nil)
return
}
let settings = AuthSettings()
settings.map(response.result["result"], realm: realm)
persistPublicSettings(settings: settings, realm: realm, completion: completion)
}
}
}
|
b6cbcbbb48da9d77278646ee6b1687d6
| 32.16 | 154 | 0.586248 | false | false | false | false |
jonbrown21/Seafood-Guide-iOS
|
refs/heads/master
|
Seafood Guide/Lingo/ViewControllers/LingoTableViewController.swift
|
mit
|
1
|
// Converted to Swift 5.1 by Swiftify v5.1.26565 - https://objectivec2swift.com/
//
// LingoTableViewController.swift
// Seafood Guide
//
// Created by Jon Brown on 9/1/14.
// Copyright (c) 2014 Jon Brown Designs. All rights reserved.
//
import UIKit
import CoreData
class LingoTableViewController: UITableViewController, UINavigationBarDelegate, UINavigationControllerDelegate {
var uppercaseFirstLetterOfName = ""
var predicateKey = ""
var window: UIWindow?
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
lazy var managedObjectContext: NSManagedObjectContext? = {
return (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
}()
var sectionIndexTitles: [AnyHashable] = []
init(lingoSize size: String?) {
super.init(style: .plain)
}
func setupFetchedResultsController() {
let entityName = "Lingo" // Put your entity name here
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.sortDescriptors = [NSSortDescriptor.init(key: "titlenews", ascending: true)]
if let managedObjectContext = managedObjectContext {
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "uppercaseFirstLetterOfName", cacheName: nil)
}
do {
try fetchedResultsController?.performFetch()
} catch {
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
weak var sectionInfo = fetchedResultsController?.sections?[section]
return sectionInfo?.name
}
override func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int {
weak var sectionInfo = fetchedResultsController?.sections?[section]
return sectionInfo?.numberOfObjects ?? 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupFetchedResultsController()
}
static let tableViewCellIdentifier = "lingocells"
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: LingoTableViewController.tableViewCellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: LingoTableViewController.tableViewCellIdentifier)
}
cell?.accessoryType = .disclosureIndicator
let lingo = fetchedResultsController?.object(at: indexPath) as? Lingo
cell?.textLabel?.text = lingo?.titlenews
return cell!
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return UILocalizedIndexedCollation.current().sectionIndexTitles
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return UILocalizedIndexedCollation.current().section(forSectionIndexTitle: index)
}
convenience override init(style: UITableView.Style) {
self.init(lingoSize: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem?.title = "Back"
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Table view sends data to detail view
override func tableView(_ aTableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailViewController = DetailLingoViewController.init(style: .plain)
var sumSections = 0
for i in 0..<indexPath.section {
let rowsInSection = tableView.numberOfRows(inSection: i)
sumSections += rowsInSection
}
let currentRow = sumSections + indexPath.row
let allLingo = fetchedResultsController?.fetchedObjects?[currentRow] as? Lingo
detailViewController.item = allLingo
navigationController?.pushViewController(detailViewController, animated: true)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationItem.hidesBackButton = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
838ae68ad44628b978b0eeb0bc19e5f7
| 32.708029 | 198 | 0.701386 | false | false | false | false |
iamyuiwong/swift-common
|
refs/heads/master
|
util/StringUtil.swift
|
lgpl-3.0
|
1
|
/*
* NAME StringUtil - string util
*
* DESC
* - Current for iOS 9
* - See diffs: (2015-10-04 17:43:24 +0800)
* https://developer.apple.com/library/prerelease/ios/releasenotes/General/iOS90APIDiffs/Swift/Swift.html
*
* V. See below
*/
import Foundation
/*
* NAME NSObjectString - class NSObjectString
*
* V
* - 1.0.0.0_2015100800
*/
public class NSObjectString: NSObject {
public var s: String?
}
/*
* NAME StringUtil - class StringUtil
*
* V
* - 1.0.0.3_20151009175522800
*/
public class StringUtil {
public static func toString () -> String {
return "StringUtilv1.0.0.3_20151009175522800"
}
/*
* NAME toString - from String Array
*
* ARGS
* - struct Array<T>
* - struct String
*
* DESC
* - E.X. ["1", "2", "3"] -> "123"
*/
public static func toString (let fromStringArray sa: [String]) -> String {
var ret = ""
for s in sa {
ret += s
}
return ret
}
/*
* NAME toString - from String Array and insert separator
*
* ARGS
* - struct Array<T>
* - struct String
* - ht if true always append sep to last
*/
public static func toString (let fromStringArray sa: [String],
insSeparator sep: String, hasTail ht: Bool) -> String {
var ret = ""
let c = sa.count
for i in 0..<c {
ret += sa[i] + sep
}
if let l = sa.last {
ret += l
}
if (ht) {
ret += sep
}
return ret
}
public static func toString (let byFormat fmt: String,
args: [CVarArgType]) -> String {
let ret = String(format: fmt, arguments: args)
return ret /* success */
}
public static func toString (fromCstring s: UnsafeMutablePointer<Int8>,
encoding: NSStringEncoding = NSUTF8StringEncoding)
-> String? {
if (nil == s) {
return nil
}
return String(CString: s, encoding: encoding)
}
public static func toString (fromCstring2 s: [Int8],
encoding: NSStringEncoding = NSUTF8StringEncoding)
-> String? {
return String(CString: s, encoding: encoding)
}
public static func toString (fromCstring3 s: UnsafePointer<Int8>,
encoding: NSStringEncoding = NSUTF8StringEncoding)
-> String? {
if (nil == s) {
return nil
}
return String(CString: s, encoding: encoding)
}
public static func toString (fromErrno en: Int32)
-> String {
let _ret = strerror(en)
let reto = StringUtil.toString(fromCstring: _ret,
encoding: NSUTF8StringEncoding)
if let ret = reto {
return ret
} else {
return "errno: \(en)"
}
}
/*
* NAME tocstring - from String
*
* DESC
* - String to "char *" use "encoding"
*/
public static func tocstringArray (let fromString s: String,
let encoding enc: NSStringEncoding = NSUTF8StringEncoding)
-> array<Int8>? {
let ret = array<Int8>()
ret.data = s.cStringUsingEncoding(enc)
return ret
}
public static func toCString (let fromString s: String,
let encoding enc: NSStringEncoding = NSUTF8StringEncoding)
-> [Int8]? {
return s.cStringUsingEncoding(enc)
}
public static func toCString_2 (let fromString s: String,
encoding: NSStringEncoding = NSUTF8StringEncoding)
-> [Int8]? {
/* e.x. NSUTF8StringEncoding */
let data = s.dataUsingEncoding(encoding, allowLossyConversion: false)
if (nil == data) {
return nil
}
let l = data!.length
var buf: [Int8] = [Int8](count: l, repeatedValue: 0x0)
Log.v(tag: TAG, items: "len: \(l)")
data!.getBytes(&buf, length: l)
return buf
}
public static func toHexDataStr (let fromCString arr: [Int8],
start: Int = 0,
count: size_t? = nil,
uppercase: Bool = false) -> String? {
let cc = ArrayChecker.check(array: arr, start: start, count: count)
if (cc < 0) {
return nil
}
var ret = ""
var f: String?
if (uppercase) {
f = "%.2X"
} else {
f = "%.2x"
}
for i in 0..<cc {
let b = arr[i + start]
ret += String(format: f!, b)
}
return ret
}
/**
* NAME toHexDataStr - fromData<br>
* E.x. { '0', '9', 0xa } => { 30, 39, 10 }<br>
* => { '3', '0', '3', '9', '1', '0' }<br>
* => final result "303910"<br>
*
* NOTE
* All lower case
*/
public static func toHexDataStr (let fromData arr: [UInt8],
start: Int = 0,
count: size_t? = nil,
uppercase: Bool = false) -> String? {
let cc = ArrayChecker.check(array: arr, start: start, count: count)
if (cc < 0) {
return nil
}
var ret = ""
var f: String?
if (uppercase) {
f = "%.2X"
} else {
f = "%.2x"
}
for i in 0..<cc {
let b = arr[i + start]
ret += String(format: f!, b)
}
return ret
}
public static func toInt (fromBinString s: String) -> Int64 {
if let ret = Int64(s, radix: 2) {
return ret
} else {
return 0
}
}
public static func toInt (fromOctString s: String) -> Int64 {
if let ret = Int64(s, radix: 8) {
return ret
} else {
return 0
}
}
public static func toInt (fromDecString s: String) -> Int64 {
if let ret = Int64(s, radix: 10) {
return ret
} else {
return 0
}
}
public static func toInt (fromHexString s: String) -> Int64 {
if let ret = Int64(s, radix: 16) {
return ret
} else {
return 0
}
}
public static func toInt (fromString s: String, radix r: Int) -> Int64 {
if let ret = Int64(s, radix: r) {
return ret
} else {
return 0
}
}
public static func toData (let fromString s: String,
let encoding enc: NSStringEncoding = NSUTF8StringEncoding)
-> [UInt8]? {
/* check */
if (s.isEmpty) {
return [0x0]
}
let nsdata = s.dataUsingEncoding(enc, allowLossyConversion: false)
if (nil == nsdata) {
return nil
} else {
}
let l = nsdata!.length
var buf: [UInt8] = [UInt8](count: l, repeatedValue: 0x0)
nsdata!.getBytes(&buf, length: l)
return buf
}
/*
* NAME split - split string by ONE Character to strings
*/
public static func split (string s: String,
byCharacter separator: Character) -> [String] {
return s.componentsSeparatedByString(String(separator))
}
/*
* NAME split - split string by characters to strings
*/
public static func split (let string s: String,
let byString separator: String) -> [String] {
return s.componentsSeparatedByString(separator)
}
/*
* NAME charsCount - string characters count
*/
public static func charsCount (let ofString s: String) -> Int {
return s.characters.count
}
/*
* NAME cstringCount - c string count whenEncoding is encoding
*/
public static func cstringCount (let ofString s: String,
whenEncoding encoding: NSStringEncoding = NSUTF8StringEncoding)
-> Int {
if let cs = StringUtil.toCString(fromString: s, encoding: encoding) {
return cs.count
} else {
return -1
}
}
/*
* NAME dataCount - c string count whenEncoding is encoding
*/
public static func dataCount (let ofString s: String,
whenEncoding encoding: NSStringEncoding = NSUTF8StringEncoding)
-> Int {
return StringUtil.cstringCount(ofString: s, whenEncoding: encoding)
}
/*
* NAME substring - sub string of string (by character)
*
* DESC
* - from start Char index to end(no end)
*/
public static func substring (let ofString s: String,
fromCharIndex ib: Int,
to ie: Int) -> String? {
let c = s.characters.count
if ((ib < 0) || (ie > c) || (ie < (ib + 1))) {
return nil
} else {
let start = s.startIndex.advancedBy(ib)
let end = s.startIndex.advancedBy(ie - 1)
return s[start...end]
}
}
/*
* NAME substring - sub string of string (by character)
*
* DESC
* - from start Char index and count Chars
*/
public static func substring (let ofString s: String,
fromCharIndex ib: Int,
count c: Int) -> String? {
let ec = s.characters.count
if ((ib < 0) || (c <= 0) || ((c + ib) > ec)) {
return nil
} else {
let start = s.startIndex.advancedBy(ib)
let end = s.startIndex.advancedBy(ib + c - 1)
return s[start...end]
}
}
/*
* NAME reverse - reverse string to reversed string
*/
public static func reverse (let tostring ori: String) -> String {
return String(ori.characters.reverse())
}
/*
* NAME reverse - reverse string to reversed CS
*/
public static func reverse (let tocs ori: String) -> [Character] {
return ori.characters.reverse()
}
/*
* NAME remove - remove:inString:fromCharIndex:to
*
* DESC
* - String copy .. -- but if not !!
* - And acceptable: to get a new string and keep origin!!
* - indclude "to" index (remove)
*/
public static func remove (let inString _s: String, fromCharIndex f: Int,
to t: Int) -> String {
let c = _s.characters.count
if ((f < 0) || (t < 0) || (c <= 0) || (f > t) || (t >= c)) {
return _s
}
let start = _s.startIndex.advancedBy(f)
let end = _s.startIndex.advancedBy(t)
var s = _s
s.removeRange(start...end)
return s
}
/*
* NAME remove - remove:inString:fromCharIndex:count
*/
public static func remove (let inString _s: String, fromCharIndex f: Int,
count c: Int) -> String {
let ec = _s.characters.count
if ((f < 0) || (c <= 0) || ((c + f) > ec)) {
return _s
}
let start = _s.startIndex.advancedBy(f)
let end = _s.startIndex.advancedBy(f + c - 1)
var s = _s
s.removeRange(start...end)
return s
}
private static let TAG: String = StringUtil.toString()
}
func string2double (s: String) -> Double {
return NSNumberFormatter().numberFromString(s)!.doubleValue
}
func string2uint8 (s: String) -> UInt8 {
return UInt8(NSNumberFormatter().numberFromString(s)!.unsignedShortValue)
}
/*
* NAME numeric2string - to string
*/
func numeric2string (d: Double) -> String {
/* Double to String no .0 suffix */
let s: String = "\(d)"
if (s.hasSuffix(".0")) {
let n = s.characters.count
return String(s.characters.prefix(n - 2))
} else {
return s
}
}
func numeric2string (i: Int) -> String {
/* Int to String */
let s: String = "\(i)"
return s
}
func numeric2string (i: Int32) -> String {
/* Int32 to String */
let s: String = "\(i)"
return s
}
func numeric2string (u: UInt32) -> String {
/* UInt32 to String */
let s: String = "\(u)"
return s
}
/*
* NAME append2string - this is for <Integer>.<Frac>
*
* DESCRIPTION
* E.x. "1.1", 3, 1 => "1.13"
* "1.012", 3, 5 => "1.012003"
*/
func append2string (final s: String, frac: UInt8, n: UInt32) -> String {
var res = s
print(s, frac, n)
if (res.characters.contains(".")) {
let ss = res.characters.split(".")
let l = ss[1].count
let le = n - UInt32(l)
for (var i: UInt32 = 0; i < le; ++i) {
res += "0"
}
res += numeric2string(UInt32(frac))
} else {
res += "."
for (var i: UInt32 = 0; i < n; ++i) {
res += "0"
}
res += numeric2string(UInt32(frac))
}
return res
}
|
2520ef4950967bc815948f797836d7d5
| 17.353448 | 106 | 0.617097 | false | false | false | false |
ivanbruel/SwipeIt
|
refs/heads/master
|
Pods/Localizable/Pod/Network.swift
|
mit
|
1
|
//
// Network.swift
// Localizable
//
// Created by Ivan Bruel on 23/02/16.
// Copyright © 2016 Localizable. All rights reserved.
//
import Foundation
class Network: NSObject {
private static let defaultApiURL = "https://localizable-api.herokuapp.com/api/v1/"
private static let timeout = 60.0
private static let jsonHeader = "application/json"
var mockData: Bool = false
var apiURL = Network.defaultApiURL
static var sharedInstance = Network()
private let session = NSURLSession(configuration:
NSURLSessionConfiguration.defaultSessionConfiguration())
func performRequest(api: API, token: String,
completion: (([String: AnyObject]?, NSError?) -> Void)? = nil) {
let url = urlFromPath(api.path)
performRequest(api.method, url: url, token: token, sampleData: api.sampleData, json: api.json,
completion: completion)
}
}
private extension Network {
private func urlFromPath(path: String) -> String {
return "\(apiURL)\(path)"
}
private func performRequest(method: Method = .GET, url: String, token: String,
sampleData: [String: AnyObject]?, json: [String: AnyObject]? = nil,
completion: (([String: AnyObject]?, NSError?) -> Void)? = nil) {
var url = url
if let json = json where method == .GET {
let queryString = json.map { "\($0.0)=\($0.1.description)"}.joinWithSeparator("&")
if queryString.characters.count > 0 {
url = "\(url)?\(queryString)"
}
}
guard let requestURL = NSURL(string: url) else {
Logger.logHttp("Invalid url \(url)")
return
}
let request = NSMutableURLRequest(URL: requestURL, cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: Network.timeout)
request.addValue(Network.jsonHeader, forHTTPHeaderField: "Content-Type")
request.addValue(Network.jsonHeader, forHTTPHeaderField: "Accept")
request.addValue(token, forHTTPHeaderField: "X-LOCALIZABLE-TOKEN")
request.HTTPMethod = method.rawValue
Logger.logHttp("\(method.rawValue) to \(url) with token \(token)")
if let json = json where method != .GET {
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json,
options: .PrettyPrinted)
request.HTTPBody = jsonData
if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
Logger.logHttp(jsonString)
}
} catch {
Logger.logHttp("Could not serialize \(json.description) into JSON")
}
}
if let sampleData = sampleData where self.mockData {
completion?(sampleData, nil)
return
}
let task = session.dataTaskWithRequest(request) { (data, response, error) in
self.handleNetworkResponse(data, response: response, error: error, completion: completion)
}
task.resume()
}
private func handleNetworkResponse(data: NSData?, response: NSURLResponse?, error: NSError?,
completion: (([String: AnyObject]?, NSError?) -> Void)?) {
if let error = error {
completion?(nil, error)
} else if let data = data where data.length > 0 {
let jsonString = String(data: data, encoding: NSUTF8StringEncoding)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
as? [String: AnyObject] {
completion?(json, nil)
} else {
Logger.logHttp("Could not cast \(jsonString) into [String: AnyObject]")
completion?([:], nil)
}
} catch {
Logger.logHttp("Could not deserialize \(jsonString) into [String: AnyObject]")
completion?([:], nil)
}
} else {
completion?([:], nil)
}
}
}
|
c705eb294f30626bb196c4e850ab3110
| 32.517857 | 100 | 0.63772 | false | false | false | false |
yakirlee/Extersion
|
refs/heads/master
|
Helpers/UIImage+Orientation.swift
|
mit
|
1
|
//
// UIImage+Orientation.swift
// TSWeChat
//
// Created by Hilen on 2/17/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
//https://github.com/cosnovae/fixUIImageOrientation/blob/master/fixImageOrientation.swift
public extension UIImage {
class func fixImageOrientation(src:UIImage) -> UIImage {
if src.imageOrientation == UIImageOrientation.Up {
return src
}
var transform: CGAffineTransform = CGAffineTransformIdentity
switch src.imageOrientation {
case UIImageOrientation.Down, UIImageOrientation.DownMirrored:
transform = CGAffineTransformTranslate(transform, src.size.width, src.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
break
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored:
transform = CGAffineTransformTranslate(transform, src.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
break
case UIImageOrientation.Right, UIImageOrientation.RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, src.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
break
case UIImageOrientation.Up, UIImageOrientation.UpMirrored:
break
}
switch src.imageOrientation {
case UIImageOrientation.UpMirrored, UIImageOrientation.DownMirrored:
CGAffineTransformTranslate(transform, src.size.width, 0)
CGAffineTransformScale(transform, -1, 1)
break
case UIImageOrientation.LeftMirrored, UIImageOrientation.RightMirrored:
CGAffineTransformTranslate(transform, src.size.height, 0)
CGAffineTransformScale(transform, -1, 1)
case UIImageOrientation.Up, UIImageOrientation.Down, UIImageOrientation.Left, UIImageOrientation.Right:
break
}
let ctx:CGContextRef = CGBitmapContextCreate(nil, Int(src.size.width), Int(src.size.height), CGImageGetBitsPerComponent(src.CGImage), 0, CGImageGetColorSpace(src.CGImage), CGImageAlphaInfo.PremultipliedLast.rawValue)!
CGContextConcatCTM(ctx, transform)
switch src.imageOrientation {
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored, UIImageOrientation.Right, UIImageOrientation.RightMirrored:
CGContextDrawImage(ctx, CGRectMake(0, 0, src.size.height, src.size.width), src.CGImage)
break
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, src.size.width, src.size.height), src.CGImage)
break
}
let cgimage:CGImageRef = CGBitmapContextCreateImage(ctx)!
let image:UIImage = UIImage(CGImage: cgimage)
return image
}
}
|
ec9e1f6e93c2f92278fde4356ba71266
| 38.391892 | 225 | 0.675129 | false | false | false | false |
tankco/TTImagePicker
|
refs/heads/master
|
TCImagePickerExample/TCImagePickerExample/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TCImagePickerExample
//
// Created by 谈超 on 2017/5/3.
// Copyright © 2017年 谈超. All rights reserved.
//
import UIKit
import TCImagePicker
class ViewController: UIViewController {
lazy private var imageView: UIImageView = {
let object = UIImageView()
object.backgroundColor = UIColor.red
return object
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 80))
view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 80))
imageView.addOnClickListener(target: self, action: #selector(ViewController.imageViewClick(imageView:)));
}
func imageViewClick(imageView:UIImageView?) {
TCImagePicker.showImagePickerFromViewController(viewController: self, allowsEditing: true, iconView: self.imageView) { [unowned self](icon) in
self.imageView.image = icon!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIView{
func addOnClickListener(target: AnyObject, action: Selector) {
let gr = UITapGestureRecognizer(target: target, action: action)
gr.numberOfTapsRequired = 1
isUserInteractionEnabled = true;
// userInteractionEnabled = true
addGestureRecognizer(gr)
}
}
|
ad72323ed7f38c4423bef4516cf921b5
| 41.244898 | 166 | 0.698068 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/Sema/diag_optional_to_any.swift
|
apache-2.0
|
1
|
// RUN: %target-parse-verify-swift
func takeAny(_ left: Any, _ right: Any) -> Int? {
return left as? Int
}
func throwing() throws -> Int? {}
func warnOptionalToAnyCoercion(value x: Int?) -> Any {
let a: Any = x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}{{17-17= ?? <#default value#>}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}{{17-17=!}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}{{17-17= as Any}}
let b: Any = x as Any
let c: Any = takeAny(a, b) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
let _: Any = takeAny(c, c) as Any
let _: Any = (x) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
let f: Any = (x as Any)
let g: Any = (x) as (Any)
_ = takeAny(f as? Int, g) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
let _: Any = takeAny(f as? Int, g) as Any // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}{{33-33= ?? <#default value#>}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}{{33-33=!}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}{{33-33= as Any}}
let _: Any = takeAny(f as? Int as Any, g) as Any
let _: Any = x! == x! ? 1 : x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
do {
let _: Any = try throwing() // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
} catch {}
return x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
}
|
82b96817f93a0d301c668d552793508e
| 51.666667 | 116 | 0.669937 | false | false | false | false |
cocoascientist/Passengr
|
refs/heads/master
|
Passengr/RefreshController.swift
|
mit
|
1
|
//
// RefreshController.swift
// Passengr
//
// Created by Andrew Shepard on 12/9/15.
// Copyright © 2015 Andrew Shepard. All rights reserved.
//
import UIKit
enum RefreshState {
case idle
case updating
case error
}
final class RefreshController: NSObject {
weak var refreshControl: UIRefreshControl?
weak var dataSource: PassDataSource?
init(refreshControl: UIRefreshControl, dataSource: PassDataSource) {
self.refreshControl = refreshControl
self.dataSource = dataSource
super.init()
// NotificationCenter.default.addObserver(self, selector: #selector(RefreshController.handleRefresh(_:)), name: NSNotification.Name.didBecomeActiveNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func setControlState(state: RefreshState) {
guard let refreshControl = refreshControl else {
fatalError("refreshControl should not be nil")
}
let string = title(for: state)
refreshControl.attributedTitle = NSAttributedString(string: string)
transition(to: state)
}
func setControlState(error: NSError) {
guard let refreshControl = refreshControl else {
fatalError("refreshControl should not be nil")
}
let string = title(for: error)
refreshControl.attributedTitle = NSAttributedString(string: string)
transition(to: .error)
}
@objc func handleRefresh(_ notification: NSNotification) {
self.dataSource?.reloadData()
}
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}()
}
extension RefreshController {
private func transition(to state: RefreshState) {
if state == .updating {
let delayTime = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { [weak self] in
self?.dataSource?.reloadData()
})
}
else {
self.refreshControl?.endRefreshing()
}
}
private func title(for state: RefreshState) -> String {
guard let dataSource = dataSource else {
fatalError("dataSource should not be nil")
}
switch state {
case .error:
return NSLocalizedString("Error", comment: "Error")
case .updating:
return NSLocalizedString("Updating...", comment: "Updating")
case .idle:
let dateString = self.dateFormatter.string(from: dataSource.lastUpdated)
let prefix = NSLocalizedString("Updated on", comment: "Updated on")
return "\(prefix) \(dateString)"
}
}
private func title(for error: NSError) -> String {
var string = title(for: .error)
if let message = error.userInfo[NSLocalizedDescriptionKey] as? String {
string = "\(string): \(message)"
}
return string
}
}
|
194027d427cb9cfb168483c27608d168
| 28.867925 | 180 | 0.612445 | false | false | false | false |
DaiYue/HAMLeetcodeSwiftSolutions
|
refs/heads/master
|
solutions/9_Palindrome_Number.playground/Contents.swift
|
mit
|
1
|
// #9 Palindrome Number https://leetcode.com/problems/palindrome-number/
// 很简单的题,没给出的条件是负数不算回文数。有个 case 1000021 一开始做错了。另外一开始写了个递归,后来发现没必要……
// 时间复杂度:O(n) 空间复杂度:O(1)
class Solution {
func isPalindrome(_ x: Int) -> Bool {
guard x >= 0 else {
return false
}
var divider = 1
while divider * 10 <= x {
divider *= 10
}
var target = x
while divider >= 10 {
if target / divider != target % 10 {
return false
}
target = (target % divider) / 10
divider = divider / 100
}
return true
}
}
Solution().isPalindrome(11)
|
7d11cb415a8b1db1158e8951f9d596b6
| 22.866667 | 72 | 0.486034 | false | false | false | false |
devinross/curry-fire
|
refs/heads/master
|
curryfire/TKBounceBehavior.swift
|
mit
|
1
|
//
// TKBounceBehavior.swift
// Created by Devin Ross on 9/15/16.
//
/*
curryfire || https://github.com/devinross/curry-fire
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
public class TKBounceBehavior: UIDynamicBehavior {
@objc public var gravityBehavior: UIGravityBehavior
@objc public var pushBehavior: UIPushBehavior
@objc public var itemBehavior: UIDynamicItemBehavior
@objc public var collisionBehavior: UICollisionBehavior
private var _bounceDirection: CGVector = CGVector(dx: 0, dy:2.0)
public init(items: [UIDynamicItem] ) {
gravityBehavior = UIGravityBehavior(items: items)
collisionBehavior = UICollisionBehavior(items: items)
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
pushBehavior = UIPushBehavior(items: items, mode: .instantaneous)
pushBehavior.pushDirection = _bounceDirection
pushBehavior.active = false
itemBehavior = UIDynamicItemBehavior(items: items)
itemBehavior.elasticity = 0.45
super.init()
self.addChildBehavior(gravityBehavior)
self.addChildBehavior(pushBehavior)
self.addChildBehavior(itemBehavior)
self.addChildBehavior(collisionBehavior)
}
@objc public var bounceDirection : CGVector {
get {
return _bounceDirection
}
set (vector) {
_bounceDirection = vector
self.pushBehavior.pushDirection = vector
var dx: CGFloat = 0
var dy: CGFloat = 0
if vector.dx > 0 {
dx = -1
}
else if vector.dx < 0 {
dx = 1
}
if vector.dy > 0 {
dy = -1
}
else if vector.dy < 0 {
dy = 1
}
self.gravityBehavior.gravityDirection = CGVector(dx: dx, dy:dy)
}
}
@objc public func bounce() {
self.pushBehavior.active = true
}
}
|
e67e1be12840baa918a635fb85ad6048
| 26.408163 | 67 | 0.748325 | false | false | false | false |
yhx189/WildHacks
|
refs/heads/master
|
SwiftMaps/PlayViewController.swift
|
apache-2.0
|
1
|
//
// PlayViewController.swift
// SwiftMaps
//
// Created by Yang Hu on 11/21/15.
// Copyright © 2015 Brett Morgan. All rights reserved.
//
import Foundation
import UIKit
import GoogleMaps
import Parse
import AVFoundation
class PlayViewController: UIViewController , ESTBeaconManagerDelegate,AVAudioPlayerDelegate, AVAudioRecorderDelegate {
var allRecords: [String] = []
var audioPlayer: AVAudioPlayer?
var timer = NSTimer()
var counter = 0
let beaconManager = ESTBeaconManager()
let beaconRegion = CLBeaconRegion(
proximityUUID: NSUUID(UUIDString: "CF1A5302-EEBB-5C4F-AA18-851A36494C3D")!,
identifier: "blueberry")
let placesByBeacons = [
"583:38376": [
"Heavenly Sandwiches": 50,
"Green & Green Salads": 150,
"Mini Panini": 325
],
"648:12": [
"Heavenly Sandwiches": 250,
"Green & Green Salads": 100,
"Mini Panini": 20
],
"17581:4351": [
"Heavenly Sandwiches": 350,
"Green & Green Salads": 500,
"Mini Panini": 170
]
]
func placesNearBeacon(beacon: CLBeacon) -> [String] {
let beaconKey = "\(beacon.major):\(beacon.minor)"
if let places = self.placesByBeacons[beaconKey] {
let sortedPlaces = Array(places).sort( { $0.1 < $1.1 }).map { $0.0 }
return sortedPlaces
}
return []
}
func beaconManager(manager: AnyObject!, beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
print("ssss")
if let nearestBeacon = beacons.first as? CLBeacon {
let places = placesNearBeacon(nearestBeacon)
// TODO: update the UI here
print(places) // TODO: remove after implementing the UI
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.beaconManager.delegate = self
// 4. We need to request this authorization for every beacon manager
self.beaconManager.requestAlwaysAuthorization()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.beaconManager.startRangingBeaconsInRegion(self.beaconRegion)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.beaconManager.stopRangingBeaconsInRegion(self.beaconRegion)
}
}
|
c131783df24fd6b118e6077687a3778b
| 27.375 | 118 | 0.602965 | false | false | false | false |
rahuliyer95/iShowcase
|
refs/heads/master
|
Example/iShowcaseExample/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// iShowcaseExample
//
// Created by Rahul Iyer on 14/10/15.
// Copyright © 2015 rahuliyer. All rights reserved.
//
import UIKit
import iShowcase
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, iShowcaseDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var backgroundColor: UITextField!
@IBOutlet weak var titleColor: UITextField!
@IBOutlet weak var detailsColor: UITextField!
@IBOutlet weak var highlightColor: UITextField!
let tableData = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
var showcase: iShowcase!
var custom: Bool = false
var multiple: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
setupShowcase()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
UIView.animate(withDuration: duration, animations: {
if let showcase = self.showcase {
showcase.setNeedsLayout()
}
})
}
@IBAction func barButtonClick(_ sender: UIBarButtonItem) {
showcase.titleLabel.text = "Bar Button Example"
showcase.detailsLabel.text = "This example highlights the Bar Button Item"
showcase.setupShowcaseForBarButtonItem(sender)
showcase.show()
}
@IBAction func defaultShowcaseClick(_ sender: UIButton) {
showcase.titleLabel.text = "Default"
showcase.detailsLabel.text = "This is default iShowcase with long long long long long long long long text"
showcase.setupShowcaseForView(sender)
showcase.show()
}
@IBAction func multipleShowcaseClick(_ sender: UIButton) {
multiple = true
defaultShowcaseClick(sender)
}
@IBAction func tableViewShowcaseClick(_ sender: UIButton) {
showcase.titleLabel.text = "UITableView"
showcase.detailsLabel.text = "This is default position example"
showcase.setupShowcaseForTableView(tableView)
showcase.show()
}
@IBAction func customShowcaseClick(_ sender: UIButton) {
if backgroundColor.text!.characters.count > 0 {
showcase.coverColor = UIColor.colorFromHexString(backgroundColor.text!)
}
if titleColor.text!.characters.count > 0 {
showcase.titleLabel.textColor = UIColor.colorFromHexString(titleColor.text!)
}
if detailsColor.text!.characters.count > 0 {
showcase.detailsLabel.textColor = UIColor.colorFromHexString(detailsColor.text!)
}
if highlightColor.text!.characters.count > 0 {
showcase.highlightColor = UIColor.colorFromHexString(highlightColor.text!)
}
custom = true
showcase.type = .circle
showcase.titleLabel.text = "Custom"
showcase.detailsLabel.text = "This is custom iShowcase"
showcase.setupShowcaseForView(sender)
// Uncomment this to show the showcase only once after 1st run
// showcase.singleShotId = 47
showcase.show()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, with: event)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
if let cell = cell {
cell.textLabel!.text = tableData[(indexPath as NSIndexPath).row]
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
showcase.titleLabel.text = "UITableView"
showcase.detailsLabel.text = "This is custom position example"
showcase.setupShowcaseForTableView(tableView, withIndexPath: indexPath)
showcase.show()
tableView.deselectRow(at: indexPath, animated: true)
}
fileprivate func setupShowcase() {
showcase = iShowcase()
showcase.delegate = self
}
func iShowcaseDismissed(_ showcase: iShowcase) {
if multiple {
showcase.titleLabel.text = "Multiple"
showcase.detailsLabel.text = "This is multiple iShowcase"
showcase.setupShowcaseForView(titleColor)
showcase.show()
multiple = false
}
if custom {
setupShowcase()
custom = false
}
}
}
|
2c6099fc2f3b8e8008d627a1ef1f5489
| 31.89404 | 124 | 0.658345 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK
|
refs/heads/master
|
Modules/FlagKit/FlagKit.swift
|
mit
|
1
|
//
// FlagKit.swift
// MobileTrading
//
// Created by Nguyen Minh on 4/6/17.
// Copyright © 2017 AHDEnglish. All rights reserved.
//
import UIKit
import Foundation
import CoreGraphics
open class SpriteSheet {
typealias GridSize = (cols: Int, rows: Int)
typealias ImageSize = (width: CGFloat, height: CGFloat)
typealias Margin = (top: CGFloat, left: CGFloat, right: CGFloat, bottom: CGFloat)
struct SheetInfo {
fileprivate(set) var gridSize: GridSize
fileprivate(set) var spriteSize: ImageSize
fileprivate(set) var spriteMargin: Margin
fileprivate(set) var codes: [String]
}
fileprivate(set) var info: SheetInfo
fileprivate(set) var image: UIImage
fileprivate var imageCache = [String:UIImage]()
init?(sheetImage: UIImage, info sInfo: SheetInfo) {
image = sheetImage
info = sInfo
}
func getImageFor(code: String) -> UIImage? {
var cimg: UIImage?
cimg = imageCache[code]
if cimg == nil {
let rect = getRectFor(code)
cimg = image.cropped(to: rect)
cimg = image.cropped(to: rect)
imageCache[code] = cimg
}
return cimg
}
open func getRectFor(_ code: String) -> CGRect {
let spriteW = info.spriteSize.width
let spriteH = info.spriteSize.height
let realSpriteW = spriteW - info.spriteMargin.left - info.spriteMargin.right
let realSpriteH = spriteH - info.spriteMargin.top - info.spriteMargin.bottom
let idx = info.codes.index(of: code.lowercased()) ?? 0
let dx = idx % info.gridSize.cols
let dy = idx/info.gridSize.cols
let x = CGFloat(dx) * spriteW + info.spriteMargin.top
let y = CGFloat(dy) * spriteH + info.spriteMargin.left
return CGRect(x: x, y: y, width: realSpriteW, height: realSpriteH)
}
deinit {
imageCache.removeAll()
}
}
open class FlagKit: NSObject {
static let shared = FlagKit()
var spriteSheet: SpriteSheet?
override init() {
super.init()
spriteSheet = FlagKit.loadDefault()
}
open class func loadDefault() -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoFile = assetsBundle.path(forResource: "flags_v1", ofType: "json") {
return self.loadSheetFrom(infoFile)
}
return nil
}
open class func loadSheetFrom(_ file: String) -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoData = try? Data(contentsOf: URL(fileURLWithPath: file)) {
do {
if let infoObj = try JSONSerialization.jsonObject(with: infoData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String:Any] {
if let gridSizeObj = infoObj["gridSize"] as? [String:Int],
let spriteSizeObj = infoObj["spriteSize"] as? [String:CGFloat],
let spriteMarginObj = infoObj["margin"] as? [String:CGFloat] {
let gridSize = (gridSizeObj["cols"]!, gridSizeObj["rows"]!)
let spriteSize = (spriteSizeObj["width"]!, spriteSizeObj["height"]!)
let spriteMargin = (spriteMarginObj["top"]!, spriteMarginObj["left"]!, spriteMarginObj["right"]!, spriteMarginObj["bottom"]!)
if let codes = (infoObj["codes"] as? String)?.components(separatedBy: ",") {
if let sheetFileName = infoObj["sheetFile"] as? String,
let resourceUrl = assetsBundle.resourceURL {
let sheetFileUrl = resourceUrl.appendingPathComponent(sheetFileName)
if let image = UIImage(contentsOfFile: sheetFileUrl.path) {
let info = SpriteSheet.SheetInfo(gridSize: gridSize, spriteSize: spriteSize, spriteMargin: spriteMargin, codes: codes)
return SpriteSheet(sheetImage: image, info: info)
}
}
}
}
}
} catch {
}
}
return nil
}
fileprivate class func assetsBundle() -> Bundle? {
let bundle = Bundle(for: self)
guard let assetsBundlePath = bundle.path(forResource: "flag-assets", ofType: "bundle") else {
return nil
}
return Bundle(path: assetsBundlePath);
}
}
extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in PNG format
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
var png: Data? { return UIImagePNGRepresentation(self) }
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ quality: JPEGQuality) -> Data? { return UIImageJPEGRepresentation(self, quality.rawValue) }
/// UIImage Cropped to CGRect.
///
/// - Parameter rect: CGRect to crop UIImage to.
/// - Returns: cropped UIImage
public func cropped(to rect: CGRect) -> UIImage {
guard rect.size.height < size.height && rect.size.width < size.width else {
return self
}
guard let image: CGImage = cgImage?.cropping(to: rect) else {
return self
}
return UIImage(cgImage: image)
}
}
|
941188dc8552b1233d807572d3bdde7c
| 38.913043 | 242 | 0.59197 | false | false | false | false |
adamnemecek/AudioKit
|
refs/heads/main
|
Tests/AudioKitTests/Node Tests/Effects Tests/ExpanderTests.swift
|
mit
|
1
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class ExpanderTests: XCTestCase {
func testDefault() throws {
try XCTSkipIf(true, "TODO This test gives different results on local machines from what CI does")
let engine = AudioEngine()
let url = Bundle.module.url(forResource: "12345", withExtension: "wav", subdirectory: "TestResources")!
let input = AudioPlayer(url: url)!
engine.output = Expander(input)
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
}
|
1f0612e860ae81efce205fa584ee4544
| 33.9 | 111 | 0.679083 | false | true | false | false |
cloudinary/cloudinary_ios
|
refs/heads/master
|
Cloudinary/Classes/Core/BaseNetwork/CLDNValidation.swift
|
mit
|
1
|
//
// CLDNValidation.swift
//
// 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
extension CLDNRequest {
// MARK: Helper Types
fileprivate typealias ErrorReason = CLDNError.ResponseValidationFailureReason
/// Used to represent whether validation was successful or encountered an error resulting in a failure.
///
/// - success: The validation was successful.
/// - failure: The validation failed encountering the provided error.
internal enum ValidationResult {
case success
case failure(Error)
}
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { return type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
#if swift(>=3.2)
let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
#else
let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
#endif
return split.components(separatedBy: "/")
}()
if let type = components.first, let subtype = components.last {
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(_ mime: MIMEType) -> Bool {
switch (type, subtype) {
case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
return true
default:
return false
}
}
}
// MARK: Properties
internal var acceptableStatusCodes: [Int] { return Array(200..<300) }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(
statusCode acceptableStatusCodes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == Int
{
if acceptableStatusCodes.contains(response.statusCode) {
return .success
} else {
let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
return .failure(CLDNError.responseValidationFailed(reason: reason))
}
}
// MARK: Content Type
fileprivate func validate<S: Sequence>(
contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String
{
guard let data = data, data.count > 0 else { return .success }
guard
let responseContentType = response.mimeType,
let responseMIMEType = MIMEType(responseContentType)
else {
for contentType in acceptableContentTypes {
if let mimeType = MIMEType(contentType), mimeType.isWildcard {
return .success
}
}
let error: CLDNError = {
let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
return CLDNError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
return .success
}
}
let error: CLDNError = {
let reason: ErrorReason = .unacceptableContentType(
acceptableContentTypes: Array(acceptableContentTypes),
responseContentType: responseContentType
)
return CLDNError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
}
// MARK: -
extension CLDNDataRequest {
/// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
/// request was valid.
internal typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
/// Validates the request, using the specified closure.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter validation: A closure to validate the request.
///
/// - returns: The request.
@discardableResult
internal func validate(_ validation: @escaping Validation) -> Self {
let validationExecution: () -> Void = { [unowned self] in
if
let response = self.response,
self.delegate.error == nil,
case let .failure(error) = validation(self.request, response, self.delegate.data)
{
self.delegate.error = error
}
}
validations.append(validationExecution)
return self
}
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
internal func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _ in
return self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
internal func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, data in
return self.validate(contentType: acceptableContentTypes, response: response, data: data)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
internal func validate() -> Self {
let contentTypes = { [unowned self] in
self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
|
a1092ba16b54f238879c897f94749336
| 35.24 | 123 | 0.629507 | false | false | false | false |
jayesh15111988/JKLoginMVVMDemoSwift
|
refs/heads/master
|
JKLoginMVVMDemoSwift/TableDemoViewModel.swift
|
mit
|
1
|
//
// TableDemoViewModel.swift
// JKLoginMVVMDemoSwift
//
// Created by Jayesh Kawli on 10/24/16.
// Copyright © 2016 Jayesh Kawli. All rights reserved.
//
import Foundation
import ReactiveCocoa
class TableDemoViewModel: NSObject {
var addItemButtonActionCommand: RACCommand?
dynamic var items: [String]
dynamic var addItemButtonIndicator: Bool
override init() {
addItemButtonIndicator = false
items = []
super.init()
addItemButtonActionCommand = RACCommand(signal: { (signal) -> RACSignal? in
return RACSignal.return(true)
})
_ = addItemButtonActionCommand?.executionSignals.flatten(1).subscribeNext({ [weak self] (value) in
if let value = value as? Bool {
self?.addItemButtonIndicator = value
}
})
}
func addItem() {
items.append("\(items.count)")
}
func removeItem(at index: Int) {
items.remove(at: index)
}
}
|
0faa8b99d9de90c28a24473fccc9a28f
| 23.804878 | 106 | 0.60472 | false | false | false | false |
Ethenyl/JAMFKit
|
refs/heads/master
|
JamfKit/Sources/Models/Partition.swift
|
mit
|
1
|
//
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents a logical partition for an hard drive installed inside an hardware element managed by Jamf.
@objc(JMFKPartition)
public final class Partition: NSObject, Requestable {
// MARK: - Constants
static let NameKey = "name"
static let SizeGigabytesKey = "size_gb"
static let MaximumPercentageKey = "maximum_percentage"
static let FormatKey = "format"
static let IsRestorePartitionKey = "is_restore_partition"
static let ComputerConfigurationKey = "computer_configuration"
static let ReimageKey = "reimage"
static let AppendToNameKey = "append_to_name"
// MARK: - Properties
@objc
public var name = ""
@objc
public var sizeInGigabytes: UInt = 0
@objc
public var maximumPercentage: UInt = 0
@objc
public var format = ""
@objc
public var isRestorePartition = false
@objc
public var computerConfiguration = ""
@objc
public var reimage = false
@objc
public var appendToName = ""
@objc
public override var description: String {
return "[\(String(describing: type(of: self)))][\(name)]"
}
// MARK: - Initialization
public init?(json: [String: Any], node: String = "") {
name = json[Partition.NameKey] as? String ?? ""
sizeInGigabytes = json[Partition.SizeGigabytesKey] as? UInt ?? 0
maximumPercentage = json[Partition.MaximumPercentageKey] as? UInt ?? 0
format = json[Partition.FormatKey] as? String ?? ""
isRestorePartition = json[Partition.IsRestorePartitionKey] as? Bool ?? false
computerConfiguration = json[Partition.ComputerConfigurationKey] as? String ?? ""
reimage = json[Partition.ReimageKey] as? Bool ?? false
appendToName = json[Partition.AppendToNameKey] as? String ?? ""
}
public init?(name: String) {
guard !name.isEmpty else {
return nil
}
self.name = name
super.init()
}
// MARK: - Functions
public func toJSON() -> [String: Any] {
var json = [String: Any]()
json[Partition.NameKey] = name
json[Partition.SizeGigabytesKey] = sizeInGigabytes
json[Partition.MaximumPercentageKey] = maximumPercentage
json[Partition.FormatKey] = format
json[Partition.IsRestorePartitionKey] = isRestorePartition
json[Partition.ComputerConfigurationKey] = computerConfiguration
json[Partition.ReimageKey] = reimage
json[Partition.AppendToNameKey] = appendToName
return json
}
}
|
cea4d52bc7a6939853a994d52bace281
| 28.747253 | 106 | 0.66014 | false | true | false | false |
kallahir/AlbumTrackr-iOS
|
refs/heads/master
|
AlbumTracker/Artist.swift
|
agpl-3.0
|
1
|
//
// Artist.swift
// AlbumTracker
//
// Created by Itallo Rossi Lucas on 5/2/16.
// Copyright © 2016 AlbumTrackr. All rights reserved.
//
import CoreData
class Artist: NSManagedObject {
@NSManaged var id: NSNumber
@NSManaged var name: String?
@NSManaged var style: String?
@NSManaged var lastAlbum: String?
@NSManaged var imagePath: String?
// var artistAlbums: [Album] = []
struct Keys {
static let id = "id"
static let name = "name"
static let style = "style"
static let lastAlbum = "lastAlbum"
static let imagePath = "imagePath"
static let albums = "albums"
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Artist", inManagedObjectContext: context)!
super.init(entity: entity,insertIntoManagedObjectContext: context)
// id = dictionary[Keys.id] as! Int
name = dictionary[Keys.name] as? String
// style = dictionary[Keys.style] as? String
lastAlbum = dictionary[Keys.lastAlbum] as? String
imagePath = dictionary[Keys.imagePath] as? String
}
}
|
45da759e6c52f5bb9f7e924e39a324af
| 31.511628 | 113 | 0.65927 | false | false | false | false |
qiscus/qiscus-sdk-ios
|
refs/heads/master
|
Qiscus/Qiscus/Extension/String+Localization.swift
|
mit
|
1
|
//
// String+Localization.swift
// Qiscus
//
// Created by Rahardyan Bisma on 03/05/18.
//
import Foundation
extension String {
func getLocalize(value: Int) -> String {
var bundle = Qiscus.bundle
if Qiscus.disableLocalization {
let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj")
bundle = Bundle(path: path!)!
}
return String(format: NSLocalizedString(self, bundle: bundle, comment: ""), value)
}
func getLocalize(value: String) -> String {
var bundle = Qiscus.bundle
if Qiscus.disableLocalization {
let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj")
bundle = Bundle(path: path!)!
}
return String(format: NSLocalizedString(self, bundle: bundle, comment: ""), value)
}
func getLocalize() -> String {
var bundle = Qiscus.bundle
if Qiscus.disableLocalization {
let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj")
bundle = Bundle(path: path!)!
}
return NSLocalizedString(self, bundle: bundle, comment: "")
}
}
|
c5b30e91e934e88256cbdd0c3436e010
| 27.139535 | 90 | 0.570248 | false | false | false | false |
mmiroslav/LinEqua
|
refs/heads/master
|
Example/LinEqua/Data/Data.swift
|
mit
|
1
|
//
// Data.swift
// LinEqua
//
// Created by Miroslav Milivojevic on 7/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import LinEqua
class Data: NSObject {
static let shared = Data()
var matrix: Matrix? {
if insertedMatrix != nil {
return insertedMatrix
}
return generatedMatrix
}
var generatedMatrix: Matrix?
var insertedMatrix: Matrix?
var resultsGauss: [Double]? = []
var resultsGaussJordan: [Double]? = []
private override init() {}
func calculateGausError() -> Double {
guard let resultsGauss = resultsGauss else { return 0.0 }
let gaussResultsVector = Vector(withArray: resultsGauss)
guard let matrix = generatedMatrix else {return 0.0}
var sumGausErrors = 0.0
for row in matrix.elements {
let rowVector = Vector(withArray: row)
let result = rowVector.popLast()
sumGausErrors += result! - (rowVector * gaussResultsVector).sum()
}
let rv = sumGausErrors / Double(gaussResultsVector.count)
print("Gauss error: \(rv)")
return abs(rv)
}
func calculateGausJordanError() -> Double {
guard let resultsGauss = resultsGaussJordan else { return 0.0 }
let gaussJordanResultsVector = Vector(withArray: resultsGauss)
guard let matrix = generatedMatrix else {return 0.0}
var sumGausJordanErrors = 0.0
for row in matrix.elements {
let rowVector = Vector(withArray: row)
let result = rowVector.popLast()
sumGausJordanErrors += result! - (rowVector * gaussJordanResultsVector).sum()
}
let rv = sumGausJordanErrors / Double(gaussJordanResultsVector.count)
print("Gauss Jordan error: \(rv)")
return abs(rv)
}
}
|
7464f939c5f83f95d0004b6c9b9711cf
| 27.850746 | 89 | 0.595965 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Sources/Controllers/Editorials/Cells/EditorialJoinCell.swift
|
mit
|
1
|
////
/// EditorialJoinCell.swift
//
class EditorialJoinCell: EditorialCellContent {
private let joinLabel = StyledLabel(style: .editorialHeader)
private let joinCaption = StyledLabel(style: .editorialCaption)
private let emailField = ElloTextField()
private let usernameField = ElloTextField()
private let passwordField = ElloTextField()
private let submitButton = StyledButton(style: .editorialJoin)
var onJoinChange: ((Editorial.JoinInfo) -> Void)?
private var isValid: Bool {
guard
let email = emailField.text,
let username = usernameField.text,
let password = passwordField.text
else { return false }
return Validator.hasValidSignUpCredentials(
email: email,
username: username,
password: password,
isTermsChecked: true
)
}
@objc
func submitTapped() {
guard
let email = emailField.text,
let username = usernameField.text,
let password = passwordField.text
else { return }
let info: Editorial.JoinInfo = (
email: emailField.text, username: usernameField.text, password: passwordField.text,
submitted: true
)
onJoinChange?(info)
emailField.isEnabled = false
usernameField.isEnabled = false
passwordField.isEnabled = false
submitButton.isEnabled = false
let responder: EditorialToolsResponder? = findResponder()
responder?.submitJoin(
cell: self.editorialCell,
email: email,
username: username,
password: password
)
}
override func style() {
super.style()
joinLabel.text = InterfaceString.Editorials.Join
joinLabel.isMultiline = true
joinCaption.text = InterfaceString.Editorials.JoinCaption
joinCaption.isMultiline = true
ElloTextFieldView.styleAsEmailField(emailField)
ElloTextFieldView.styleAsUsernameField(usernameField)
ElloTextFieldView.styleAsPasswordField(passwordField)
emailField.backgroundColor = .white
emailField.placeholder = InterfaceString.Editorials.EmailPlaceholder
usernameField.backgroundColor = .white
usernameField.placeholder = InterfaceString.Editorials.UsernamePlaceholder
passwordField.backgroundColor = .white
passwordField.placeholder = InterfaceString.Editorials.PasswordPlaceholder
submitButton.isEnabled = false
submitButton.title = InterfaceString.Editorials.SubmitJoin
}
override func updateConfig() {
super.updateConfig()
emailField.text = config.join?.email
usernameField.text = config.join?.username
passwordField.text = config.join?.password
let enabled = !(config.join?.submitted ?? false)
emailField.isEnabled = enabled
usernameField.isEnabled = enabled
passwordField.isEnabled = enabled
submitButton.isEnabled = enabled
}
override func bindActions() {
super.bindActions()
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
emailField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
usernameField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
passwordField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}
override func arrange() {
super.arrange()
editorialContentView.addSubview(joinLabel)
editorialContentView.addSubview(joinCaption)
editorialContentView.addSubview(emailField)
editorialContentView.addSubview(usernameField)
editorialContentView.addSubview(passwordField)
editorialContentView.addSubview(submitButton)
joinLabel.snp.makeConstraints { make in
make.top.equalTo(editorialContentView).inset(Size.smallTopMargin)
make.leading.equalTo(editorialContentView).inset(Size.defaultMargin)
make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin)
.priority(Priority.required)
}
joinCaption.snp.makeConstraints { make in
make.top.equalTo(joinLabel.snp.bottom).offset(Size.textFieldMargin)
make.leading.equalTo(editorialContentView).inset(Size.defaultMargin)
make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin)
.priority(Priority.required)
}
let fields = [emailField, usernameField, passwordField]
fields.forEach { field in
field.snp.makeConstraints { make in
make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin)
}
}
submitButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight).priority(Priority.required)
make.bottom.equalTo(editorialContentView).offset(-Size.defaultMargin.bottom)
make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin)
}
}
override func layoutSubviews() {
super.layoutSubviews()
layoutIfNeeded() // why-t-f is this necessary!?
// doing this simple height calculation in auto layout was a total waste of time
let fields = [emailField, usernameField, passwordField]
let textFieldsBottom = frame.height - Size.defaultMargin.bottom - Size.buttonHeight
- Size.textFieldMargin
var remainingHeight = textFieldsBottom - joinCaption.frame.maxY - Size.textFieldMargin
- CGFloat(fields.count) * Size.joinMargin
if remainingHeight < Size.minFieldHeight * 3 {
joinCaption.isHidden = true
remainingHeight += joinCaption.frame.height + Size.textFieldMargin
}
else {
joinCaption.isVisible = true
}
let fieldHeight: CGFloat = min(
max(ceil(remainingHeight / 3), Size.minFieldHeight),
Size.maxFieldHeight
)
var y: CGFloat = textFieldsBottom
for field in fields.reversed() {
y -= fieldHeight
field.frame.origin.y = y
field.frame.size.height = fieldHeight
y -= Size.joinMargin
}
}
override func prepareForReuse() {
super.prepareForReuse()
onJoinChange = nil
}
}
extension EditorialJoinCell {
@objc
func textFieldDidChange() {
let info: Editorial.JoinInfo = (
email: emailField.text, username: usernameField.text, password: passwordField.text,
submitted: false
)
onJoinChange?(info)
submitButton.isEnabled = isValid
}
}
|
d76b045c63b379ed4eeaa6063dff1e34
| 35.918919 | 98 | 0.659883 | false | false | false | false |
peferron/algo
|
refs/heads/master
|
EPI/Linked Lists/Merge two sorted lists/swift/test.swift
|
mit
|
1
|
import Darwin
let tests = [
(
a: [0],
b: [0],
merged: [0, 0]
),
(
a: [0],
b: [1],
merged: [0, 1]
),
(
a: [0, 1, 3, 4, 5, 12],
b: [2, 4, 4, 6, 20],
merged: [0, 1, 2, 3, 4, 4, 4, 5, 6, 12, 20]
),
]
func toList(_ values: [Int]) -> Node {
let first = Node(value: values.first!)
var previous = first
for value in values.dropFirst(1) {
let current = Node(value: value)
previous.next = current
previous = current
}
return first
}
func toArray(_ head: Node) -> [Int] {
var values = [Int]()
var current: Node? = head
while let c = current {
values.append(c.value)
current = c.next
}
return values
}
for test in tests {
let actual = toArray(toList(test.a).merge(toList(test.b)))
guard actual == test.merged else {
print("For a \(test.a) and b \(test.b), expected merged to be \(test.merged), " +
"but was \(actual)")
exit(1)
}
}
|
6dd435bdc144f065177690bba6d8f6db
| 18.679245 | 89 | 0.479386 | false | true | false | false |
customerly/Customerly-iOS-SDK
|
refs/heads/master
|
CustomerlySDK/Library/CyConfig.swift
|
apache-2.0
|
1
|
//
// CyConfig.swift
// Customerly
//
// Created by Paolo Musolino on 09/10/16.
//
//
import Foundation
let API_BASE_URL = "https://tracking.customerly.io" + API_VERSION
let API_VERSION = "/v" + cy_api_version
let CUSTOMERLY_URL = "https://www.customerly.io"
// The domain used for creating all Customerly errors.
let cy_domain = "io.customerly.CustomerlySDK"
// Extra device and app info
let cy_app_version = "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "")"
let cy_app_build : String = Bundle.main.object(forInfoDictionaryKey:kCFBundleVersionKey as String) as! String
let cy_device = UIDevice.current.model
let cy_os = UIDevice.current.systemName
let cy_os_version = UIDevice.current.systemVersion
let cy_app_name : String = Bundle.main.object(forInfoDictionaryKey:kCFBundleNameKey as String) as! String
let cy_sdk_version = "3.1.1"
let cy_api_version = "1"
let cy_socket_version = "0.0.1"
let cy_preferred_language = NSLocale.preferredLanguages.count > 0 ? NSLocale.preferredLanguages[0] : nil
//Default parameters
let base_color_template = UIColor(hexString: "#65A9E7")
var user_color_template: UIColor?
//Images
func adminImageURL(id: Int?, pxSize: Int) -> URL{
if let admin_id = id{
return URL(string: "https://pictures.customerly.io/accounts/\(admin_id)/\(pxSize)")!
}
return URL(string: "https://pictures.customerly.io/accounts/-/\(pxSize)")!
}
func userImageURL(id: Int?, pxSize: Int) -> URL{
if let user_id = id{
return URL(string: "https://pictures.customerly.io/users/\(user_id)/\(pxSize)")!
}
return URL(string: "https://pictures.customerly.io/users/-/\(pxSize)")!
}
enum CyUserType: Int {
case anonymous = 1
case lead = 2
case user = 4
}
|
63239187c93a9b880dfd29c2d4a49d8b
| 32.037736 | 109 | 0.70474 | false | false | false | false |
4dot/MatchMatch
|
refs/heads/master
|
MatchMatch/Controller/MatchCollectionViewDataSource.swift
|
mit
|
1
|
//
// MatchCollectionViewDataSource.swift
// MatchMatch
//
// Created by Park, Chanick on 5/23/17.
// Copyright © 2017 Chanick Park. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
// game card type
typealias gameCardType = (opend: Bool, matched: Bool, card: MatchCard)
//
// MatchCollectionViewDataSource Class
//
class MatchCollectionViewDataSource : NSObject, UICollectionViewDataSource {
// game cards
var cards: [gameCardType] = []
// place hoder image
var placeHoder: MatchCard!
// total = rows * cols
var rowsCnt: Int = 0
var colsCnt: Int = 0
/**
@desc Request random images
@param count request count
*/
func requestCards(rows: Int, cols: Int, complete: @escaping (Bool, [gameCardType])->Void) {
let params: [String : Any] = ["tags" : "kitten",
"per_page" : (rows * cols) / 2] // request count/2
// save rows, cols count for devide sections
rowsCnt = rows
colsCnt = cols
cards.removeAll()
flickrSearch(with: params) { [weak self] (success, cards) in
guard let strongSelf = self else {
complete(success, [])
return
}
var imageURLs: [String] = []
// save 2 times and shuffle
for card in cards {
strongSelf.cards.append((false, false, card))
strongSelf.cards.append((false, false, card))
imageURLs.append(card.frontImageURL)
}
// shuffle
strongSelf.cards = strongSelf.cards.shuffled()
// request images
strongSelf.requestImages(from: imageURLs, complete: { (result, images) in
complete(result, strongSelf.cards)
})
}
}
/**
@desc Request random placeholder images
*/
func requestPlaceHoder(complete: @escaping (Bool, MatchCard)->Void) {
let params: [String : Any] = ["tags" : "card deck",
"per_page" : 5] // request 5 images information
flickrSearch(with: params) { (success, cards) in
// select one of 5
let placeHolder = cards[Int(arc4random_uniform(UInt32(cards.count)))]
complete(success, placeHolder)
}
}
// MARK: - private functions
/**
@desc Request random images
@param count request count
*/
private func flickrSearch(with params: [String : Any], complete: @escaping (Bool, [MatchCard])->Void) {
var parameters = params
// add deault params
parameters["method"] = FlickrSearchMethod
parameters["api_key"] = APIKey
parameters["format"] = "json"
parameters["extras"] = "url_n" // URL of small, 320 on longest side size image
parameters["nojsoncallback"] = 1
// request
Alamofire.request(FlickrRestSeerviceURL, method: .get, parameters: parameters)
.validate()
.responseJSON { [weak self] (response) in
var searchedCards: [MatchCard] = []
// request fail
guard let _ = self else {
complete(false, searchedCards)
return
}
switch response.result {
case .failure(let error):
print(error)
case .success:
if let values = response.result.value {
let json = JSON(values)
print("JSON: \(json)")
// get photo list
let photos = json["photos"]["photo"]
for (_, photoJson):(String, JSON) in photos {
// add card data
let card = MatchCard(with: photoJson)
searchedCards.append(card)
}
}
}
// callback
complete(true, searchedCards)
}
}
/**
@desc request images with URL, waiting until download all images using dispatch_group
*/
private func requestImages(from URLs: [String], complete: @escaping (Bool, [Image])->Void) {
// create dispatch group
let downloadGroup = DispatchGroup()
var images: [Image] = []
let _ = DispatchQueue.global(qos: .userInitiated)
DispatchQueue.concurrentPerform(iterations: URLs.count) { idx in
let address = URLs[Int(idx)]
downloadGroup.enter()
// store to cache
_ = CardImageManager.sharedInstance.retrieveImage(for: address, completion: { (image) in
guard let img = image else { //?.cgImage?.copy()
complete(false, images)
return
}
// copy image
//let newImage = UIImage(cgImage: img)
// save
images.append(img)
downloadGroup.leave()
})
}
// notifiy when finished download all
downloadGroup.notify(queue: DispatchQueue.main) {
complete(true, images)
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if rowsCnt <= 0 {
return 0
}
return cards.count / rowsCnt
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
if colsCnt <= 0 {
return 0
}
return cards.count / colsCnt
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MATCH_COLLECTIONVIEW_CELL_ID, for: indexPath) as! MatchCollectionViewCell
cell.clear()
// save card index
cell.tag = indexPath.row + (indexPath.section * colsCnt)
let card = cards[cell.tag]
// default placeholder(back view)
cell.imageView[CardViewType.Back.rawValue].image =
UIImage(named: "placeHolder")?.af_imageRounded(withCornerRadius: 4.0)
let imgURL = card.card.frontImageURL
if imgURL.isEmpty {
return cell
}
// Request image from cache (already stored cache)
_ = CardImageManager.sharedInstance.retrieveImage(for: imgURL) { image in
if image != nil {
DispatchQueue.main.async {
// set front image
cell.imageView[CardViewType.Front.rawValue].image =
image?.af_imageRounded(withCornerRadius: 4.0)
}
}
}
return cell
}
}
|
28a7fad44f7a871742a40e59379b7ad1
| 31.231441 | 148 | 0.511177 | false | false | false | false |
openHPI/xikolo-ios
|
refs/heads/dev
|
iOS/ViewControllers/Login/PasswordLoginViewController.swift
|
gpl-3.0
|
1
|
//
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import SafariServices
import UIKit
import WebKit
class PasswordLoginViewController: UIViewController, LoginViewController, WKUIDelegate {
@IBOutlet private weak var emailField: UITextField!
@IBOutlet private weak var passwordField: UITextField!
@IBOutlet private weak var loginButton: LoadingButton!
@IBOutlet private weak var registerButton: UIButton!
@IBOutlet private weak var singleSignOnView: UIView!
@IBOutlet private weak var singleSignOnLabel: UILabel!
@IBOutlet private weak var singleSignOnButton: UIButton!
@IBOutlet private weak var centerInputFieldsConstraints: NSLayoutConstraint!
@IBOutlet private var textFieldBackgroundViews: [UIView]!
weak var loginDelegate: LoginDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.loginButton.backgroundColor = Brand.default.colors.primary
self.registerButton.backgroundColor = Brand.default.colors.primaryLight
self.registerButton.tintColor = ColorCompatibility.secondaryLabel
self.textFieldBackgroundViews.forEach { $0.layer.roundCorners(for: .default) }
self.loginButton.layer.roundCorners(for: .default)
self.registerButton.layer.roundCorners(for: .default)
self.singleSignOnButton.layer.roundCorners(for: .default)
self.loginButton.layer.roundCorners(for: .default)
self.registerButton.layer.roundCorners(for: .default)
self.singleSignOnButton.layer.roundCorners(for: .default)
NotificationCenter.default.addObserver(self,
selector: #selector(adjustViewForKeyboardShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(adjustViewForKeyboardHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
if let singleSignOnConfig = Brand.default.singleSignOn {
self.singleSignOnView.isHidden = false
self.singleSignOnButton.backgroundColor = Brand.default.colors.primary
self.singleSignOnButton.setTitle(singleSignOnConfig.buttonTitle, for: .normal)
// Disable native registration
self.registerButton.isHidden = singleSignOnConfig.disabledRegistration
if singleSignOnConfig.disabledRegistration {
self.singleSignOnLabel.text = NSLocalizedString("login.sso.label.login or sign up with", comment: "Label for SSO login and signup")
} else {
self.singleSignOnLabel.text = NSLocalizedString("login.sso.label.login with", comment: "Label for SSO login")
}
} else {
self.singleSignOnView.isHidden = true
}
}
@IBAction private func dismiss() {
self.presentingViewController?.dismiss(animated: trueUnlessReduceMotionEnabled)
}
@IBAction private func login() {
guard let email = emailField.text, let password = passwordField.text else {
self.emailField.shake()
self.passwordField.shake()
return
}
self.loginButton.startAnimation()
let dispatchTime = 500.milliseconds.fromNow
UserProfileHelper.shared.login(email, password: password).earliest(at: dispatchTime).onComplete { [weak self] _ in
self?.loginButton.stopAnimation()
}.onSuccess { [weak self] _ in
self?.loginDelegate?.didSuccessfullyLogin()
self?.presentingViewController?.dismiss(animated: trueUnlessReduceMotionEnabled)
}.onFailure { [weak self] _ in
self?.emailField.shake()
self?.passwordField.shake()
}
}
@IBAction private func register() {
let safariVC = SFSafariViewController(url: Routes.register)
safariVC.preferredControlTintColor = Brand.default.colors.window
self.present(safariVC, animated: trueUnlessReduceMotionEnabled)
}
@IBAction private func forgotPassword() {
let safariVC = SFSafariViewController(url: Routes.localizedForgotPasswordURL)
safariVC.preferredControlTintColor = Brand.default.colors.window
self.present(safariVC, animated: true)
}
@IBAction private func singleSignOn() {
self.performSegue(withIdentifier: R.segue.passwordLoginViewController.showSSOWebView, sender: self)
}
@IBAction private func dismissKeyboard() {
self.emailField.resignFirstResponder()
self.passwordField.resignFirstResponder()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let typedInfo = R.segue.passwordLoginViewController.showSSOWebView(segue: segue) {
typedInfo.destination.loginDelegate = self.loginDelegate
typedInfo.destination.url = Routes.singleSignOn
}
}
@objc func adjustViewForKeyboardShow(_ notification: Notification) {
// On some devices, the keyboard can overlap with some UI elements. To prevent this, we move
// the `inputContainer` upwards. The other views will reposition accordingly.
let keyboardFrameValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
let keyboardHeight = keyboardFrameValue?.cgRectValue.size.height ?? 0.0
let contentInset = self.view.safeAreaInsets.top + self.view.safeAreaInsets.bottom
let viewHeight = self.view.frame.size.height - contentInset
let overlappingOffset = 0.5 * viewHeight - keyboardHeight - self.emailField.frame.size.height - 8.0
self.centerInputFieldsConstraints.constant = min(overlappingOffset, 0) // we only want to move the container upwards
UIView.animate(withDuration: defaultAnimationDuration) {
self.view.layoutIfNeeded()
}
}
@objc func adjustViewForKeyboardHide(_ notification: Notification) {
self.centerInputFieldsConstraints.constant = 0
UIView.animate(withDuration: defaultAnimationDuration) {
self.view.layoutIfNeeded()
}
}
}
extension PasswordLoginViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
self.emailField.layoutIfNeeded()
self.passwordField.layoutIfNeeded()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if textField == self.emailField {
self.passwordField.becomeFirstResponder()
} else if textField === self.passwordField {
self.login()
}
return true
}
}
protocol LoginViewController: AnyObject {
var loginDelegate: LoginDelegate? { get set }
}
protocol LoginDelegate: AnyObject {
func didSuccessfullyLogin()
}
|
90535b47127493364d5c6dc8406b601a
| 39.090395 | 147 | 0.678269 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Conversation/InputBar/InputBar.swift
|
gpl-3.0
|
1
|
//
// 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 UIKit
import Down
import WireDataModel
import WireCommonComponents
extension Settings {
var returnKeyType: UIReturnKeyType {
let disableSendButton: Bool? = self[.sendButtonDisabled]
return disableSendButton == true ? .send : .default
}
}
enum EphemeralState: Equatable {
case conversation
case message
case none
var isEphemeral: Bool {
return [.message, .conversation].contains(self)
}
}
enum InputBarState: Equatable {
case writing(ephemeral: EphemeralState)
case editing(originalText: String, mentions: [Mention])
case markingDown(ephemeral: EphemeralState)
var isWriting: Bool {
switch self {
case .writing: return true
default: return false
}
}
var isEditing: Bool {
switch self {
case .editing: return true
default: return false
}
}
var isMarkingDown: Bool {
switch self {
case .markingDown: return true
default: return false
}
}
var isEphemeral: Bool {
switch self {
case .markingDown(let ephemeral):
return ephemeral.isEphemeral
case .writing(let ephemeral):
return ephemeral.isEphemeral
default:
return false
}
}
var isEphemeralEnabled: Bool {
switch self {
case .markingDown(let ephemeral):
return ephemeral == .message
case .writing(let ephemeral):
return ephemeral == .message
default:
return false
}
}
mutating func changeEphemeralState(to newState: EphemeralState) {
switch self {
case .markingDown:
self = .markingDown(ephemeral: newState)
case .writing:
self = .writing(ephemeral: newState)
default:
return
}
}
}
private struct InputBarConstants {
let buttonsBarHeight: CGFloat = 56
}
final class InputBar: UIView {
typealias ConversationInputBar = L10n.Localizable.Conversation.InputBar
private let inputBarVerticalInset: CGFloat = 34
static let rightIconSize: CGFloat = 32
private let textViewFont = FontSpec.normalRegularFont.font!
let textView = MarkdownTextView(with: DownStyle.compact)
let leftAccessoryView = UIView()
let rightAccessoryStackView: UIStackView = {
let stackView = UIStackView()
let rightInset = (stackView.conversationHorizontalMargins.left - rightIconSize) / 2
stackView.spacing = 16
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
// Contains and clips the buttonInnerContainer
let buttonContainer = UIView()
// Contains editingView and mardownView
let secondaryButtonsView: InputBarSecondaryButtonsView
let buttonsView: InputBarButtonsView
let editingView = InputBarEditView()
let markdownView = MarkdownBarView()
var editingBackgroundColor = SemanticColors.LegacyColors.brightYellow
var barBackgroundColor: UIColor? = SemanticColors.SearchBar.backgroundInputView
var writingSeparatorColor: UIColor? = SemanticColors.View.backgroundSeparatorCell
var ephemeralColor: UIColor {
return .accent()
}
var placeholderColor: UIColor = SemanticColors.SearchBar.textInputViewPlaceholder
var textColor: UIColor? = SemanticColors.SearchBar.textInputView
private lazy var rowTopInsetConstraint: NSLayoutConstraint = buttonInnerContainer.topAnchor.constraint(equalTo: buttonContainer.topAnchor, constant: -constants.buttonsBarHeight)
// Contains the secondaryButtonsView and buttonsView
private let buttonInnerContainer = UIView()
fileprivate let buttonRowSeparator = UIView()
fileprivate let constants = InputBarConstants()
private lazy var leftAccessoryViewWidthConstraint: NSLayoutConstraint = leftAccessoryView.widthAnchor.constraint(equalToConstant: conversationHorizontalMargins.left)
var isEditing: Bool {
return inputBarState.isEditing
}
var isMarkingDown: Bool {
return inputBarState.isMarkingDown
}
private var inputBarState: InputBarState = .writing(ephemeral: .none) {
didSet {
updatePlaceholder()
updatePlaceholderColors()
}
}
func changeEphemeralState(to newState: EphemeralState) {
inputBarState.changeEphemeralState(to: newState)
}
var invisibleInputAccessoryView: InvisibleInputAccessoryView? {
didSet {
textView.inputAccessoryView = invisibleInputAccessoryView
}
}
var availabilityPlaceholder: NSAttributedString? {
didSet {
updatePlaceholder()
}
}
override var bounds: CGRect {
didSet {
invisibleInputAccessoryView?.overriddenIntrinsicContentSize = CGSize(width: UIView.noIntrinsicMetric, height: bounds.height)
}
}
override func didMoveToWindow() {
super.didMoveToWindow()
// This is a workaround for UITextView truncating long contents.
// However, this breaks the text view on iOS 8 ¯\_(ツ)_/¯.
textView.isScrollEnabled = false
textView.isScrollEnabled = true
}
required init(buttons: [UIButton]) {
buttonsView = InputBarButtonsView(buttons: buttons)
secondaryButtonsView = InputBarSecondaryButtonsView(editBarView: editingView, markdownBarView: markdownView)
super.init(frame: CGRect.zero)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapBackground))
addGestureRecognizer(tapGestureRecognizer)
buttonsView.clipsToBounds = true
buttonContainer.clipsToBounds = true
[leftAccessoryView, textView, rightAccessoryStackView, buttonContainer, buttonRowSeparator].forEach(addSubview)
buttonContainer.addSubview(buttonInnerContainer)
[buttonsView, secondaryButtonsView].forEach(buttonInnerContainer.addSubview)
setupViews()
updateRightAccessoryStackViewLayoutMargins()
createConstraints()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(markdownView, selector: #selector(markdownView.textViewDidChangeActiveMarkdown), name: Notification.Name.MarkdownTextViewDidChangeActiveMarkdown, object: textView)
notificationCenter.addObserver(self, selector: #selector(textViewTextDidChange), name: UITextView.textDidChangeNotification, object: textView)
notificationCenter.addObserver(self, selector: #selector(textViewDidBeginEditing), name: UITextView.textDidBeginEditingNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(textViewDidEndEditing), name: UITextView.textDidEndEditingNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(sendButtonEnablingDidApplyChanges), name: NSNotification.Name.disableSendButtonChanged, object: nil)
}
/// Update return key type when receiving a notification (from setting->toggle send key option)
@objc
private func sendButtonEnablingDidApplyChanges() {
updateReturnKey()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupViews() {
textView.accessibilityIdentifier = "inputField"
updatePlaceholder()
textView.lineFragmentPadding = 0
textView.textAlignment = .natural
textView.textContainerInset = UIEdgeInsets(top: inputBarVerticalInset / 2, left: 0, bottom: inputBarVerticalInset / 2, right: 4)
textView.placeholderTextContainerInset = UIEdgeInsets(top: 21, left: 10, bottom: 21, right: 0)
textView.keyboardType = .default
textView.keyboardAppearance = .default
textView.placeholderTextTransform = .none
textView.tintAdjustmentMode = .automatic
textView.font = textViewFont
textView.placeholderFont = textViewFont
textView.backgroundColor = .clear
markdownView.delegate = textView
self.addBorder(for: .top)
updateReturnKey()
updateInputBar(withState: inputBarState, animated: false)
updateColors()
}
fileprivate func createConstraints() {
[buttonContainer,
textView,
buttonRowSeparator,
leftAccessoryView,
rightAccessoryStackView,
secondaryButtonsView,
buttonsView,
buttonInnerContainer].prepareForLayout()
let rightAccessoryViewWidthConstraint = rightAccessoryStackView.widthAnchor.constraint(equalToConstant: 0)
rightAccessoryViewWidthConstraint.priority = .defaultHigh
NSLayoutConstraint.activate([
leftAccessoryView.leadingAnchor.constraint(equalTo: leftAccessoryView.superview!.leadingAnchor),
leftAccessoryView.topAnchor.constraint(equalTo: leftAccessoryView.superview!.topAnchor),
leftAccessoryView.bottomAnchor.constraint(equalTo: buttonContainer.topAnchor),
leftAccessoryViewWidthConstraint,
rightAccessoryStackView.trailingAnchor.constraint(equalTo: rightAccessoryStackView.superview!.trailingAnchor),
rightAccessoryStackView.topAnchor.constraint(equalTo: rightAccessoryStackView.superview!.topAnchor),
rightAccessoryViewWidthConstraint,
rightAccessoryStackView.bottomAnchor.constraint(equalTo: buttonContainer.topAnchor),
buttonContainer.topAnchor.constraint(equalTo: textView.bottomAnchor),
textView.topAnchor.constraint(equalTo: textView.superview!.topAnchor),
textView.leadingAnchor.constraint(equalTo: leftAccessoryView.trailingAnchor),
textView.trailingAnchor.constraint(lessThanOrEqualTo: textView.superview!.trailingAnchor, constant: -16),
textView.trailingAnchor.constraint(equalTo: rightAccessoryStackView.leadingAnchor),
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 56),
textView.heightAnchor.constraint(lessThanOrEqualToConstant: 120),
buttonRowSeparator.topAnchor.constraint(equalTo: buttonContainer.topAnchor),
buttonRowSeparator.leadingAnchor.constraint(equalTo: buttonRowSeparator.superview!.leadingAnchor, constant: 16),
buttonRowSeparator.trailingAnchor.constraint(equalTo: buttonRowSeparator.superview!.trailingAnchor, constant: -16),
buttonRowSeparator.heightAnchor.constraint(equalToConstant: .hairline),
secondaryButtonsView.topAnchor.constraint(equalTo: buttonInnerContainer.topAnchor),
secondaryButtonsView.leadingAnchor.constraint(equalTo: buttonInnerContainer.leadingAnchor),
secondaryButtonsView.trailingAnchor.constraint(equalTo: buttonInnerContainer.trailingAnchor),
secondaryButtonsView.bottomAnchor.constraint(equalTo: buttonsView.topAnchor),
secondaryButtonsView.heightAnchor.constraint(equalToConstant: constants.buttonsBarHeight),
buttonsView.leadingAnchor.constraint(equalTo: buttonInnerContainer.leadingAnchor),
buttonsView.trailingAnchor.constraint(lessThanOrEqualTo: buttonInnerContainer.trailingAnchor),
buttonsView.bottomAnchor.constraint(equalTo: buttonInnerContainer.bottomAnchor),
buttonContainer.bottomAnchor.constraint(equalTo: buttonContainer.superview!.bottomAnchor),
buttonContainer.leadingAnchor.constraint(equalTo: buttonContainer.superview!.leadingAnchor),
buttonContainer.trailingAnchor.constraint(equalTo: buttonContainer.superview!.trailingAnchor),
buttonContainer.heightAnchor.constraint(equalToConstant: constants.buttonsBarHeight),
buttonInnerContainer.leadingAnchor.constraint(equalTo: buttonContainer.leadingAnchor),
buttonInnerContainer.trailingAnchor.constraint(equalTo: buttonContainer.trailingAnchor),
rowTopInsetConstraint
])
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass else { return }
updateLeftAccessoryViewWidth()
updateRightAccessoryStackViewLayoutMargins()
}
fileprivate func updateLeftAccessoryViewWidth() {
leftAccessoryViewWidthConstraint.constant = conversationHorizontalMargins.left
}
fileprivate func updateRightAccessoryStackViewLayoutMargins() {
let rightInset = (conversationHorizontalMargins.left - InputBar.rightIconSize) / 2
rightAccessoryStackView.layoutMargins = UIEdgeInsets(top: 0, left: rightInset, bottom: 0, right: rightInset)
}
@objc
private func didTapBackground(_ gestureRecognizer: UITapGestureRecognizer!) {
guard gestureRecognizer.state == .recognized else { return }
buttonsView.showRow(0, animated: true)
}
func updateReturnKey() {
textView.returnKeyType = isMarkingDown ? .default : Settings.shared.returnKeyType
textView.reloadInputViews()
}
func updatePlaceholder() {
textView.attributedPlaceholder = placeholderText(for: inputBarState)
textView.setNeedsLayout()
}
func placeholderText(for state: InputBarState) -> NSAttributedString? {
var placeholder = NSAttributedString(string: ConversationInputBar.placeholder)
if let availabilityPlaceholder = availabilityPlaceholder {
placeholder = availabilityPlaceholder
} else if inputBarState.isEphemeral {
placeholder = NSAttributedString(string: ConversationInputBar.placeholderEphemeral) && ephemeralColor
}
if state.isEditing {
return nil
} else {
return placeholder
}
}
// MARK: - Disable interactions on the lower part to not to interfere with the keyboard
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if self.textView.isFirstResponder {
if super.point(inside: point, with: event) {
let locationInButtonRow = buttonInnerContainer.convert(point, from: self)
return locationInButtonRow.y < buttonInnerContainer.bounds.height / 1.3
} else {
return false
}
} else {
return super.point(inside: point, with: event)
}
}
// MARK: - InputBarState
func setInputBarState(_ state: InputBarState, animated: Bool) {
let oldState = inputBarState
inputBarState = state
updateInputBar(withState: state, oldState: oldState, animated: animated)
}
private func updateInputBar(withState state: InputBarState, oldState: InputBarState? = nil, animated: Bool = true) {
updateEditViewState()
updatePlaceholder()
updateReturnKey()
rowTopInsetConstraint.constant = state.isWriting ? -constants.buttonsBarHeight : 0
let textViewChanges = {
switch state {
case .writing:
if let oldState = oldState, oldState.isEditing {
self.textView.text = nil
}
case .editing(let text, let mentions):
self.setInputBarText(text, mentions: mentions)
self.secondaryButtonsView.setEditBarView()
case .markingDown:
self.secondaryButtonsView.setMarkdownBarView()
}
}
let completion: () -> Void = {
self.updateColors()
self.updatePlaceholderColors()
if state.isEditing {
self.textView.becomeFirstResponder()
}
}
if animated && self.superview != nil {
UIView.animate(easing: .easeInOutExpo, duration: 0.3, animations: layoutIfNeeded)
UIView.transition(with: self.textView, duration: 0.1, options: [], animations: textViewChanges) { _ in
self.updateColors()
completion()
}
} else {
layoutIfNeeded()
textViewChanges()
completion()
}
}
func updateEphemeralState() {
guard inputBarState.isWriting else { return }
updateColors()
updatePlaceholder()
}
fileprivate func backgroundColor(forInputBarState state: InputBarState) -> UIColor? {
guard let writingColor = barBackgroundColor else { return nil }
return state.isWriting || state.isMarkingDown ? writingColor : writingColor.mix(editingBackgroundColor, amount: 0.16)
}
fileprivate func updatePlaceholderColors() {
if inputBarState.isEphemeral &&
inputBarState.isEphemeralEnabled &&
availabilityPlaceholder == nil {
textView.placeholderTextColor = ephemeralColor
} else {
textView.placeholderTextColor = placeholderColor
}
}
fileprivate func updateColors() {
backgroundColor = backgroundColor(forInputBarState: inputBarState)
buttonRowSeparator.backgroundColor = writingSeparatorColor
updatePlaceholderColors()
textView.tintColor = .accent()
textView.updateTextColor(base: textColor)
var buttons = self.buttonsView.buttons
buttons.append(self.buttonsView.expandRowButton)
buttons.forEach { button in
guard let button = button as? IconButton else { return }
button.layer.borderWidth = 1
button.setIconColor(SemanticColors.Button.textInputBarItemEnabled, for: .normal)
button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemEnabled, for: .normal)
button.setBorderColor(SemanticColors.Button.borderInputBarItemEnabled, for: .normal)
button.setIconColor(SemanticColors.Button.textInputBarItemHighlighted, for: .highlighted)
button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemHighlighted, for: .highlighted)
button.setBorderColor(SemanticColors.Button.borderInputBarItemHighlighted, for: .highlighted)
button.setIconColor(SemanticColors.Button.textInputBarItemHighlighted, for: .selected)
button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemHighlighted, for: .selected)
button.setBorderColor(SemanticColors.Button.borderInputBarItemHighlighted, for: .selected)
}
}
// MARK: – Editing View State
func setInputBarText(_ text: String, mentions: [Mention]) {
textView.setText(text, withMentions: mentions)
textView.setContentOffset(.zero, animated: false)
textView.undoManager?.removeAllActions()
updateEditViewState()
}
func undo() {
guard inputBarState.isEditing else { return }
guard let undoManager = textView.undoManager, undoManager.canUndo else { return }
undoManager.undo()
updateEditViewState()
}
fileprivate func updateEditViewState() {
if case .editing(let text, _) = inputBarState {
let canUndo = textView.undoManager?.canUndo ?? false
editingView.undoButton.isEnabled = canUndo
// We do not want to enable the confirm button when
// the text is the same as the original message
let trimmedText = textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let hasChanges = text != trimmedText && canUndo
editingView.confirmButton.isEnabled = hasChanges
}
}
}
extension InputBar {
@objc func textViewTextDidChange(_ notification: Notification) {
updateEditViewState()
}
@objc func textViewDidBeginEditing(_ notification: Notification) {
updateEditViewState()
}
@objc func textViewDidEndEditing(_ notification: Notification) {
updateEditViewState()
}
}
|
2d9324989f9174c29e7c7a723cfc7278
| 37.349265 | 202 | 0.697584 | false | false | false | false |
cornerAnt/Digger
|
refs/heads/master
|
Sources/DiggerManager.swift
|
mit
|
1
|
//
// DiggerManager.swift
// Digger
//
// Created by ant on 2017/10/25.
// Copyright © 2017年 github.cornerant. All rights reserved.
//
import Foundation
public protocol DiggerManagerProtocol{
/// logLevel hing,low,none
var logLevel : LogLevel { set get }
/// Apple limit is per session,The default value is 6 in macOS, or 4 in iOS.
var maxConcurrentTasksCount : Int {set get}
var allowsCellularAccess : Bool { set get }
var timeout: TimeInterval { set get }
/// Start the task at once,default is true
var startDownloadImmediately : Bool { set get }
func startTask(for diggerURL: DiggerURL)
func stopTask(for diggerURL: DiggerURL)
/// If the task is cancelled, the temporary file will be deleted
func cancelTask(for diggerURL: DiggerURL)
func startAllTasks()
func stopAllTasks()
func cancelAllTasks()
}
open class DiggerManager:DiggerManagerProtocol {
// MARK:- property
public static var shared = DiggerManager(name: digger)
public var logLevel: LogLevel = .high
open var startDownloadImmediately = true
open var timeout: TimeInterval = 100
fileprivate var diggerSeeds = [URL: DiggerSeed]()
fileprivate var session: URLSession
fileprivate var diggerDelegate: DiggerDelegate?
fileprivate let barrierQueue = DispatchQueue.barrier
fileprivate let delegateQueue = OperationQueue.downloadDelegateOperationQueue
public var maxConcurrentTasksCount: Int = 3 {
didSet{
let count = maxConcurrentTasksCount == 0 ? 1 : maxConcurrentTasksCount
session.invalidateAndCancel()
session = setupSession(allowsCellularAccess, count)
}
}
public var allowsCellularAccess: Bool = true {
didSet{
session.invalidateAndCancel()
session = setupSession(allowsCellularAccess, maxConcurrentTasksCount)
}
}
// MARK:- lifeCycle
private init(name: String) {
DiggerCache.cachesDirectory = digger
if name.isEmpty {
fatalError("DiggerManager must hava a name")
}
diggerDelegate = DiggerDelegate()
let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.allowsCellularAccess = allowsCellularAccess
sessionConfiguration.httpMaximumConnectionsPerHost = maxConcurrentTasksCount
session = URLSession(configuration: sessionConfiguration, delegate: diggerDelegate, delegateQueue: delegateQueue)
}
deinit {
session.invalidateAndCancel()
}
private func setupSession(_ allowsCellularAccess:Bool ,_ maxDownloadTasksCount:Int ) -> URLSession{
diggerDelegate = DiggerDelegate()
let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.allowsCellularAccess = allowsCellularAccess
sessionConfiguration.httpMaximumConnectionsPerHost = maxDownloadTasksCount
let session = URLSession(configuration: sessionConfiguration, delegate: diggerDelegate, delegateQueue: delegateQueue)
return session
}
/// download file
/// DiggerSeed contains information about the file
/// - Parameter diggerURL: url
/// - Returns: the diggerSeed of file
@discardableResult
public func download(with diggerURL: DiggerURL) -> DiggerSeed{
switch isDiggerURLCorrect(diggerURL) {
case .success(let url):
return createDiggerSeed(with: url)
case .failure(_):
fatalError("Please make sure the url or urlString is correct")
}
}
}
// MARK:- diggerSeed control
extension DiggerManager{
func createDiggerSeed(with url: URL) -> DiggerSeed{
if let DiggerSeed = findDiggerSeed(with: url) {
return DiggerSeed
}else{
barrierQueue.sync(flags: .barrier){
let timeout = self.timeout == 0.0 ? 100 : self.timeout
let diggerSeed = DiggerSeed(session: session, url: url, timeout: timeout)
diggerSeeds[url] = diggerSeed
}
let diggerSeed = findDiggerSeed(with: url)!
diggerDelegate?.manager = self
if self.startDownloadImmediately{
diggerSeed.downloadTask.resume()
}
return diggerSeed
}
}
public func removeDigeerSeed(for url : URL){
barrierQueue.sync(flags: .barrier) {
diggerSeeds.removeValue(forKey: url)
if diggerSeeds.isEmpty{
diggerDelegate = nil
}
}
}
func isDiggerURLCorrect(_ diggerURL: DiggerURL) -> Result<URL> {
var correctURL: URL
do {
correctURL = try diggerURL.asURL()
return Result.success(correctURL)
} catch {
diggerLog(error)
return Result.failure(error)
}
}
func findDiggerSeed(with diggerURL: DiggerURL) -> DiggerSeed? {
var diggerSeed: DiggerSeed?
switch isDiggerURLCorrect(diggerURL) {
case .success(let url):
barrierQueue.sync(flags: .barrier) {
diggerSeed = diggerSeeds[url]
}
return diggerSeed
case .failure(_):
return diggerSeed
}
}
}
// MARK:- downloadTask control
extension DiggerManager{
public func cancelTask(for diggerURL: DiggerURL) {
switch isDiggerURLCorrect(diggerURL) {
case .failure(_):
return
case .success(let url):
barrierQueue.sync(flags: .barrier){
guard let diggerSeed = diggerSeeds[url] else {
return
}
diggerSeed.downloadTask.cancel()
}
}
}
public func stopTask(for diggerURL: DiggerURL) {
switch isDiggerURLCorrect(diggerURL) {
case .failure(_):
return
case .success(let url):
barrierQueue.sync(flags: .barrier){
guard let diggerSeed = diggerSeeds[url] else {
return
}
if diggerSeed.downloadTask.state == .running{
diggerSeed.downloadTask.suspend()
diggerDelegate?.notifySpeedZeroCallback(diggerSeed)
}
}
}
}
public func startTask(for diggerURL: DiggerURL) {
switch isDiggerURLCorrect(diggerURL) {
case .failure(_):
return
case .success(let url):
barrierQueue.sync(flags: .barrier){
guard let diggerSeed = diggerSeeds[url] else {
return
}
if diggerSeed.downloadTask.state != .running{
diggerSeed.downloadTask.resume()
self.diggerDelegate?.notifySpeedCallback(diggerSeed)
}
}
}
}
public func startAllTasks() {
_ = diggerSeeds.keys.map{ (url) in
startTask(for: url)
}
}
public func stopAllTasks() {
_ = diggerSeeds.keys.map{ (url) in
stopTask(for : url)
}
}
public func cancelAllTasks() {
_ = diggerSeeds.keys.map{ (url) in
cancelTask(for: url)
}
}
}
// MARK:- URLSessionExtension
extension URLSession {
public func dataTask(with url : URL,timeout:TimeInterval) -> URLSessionDataTask{
let range = DiggerCache.fileSize(filePath: DiggerCache.tempPath(url: url))
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
let headRange = "bytes=" + String(range) + "-"
request.setValue(headRange, forHTTPHeaderField: "Range")
let task = dataTask(with: request)
task.priority = URLSessionTask.defaultPriority
return task
}
}
|
43c22c500b58b71bf2604f480d851e87
| 24.428161 | 125 | 0.547746 | false | false | false | false |
rechsteiner/Parchment
|
refs/heads/main
|
Example/Examples/Icons/IconPagingCell.swift
|
mit
|
1
|
import Parchment
import UIKit
struct IconPagingCellViewModel {
let image: UIImage?
let selected: Bool
let tintColor: UIColor
let selectedTintColor: UIColor
init(image: UIImage?, selected: Bool, options: PagingOptions) {
self.image = image
self.selected = selected
tintColor = options.textColor
selectedTintColor = options.selectedTextColor
}
}
class IconPagingCell: PagingCell {
fileprivate var viewModel: IconPagingCellViewModel?
fileprivate lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
setupConstraints()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setPagingItem(_ pagingItem: PagingItem, selected: Bool, options: PagingOptions) {
if let item = pagingItem as? IconItem {
let viewModel = IconPagingCellViewModel(
image: item.image,
selected: selected,
options: options
)
imageView.image = viewModel.image
if viewModel.selected {
imageView.transform = CGAffineTransform(scaleX: 1, y: 1)
imageView.tintColor = viewModel.selectedTintColor
} else {
imageView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
imageView.tintColor = viewModel.tintColor
}
self.viewModel = viewModel
}
}
open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
guard let viewModel = viewModel else { return }
if let attributes = layoutAttributes as? PagingCellLayoutAttributes {
let scale = (0.4 * attributes.progress) + 0.6
imageView.transform = CGAffineTransform(scaleX: scale, y: scale)
imageView.tintColor = UIColor.interpolate(
from: viewModel.tintColor,
to: viewModel.selectedTintColor,
with: attributes.progress
)
}
}
private func setupConstraints() {
imageView.translatesAutoresizingMaskIntoConstraints = false
let topContraint = NSLayoutConstraint(
item: imageView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1.0,
constant: 15
)
let bottomConstraint = NSLayoutConstraint(
item: imageView,
attribute: .bottom,
relatedBy: .equal,
toItem: contentView,
attribute: .bottom,
multiplier: 1.0,
constant: -15
)
let leadingContraint = NSLayoutConstraint(
item: imageView,
attribute: .leading,
relatedBy: .equal,
toItem: contentView,
attribute: .leading,
multiplier: 1.0,
constant: 0
)
let trailingContraint = NSLayoutConstraint(
item: imageView,
attribute: .trailing,
relatedBy: .equal,
toItem: contentView,
attribute: .trailing,
multiplier: 1.0,
constant: 0
)
contentView.addConstraints([
topContraint,
bottomConstraint,
leadingContraint,
trailingContraint,
])
}
}
|
7be68cdc38e47b3a590dbeb3d234b5c8
| 28.836066 | 99 | 0.577473 | false | false | false | false |
iachievedit/swiftychatter
|
refs/heads/master
|
chatterserver/Sources/ChatterServer.swift
|
mit
|
1
|
// ChatterServer.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2016 iAchieved.it 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 swiftysockets
import Foundation
class ChatterServer {
private let ip:IP?
private let server:TCPServerSocket?
init?() {
do {
self.ip = try IP(port:5555)
self.server = try TCPServerSocket(ip:self.ip!)
} catch let error {
print(error)
return nil
}
}
func start() {
while true {
do {
let client = try server!.accept()
self.addClient(client)
} catch let error {
print(error)
}
}
}
private var connectedClients:[TCPClientSocket] = []
private var connectionCount = 0
private func addClient(client:TCPClientSocket) {
self.connectionCount += 1
let handlerThread = NSThread(){
let clientId = self.connectionCount
print("Client \(clientId) connected")
while true {
do {
if let s = try client.receiveString(untilDelimiter: "\n") {
print("Received from client \(clientId): \(s)", terminator:"")
self.broadcastMessage(s, except:client)
}
} catch let error {
print ("Client \(clientId) disconnected: \(error)")
self.removeClient(client)
return
}
}
}
handlerThread.start()
connectedClients.append(client)
}
private func removeClient(client:TCPClientSocket) {
connectedClients = connectedClients.filter(){$0 !== client}
}
private func broadcastMessage(message:String, except:TCPClientSocket) {
for client in connectedClients where client !== except {
do {
try client.sendString(message)
try client.flush()
} catch {
//
}
}
}
}
|
4a3893ea8f2f22e3363a2ca119c44e61
| 28.736842 | 80 | 0.661239 | false | false | false | false |
Drakken-Engine/GameEngine
|
refs/heads/master
|
DrakkenEngine/dDebug.swift
|
gpl-3.0
|
1
|
//
// dDebug.swift
// DrakkenEngine
//
// Created by Allison Lindner on 25/10/16.
// Copyright © 2016 Drakken Studio. All rights reserved.
//
import Foundation
import JavaScriptCore
@objc public protocol dDebugExport: JSExport {
func log(_ content: String)
}
public class dLog {
public var transformName: String
public var date: Date
public var content: String
public init(_ transformName: String, _ date: Date, _ content: String) {
self.transformName = transformName
self.date = date
self.content = content
}
public func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy.MM.dd - HH:mm:ss:SSSS"
let dateString = dateFormatter.string(from: date)
return "\(dateString) - \(transformName) - \(content)"
}
}
public class dDebug: NSObject, dDebugExport {
private var logs: [dLog] = []
internal var transform: dTransform
public init(_ transform: dTransform) {
self.transform = transform
}
public func log(_ content: String) {
if transform._scene.DEBUG_MODE {
let l = dLog(self.transform.name, Date(), String(content))
self.logs.append(l)
dCore.instance.allDebugLogs.append(l)
}
}
}
|
11a1bc590ec5d001e2fd551e100b38bc
| 25.098039 | 75 | 0.623591 | false | false | false | false |
qimuyunduan/ido_ios
|
refs/heads/master
|
ido_ios/SetPwdController.swift
|
mit
|
1
|
//
// SetPwdController.swift
// ido_ios
//
// Created by qimuyunduan on 16/6/8.
// Copyright © 2016年 qimuyunduan. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class SetPwdController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var setPwd: UITextField!
@IBOutlet weak var confirmPwd: UITextField!
@IBOutlet weak var confirmButton: UIButton!
var personName :String?
override func viewDidLoad() {
super.viewDidLoad()
confirmPwd.delegate = self
confirmButton.addTarget(self, action: #selector(SetPwdController.login), forControlEvents: UIControlEvents.TouchUpInside)
}
func textFieldDidBeginEditing(textField: UITextField) {
confirmButton.setBackgroundImage(UIImage(named: "loginEnabled"), forState: UIControlState.Normal)
}
func login() -> Void {
if setPwd.text == confirmPwd.text && setPwd.text?.characters.count >= 6 {
let destinationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myTableViewController") as! MyTableViewController
newUser()
// if newUser()["result"] == "200" {
// let userDefaults = NSUserDefaults.standardUserDefaults()
// userDefaults.setBool(true, forKey: "registered")
// userDefaults.setObject(personName, forKey: "userName")
// destinationController.personalInfo["name"] = personName
// destinationController.personalInfo["insureCompany"] = "ido cor"
// destinationController.personalInfo["moneyLeft"] = "0"
// self.presentViewController(destinationController, animated: false, completion: nil)
// }
}
}
func newUser() -> Void {
let paras = ["userName":personName!,"password":String(setPwd.text),"salt":String(setPwd.text),"phone":personName!]
Alamofire.request(.POST, HOST+"user",parameters:paras).responseJSON{
response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print(json)
}
case .Failure(let error):
print(error)
}
}
}
}
|
cefb96ace5a6e9839e9a3b834a6c50df
| 32.821918 | 170 | 0.593358 | false | false | false | false |
domenicosolazzo/practice-swift
|
refs/heads/master
|
Vision/VisionFaceLandmarks/VisionFaceLandmarks/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// VisionFaceLandmarks
//
// Created by Domenico Solazzo on 8/25/17.
// Copyright © 2017 Domenico Solazzo. All rights reserved.
//
import UIKit
import AVFoundation
import Vision
class ViewController: UIViewController {
// AVCapture Session
var session: AVCaptureSession?
// Shape Layer
let shapeLayer = CAShapeLayer()
// Vision requests
let faceDetection = VNDetectFaceRectanglesRequest()
// Face Landmarks request
let faceLandmarks = VNDetectFaceLandmarksRequest()
// Face Detection request handler
let faceDetectionRequest = VNSequenceRequestHandler()
// Face Landmarks request handler
let faceLandmarksRequest = VNSequenceRequestHandler()
// Preview Layer
lazy var previewLayer: AVCaptureVideoPreviewLayer? = {
// Check if the AVCapture session is initialized, otherwise return nil
guard let session = self.session else { return nil }
// Create the preview layer
var previewLayer = AVCaptureVideoPreviewLayer(session: session)
// Set the aspect of the preview video
previewLayer.videoGravity = .resizeAspectFill
return previewLayer
}()
// Camera to use
var frontCamera: AVCaptureDevice? = {
return AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: .video, position: AVCaptureDevice.Position.front)
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
sessionPrepare()
session?.startRunning()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer?.frame = view.frame
shapeLayer.frame = view.frame
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let previewLayer = previewLayer else { return }
view.layer.addSublayer(previewLayer)
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 2.0
//needs to filp coordinate system for Vision
shapeLayer.setAffineTransform(CGAffineTransform(scaleX: -1, y: -1))
view.layer.addSublayer(shapeLayer)
}
// Prepare the session
func sessionPrepare() {
session = AVCaptureSession()
guard let session = session, let captureDevice = frontCamera else { return }
do {
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
session.beginConfiguration()
if session.canAddInput(deviceInput) {
session.addInput(deviceInput)
}
let output = AVCaptureVideoDataOutput()
output.videoSettings = [
String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
]
output.alwaysDiscardsLateVideoFrames = true
if session.canAddOutput(output) {
session.addOutput(output)
}
session.commitConfiguration()
let queue = DispatchQueue(label: "output.queue")
output.setSampleBufferDelegate(self, queue: queue)
print("Setup delegate")
} catch {
print("Can't setup session")
}
}
}
extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, sampleBuffer, kCMAttachmentMode_ShouldPropagate)
let ciImage = CIImage(cvImageBuffer: pixelBuffer!, options: attachments as! [String : Any]?)
//leftMirrored for front camera
let ciImageWithOrientation = ciImage.oriented(forExifOrientation: Int32(UIImageOrientation.leftMirrored.rawValue))
detectFace(on: ciImageWithOrientation)
}
}
extension ViewController {
func detectFace(on image: CIImage) {
try? faceDetectionRequest.perform([faceDetection], on: image)
if let results = faceDetection.results as? [VNFaceObservation] {
if !results.isEmpty {
faceLandmarks.inputFaceObservations = results
DispatchQueue.main.async {
self.shapeLayer.sublayers?.removeAll()
}
}
}
}
func detectLandmarks(on image: CIImage) {
try? faceLandmarksDetectionRequest.perform([faceLandmarks], on: image)
if let landmarksResults = faceLandmarks.results as? [VNFaceObservation] {
for observation in landmarksResults {
DispatchQueue.main.async {
if let boundingBox = self.faceLandmarks.inputFaceObservations?.first?.boundingBox {
let faceBoundingBox = boundingBox.scaled(to: self.view.bounds.size)
//different types of landmarks
let faceContour = observation.landmarks?.faceContour
self.convertPointsForFace(faceContour, faceBoundingBox)
let leftEye = observation.landmarks?.leftEye
self.convertPointsForFace(leftEye, faceBoundingBox)
let rightEye = observation.landmarks?.rightEye
self.convertPointsForFace(rightEye, faceBoundingBox)
let nose = observation.landmarks?.nose
self.convertPointsForFace(nose, faceBoundingBox)
let lips = observation.landmarks?.innerLips
self.convertPointsForFace(lips, faceBoundingBox)
let leftEyebrow = observation.landmarks?.leftEyebrow
self.convertPointsForFace(leftEyebrow, faceBoundingBox)
let rightEyebrow = observation.landmarks?.rightEyebrow
self.convertPointsForFace(rightEyebrow, faceBoundingBox)
let noseCrest = observation.landmarks?.noseCrest
self.convertPointsForFace(noseCrest, faceBoundingBox)
let outerLips = observation.landmarks?.outerLips
self.convertPointsForFace(outerLips, faceBoundingBox)
}
}
}
}
}
func convertPointsForFace(_ landmark: VNFaceLandmarkRegion2D?, _ boundingBox: CGRect) {
if (landmark?.pointCount) != nil {
let points = landmark?.normalizedPoints
let convertedPoints = convert(points!)
let faceLandmarkPoints = convertedPoints.map { (point: (x: CGFloat, y: CGFloat)) -> (x: CGFloat, y: CGFloat) in
let pointX = point.x * boundingBox.width + boundingBox.origin.x
let pointY = point.y * boundingBox.height + boundingBox.origin.y
return (x: pointX, y: pointY)
}
DispatchQueue.main.async {
self.draw(points: faceLandmarkPoints)
}
}
}
func draw(points: [(x: CGFloat, y: CGFloat)]) {
let newLayer = CAShapeLayer()
newLayer.strokeColor = UIColor.red.cgColor
newLayer.lineWidth = 2.0
let path = UIBezierPath()
path.move(to: CGPoint(x: points[0].x, y: points[0].y))
for i in 0..<points.count - 1 {
let point = CGPoint(x: points[i].x, y: points[i].y)
path.addLine(to: point)
path.move(to: point)
}
path.addLine(to: CGPoint(x: points[0].x, y: points[0].y))
newLayer.path = path.cgPath
shapeLayer.addSublayer(newLayer)
}
func convert(_ points: [CGPoint]) -> [(x: CGFloat, y: CGFloat)] {
var convertedPoints = [(x: CGFloat, y: CGFloat)]()
for point in points {
convertedPoints.append((x: point.x, y: point.y))
}
return convertedPoints
}
}
|
0dd24a9ef29864b2a08533ef2775dade
| 36.131356 | 144 | 0.589182 | false | false | false | false |
Reaction-Framework/react-native-canvas
|
refs/heads/master
|
ios/RCTIONImage2DContext.swift
|
mit
|
2
|
//
// RCTIONImage2DContext.swift
// RCTIONImage2D
//
// Created by Marko on 14/01/16.
//
//
import Foundation
import ImageIO
import MobileCoreServices
class RCTIONImage2DContext: NSObject {
private var contextId = NSUUID().UUIDString
private var image: CGImageRef?
func getContextId() -> String {
return self.contextId;
}
func createFromFileUrl(fileUrl: String, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void {
let imageData = NSData.init(contentsOfURL: NSURL.init(fileURLWithPath: fileUrl))!
self.createFromData(imageData, withMaxWidth: maxWidth, withMaxHeight: maxHeight)
}
func createFromBase64String(base64: String, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void {
let imageData = NSData.init(base64EncodedString: base64, options: NSDataBase64DecodingOptions(rawValue: 0))!
self.createFromData(imageData, withMaxWidth: maxWidth, withMaxHeight: maxHeight)
}
private func createFromData(imageData: NSData, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void {
let imageSource = CGImageSourceCreateWithData(imageData, nil)!
let newImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)!
self.createFromImage(newImage, withMaxWidth: maxWidth, withMaxHeight: maxHeight)
}
private func createFromImage(image: CGImageRef, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void {
let orgWidth = Double(CGImageGetWidth(image))
let orgHeight = Double(CGImageGetHeight(image))
var calcNewWidth = Double(maxWidth)
var calcNewHeight = Double(maxHeight)
if orgWidth <= calcNewWidth && orgHeight <= calcNewHeight {
self.image = image
return;
}
if orgWidth / calcNewWidth < orgHeight / calcNewHeight {
calcNewWidth = (calcNewHeight / orgHeight) * orgWidth
} else {
calcNewHeight = (calcNewWidth / orgWidth) * orgHeight
}
let newWidth = Int(calcNewWidth)
let newHeight = Int(calcNewHeight)
let context = CGBitmapContextCreate(
nil,
newWidth,
newHeight,
CGImageGetBitsPerComponent(image),
32 * newWidth,
CGImageGetColorSpace(image),
CGImageGetAlphaInfo(image).rawValue
)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(newWidth), CGFloat(newHeight)), image)
self.image = CGBitmapContextCreateImage(context)
}
func save(fileName: String) -> String {
let imageData = self.getAsData()
let documentsDirectory: NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let fileManager = NSFileManager.defaultManager()
let imagePath = (documentsDirectory.stringByAppendingPathComponent(fileName) as NSString).stringByAppendingPathExtension("jpg")!
fileManager.createFileAtPath(imagePath, contents: imageData, attributes: nil)
return imagePath
}
func getAsBase64String() -> String {
return self.getAsData().base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
private func getAsData() -> NSData {
let imageData = CFDataCreateMutable(nil, 0)
let type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, "image/png", kUTTypeImage)!.takeRetainedValue()
let destination = CGImageDestinationCreateWithData(imageData, type, 1, nil)!
CGImageDestinationAddImage(destination, self.image!, nil)
CGImageDestinationFinalize(destination)
return imageData
}
func getWidth() -> Int {
return CGImageGetWidth(self.image);
}
func getHeight() -> Int {
return CGImageGetHeight(self.image);
}
func crop(cropRectangle: CGRect) -> Void {
self.image = CGImageCreateWithImageInRect(self.image, cropRectangle);
}
func drawBorder(color: String, withLeftTop leftTop: CGSize, withRightBottom rightBottom: CGSize) throws -> Void {
let orgWidth = self.getWidth()
let orgHeight = self.getHeight()
let newWidth = orgWidth + Int(leftTop.width + rightBottom.width);
let newHeight = orgHeight + Int(leftTop.height + rightBottom.height);
let context = CGBitmapContextCreate(
nil,
newWidth,
newHeight,
CGImageGetBitsPerComponent(self.image),
32 * newWidth,
CGImageGetColorSpace(self.image),
CGImageGetAlphaInfo(self.image).rawValue
)
CGContextBeginPath(context);
CGContextSetFillColorWithColor(context, try UIColor.parseColor(color).CGColor);
CGContextFillRect(context, CGRectMake(0, 0, CGFloat(newWidth), CGFloat(newHeight)));
CGContextDrawImage(context, CGRectMake(leftTop.width, rightBottom.height, CGFloat(orgWidth), CGFloat(orgHeight)), self.image);
self.image = CGBitmapContextCreateImage(context);
}
deinit {
self.image = nil;
}
}
|
30b69af38fb3306cb879ac147112bfad
| 34.021898 | 132 | 0.722176 | false | false | false | false |
ploden/viral-bible-ios
|
refs/heads/master
|
Viral-Bible-Ios/Viral-Bible-Ios/Classes/Controllers/BooksVC.swift
|
mit
|
1
|
//
// BooksVC.swift
// Viral-Bible-Ios
//
// Created by Philip Loden on 10/4/15.
// Copyright © 2015 Alan Young. All rights reserved.
//
import UIKit
class BooksVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var bibleVersion : BibleVersion?
var books : [BibleBook]?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
if let version = self.bibleVersion {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
APIController.getBooks(version) { (books, error) -> () in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.books = books
self.tableView.reloadData()
})
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let books = self.books {
return books.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let aCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
if let books = self.books {
let book = books[indexPath.row]
aCell.titleLabel.text = book.bookName
}
return aCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let books = self.books {
let selectedBook = books[indexPath.row]
let vc = ChaptersVC.VB_instantiateFromStoryboard() as! ChaptersVC
vc.bibleBook = selectedBook
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
5d0910b007886f3301515f69e84e67bb
| 30.573529 | 119 | 0.61714 | false | false | false | false |
codwam/NPB
|
refs/heads/master
|
Demos/NPBDemo/NPB/Private/NPBSwizzle.swift
|
mit
|
1
|
//
// NPBSwizzle.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/12.
// Copyright © 2017年 codwam. All rights reserved.
//
import Foundation
// MARK: - Instance
func npb_instanceMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
let originalMethod = class_getInstanceMethod(cls, originalSelector)
let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector)
npb_addMethodSwizzling(cls: cls, originalSelector: originalSelector, swizzledSelector: swizzledSelector, originalMethod: originalMethod, swizzledMethod: swizzledMethod)
}
func npb_instanceMethodReplaceSwizzling(cls: AnyClass, originalSelector: Selector, swizzledIMP: IMP) {
let originalMethod = class_getInstanceMethod(cls, originalSelector)
let didAddMethod = class_addMethod(cls, originalSelector, swizzledIMP, method_getTypeEncoding(originalMethod))
if !didAddMethod {
method_setImplementation(originalMethod, swizzledIMP)
}
}
// MARK: - Class
func npb_classMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
let cls: AnyClass = object_getClass(cls)
let originalMethod = class_getClassMethod(cls, originalSelector)
let swizzledMethod = class_getClassMethod(cls, swizzledSelector)
npb_addMethodSwizzling(cls: cls, originalSelector: originalSelector, swizzledSelector: swizzledSelector, originalMethod: originalMethod, swizzledMethod: swizzledMethod)
}
// MARK: - Basic
func npb_addMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector, originalMethod: Method?, swizzledMethod: Method?) {
let didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
|
b19e1fd4cb0f26259f7fa9239f041caf
| 41.0625 | 172 | 0.78207 | false | false | false | false |
baottran/nSURE
|
refs/heads/master
|
nSURE/ESMonthDropOffViewController.swift
|
mit
|
1
|
//
// ASScheduleDropOffViewController.swift
// nSURE
//
// Created by Bao Tran on 7/20/15.
// Copyright (c) 2015 Sprout Designs. All rights reserved.
//
import UIKit
class ESMonthDropOffViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var monthYearLabel: UILabel!
@IBOutlet weak var calendarCollectionView: UICollectionView!
var repairObj: PFObject?
var repairArray: Array<PFObject>?
var today = NSDate.today()
var currentDate = NSDate.today()
override func viewDidLoad() {
super.viewDidLoad()
// println("assessment Array: \(assessmentArray)")
monthYearLabel.text = "\(today.monthName) \(today.year)"
self.view.addSubview(calendarCollectionView)
calendarCollectionView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func nextMonth(){
currentDate = (currentDate + 1.month).beginningOfMonth
monthYearLabel.text = "\(currentDate.monthName) \(currentDate.year)"
self.calendarCollectionView.reloadData()
}
@IBAction func previousMonth(){
let newDate = (currentDate - 1.month).beginningOfMonth
if newDate >= today.beginningOfMonth {
currentDate = newDate
monthYearLabel.text = "\(currentDate.monthName) \(currentDate.year)"
self.calendarCollectionView.reloadData()
}
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let numOfDaysInMonth = currentDate.monthDays()
let numOfCellsForMonth = numOfDaysInMonth + cellsForMonth(currentDate)
return numOfCellsForMonth
}
func cellsForMonth(currentDate: NSDate) -> Int{
var numOfCellsToAdd: Int
switch currentDate.beginningOfMonth.weekdayName {
case "Monday": numOfCellsToAdd = 1
case "Tuesday": numOfCellsToAdd = 2
case "Wednesday": numOfCellsToAdd = 3
case "Thursday": numOfCellsToAdd = 4
case "Friday": numOfCellsToAdd = 5
case "Saturday": numOfCellsToAdd = 6
case "Sunday": numOfCellsToAdd = 0
default:
numOfCellsToAdd = 0
}
return numOfCellsToAdd
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dayCell", forIndexPath: indexPath) as! MonthDayCollectionViewCell
let cellDate = currentDate.beginningOfMonth + (indexPath.row - cellsForMonth(currentDate)).days
var numOfDropOffs: Int = 0
if let repairs = repairArray {
for repair in repairs {
if let dropOffDate = repair["dropOffDate"] as? NSDate {
if (dropOffDate >= cellDate.beginningOfDay) && (dropOffDate <= (cellDate.beginningOfDay + 1.day)){
numOfDropOffs = numOfDropOffs + 1
}
}
}
}
cell.dayNum.text = String(cellDate.day)
cell.dayNum.userInteractionEnabled = false
cell.dayNum.userInteractionEnabled = false
if indexPath.row < cellsForMonth(currentDate){
cell.dayLabel.text = ""
cell.backgroundColor = UIColor.grayColor()
} else if (currentDate.month == today.month) && (currentDate.year == today.year) && (indexPath.row < (cellsForMonth(currentDate) + today.day - 1)){
cell.dayLabel.text = ""
cell.backgroundColor = UIColor.grayColor()
} else {
cell.dayLabel.text = "\(10 - numOfDropOffs) open drop offs"
cell.backgroundColor = UIColor.greenColor()
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Choose Drop Off Time" {
let dayController = segue.destinationViewController as! ESDayDropOffViewController
if let indexPath = calendarCollectionView.indexPathForCell(sender as! UICollectionViewCell){
let cellDate = currentDate.beginningOfMonth + (indexPath.row - cellsForMonth(currentDate)).days
dayController.currentDate = cellDate
dayController.repairObj = repairObj
dayController.repairArray = repairArray
}
}
}
}
|
0d98ebadaa857370d9e58279f2e82fbe
| 35.569231 | 155 | 0.631679 | false | false | false | false |
mathiasquintero/Sweeft
|
refs/heads/master
|
Example/Sweeft/Person.swift
|
mit
|
1
|
//
// Person.swift
// Sweeft
//
// Created by Mathias Quintero on 12/28/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import Sweeft
final class Person: Observable {
let id: Int
let name: String
var photo: UIImage?
var listeners = [Listener]()
init(id: Int, name: String, photo: UIImage? = nil) {
self.id = id
self.name = name
self.photo = photo
}
func fetchImage(with path: String) {
MovieImageAPI.fetchImage(with: path).onSuccess { image in
self.photo = image
self.hasChanged()
}
}
}
extension Person: Deserializable {
convenience init?(from json: JSON) {
guard let id = json["id"].int,
let name = json["name"].string else {
return nil
}
self.init(id: id, name: name)
json["profile_path"].string | fetchImage
}
}
extension Person {
static func person(with id: Int, using api: MoviesAPI = .shared) -> Person.Result {
return Person.get(using: api, at: .person, arguments: ["id": id])
}
static func people(with ids: [Int], using api: MoviesAPI = .shared) -> Person.Results {
return api.doBulkObjectRequest(to: .person, arguments: ids => { ["id": $0] })
}
}
extension Person {
func getMovies(using api: MoviesAPI = .shared, limitedTo limit: Int = 25) -> Movie.Results {
return api.doJSONRequest(to: .moviesForPerson,
arguments: ["id": id]).flatMap(completionQueue: .main) { json -> Response<[Movie]> in
let ids = json["cast"].array ==> { $0["id"].int }
return Movie.movies(with: ids.array(withFirst: limit), using: api)
}
}
}
|
36d241171fa9ed66775c758354c6fe50
| 24.985915 | 118 | 0.547967 | false | false | false | false |
himanshuy/MemeMe-v1.0
|
refs/heads/master
|
ImagePick/MemeMeViewController.swift
|
mit
|
1
|
//
// MemeMeViewController.swift
// ImagePick
//
// Created by Himanshu Yadav on 8/25/15.
// Copyright (c) 2015 Himanshu Yadav. All rights reserved.
//
import UIKit
class MemeMeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var pickedImage: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var topMemeText: UITextField!
@IBOutlet weak var bottomMemeText: UITextField!
@IBOutlet weak var topBar: UIToolbar!
@IBOutlet weak var bottomToolbar: UIToolbar!
@IBOutlet weak var shareButton: UIBarButtonItem!
var currentKeyboardHeight: CGFloat = 0.0
let memeTextAttributes = [
NSStrokeColorAttributeName: UIColor.blackColor(),
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -2
]
override func viewDidLoad() {
super.viewDidLoad()
topMemeText.text = "TOP"
bottomMemeText.text = "BOTTOM"
shareButton.enabled = false
memeTextFieldLayout(topMemeText)
memeTextFieldLayout(bottomMemeText)
}
func memeTextFieldLayout(textField: UITextField) {
textField.delegate = self
textField.textAlignment = NSTextAlignment.Center
textField.defaultTextAttributes = memeTextAttributes
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
@IBAction func pickImageFromAlbum(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(imagePicker, animated: true){
self.shareButton.enabled = true
}
}
@IBAction func pickImageFromCamera(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func shareMeme(sender: UIBarButtonItem) {
let activityController = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
presentViewController(activityController, animated: true, completion: nil)
activityController.completionWithItemsHandler = { activity, success, items, error in
if( activity == UIActivityTypeSaveToCameraRoll && success) {
self.saveMeme()
self.presentSentMeme()
}
}
}
@IBAction func cancelShare(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
presentSentMeme()
}
func saveMeme() {
//create the Meme
if(pickedImage.image != nil){
let meme = Meme(topText: topMemeText.text!, bottomText: bottomMemeText.text!, image: pickedImage.image!, memedImage: generateMemedImage())
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
UIImageWriteToSavedPhotosAlbum(generateMemedImage(), self, Selector("image:didFinishSavingWithError:contextInfo:"), nil)
}
}
func presentSentMeme() {
let memeMeTabBarViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tabBarController") as! UITabBarController
self.presentViewController(memeMeTabBarViewController, animated: true, completion: nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>) {
dispatch_async(dispatch_get_main_queue(), {
UIAlertView(title: "Success", message: "This image has been saved to your Photo album successfully", delegate: nil, cancelButtonTitle: "Close").show()
})
}
func generateMemedImage() -> UIImage {
topBar.hidden = true
bottomToolbar.hidden = true
//Generate Meme
UIGraphicsBeginImageContext(view.frame.size)
view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
topBar.hidden = false
bottomToolbar.hidden = false
return memedImage
}
//Clear the text field
func textFieldDidBeginEditing(textField: UITextField) {
if textField.text == "TOP" || textField.text == "BOTTOM" {
textField.text = ""
}
}
//When user presses return, keyboard dismissed.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
pickedImage.image = image
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if bottomMemeText.isFirstResponder() {
let kbSize: CGFloat = getKeyboardHeight(notification)
let deltaHeight: CGFloat = kbSize - currentKeyboardHeight
view.frame.origin.y -= deltaHeight
currentKeyboardHeight = kbSize
}
}
func keyboardWillHide(notification: NSNotification) {
//view.frame.origin.y += getKeyboardHeight(notification)
currentKeyboardHeight = 0
view.frame.origin.y = 0
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue //of CGRect
return keyboardSize.CGRectValue().height
}
}
|
f8f824c4ddc994d1bbb0ef52a01eb7d5
| 38.016043 | 162 | 0.690789 | false | false | false | false |
Isuru-Nanayakkara/Broadband-Usage-Meter-OSX
|
refs/heads/master
|
Broadband Usage Meter/Broadband Usage Meter/PreferencesWindow.swift
|
mit
|
1
|
//
// PreferencesWindow.swift
// SLT Usage Meter
//
// Created by Isuru Nanayakkara on 10/23/15.
// Copyright © 2015 BitInvent. All rights reserved.
//
import Cocoa
protocol PreferencesDelegate {
func preferencesDidUpdate()
}
class PreferencesWindow: NSWindowController, NSWindowDelegate {
@IBOutlet weak var userIDTextField: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField!
var delegate: PreferencesDelegate?
override var windowNibName: String {
return "PreferencesWindow"
}
override func windowDidLoad() {
super.windowDidLoad()
window?.center()
window?.makeKeyAndOrderFront(nil)
NSApp.activateIgnoringOtherApps(true)
// TODO: Refector NSUserDefaults code duplication
let userDefaults = NSUserDefaults.standardUserDefaults()
let userID = userDefaults.stringForKey("userID")
let password = userDefaults.stringForKey("password")
if let userID = userID, let password = password {
userIDTextField.stringValue = userID
passwordTextField.stringValue = password
}
// TODO: Add this in the next version. Current placement of the label is ugly
// registerLabel.allowsEditingTextAttributes = true
// registerLabel.selectable = true
//
// let url = NSURL(string: "https://www.internetvas.slt.lk/SLTVasPortal-war/register/register.jsp")!
// let str = NSMutableAttributedString(string: "If you don't have a portal account, create one ")
// str.appendAttributedString(NSAttributedString.hyperlinkFromString("here", withURL: url))
// registerLabel.attributedStringValue = str
// registerLabel.alignment = .Center
}
@IBAction func loginButtonClicked(sender: NSButton) {
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(userIDTextField.stringValue, forKey: "userID")
userDefaults.setValue(passwordTextField.stringValue, forKey: "password")
delegate?.preferencesDidUpdate()
close()
}
}
|
b72cf6958e778a14832408b3fc3d8e6b
| 33.206349 | 107 | 0.676102 | false | false | false | false |
eofster/Telephone
|
refs/heads/master
|
UseCasesTestDoubles/RingtonePlaybackUseCaseSpy.swift
|
gpl-3.0
|
1
|
//
// RingtonePlaybackUseCaseSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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 UseCases
public final class RingtonePlaybackUseCaseSpy: NSObject {
public private(set) var isPlaying = false
public private(set) var didCallStart = false
public private(set) var didCallStop = false
}
extension RingtonePlaybackUseCaseSpy: RingtonePlaybackUseCase {
public func start() throws {
didCallStart = true
isPlaying = true
}
public func stop() {
didCallStop = true
isPlaying = false
}
}
|
a79787490deb8ee21b418473d9dc3ebe
| 29.108108 | 72 | 0.717235 | false | false | false | false |
swernimo/iOS
|
refs/heads/master
|
UI Kit Fundamentals 1/ClickCounter/ClickCounter/ViewController(old).swift
|
mit
|
1
|
//
// ViewController.swift
// ClickCounter
//
// Created by Sean Wernimont on 10/23/15.
// Copyright © 2015 Just One Guy. All rights reserved.
//
import UIKit
class ViewControllerOld: UIViewController {
var count = 0;
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let label = createLabel();
let button = createButton("Increase Count");
button.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside);
let decrementButton = createButton("Decrease Count");
decrementButton.frame = CGRectMake(100, 200, 60, 60);
decrementButton.addTarget(self, action: "decreaseCount", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(label);
self.view.addSubview(button);
self.view.addSubview(decrementButton);
self.label = label;
}
func createLabel() -> UILabel{
let label = UILabel();
label.frame = CGRectMake(150, 150, 60, 60);
label.text = "0";
return label;
}
func createButton(title: String) -> UIButton{
let button = UIButton();
button.frame = CGRectMake(150, 250, 60, 60);
button.setTitle(title, forState: .Normal);
button.setTitleColor(UIColor.blueColor(), forState: .Normal);
return button;
}
func incrementCount() -> Void{
self.count++;
self.label.text = "\(self.count)";
}
func decreaseCount() -> Void{
self.count--;
self.label.text = "\(self.count)";
}
}
|
fb680b125658edb56b7fc99741e0bab1
| 27.224138 | 114 | 0.603301 | false | false | false | false |
google-books/swift-api-client
|
refs/heads/develop
|
GoogleBooksApiClient/HttpClient.swift
|
mit
|
1
|
import Foundation
typealias RequestParameter = (key: String, value: String)
typealias RequestHeader = (key: String, value: String)
enum HttpMethod: String {
case get = "GET"
case post = "POST"
}
// A Simple wrapper of URLSession.dataTask
final class HttpClient {
private let session: URLSession
init(session: URLSession) {
self.session = session
}
func execute(request: URLRequest, completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) -> URLSessionDataTask {
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
guard let response = response, let data = data else {
completionHandler(nil, nil, HttpClientError.unknown)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completionHandler(data, nil, HttpClientError.nonHTTPResponse(response: response))
return
}
completionHandler(data, httpResponse, error)
})
return task
}
}
enum HttpClientError: Error {
case unknown
case nonHTTPResponse(response: URLResponse)
}
|
60071b6ad760b44e407ff1616f3df986
| 27.952381 | 133 | 0.632401 | false | false | false | false |
LYM-mg/MGOFO
|
refs/heads/master
|
MGOFO/MGOFO/Class/Tools/SQLiteManager.swift
|
mit
|
1
|
//
// SQLiteManager.swift
// FMDB的基本使用
//
// Created by ming on 16/4/18.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
class SQLiteManager: NSObject {
// 单例
static let shareInstance: SQLiteManager = SQLiteManager()
override init() {
super.init()
openDB(name: "statues.db")
}
var dbQueue: FMDatabaseQueue?
// 打开数据库/数据库的名称
func openDB(name: String) {
// 1.拼接路径
let path = name.cache()
// debugPrint(path)
// 2.创建数据库对象 // 这哥们会自动打开。内部已经封装创建db
dbQueue = FMDatabaseQueue(path: path)
// 3.创建表
creatTable()
}
/// 创建表
private func creatTable(){
// 1.编写SQL语句
// let sql = "CREATE TABLE IF NOT EXISTS t_productmodels(" +
// "id INTEGER PRIMARY KEY AUTOINCREMENT," +
// "modelId decimal," +
// "modelText TEXT," +
// "userId INTEGER," +
// "creatTime TEXT NOT NULL DEFAULT (datetime('now','localtime'))" +
// ");"
let sql = "CREATE TABLE IF NOT EXISTS t_productmodels (" +
"modelId TEXT PRIMARY KEY, " +
"modelText TEXT, " +
"userId TEXT, " +
"creatTime TEXT NOT NULL DEFAULT (datetime('now','localtime'))" +
");"
// 2.执行SQL语句
/// 在FMDB中除了查询语句其他所有的操作都称为更新
/// 在这里执行的操作就是线程安全的?为什么呢?因为其内部是一个串行队列内部开启一条子线程
dbQueue?.inDatabase({ (db) -> Void in
db?.executeUpdate(sql, withArgumentsIn: nil)
})
}
}
|
0289fe9262812edf93320179486b8d01
| 22.69697 | 79 | 0.530051 | false | false | false | false |
steven7/ParkingApp
|
refs/heads/master
|
MapboxNavigationTests/MapboxNavigationTests.swift
|
isc
|
1
|
import XCTest
import FBSnapshotTestCase
import MapboxDirections
@testable import MapboxNavigation
class MapboxNavigationTests: FBSnapshotTestCase {
var shieldImage: UIImage {
get {
let bundle = Bundle(for: MapboxNavigationTests.self)
return UIImage(named: "80px-I-280", in: bundle, compatibleWith: nil)!
}
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
recordMode = false
isDeviceAgnostic = true
}
func storyboard() -> UIStoryboard {
return UIStoryboard(name: "Navigation", bundle: Bundle.navigationUI)
}
func testManeuverViewMultipleLines() {
let controller = storyboard().instantiateViewController(withIdentifier: "RouteManeuverViewController") as! RouteManeuverViewController
XCTAssert(controller.view != nil)
controller.distance = nil
controller.streetLabel.text = "This should be multiple lines"
controller.turnArrowView.isEnd = true
controller.shieldImage = shieldImage
FBSnapshotVerifyView(controller.view)
}
func testManeuverViewSingleLine() {
let controller = storyboard().instantiateViewController(withIdentifier: "RouteManeuverViewController") as! RouteManeuverViewController
XCTAssert(controller.view != nil)
controller.distance = 1000
controller.streetLabel.text = "This text should shrink"
controller.turnArrowView.isEnd = true
controller.shieldImage = shieldImage
FBSnapshotVerifyView(controller.view)
}
}
|
37c9f085346e8e2cff64f3ebfd0b4972
| 33.897959 | 142 | 0.677193 | false | true | false | false |
venticake/RetricaImglyKit-iOS
|
refs/heads/master
|
RetricaImglyKit/Classes/Frontend/Editor/Tools/FocusToolController.swift
|
mit
|
1
|
// This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
* A `FocusToolController` is reponsible for displaying the UI to adjust the focus of an image.
*/
@available(iOS 8, *)
@objc(IMGLYFocusToolController) public class FocusToolController: PhotoEditToolController {
// MARK: - Statics
private static let IconCaptionCollectionViewCellReuseIdentifier = "IconCaptionCollectionViewCellReuseIdentifier"
private static let IconCaptionCollectionViewCellSize = CGSize(width: 64, height: 80)
// MARK: - Properties
private lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = FocusToolController.IconCaptionCollectionViewCellSize
flowLayout.scrollDirection = .Horizontal
flowLayout.minimumLineSpacing = 8
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.registerClass(IconCaptionCollectionViewCell.self, forCellWithReuseIdentifier: FocusToolController.IconCaptionCollectionViewCellReuseIdentifier)
collectionView.backgroundColor = UIColor.clearColor()
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
private var activeFocusType: IMGLYFocusType = .Off {
didSet {
if oldValue != activeFocusType {
switch activeFocusType {
case .Off:
UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: {
self.circleGradientView?.alpha = 0
self.boxGradientView?.alpha = 0
self.sliderContainerView?.alpha = 0
}) { _ in
self.circleGradientView?.hidden = true
self.boxGradientView?.hidden = true
}
case .Linear:
boxGradientView?.hidden = false
UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: {
self.circleGradientView?.alpha = 0
self.boxGradientView?.alpha = 1
self.sliderContainerView?.alpha = 1
}) { _ in
self.circleGradientView?.hidden = true
}
case .Radial:
circleGradientView?.hidden = false
UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: {
self.circleGradientView?.alpha = 1
self.boxGradientView?.alpha = 0
self.sliderContainerView?.alpha = 1
}) { _ in
self.boxGradientView?.hidden = true
}
}
}
}
}
private var boxGradientView: BoxGradientView?
private var circleGradientView: CircleGradientView?
private var sliderContainerView: UIView?
private var slider: Slider?
private var sliderConstraints: [NSLayoutConstraint]?
private var gradientViewConstraints: [NSLayoutConstraint]?
private var didPerformInitialGradientViewLayout = false
// MARK: - UIViewController
/**
:nodoc:
*/
public override func viewDidLoad() {
super.viewDidLoad()
toolStackItem.performChanges {
toolStackItem.mainToolbarView = collectionView
toolStackItem.titleLabel?.text = options.title
if let applyButton = toolStackItem.applyButton {
applyButton.addTarget(self, action: #selector(FocusToolController.apply(_:)), forControlEvents: .TouchUpInside)
applyButton.accessibilityLabel = Localize("Apply changes")
options.applyButtonConfigurationClosure?(applyButton)
}
if let discardButton = toolStackItem.discardButton {
discardButton.addTarget(self, action: #selector(FocusToolController.discard(_:)), forControlEvents: .TouchUpInside)
discardButton.accessibilityLabel = Localize("Discard changes")
options.discardButtonConfigurationClosure?(discardButton)
}
}
let boxGradientView = BoxGradientView()
boxGradientView.gradientViewDelegate = self
boxGradientView.hidden = true
boxGradientView.alpha = 0
view.addSubview(boxGradientView)
self.boxGradientView = boxGradientView
options.boxGradientViewConfigurationClosure?(boxGradientView)
let circleGradientView = CircleGradientView()
circleGradientView.gradientViewDelegate = self
circleGradientView.hidden = true
circleGradientView.alpha = 0
view.addSubview(circleGradientView)
self.circleGradientView = circleGradientView
options.circleGradientViewConfigurationClosure?(circleGradientView)
switch photoEditModel.focusType {
case .Off:
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Off.rawValue, inSection: 0), animated: false, scrollPosition: .None)
case .Linear:
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Linear.rawValue, inSection: 0), animated: false, scrollPosition: .None)
boxGradientView.hidden = false
boxGradientView.alpha = 1
activeFocusType = .Linear
case .Radial:
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Radial.rawValue, inSection: 0), animated: false, scrollPosition: .None)
circleGradientView.hidden = false
circleGradientView.alpha = 1
activeFocusType = .Radial
}
let sliderContainerView = UIView()
sliderContainerView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
sliderContainerView.translatesAutoresizingMaskIntoConstraints = false
sliderContainerView.alpha = photoEditModel.focusType == .Off ? 0 : 1
view.addSubview(sliderContainerView)
self.sliderContainerView = sliderContainerView
options.sliderContainerConfigurationClosure?(sliderContainerView)
let slider = Slider()
slider.accessibilityLabel = Localize("Blur intensity")
slider.translatesAutoresizingMaskIntoConstraints = false
slider.maximumValue = 15
slider.neutralValue = 2
slider.minimumValue = 2
slider.neutralPointTintColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1)
slider.thumbTintColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1)
slider.filledTrackColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1)
slider.value = photoEditModel.focusBlurRadius
sliderContainerView.addSubview(slider)
slider.addTarget(self, action: #selector(FocusToolController.changeValue(_:)), forControlEvents: .ValueChanged)
self.slider = slider
options.sliderConfigurationClosure?(slider)
view.setNeedsUpdateConstraints()
}
private var options: FocusToolControllerOptions {
get {
return configuration.focusToolControllerOptions
}
}
/**
:nodoc:
*/
public override func updateViewConstraints() {
super.updateViewConstraints()
if let boxGradientView = boxGradientView, circleGradientView = circleGradientView where gradientViewConstraints == nil {
var constraints = [NSLayoutConstraint]()
boxGradientView.translatesAutoresizingMaskIntoConstraints = false
circleGradientView.translatesAutoresizingMaskIntoConstraints = false
constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0))
NSLayoutConstraint.activateConstraints(constraints)
gradientViewConstraints = constraints
}
if let sliderContainerView = sliderContainerView, slider = slider where sliderConstraints == nil {
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44))
constraints.append(NSLayoutConstraint(item: slider, attribute: .CenterY, relatedBy: .Equal, toItem: sliderContainerView, attribute: .CenterY, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: slider, attribute: .Left, relatedBy: .Equal, toItem: sliderContainerView, attribute: .Left, multiplier: 1, constant: 20))
constraints.append(NSLayoutConstraint(item: slider, attribute: .Right, relatedBy: .Equal, toItem: sliderContainerView, attribute: .Right, multiplier: 1, constant: -20))
NSLayoutConstraint.activateConstraints(constraints)
sliderConstraints = constraints
}
}
/**
:nodoc:
*/
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
guard let previewView = delegate?.photoEditToolControllerPreviewView(self), previewContainer = delegate?.photoEditToolControllerPreviewViewScrollingContainer(self) else {
return
}
let flippedControlPoint1 = flipNormalizedPointVertically(photoEditModel.focusNormalizedControlPoint1)
let flippedControlPoint2 = flipNormalizedPointVertically(photoEditModel.focusNormalizedControlPoint2)
let leftMargin = (previewContainer.bounds.width - previewView.bounds.width) / 2
let topMargin = (previewContainer.bounds.height - previewView.bounds.height) / 2
let denormalizedControlPoint1 = CGPoint(x: flippedControlPoint1.x * previewView.bounds.width + leftMargin, y: flippedControlPoint1.y * previewView.bounds.height + topMargin)
let denormalizedControlPoint2 = CGPoint(x: flippedControlPoint2.x * previewView.bounds.width + leftMargin, y: flippedControlPoint2.y * previewView.bounds.height + topMargin)
boxGradientView?.controlPoint1 = denormalizedControlPoint1
boxGradientView?.controlPoint2 = denormalizedControlPoint2
circleGradientView?.controlPoint1 = denormalizedControlPoint1
circleGradientView?.controlPoint2 = denormalizedControlPoint2
}
// MARK: - PhotoEditToolController
/**
:nodoc:
*/
public override func photoEditModelDidChange(notification: NSNotification) {
super.photoEditModelDidChange(notification)
activeFocusType = photoEditModel.focusType
slider?.value = photoEditModel.focusBlurRadius
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: activeFocusType.rawValue, inSection: 0), animated: true, scrollPosition: .None)
}
/**
:nodoc:
*/
public override func didBecomeActiveTool() {
super.didBecomeActiveTool()
options.didEnterToolClosure?()
}
/**
:nodoc:
*/
public override func willResignActiveTool() {
super.willResignActiveTool()
options.willLeaveToolClosure?()
}
// MARK: - Actions
@objc private func changeValue(sender: Slider) {
photoEditModel.performChangesWithBlock {
self.photoEditModel.focusBlurRadius = CGFloat(sender.value)
}
options.sliderChangedValueClosure?(sender, activeFocusType)
}
@objc private func apply(sender: UIButton) {
delegate?.photoEditToolControllerDidFinish(self)
}
@objc private func discard(sender: UIButton) {
delegate?.photoEditToolController(self, didDiscardChangesInFavorOfPhotoEditModel: uneditedPhotoEditModel)
}
// MARK: - Helpers
private func normalizeControlPoint(point: CGPoint) -> CGPoint {
guard let previewView = delegate?.photoEditToolControllerPreviewView(self) else {
return point
}
if let boxGradientView = boxGradientView where activeFocusType == .Linear {
let convertedPoint = previewView.convertPoint(point, fromView: boxGradientView)
return CGPoint(x: convertedPoint.x / previewView.bounds.size.width, y: convertedPoint.y / previewView.bounds.size.height)
} else if let circleGradientView = circleGradientView where activeFocusType == .Radial {
let convertedPoint = previewView.convertPoint(point, fromView: circleGradientView)
return CGPoint(x: convertedPoint.x / previewView.bounds.size.width, y: convertedPoint.y / previewView.bounds.size.height)
}
return point
}
private func denormalizeControlPoint(point: CGPoint) -> CGPoint {
guard let previewView = delegate?.photoEditToolControllerPreviewView(self) else {
return point
}
if let boxGradientView = boxGradientView where activeFocusType == .Linear {
let denormalizedPoint = CGPoint(x: point.x * previewView.bounds.size.width, y: point.y * previewView.bounds.size.height)
return previewView.convertPoint(denormalizedPoint, toView: boxGradientView)
} else if let circleGradientView = circleGradientView where activeFocusType == .Radial {
let denormalizedPoint = CGPoint(x: point.x * previewView.bounds.size.width, y: point.y * previewView.bounds.size.height)
return previewView.convertPoint(denormalizedPoint, toView: circleGradientView)
}
return point
}
private func flipNormalizedPointVertically(point: CGPoint) -> CGPoint {
return CGPoint(x: point.x, y: 1 - point.y)
}
}
@available(iOS 8, *)
extension FocusToolController: UICollectionViewDelegate {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let actionType = options.allowedFocusTypes[indexPath.item]
photoEditModel.focusType = actionType
switch actionType {
case .Off:
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
case .Linear:
photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(boxGradientView?.controlPoint1 ?? CGPoint.zero))
photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(boxGradientView?.controlPoint2 ?? CGPoint.zero))
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, boxGradientView)
case.Radial:
photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(circleGradientView?.controlPoint1 ?? CGPoint.zero))
photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(circleGradientView?.controlPoint2 ?? CGPoint.zero))
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, circleGradientView)
}
options.focusTypeSelectedClosure?(activeFocusType)
}
}
@available(iOS 8, *)
extension FocusToolController: UICollectionViewDataSource {
/**
:nodoc:
*/
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return options.allowedFocusTypes.count
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FocusToolController.IconCaptionCollectionViewCellReuseIdentifier, forIndexPath: indexPath)
let actionType = options.allowedFocusTypes[indexPath.item]
if let iconCaptionCell = cell as? IconCaptionCollectionViewCell {
if actionType == .Off {
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_off", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("No Focus")
iconCaptionCell.accessibilityLabel = Localize("No Focus")
} else if actionType == .Linear {
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_linear", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Linear")
iconCaptionCell.accessibilityLabel = Localize("Linear focus")
} else if actionType == .Radial {
iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_radial", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)
iconCaptionCell.captionLabel.text = Localize("Radial")
iconCaptionCell.accessibilityLabel = Localize("Radial focus")
}
options.focusTypeButtonConfigurationClosure?(iconCaptionCell, actionType)
}
return cell
}
}
@available(iOS 8, *)
extension FocusToolController: UICollectionViewDelegateFlowLayout {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
return UIEdgeInsetsZero
}
let cellSpacing = flowLayout.minimumLineSpacing
let cellWidth = flowLayout.itemSize.width
let cellCount = collectionView.numberOfItemsInSection(section)
let inset = max((collectionView.bounds.width - (CGFloat(cellCount) * (cellWidth + cellSpacing))) * 0.5, 0)
return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: 0)
}
}
@available(iOS 8, *)
extension FocusToolController: GradientViewDelegate {
/**
:nodoc:
*/
public func gradientViewUserInteractionStarted(gradientView: UIView) {
}
/**
:nodoc:
*/
public func gradientViewUserInteractionEnded(gradientView: UIView) {
}
/**
:nodoc:
*/
public func gradientViewControlPointChanged(gradientView: UIView) {
if let gradientView = gradientView as? CircleGradientView where gradientView == circleGradientView {
photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint1))
photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint2))
} else if let gradientView = gradientView as? BoxGradientView where gradientView == boxGradientView {
photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint1))
photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint2))
}
}
}
|
8ba15830f301cd7bc1bfa4d0989e1fab
| 46.837004 | 210 | 0.698269 | false | false | false | false |
APUtils/APExtensions
|
refs/heads/master
|
APExtensions/Classes/Core/_Extensions/_UIKit/UIImage+Utils.swift
|
mit
|
1
|
//
// UIImage+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 9/20/17.
// Copyright © 2019 Anton Plebanovich. All rights reserved.
//
import UIKit
public extension UIImage {
/// Creates image from contents of local file
/// - return: Returns nil if image can not be created or file can not be found.
@available(iOS 9.0, *)
convenience init?(contentsOfFile file: URL) {
guard file.isFileURL && !file.hasDirectoryPath else { return nil }
self.init(contentsOfFile: file.path)
}
/// Returns image with overlay image drawn the center on top.
func image(withOverlayImageAtCenter overlayImage: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
defer { UIGraphicsEndImageContext() }
draw(at: CGPoint(x: 0, y: 0))
let centerRectOrigin = CGPoint(x: (size.width - overlayImage.size.width) / 2, y: (size.height - overlayImage.size.height) / 2)
let centerRect = CGRect(origin: centerRectOrigin, size: overlayImage.size)
overlayImage.draw(in: centerRect)
if let image = UIGraphicsGetImageFromCurrentImageContext() {
return image
} else {
return self
}
}
/// Returns image with overlay image drawn in the `rect` on top.
func image(withOverlayImage overlayImage: UIImage, inRect rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
defer { UIGraphicsEndImageContext() }
draw(at: CGPoint(x: 0, y: 0))
overlayImage.draw(in: rect)
if let image = UIGraphicsGetImageFromCurrentImageContext() {
return image
} else {
return self
}
}
/// Resizes specified image to required size. It uses aspect fill approach and high interpolation quality.
/// - parameters:
/// - size: Required size.
/// - returns: Resized image.
func image(withSize size: CGSize) -> UIImage {
guard self.size != size else { return self }
let scale = max(size.width / self.size.width, size.height / self.size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = .high
let scaledWidth = self.size.width * scale
let scaledHeight = self.size.height * scale
let originX = (size.width - scaledWidth) / 2
let originY = (size.height - scaledHeight) / 2
draw(in: CGRect(x: originX, y: originY, width: scaledWidth, height: scaledHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
return newImage ?? self
}
}
|
ff9c4fb7fa8968b4b5770c1fc6089635
| 35.384615 | 134 | 0.630374 | false | false | false | false |
SwiftGFX/SwiftMath
|
refs/heads/master
|
Sources/String+Math.swift
|
bsd-2-clause
|
1
|
//
// String+Math.swift
// SwiftMath
//
// Created by Andrey Volodin on 02.11.16.
//
//
import Foundation
internal extension String {
var floatArray: [Float] {
let ignoredCharacters = CharacterSet(charactersIn: "{} ,")
let components = self.components(separatedBy: ignoredCharacters)
return components.filter { $0.count > 0 }
.map { return Float($0)! }
}
}
public extension Vector2f {
// String should be {p.x, p.y}
init(_ string: String) {
let components = string.floatArray
if components.count == 2 {
self.init(components[0], components[1])
} else {
self.init()
}
}
}
public extension Rect {
// String should be {o.x, o.y, s.w, s.h}
init(_ string: String) {
let components = string.floatArray
if components.count == 2 {
self.init(origin: Point(components[0], components[1]),
size: Size(components[2], components[3]))
} else {
self.init()
}
}
}
|
7e94cc614ad6eeb24118a4c9f6e62899
| 23.727273 | 72 | 0.539522 | false | false | false | false |
jverkoey/FigmaKit
|
refs/heads/main
|
Sources/FigmaKit/Node/SliceNode.swift
|
apache-2.0
|
1
|
extension Node {
public final class SliceNode: Node {
/// Bounding box of the node in absolute space coordinates.
public let absoluteBoundingBox: FigmaKit.Rectangle
/// An array of export settings representing images to export from the node.
public let exportSettings: [ExportSetting]
/// The top two rows of a matrix that represents the 2D transform of this node relative to its parent.
///
/// The bottom row of the matrix is implicitly always (0, 0, 1). Use to transform coordinates in geometry.
public let relativeTransform: Transform
/// Width and height of element.
///
/// This is different from the width and height of the bounding box in that the absolute bounding box
/// represents the element after scaling and rotation.
public let size: FigmaKit.Vector
private enum CodingKeys: String, CodingKey {
case absoluteBoundingBox
case exportSettings
case relativeTransform
case size
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.absoluteBoundingBox = try keyedDecoder.decode(FigmaKit.Rectangle.self, forKey: .absoluteBoundingBox)
self.exportSettings = try keyedDecoder.decodeIfPresent([ExportSetting].self, forKey: .exportSettings) ?? []
self.relativeTransform = try keyedDecoder.decode(Transform.self, forKey: .relativeTransform)
self.size = try keyedDecoder.decode(FigmaKit.Vector.self, forKey: .size)
try super.init(from: decoder)
}
public override func encode(to encoder: Encoder) throws {
fatalError("Not yet implemented")
}
override var contentDescription: String {
return """
- absoluteBoundingBox: \(absoluteBoundingBox)
- exportSettings:
\(exportSettings.description.indented(by: 2))
- relativeTransform: \(relativeTransform)
- size: \(size)
"""
}
}
}
|
784fb4d407d4baafddccec49146074a6
| 39.22 | 113 | 0.683739 | false | false | false | false |
ozbe/dwift
|
refs/heads/master
|
Dwift.playground/contents.swift
|
mit
|
1
|
import UIKit
// Replace token & pin for uat
let token = ""
let pin = ""
//:
//: Constants
//:
class Paths {
static let host = "https://uat.dwolla.com/oauth/rest"
static let transactionsSubpath = "/transactions"
static let sendSubpath = transactionsSubpath + "/send"
}
class ErrorMessages {
static let InvalidAccessToken = "Invalid access token"
static let InsufficientBalance = "Insufficient balance"
static let InvalidAccountPin = "Invalid account PIN"
}
class RequestKeys {
static let DestinationId = "destinationId"
static let Pin = "pin"
static let Amount = "amount"
static let DestinationType = "destinationType"
static let FundsSource = "fundsSource"
static let Notes = "notes"
static let AssumeCosts = "assumeCosts"
static let AdditionalFees = "additionalFees"
static let Metadata = "metadata"
static let AssumeAdditionalFees = "assumeAdditionalFees"
static let FacilitatorAmount = "facilitatorAmount"
}
class ResponseKeys {
static let Success = "Success"
static let Message = "Message"
static let Response = "Response"
}
//:
//: Enums
//:
enum TransactionStatus {
case Pending
case Processed
case Failed
case Cancelled
case Reclaimed
}
enum TransactionType {
case MoneySent
case MoneyReceived
case Deposit
case Withdrawal
case Fee
}
enum DestinationType {
case Dwolla
case Email
case Phone
case Twitter
case Facebook
case LinkedIn
}
enum Scopes {
case Send
}
enum HttpMethod: String {
case GET = "GET"
case POST = "POST"
}
//:
//: Structs
//:
struct JsonRequest {
var url: String
var method: HttpMethod
var headers: [String: String?]?
var params: [String: String]?
var body: [String: AnyObject]?
init(url: String,
method: HttpMethod = .GET,
headers: [String: String?]? = nil,
params: [String: String]? = nil,
body: [String: AnyObject]? = nil) {
self.url = url
self.method = method
self.headers = headers
self.params = params
self.body = body
}
}
struct JsonResponse {
let status: Int
let headers: [String: String]? = nil
let body: [String: AnyObject]? = nil
}
struct Response<T> {
let success: Bool
let message: String
let response: T?
}
struct Entity {
let id: String
let name: String
}
struct SendRequest {
let destinationId: String
let pin: String
let amount: Double
let destinationType: DestinationType?
let fundsSource: String?
let notes: String?
let assumeCosts: Bool?
let additionalFeeds: Bool?
let metadata: [String: String]?
let assumeAdditionalFees: Bool?
let facilitatorAmount: Bool?
init(destinationId: String,
pin: String,
amount: Double,
destinationType: DestinationType? = nil,
fundsSource: String? = nil,
notes: String? = nil,
assumeCosts: Bool? = nil,
additionalFeeds: Bool? = nil,
metadata: [String: String]? = nil,
assumeAdditionalFees: Bool? = nil,
facilitatorAmount: Bool? = nil) {
self.destinationId = destinationId
self.pin = pin
self.amount = amount
self.destinationType = destinationType
self.fundsSource = fundsSource
self.notes = notes
self.assumeCosts = assumeCosts
self.additionalFeeds = additionalFeeds
self.metadata = metadata
self.assumeAdditionalFees = assumeAdditionalFees
self.facilitatorAmount = facilitatorAmount
}
}
//:
//: ## Protocols
//:
protocol ToJson {
func toJson() -> [String: AnyObject]
}
protocol ToJsonValue {
func toJsonValue() -> String
}
protocol JsonClient {
func execute(request: JsonRequest) -> (JsonResponse?, NSError?)
}
protocol DwollaApi {
func send(request: SendRequest) -> Response<Double>
}
//:
//: ## Extensions
//:
// From good 'ol stackoverflow
extension Dictionary {
init(_ pairs: [Element]) {
self.init()
for (k, v) in pairs {
self[k] = v
}
}
func map<OutKey: Hashable, OutValue>(transform: Element -> (OutKey, OutValue)) -> [OutKey: OutValue] {
return Dictionary<OutKey, OutValue>(Swift.map(self, transform))
}
func filter(includeElement: Element -> Bool) -> [Key: Value] {
return Dictionary(Swift.filter(self, includeElement))
}
}
extension TransactionStatus: ToJsonValue {
func toJsonValue() -> String {
switch self {
case .Cancelled:
return "cancelled"
default:
return ""
}
}
}
extension DestinationType: ToJsonValue {
func toJsonValue() -> String {
switch self {
case .Dwolla:
return "dwolla"
default:
return ""
}
}
}
extension SendRequest: ToJson {
func toJson() -> [String : AnyObject] {
return [
RequestKeys.DestinationId: self.destinationId,
RequestKeys.Pin: self.pin,
RequestKeys.Amount: self.amount,
RequestKeys.DestinationType: getOptionalJson(self.destinationType)
]
}
private func getOptionalJson(value: Optional<ToJsonValue>) -> String {
return value?.toJsonValue() ?? ""
}
}
//:
//: ## Classes
//:
class NSURLRequestBuilder {
var urlRequest = NSMutableURLRequest()
func setUrl(url: String?) -> NSURLRequestBuilder {
if let url = url {
urlRequest.URL = NSURL(string: url)
} else {
urlRequest.URL = nil
}
return self
}
func setMethod(method: HttpMethod) -> NSURLRequestBuilder {
urlRequest.HTTPMethod = method.rawValue
return self
}
func setHeaders(headers: [String: String?]?) -> NSURLRequestBuilder {
if let headers = headers {
for header in headers {
urlRequest.setValue(header.1, forHTTPHeaderField: header.0)
}
} else {
urlRequest.allHTTPHeaderFields = nil
}
return self
}
func setParams(params: [String: String]?, encode: Bool = true) -> NSURLRequestBuilder {
// TODO
// encode?
// fun?
// may have to set url in build with params
return self
}
func setBody(body: [String: AnyObject]?, error: NSErrorPointer) -> NSURLRequestBuilder {
if let body = body,
let data = NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.allZeros, error: error) {
setBody(data)
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
} else {
setBody(nil)
}
return self
}
func setBody(body: NSData?) -> NSURLRequestBuilder {
urlRequest.HTTPBody = body
urlRequest.setValue(body?.length.description, forHTTPHeaderField: "Content-Length")
return self
}
func setJsonRequest(jsonRequest: JsonRequest, error: NSErrorPointer) -> NSURLRequestBuilder {
return self
.setUrl(jsonRequest.url)
.setMethod(jsonRequest.method)
.setHeaders(jsonRequest.headers)
.setParams(jsonRequest.params)
.setBody(jsonRequest.body, error: error)
}
func reset() {
urlRequest = NSMutableURLRequest()
}
func build() -> NSURLRequest {
return urlRequest.copy() as! NSURLRequest
}
}
class NSJsonClient: JsonClient {
let dummyError = NSError(domain: "", code: 1, userInfo: nil)
let urlBuilder = NSURLRequestBuilder()
func execute(request: JsonRequest) -> (JsonResponse?, NSError?) {
switch createURLRequest(request) {
case let (_, .Some(error)):
return (nil, error)
case let (.Some(urlRequest), _):
return execute(urlRequest)
default:
return (nil, dummyError)
}
}
private func createURLRequest(jsonRequest: JsonRequest) -> (NSURLRequest?, NSError?) {
var error: NSError?
if let url = NSURL(string: jsonRequest.url) {
let urlRequest = urlBuilder
.setJsonRequest(jsonRequest, error: &error)
.build()
return (urlRequest, error)
} else {
return (nil, dummyError)
}
}
private func execute(urlRequest: NSURLRequest) -> (JsonResponse?, NSError?) {
switch performRequest(urlRequest) {
case let (_, _, error) where error != nil:
return (nil, error)
case let (.Some(data), .Some(urlResponse), _) where urlResponse is NSHTTPURLResponse:
return createJsonResponse(data, response: urlResponse as! NSHTTPURLResponse)
default:
return (nil, dummyError)
}
}
private func performRequest(urlRequest: NSURLRequest) -> (NSData?, NSURLResponse?, NSError?) {
let semaphore = dispatch_semaphore_create(0);
var data: NSData? = nil
var response: NSURLResponse? = nil
var error: NSError? = nil
NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (taskData, taskResponse, taskError) -> Void in
data = taskData
response = taskResponse
error = taskError
dispatch_semaphore_signal(semaphore);
}).resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return (data, response, error)
}
private func createJsonResponse(data: NSData, response: NSHTTPURLResponse) -> (JsonResponse?, NSError?) {
var error: NSError?
let headers = response.allHeaderFields.map { (k, v) in (k as! String, v as! String) }
let body = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as! Dictionary<String, AnyObject>
return (JsonResponse(status: response.statusCode, headers: headers, body: body), error)
}
}
class DwollaApiV2: DwollaApi {
let headers: [String: String?]
let client: JsonClient
let host: String
convenience init(token: String) {
self.init(token: token, host: Paths.host, client: NSJsonClient())
}
init(token: String,
host: String,
client: JsonClient) {
headers = [
"Authorization": "Bearer \(token)"
]
self.host = host
self.client = client
}
func send(request: SendRequest) -> Response<Double> {
return post(Paths.sendSubpath, body: request.toJson()) {
response in
if let response = response as? Double {
return response
}
return nil
}
}
private func get<T>(subPath: String, params: [String: String]?, responseTransform: (AnyObject?) -> T?) -> Response<T> {
let jsonRequest = JsonRequest(url: host + subPath, method: .GET, headers: headers, params: params)
return execute(jsonRequest, responseTransform: responseTransform)
}
private func post<T>(subPath: String, body: [String: AnyObject], responseTransform: (AnyObject?) -> T?) -> Response<T> {
let jsonRequest = JsonRequest(url: host + subPath, method: .POST, headers: headers, body: body)
return execute(jsonRequest, responseTransform: responseTransform)
}
private func execute<T>(jsonRequest: JsonRequest, responseTransform: (AnyObject?) -> T?) -> Response<T> {
switch client.execute(jsonRequest) {
case let (_, .Some(error)):
return Response(success: false, message: error.description, response: nil)
case let (.Some(jsonResponse), _):
return parse(jsonResponse.body, transform: responseTransform)
default:
return Response(success: false, message: "Unexpected error", response: nil)
}
}
private func parse<T>(body: [String: AnyObject]?, transform: (AnyObject?) -> T?) -> Response<T> {
if let body = body,
let success = body[ResponseKeys.Success] as? Bool,
let message = body[ResponseKeys.Message] as? String,
let response = transform(body[ResponseKeys.Response]) {
return Response(success: success, message: message, response: response)
} else {
return Response(success: false, message: "Unknown error", response: nil)
}
}
}
//:
//: ## Send
//:
// happy path
let client = DwollaApiV2(token: token)
let sendRequest = SendRequest(destinationId: "812-741-6790", pin: pin, amount: 0.01)
let sendResponse = client.send(sendRequest)
// invalid pin
// invalid amount
|
2da3bc90a49e53ad0b50741e5fe8569f
| 27.050328 | 152 | 0.610344 | false | false | false | false |
MKGitHub/UIPheonix
|
refs/heads/master
|
Sources/UIPBaseViewController.swift
|
apache-2.0
|
1
|
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The base view controller protocol.
*/
protocol UIPBaseViewControllerProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
}
#if os(iOS) || os(tvOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:UIViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:String?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:"\(self)", bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
override func willMove(toParent parent:UIViewController?)
{
super.willMove(toParent:parent)
// `self` view controller is being removed
// i.e. we are moving back to our parent
if (parent == nil)
{
if let parentVC = parentVC,
let dict = dismissInstance()
{
parentVC.childViewController(self, willDismissWithAttributes:dict)
}
}
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#elseif os(macOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:NSViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:NSNib.Name?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:NSNib.Name("\(self)"), bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#endif
|
6e56b0a431c05d7ef451e2df71e40773
| 30.110204 | 139 | 0.610076 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/serialize-and-deserialize-bst.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/serialize-and-deserialize-bst/
*
*
*/
// Date: Sun Jun 28 11:39:57 PDT 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
/// Same as https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
class Codec {
// Encodes a tree to a single string.
func serialize(_ root: TreeNode?) -> String {
var ret: [String] = []
var queue = [root]
while queue.isEmpty == false {
let node = queue.removeFirst()
if let node = node {
ret.append("\(node.val)")
queue.insert(node.right, at: 0)
queue.insert(node.left, at: 0)
} else {
ret.append("null")
}
}
print("\(ret)")
return ret.joined(separator: ",")
}
// Decodes your encoded data to tree.
func deserialize(_ data: String) -> TreeNode? {
func build(_ data: [String], at index: inout Int) -> TreeNode? {
let content = data[index]
index += 1
if content == "null" { return nil }
let node = TreeNode(Int(content)!)
node.left = build(data, at: &index)
node.right = build(data, at: &index)
return node
}
let data = data.split(separator: ",").map { String($0) }
var index = 0
let node = build(data, at: &index)
return node
}
}
/**
* Your Codec object will be instantiated and called as such:
* let obj = Codec()
* val s = obj.serialize(root)
* let ans = obj.serialize(s)
*/
|
d9a7de9f5ecba5c72ea4cf1eeeb54745
| 27.384615 | 80 | 0.520867 | false | false | false | false |
noppoMan/aws-sdk-swift
|
refs/heads/main
|
Sources/Soto/Services/Chime/Chime_Error.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Chime
public struct ChimeErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case forbiddenException = "ForbiddenException"
case notFoundException = "NotFoundException"
case resourceLimitExceededException = "ResourceLimitExceededException"
case serviceFailureException = "ServiceFailureException"
case serviceUnavailableException = "ServiceUnavailableException"
case throttledClientException = "ThrottledClientException"
case unauthorizedClientException = "UnauthorizedClientException"
case unprocessableEntityException = "UnprocessableEntityException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Chime
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// You don't have permissions to perform the requested operation.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// The input parameters don't match the service's restrictions.
public static var badRequestException: Self { .init(.badRequestException) }
/// The request could not be processed because of conflict in the current state of the resource.
public static var conflictException: Self { .init(.conflictException) }
/// The client is permanently forbidden from making the request. For example, when a user tries to create an account from an unsupported Region.
public static var forbiddenException: Self { .init(.forbiddenException) }
/// One or more of the resources in the request does not exist in the system.
public static var notFoundException: Self { .init(.notFoundException) }
/// The request exceeds the resource limit.
public static var resourceLimitExceededException: Self { .init(.resourceLimitExceededException) }
/// The service encountered an unexpected error.
public static var serviceFailureException: Self { .init(.serviceFailureException) }
/// The service is currently unavailable.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The client exceeded its request rate limit.
public static var throttledClientException: Self { .init(.throttledClientException) }
/// The client is not currently authorized to make the request.
public static var unauthorizedClientException: Self { .init(.unauthorizedClientException) }
/// The request was well-formed but was unable to be followed due to semantic errors.
public static var unprocessableEntityException: Self { .init(.unprocessableEntityException) }
}
extension ChimeErrorType: Equatable {
public static func == (lhs: ChimeErrorType, rhs: ChimeErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ChimeErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
d10faa85556e217ba28ad13335b65e14
| 45.241379 | 148 | 0.701715 | false | false | false | false |
spritekitbook/flappybird-swift
|
refs/heads/master
|
Chapter 10/Finish/FloppyBird/FloppyBird/Settings.swift
|
apache-2.0
|
7
|
//
// Settings.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/27/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import Foundation
class Settings {
static let sharedInstance = Settings()
// MARK: - Private class constants
private let defaults = UserDefaults.standard
private let keyFirstRun = "First Run"
private let keyBestScore = "Best Score"
// MARK: - Init
init() {
if defaults.object(forKey: keyFirstRun) == nil {
firstLaunch()
}
}
private func firstLaunch() {
defaults.set(0, forKey: keyBestScore)
defaults.set(false, forKey: keyFirstRun)
defaults.synchronize()
}
// MARK: - Public saving methods
func saveBest(score: Int) {
defaults.set(score, forKey: keyBestScore)
defaults.synchronize()
}
// MARK: - Public retrieving methods
func getBestScore() -> Int {
return defaults.integer(forKey: keyBestScore)
}
}
|
acff42b37a8dee5326815a31815289ee
| 21.933333 | 57 | 0.600775 | false | false | false | false |
anto0522/AdMate
|
refs/heads/AppStore_Version
|
Pods/SQLite.swift/SQLite/Extensions/FTS5.swift
|
mit
|
3
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.
//
extension Module {
@warn_unused_result public static func FTS5(config: FTS5Config) -> Module {
return Module(name: "fts5", arguments: config.arguments())
}
}
/// Configuration for the [FTS5](https://www.sqlite.org/fts5.html) extension.
///
/// **Note:** this is currently only applicable when using SQLite.swift together with a FTS5-enabled version
/// of SQLite.
public class FTS5Config : FTSConfig {
public enum Detail : CustomStringConvertible {
/// store rowid, column number, term offset
case Full
/// store rowid, column number
case Column
/// store rowid
case None
public var description: String {
switch self {
case Full: return "full"
case Column: return "column"
case None: return "none"
}
}
}
var detail: Detail?
var contentRowId: Expressible?
var columnSize: Int?
override public init() {
}
/// [External Content Tables](https://www.sqlite.org/fts5.html#section_4_4_2)
public func contentRowId(column: Expressible) -> Self {
self.contentRowId = column
return self
}
/// [The Columnsize Option](https://www.sqlite.org/fts5.html#section_4_5)
public func columnSize(size: Int) -> Self {
self.columnSize = size
return self
}
/// [The Detail Option](https://www.sqlite.org/fts5.html#section_4_6)
public func detail(detail: Detail) -> Self {
self.detail = detail
return self
}
override func options() -> Options {
var options = super.options()
options.append("content_rowid", value: contentRowId)
if let columnSize = columnSize {
options.append("columnsize", value: Expression<Int>(value: columnSize))
}
options.append("detail", value: detail)
return options
}
override func formatColumnDefinitions() -> [Expressible] {
return columnDefinitions.map { definition in
if definition.options.contains(.unindexed) {
return " ".join([definition.0, Expression<Void>(literal: "UNINDEXED")])
} else {
return definition.0
}
}
}
}
|
da047447ada7174e8c37d97a17638d00
| 34.381443 | 108 | 0.656469 | false | true | false | false |
28stephlim/Heartbeat-Analyser
|
refs/heads/master
|
Music/VoiceMemos/VoiceMemos/Model/CoreDataStack.swift
|
mit
|
5
|
//
// CoreDataStack.swift
// VoiceMemos
//
// Created by Zhouqi Mo on 2/20/15.
// Copyright (c) 2015 Zhouqi Mo. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
var context:NSManagedObjectContext
var psc:NSPersistentStoreCoordinator
var model:NSManagedObjectModel
var store:NSPersistentStore?
init() {
let bundle = NSBundle.mainBundle()
let modelURL =
bundle.URLForResource("VoiceMemos", withExtension:"momd")
model = NSManagedObjectModel(contentsOfURL: modelURL!)!
psc = NSPersistentStoreCoordinator(managedObjectModel:model)
context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = psc
let documentsURL = applicationDocumentsDirectory()
let storeURL = documentsURL.URLByAppendingPathComponent("VoiceMemos.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
do {
try store = psc.addPersistentStoreWithType(NSSQLiteStoreType,
configuration: nil,
URL: storeURL,
options: options)
} catch {
debugPrint("Error adding persistent store: \(error)")
abort()
}
}
func saveContext() {
if context.hasChanges {
do {
try context.save()
}
catch {
debugPrint("Could not save: \(error)")
}
}
}
func applicationDocumentsDirectory() -> NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}
}
|
c107104140c9ced10461a77f1ed950ad
| 28 | 120 | 0.613685 | false | false | false | false |
charles-oder/Project-Euler-Swift
|
refs/heads/master
|
ProjectEulerSwift/Palindrome.swift
|
apache-2.0
|
1
|
//
// Palindrome.swift
// ProjectEulerSwift
//
// Created by Charles Oder on 4/5/15.
// Copyright (c) 2015 Charles Oder. All rights reserved.
//
import Foundation
class Palindrome {
class func CreateDigitList(value: Int) -> NSMutableArray {
var n = value
var list: NSMutableArray = NSMutableArray()
while n > 0 {
var digit = n % 10
list.insertObject(digit, atIndex: 0)
n /= 10
}
return list
}
class func isPalindrome(value: Int) -> Bool {
let list = CreateDigitList(value)
var reversedList = NSMutableArray()
for n in list {
reversedList.insertObject(n, atIndex: 0)
}
return list == reversedList
}
class func findLargestPalindromeOfProducts(numberLength: Int) -> Int {
let max = Int(pow(10, Double(numberLength)))
var largestPalidrome = 0
for var x = 1; x < max; x++ {
for var y = 1; y < max; y++ {
let product = x * y
if isPalindrome(product) && (product > largestPalidrome) {
largestPalidrome = product
}
}
}
return largestPalidrome
}
}
|
5b98f50de1525829fa2c71d4f223f4ea
| 25.574468 | 74 | 0.538462 | false | false | false | false |
appsandwich/ppt2rk
|
refs/heads/master
|
ppt2rk/RunkeeperGPXUploadParser.swift
|
mit
|
1
|
//
// RunkeeperGPXUploadParser.swift
// ppt2rk
//
// Created by Vinny Coyne on 18/05/2017.
// Copyright © 2017 App Sandwich Limited. All rights reserved.
//
import Foundation
class RunkeeperGPXUploadParser {
var data: Data? = nil
init(_ data: Data) {
self.data = data
}
public func parseWithHandler(_ handler: @escaping (RunkeeperActivity?) -> Void) {
guard let data = self.data else {
handler(nil)
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
handler(nil)
return
}
guard let dictionary = json as? Dictionary<String, Any> else {
handler(nil)
return
}
if let error = dictionary["error"] as? String, error.characters.count > 0 {
handler(nil)
return
}
guard let trackImportData = dictionary["trackImportData"] as? Dictionary<String, Any> else {
handler(nil)
return
}
guard let duration = trackImportData["duration"] as? Double, let startTime = trackImportData["startTime"] as? Int, let trackPoints = trackImportData["trackPoints"] as? Array< Dictionary<String, Any> >, trackPoints.count > 0 else {
handler(nil)
return
}
// Thanks to https://medium.com/@ndcrandall/automating-gpx-file-imports-in-runkeeper-f446917f8a19
//str << "#{point['type']},#{point['latitude']},#{point['longitude']},#{point['deltaTime']},0,#{point['deltaDistance']};"
var totalDistance = 0.0
let runkeeperString = trackPoints.reduce("") { (string, trackPoint) -> String in
guard let type = trackPoint["type"] as? String, let latitude = trackPoint["latitude"] as? Double, let longitude = trackPoint["longitude"] as? Double, let deltaTime = trackPoint["deltaTime"] as? Double, let deltaDistance = trackPoint["deltaDistance"] as? Double else {
return string
}
let trackPointString = "\(type),\(latitude),\(longitude),\(Int(deltaTime)),0,\(deltaDistance);"
totalDistance += deltaDistance
return string + trackPointString
}
let date = Date(timeIntervalSince1970: Double(startTime) / 1000.0)
let runkeeperActivity = RunkeeperActivity(id: -1, timestamp: date, distance: "\(totalDistance)", duration: "\(duration / 1000.0)", day: "")
runkeeperActivity.convertedFromGPXString = runkeeperString
handler(runkeeperActivity)
}
}
|
9c99105a12c040f14986c02e991b3756
| 34.217949 | 279 | 0.573353 | false | false | false | false |
cristianames92/PortalView
|
refs/heads/master
|
Sources/Components/Progress.swift
|
mit
|
2
|
//
// Progress.swift
// PortalView
//
// Created by Cristian Ames on 4/11/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
public func progress<MessageType>(
progress: ProgressCounter = ProgressCounter.initial,
style: StyleSheet<ProgressStyleSheet> = ProgressStyleSheet.defaultStyleSheet,
layout: Layout = layout()) -> Component<MessageType> {
return .progress(progress, style, layout)
}
// MARK:- Style sheet
public enum ProgressContentType {
case color(Color)
case image(Image)
}
public struct ProgressStyleSheet {
public static let defaultStyleSheet = StyleSheet<ProgressStyleSheet>(component: ProgressStyleSheet())
public var progressStyle: ProgressContentType
public var trackStyle: ProgressContentType
public init(
progressStyle: ProgressContentType = .color(defaultProgressColor),
trackStyle: ProgressContentType = .color(defaultTrackColor)) {
self.progressStyle = progressStyle
self.trackStyle = trackStyle
}
}
public func progressStyleSheet(configure: (inout BaseStyleSheet, inout ProgressStyleSheet) -> ()) -> StyleSheet<ProgressStyleSheet> {
var base = BaseStyleSheet()
var custom = ProgressStyleSheet()
configure(&base, &custom)
return StyleSheet(component: custom, base: base)
}
|
502f5f998c329111ee3ac9f3bbb7ef4f
| 28.173913 | 133 | 0.716841 | false | false | false | false |
gkaimakas/SwiftValidatorsReactiveExtensions
|
refs/heads/master
|
Example/SwiftValidatorsReactiveExtensions/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SwiftValidatorsReactiveExtensions
//
// Created by gkaimakas on 03/31/2017.
// Copyright (c) 2017 gkaimakas. All rights reserved.
//
import ReactiveCocoa
import ReactiveSwift
import Result
import SwiftValidators
import SwiftValidatorsReactiveExtensions
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let viewModel = FormViewModel()
var inputs: [FieldViewModel] = []
var submitView: SumbitView!
var headerView: HeaderView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
inputs = [
viewModel.emailField,
viewModel.passwordField
]
inputs.enumerated().forEach { (offset: Int, element: FieldViewModel) in
element.hasErrors
.producer
.startWithValues({ (value: Bool) in
if value == true && self.tableView.numberOfRows(inSection: offset) == 2 {
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(item: 2, section: offset)], with: .automatic)
self.tableView.endUpdates()
}
if value == false && self.tableView.numberOfRows(inSection: offset) == 3 {
self.tableView.beginUpdates()
self.tableView.deleteRows(at: [IndexPath(item: 2, section: offset)], with: .automatic)
self.tableView.endUpdates()
}
})
}
headerView = HeaderView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 256))
headerView.viewModel = viewModel
submitView = SumbitView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 80))
submitView.credentialsAction = viewModel.submit
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 20
tableView.tableHeaderView = headerView
tableView.tableFooterView = submitView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return inputs.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2 + ( inputs[section].hasErrors.value == true ? 1 : 0)
}
if section == 1 {
return 2 + ( inputs[section].hasErrors.value == true ? 1 : 0)
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.item == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: HintTableViewCell.identifier) as! HintTableViewCell
cell.hint = inputs[indexPath.section].hint.producer
return cell
}
if indexPath.item == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: TextInputTableViewCell.identifier) as! TextInputTableViewCell
cell.validatingProperty = inputs[indexPath.section].validatingProperty
if indexPath.section == 0 {
cell.textField.keyboardType = .emailAddress
} else {
cell.textField.keyboardType = .default
}
cell.textField.isSecureTextEntry = (indexPath.section == 1)
return cell
}
if indexPath.item == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: ErrorTableViewCell.identifier) as! ErrorTableViewCell
cell.validatingProperty = inputs[indexPath.section].validatingProperty
return cell
}
return UITableViewCell()
}
}
|
732853b1b5a7ae0066439a930673d2f0
| 34.550847 | 130 | 0.599762 | false | false | false | false |
jpush/jchat-swift
|
refs/heads/master
|
JChat/Src/Utilites/3rdParty/InputBar/SAIToolboxItem.swift
|
mit
|
1
|
//
// SAIToolboxItem.swift
// SAC
//
// Created by SAGESSE on 9/15/16.
// Copyright © 2016-2017 SAGESSE. All rights reserved.
//
import UIKit
@objc open class SAIToolboxItem: NSObject {
open var name: String
open var identifier: String
open var image: UIImage?
open var highlightedImage: UIImage?
public init(_ identifier: String, _ name: String, _ image: UIImage?, _ highlightedImage: UIImage? = nil) {
self.identifier = identifier
self.name = name
self.image = image
self.highlightedImage = highlightedImage
}
}
|
6493945e9b0fe36100709d0fd39d0ca5
| 22.64 | 110 | 0.64467 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/ConversationList/ListContent/ConversationListContentController/ConversationListHeaderView.swift
|
gpl-3.0
|
1
|
// 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 UIKit
import WireCommonComponents
extension UIView {
func rotate(to angleInDegrees: CGFloat) {
transform = transform.rotated(by: angleInDegrees / 180 * CGFloat.pi)
}
}
typealias TapHandler = (_ collapsed: Bool) -> Void
final class ConversationListHeaderView: UICollectionReusableView {
private let spacing: CGFloat = 8
var folderBadge: Int = 0 {
didSet {
let isHidden = folderBadge <= 0
badgeView.updateCollapseConstraints(isCollapsed: isHidden)
badgeView.isHidden = isHidden
badgeMarginConstraint?.constant = isHidden ? 0 : -spacing
badgeWidthConstraint?.constant = isHidden ? 0 : 28
let text: String?
switch folderBadge {
case 1...99:
text = String(folderBadge)
case 100...:
text = "99+"
default:
text = nil
}
badgeView.textLabel.text = text
}
}
var collapsed = false {
didSet {
guard collapsed != oldValue else { return }
// update rotation
if collapsed {
arrowIconImageView.rotate(to: -90)
} else {
arrowIconImageView.transform = .identity
}
}
}
var tapHandler: TapHandler?
private var badgeMarginConstraint: NSLayoutConstraint?
private var badgeWidthConstraint: NSLayoutConstraint?
private let titleLabel: UILabel = {
let label = DynamicFontLabel(
fontSpec: .smallRegularFont,
color: .white)
label.textColor = SemanticColors.Label.textConversationListCell
label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
return label
}()
let badgeView: RoundedTextBadge = {
let margin: CGFloat = 12
let roundedTextBadge = RoundedTextBadge(contentInset: UIEdgeInsets(top: 2, left: margin, bottom: 2, right: margin), font: FontSpec(.medium, .semibold).font!)
roundedTextBadge.textLabel.textColor = SemanticColors.Label.conversationListTableViewCellBadge
roundedTextBadge.backgroundColor = SemanticColors.View.backgroundConversationListTableViewCellBadge
roundedTextBadge.isHidden = true
return roundedTextBadge
}()
/// display title of the header
var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
override var accessibilityLabel: String? {
get {
return title
}
set {
super.accessibilityLabel = newValue
}
}
override var accessibilityValue: String? {
get {
typealias ConversationListHeader = L10n.Accessibility.ConversationsListHeader
let state = collapsed
? ConversationListHeader.CollapsedButton.description
: ConversationListHeader.ExpandedButton.description
return state + " \(folderBadge)"
}
set {
super.accessibilityValue = newValue
}
}
private let arrowIconImageView: UIImageView = {
let imageView = UIImageView()
imageView.tintColor = SemanticColors.Label.textConversationListCell
imageView.setTemplateIcon(.downArrow, size: .tiny)
return imageView
}()
required override init(frame: CGRect) {
super.init(frame: frame)
[titleLabel, arrowIconImageView, badgeView].forEach(addSubview)
createConstraints()
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggledCollapsed)))
isAccessibilityElement = true
shouldGroupAccessibilityChildren = true
backgroundColor = SemanticColors.View.backgroundConversationList
addBorder(for: .bottom)
}
@objc
private func toggledCollapsed() {
let newCollaped = !collapsed
UIView.animate(withDuration: 0.2, animations: {
self.collapsed = newCollaped
})
tapHandler?(newCollaped)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createConstraints() {
[arrowIconImageView, titleLabel].prepareForLayout()
arrowIconImageView.setContentCompressionResistancePriority(.required, for: .horizontal)
badgeMarginConstraint = titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: badgeView.leadingAnchor, constant: 0)
badgeWidthConstraint = badgeView.widthAnchor.constraint(greaterThanOrEqualToConstant: 0)
NSLayoutConstraint.activate([
arrowIconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: CGFloat.ConversationList.horizontalMargin),
arrowIconImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
titleLabel.leadingAnchor.constraint(equalTo: arrowIconImageView.trailingAnchor, constant: spacing),
badgeMarginConstraint!,
badgeView.heightAnchor.constraint(equalToConstant: 20),
badgeWidthConstraint!,
badgeView.centerYAnchor.constraint(equalTo: centerYAnchor),
badgeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -CGFloat.ConversationList.horizontalMargin)
]
)
}
}
|
091e4a5554a75833cbabb3c0e234ca96
| 32.05291 | 165 | 0.656315 | false | false | false | false |
DrabWeb/Sudachi
|
refs/heads/master
|
Sudachi/Sudachi/SCPreferencesViewController.swift
|
gpl-3.0
|
1
|
//
// SCPreferencesViewController.swift
// Sudachi
//
// Created by Seth on 2016-04-17.
//
import Cocoa
class SCPreferencesViewController: NSViewController {
/// The main window of this view controller
var preferencesWindow : NSWindow = NSWindow();
/// The label for the theme popup button
@IBOutlet var themeLabel: NSTextField!
/// The popup button for setting the theme
@IBOutlet var themePopupButton: NSPopUpButton!
/// When we click themePopupButton...
@IBAction func themePopupButtonInteracted(sender: AnyObject) {
// If we clicked the "Add from folder..." item...
if(themePopupButton.selectedItem?.title == "Add from folder...") {
// Prompt to install a theme
SCThemingEngine().defaultEngine().promptToInstallTheme();
// Reload the menu items
addThemePopupButtonItems();
}
}
/// When we click the "Apply" button...
@IBAction func applyButtonPressed(sender: AnyObject) {
// Save the preferences
savePreferences();
// Close the window
preferencesWindow.close();
}
/// The label to tell the user they have to restart Sudachi for visual changes to take effect
@IBOutlet var restartLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
// Style the window
styleWindow();
// Load the theme
loadTheme();
// Add the theme popup button menu items
addThemePopupButtonItems();
}
/// Puts the entered preferences values into the global preferences object
func savePreferences() {
// Set the values
// If the chosen theme was Default...
if(themePopupButton.selectedItem!.title == "Default") {
// Set the theme path to ""
(NSApplication.sharedApplication().delegate as! AppDelegate).preferences.themePath = "";
}
// If we chose any other theme...
else {
// Set the theme path to the chosen item's path
(NSApplication.sharedApplication().delegate as! AppDelegate).preferences.themePath = NSHomeDirectory() + "/Library/Application Support/Sudachi/themes/" + themePopupButton.selectedItem!.title + ".sctheme";
}
}
/// Selects the current theme for themePopupButton
func selectCurrentTheme() {
// For every item in themePopupButton's item titles...
for(currentItemIndex, currentItemTitle) in themePopupButton.itemTitles.enumerate() {
// If the current item's title matches the title of the current theme...
if(currentItemTitle == NSString(string: SCThemingEngine().defaultEngine().currentThemePath).lastPathComponent.stringByReplacingOccurrencesOfString("." + NSString(string: SCThemingEngine().defaultEngine().currentThemePath).pathExtension, withString: "")) {
// Select this item
themePopupButton.selectItemAtIndex(currentItemIndex);
// Stop the loop
return;
}
// If the current item's title is Default and the theme folder path is blank...
if(currentItemTitle == "Default" && SCThemingEngine().defaultEngine().currentThemePath == "") {
// Select this item
themePopupButton.selectItemAtIndex(currentItemIndex);
// Stop the loop
return;
}
}
}
/// Sets up the menu items in themePopupButton, and then selects the current theme
func addThemePopupButtonItems() {
// Remove all the current menu items
themePopupButton.menu?.removeAllItems();
// Add the "Default" menu item
themePopupButton.addItemWithTitle("Default");
do {
// For every file in the themes folder of the Sudachi application support folder...
for(_, currentFile) in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSHomeDirectory() + "/Library/Application Support/Sudachi/themes").enumerate() {
// If the current file's extension is .sctheme and its a folder...
if(NSString(string: currentFile).pathExtension == "sctheme" && SCFileUtilities().isFolder(NSHomeDirectory() + "/Library/Application Support/Sudachi/themes/" + currentFile)) {
// Add the current theme folder to them menu, without the extension
themePopupButton.addItemWithTitle(currentFile.stringByReplacingOccurrencesOfString("." + NSString(string: currentFile).pathExtension, withString: ""));
}
}
}
catch let error as NSError {
// Print the error description
print("SCPreferencesViewController: Error reading themes directory, \(error.description)");
}
// Add the "Add from folder..." menu item
themePopupButton.addItemWithTitle("Add from folder...");
// Refresh the popup button's style
(themePopupButton as! SCPopUpButton).setMenuItemsTitleColorsAndFonts();
// Select the current theme
selectCurrentTheme();
}
/// Loads in the theme variables from SCThemingEngine
func loadTheme() {
// Set the titlebar color
preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.superview?.wantsLayer = true;
preferencesWindow.standardWindowButton(.CloseButton)?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().titlebarColor.CGColor;
preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().titlebarColor.CGColor;
// Allow the window to be transparent and set the background color
preferencesWindow.opaque = false;
preferencesWindow.backgroundColor = SCThemingEngine().defaultEngine().backgroundColor;
// If we said to hide window titlebars...
if(SCThemingEngine().defaultEngine().titlebarsHidden) {
// Hide the titlebar of the window
preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.removeFromSuperview();
// Set the content view to be full size
preferencesWindow.styleMask |= NSFullSizeContentViewWindowMask;
}
// Set the label colors
themeLabel.textColor = SCThemingEngine().defaultEngine().preferencesLabelColor;
restartLabel.textColor = SCThemingEngine().defaultEngine().preferencesLabelColor;
// Set the label fonts
themeLabel.font = SCThemingEngine().defaultEngine().setFontFamily(themeLabel.font!, size: SCThemingEngine().defaultEngine().preferencesLabelFontSize);
restartLabel.font = SCThemingEngine().defaultEngine().setFontFamily(themeLabel.font!, size: SCThemingEngine().defaultEngine().preferencesLabelFontSize);
}
/// Styles the window
func styleWindow() {
// Get the window
preferencesWindow = NSApplication.sharedApplication().windows.last!;
// Style the titlebar
preferencesWindow.titleVisibility = .Hidden;
preferencesWindow.titlebarAppearsTransparent = true;
// Get the windows center position on the X
let windowX = ((NSScreen.mainScreen()?.frame.width)! / 2) - (480 / 2);
// Get the windows center position on the Y
let windowY = (((NSScreen.mainScreen()?.frame.height)! / 2) - (270 / 2)) + 50;
// Center the window
preferencesWindow.setFrame(NSRect(x: windowX, y: windowY, width: 480, height: 270), display: false);
}
}
|
bf2b9659421a3df45b81d2aad76c0e43
| 43.704545 | 267 | 0.63849 | false | false | false | false |
gaoleegin/DamaiPlayBusinessnormal
|
refs/heads/master
|
DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/Classes/ActiveList/DMActiveListViewController.swift
|
apache-2.0
|
1
|
//
// DMActiveListViewController.swift
// DamaiPlayBusinessPhone
//
// Created by 高李军 on 15/11/4.
// Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved.
//
import UIKit
import SVProgressHUD
class DMActiveListViewController: UITableViewController {
///设置
@IBAction func settingBtnClicked(sender: AnyObject) {
let settingVC = DMSettingViewController()
navigationController?.pushViewController(settingVC, animated: true)
}
private var avtivityList:[DMActiveModel]?
private var introduction:String?
override func viewDidLoad() {
super.viewDidLoad()
///加载数据
self.loadData()
}
///加载列表数据
func loadData(){
SVProgressHUD.show()
DMActiveModel.loadActiveList(1, pageSize: 10) { (acitiviList, being) -> () in
self.avtivityList = acitiviList
self.introduction = "\(being.abeing)个进行中的活动" + " | " + "\(being.allDone)个已结束的活动"
SVProgressHUD.dismiss()
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = NSBundle.mainBundle().loadNibNamed("ActiveHeader", owner: self, options: nil).last as! DMActiveHeaderView
let user = DMUser.getUser()
headerView.userName.text = user.name
headerView.userImage.sd_setImageWithURL(NSURL(string: user.avatar))
headerView.introductionLabel.text = introduction
return headerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.avtivityList?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ActiveListcell", forIndexPath: indexPath) as! DMActiveListTableViewCell
let model = self.avtivityList![indexPath.row]
cell.activitModel = model
return cell
}
}
|
0f0235b4e635c8ded5e0836bdba96ae1
| 28.178947 | 135 | 0.646825 | false | false | false | false |
SquidKit/SquidKit
|
refs/heads/master
|
deprecated/JSONResponseEndpoint.swift
|
mit
|
1
|
//
// JSONEndpoint.swift
// SquidKit
//
// Created by Mike Leavy on 8/24/14.
// Copyright (c) 2014 SquidKit. All rights reserved.
//
import UIKit
import Alamofire
open class JSONResponseEndpoint: Endpoint {
var manager:SessionManager?
open func connect(_ completionHandler: @escaping (AnyObject?, ResponseStatus) -> Void) {
let (params, method) = self.params()
var encoding:ParameterEncoding = .URL
if let specifiedEncoding = self.encoding() {
encoding = specifiedEncoding
}
else {
switch method {
case .POST:
encoding = .JSON
default:
break
}
}
var defaultHeaders = Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
if let additionalHeaders = self.additionalHeaders() {
for (headerName, headerValue) in additionalHeaders {
defaultHeaders[headerName] = headerValue
}
}
let configuration = URLSessionConfiguration.default
configuration.HTTPAdditionalHeaders = defaultHeaders
var serverTrustPolicyManager:ServerTrustPolicyManager?
if self.serverTrustPolicy.count > 0 {
serverTrustPolicyManager = ServerTrustPolicyManager(policies: self.serverTrustPolicy)
}
self.manager = SessionManager(configuration: configuration, serverTrustPolicyManager: serverTrustPolicyManager)
let (user, password) = self.basicAuthPair()
self.request = self.manager!.request(method, self.url(), parameters: params, encoding: encoding)
.shouldAuthenticate(user: user, password: password)
.validate()
.responseJSON(options: self.jsonReadingOptions, completionHandler:{ [weak self] response in
if let strongSelf = self {
switch (response.result) {
case .Success(let value):
if let jsonDictionary = value as? [String: AnyObject] {
strongSelf.connectResponse(jsonDictionary, responseStatus: .OK, completionHandler: completionHandler)
}
else if let jsonArray = value as? [AnyObject] {
strongSelf.connectResponse(jsonArray, responseStatus: .OK, completionHandler:completionHandler)
}
else {
strongSelf.connectResponse(nil, responseStatus: .ResponseFormatError, completionHandler:completionHandler)
}
case .Failure(let error):
strongSelf.connectResponse(nil, responseStatus: strongSelf.formatError(response.response, error:error), completionHandler:completionHandler)
}
}
})
self.logRequest(encoding, headers: defaultHeaders)
}
func connectResponse(_ responseData:AnyObject?, responseStatus:ResponseStatus, completionHandler: (AnyObject?, ResponseStatus) -> Void) {
self.logResponse(responseData, responseStatus: responseStatus)
completionHandler(responseData, responseStatus)
}
//OVERRIDE
open var jsonReadingOptions:JSONSerialization.ReadingOptions {
get {
return .allowFragments
}
}
}
// MARK: Logging
extension JSONResponseEndpoint {
func logRequest(_ encoding:ParameterEncoding, headers:[NSObject : AnyObject]?) {
if let logger = self as? EndpointLoggable {
switch logger.requestLogging {
case .verbose:
logger.log( "===============================\n" +
"SquidKit Network Request\n" +
"===============================\n" +
"Request = " + "\(self.request?.description)" + "\n" +
"Encoding = " + "\(encoding)" + "\n" +
"HTTP headers: " + "\(headers)" + "\n" +
"===============================\n")
case .minimal:
logger.log(self.request?.description)
default:
break
}
}
}
func logResponse(_ responseData:AnyObject?, responseStatus:ResponseStatus) {
if let logger = self as? EndpointLoggable {
switch logger.responseLogging {
case .verbose:
logger.log( "===============================\n" +
"SquidKit Network Response for " + "\(self.request?.description)" + "\n" +
"===============================\n" +
"Response Status = " + "\(responseStatus)" + "\n" +
"JSON:" + "\n" +
"\(responseData)" + "\n" +
"===============================\n")
case .minimal:
logger.log("Response Status = " + "\(responseStatus)")
default:
break
}
}
}
}
extension Request {
func shouldAuthenticate(user: String?, password: String?) -> Self {
if let haveUser = user, let havePassword = password {
return self.authenticate(user: haveUser, password: havePassword)
}
return self
}
}
|
663568786301bdf0502b4588e53bebe1
| 37.570423 | 168 | 0.525105 | false | false | false | false |
jaiversin/AppsCatalog
|
refs/heads/master
|
AppsCatalog/Modules/CategoryList/CategoryListViewController.swift
|
mit
|
1
|
//
// CategoryListViewController.swift
// AppsCatalog
//
// Created by Jhon López on 5/22/16.
// Copyright © 2016 jaiversin. All rights reserved.
//
import UIKit
var CellIdentifier = "CategoryCell"
class CategoryListViewController: UITableViewController, CategoryListViewInterface {
var categoryListPresenter:CategoryListPresenter?
var tableDataSource : [CategoryListModel]?
@IBOutlet weak var noResultsButton: UIButton!
@IBOutlet var noResultsView: UIView!
@IBOutlet weak var categoriesTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.categoriesTable = tableView
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
self.categoryListPresenter?.loadCategories()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func reloadResults(sender: UIButton) {
NSLog("Se van a recargar, ay ay ay")
self.categoryListPresenter?.reloadCategories()
}
// MARK: - Implementación de CategoryListWireframe
func showNoResults() {
self.view = noResultsView
// self.noResultsButton.hidden = false;
// self.categoriesTable.hidden = true;
}
func showResults(categories: [CategoryListModel]) {
if categories.count == 0 {
self.showNoResults()
} else {
self.view = tableView
self.tableDataSource = categories
self.tableView.reloadData()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.tableDataSource?.count)!
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Categorías"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let currentCategory = self.tableDataSource?[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = currentCategory?.label
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCategory = self.tableDataSource?[indexPath.row]
self.categoryListPresenter?.showAppListForCategory((currentCategory?.identifier)!)
}
}
|
66edb8fc69bb5eef890f6bc971728866
| 29.326087 | 122 | 0.666308 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
refs/heads/main
|
Swift/string-to-integer-atoi.swift
|
mit
|
1
|
// This is a take away code.
// Original post: https://leetcode.com/problems/string-to-integer-atoi/discuss/1698567/Swift
class Solution {
func myAtoi(_ s: String) -> Int {
var result = 0
var sign = 1
var isStarted = false
for char in s {
if char == " " {
if isStarted {
break
}
} else if (char == "-" || char == "+") {
if isStarted {
break
}
isStarted = true
if char == "-" {
sign = -1
}
} else if char >= "0" && char <= "9" {
isStarted = true
if let val = char.wholeNumberValue {
result = result*10+val
}
if result > Int32.max {
return sign == 1 ? Int(Int32.max) : Int(Int32.min)
}
} else {
break
}
}
return result*sign
}
}
|
60ba7fd3486be2a9df4615aaab03dc8c
| 29 | 92 | 0.37619 | false | false | false | false |
CoderXiaoming/Ronaldo
|
refs/heads/master
|
SaleManager/SaleManager/ComOperation/Model/SAMOwedInfoModel.swift
|
apache-2.0
|
1
|
//
// SAMOwedInfoModel.swift
// SaleManager
//
// Created by apple on 16/12/23.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
var SAMOwedStockNode = 0.0
class SAMOwedInfoModel: NSObject {
///缺货记录的id
var id = "" {
didSet{
id = ((id == "") ? "---" : id)
}
}
///起始日期
var startDate = "" {
didSet{
startDate = ((startDate == "") ? "---" : startDate)
}
}
///交货日期
var endDate = "" {
didSet{
endDate = ((endDate == "") ? "---" : endDate)
}
}
///客户ID
var CGUnitID = "" {
didSet{
CGUnitID = ((CGUnitID == "") ? "---" : CGUnitID)
}
}
///客户名称
var CGUnitName = "" {
didSet{
CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName)
}
}
///产品编号ID
var productID = "" {
didSet{
productID = ((productID == "") ? "---" : productID)
}
}
///产品编号名称
var productIDName = "" {
didSet{
productIDName = ((productIDName == "") ? "---" : productIDName)
}
}
///缺货数量
var countM = 0.0
///缺货匹数
var countP = 0
///备注
var memoInfo = "" {
didSet{
memoInfo = ((memoInfo == "") ? "---" : memoInfo)
}
}
///状态:欠货中,已完成,已删除
var iState = "" {
didSet{
//设置状态指示图片
switch iState {
case "欠货中":
orderStateImageName = "oweding"
case "已完成":
orderStateImageName = "owedCompletion"
case "已删除":
orderStateImageName = "owedDelete"
case "统计":
orderStateImageName = "owedCount"
default:
break
}
}
}
//MARK: - 附加属性
///用户数据模型
var orderCustomerModel: SAMCustomerModel? {
//简单创建用户数据模型
let model = SAMCustomerModel()
model.CGUnitName = CGUnitName
model.id = CGUnitID
return model
}
///当前欠货的产品数据模型
var stockModel: SAMStockProductModel? {
//简单创建当前欠货的产品数据模型
let model = SAMStockProductModel()
model.productIDName = productIDName
model.id = productID
return model
}
///状态图片
var orderStateImageName = ""
///库存米数
var stockCountM: Double = 0.0
}
|
d0bf1f31429bc5a240d2ad3762ef772d
| 20.846847 | 75 | 0.447423 | false | false | false | false |
kcome/SwiftIB
|
refs/heads/master
|
SwiftIB/EClientSocket.swift
|
mit
|
1
|
//
// EClientSocket.swift
// SwiftIB
//
// Created by Harry Li on 2/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. 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
// Client version history
//
// 6 = Added parentId to orderStatus
// 7 = The new execDetails event returned for an order filled status and reqExecDetails
// Also market depth is available.
// 8 = Added lastFillPrice to orderStatus() event and permId to execution details
// 9 = Added 'averageCost', 'unrealizedPNL', and 'unrealizedPNL' to updatePortfolio event
// 10 = Added 'serverId' to the 'open order' & 'order status' events.
// We send back all the API open orders upon connection.
// Added new methods reqAllOpenOrders, reqAutoOpenOrders()
// Added FA support - reqExecution has filter.
// - reqAccountUpdates takes acct code.
// 11 = Added permId to openOrder event.
// 12 = requsting open order attributes ignoreRth, hidden, and discretionary
// 13 = added goodAfterTime
// 14 = always send size on bid/ask/last tick
// 15 = send allocation description string on openOrder
// 16 = can receive account name in account and portfolio updates, and fa params in openOrder
// 17 = can receive liquidation field in exec reports, and notAutoAvailable field in mkt data
// 18 = can receive good till date field in open order messages, and request intraday backfill
// 19 = can receive rthOnly flag in ORDER_STATUS
// 20 = expects TWS time string on connection after server version >= 20.
// 21 = can receive bond contract details.
// 22 = can receive price magnifier in version 2 contract details message
// 23 = support for scanner
// 24 = can receive volatility order parameters in open order messages
// 25 = can receive HMDS query start and end times
// 26 = can receive option vols in option market data messages
// 27 = can receive delta neutral order type and delta neutral aux price in place order version 20: API 8.85
// 28 = can receive option model computation ticks: API 8.9
// 29 = can receive trail stop limit price in open order and can place them: API 8.91
// 30 = can receive extended bond contract def, new ticks, and trade count in bars
// 31 = can receive EFP extensions to scanner and market data, and combo legs on open orders
// ; can receive RT bars
// 32 = can receive TickType.LAST_TIMESTAMP
// ; can receive "whyHeld" in order status messages
// 33 = can receive ScaleNumComponents and ScaleComponentSize is open order messages
// 34 = can receive whatIf orders / order state
// 35 = can receive contId field for Contract objects
// 36 = can receive outsideRth field for Order objects
// 37 = can receive clearingAccount and clearingIntent for Order objects
// 38 = can receive multiplier and primaryExchange in portfolio updates
// ; can receive cumQty and avgPrice in execution
// ; can receive fundamental data
// ; can receive underComp for Contract objects
// ; can receive reqId and end marker in contractDetails/bondContractDetails
// ; can receive ScaleInitComponentSize and ScaleSubsComponentSize for Order objects
// 39 = can receive underConId in contractDetails
// 40 = can receive algoStrategy/algoParams in openOrder
// 41 = can receive end marker for openOrder
// ; can receive end marker for account download
// ; can receive end marker for executions download
// 42 = can receive deltaNeutralValidation
// 43 = can receive longName(companyName)
// ; can receive listingExchange
// ; can receive RTVolume tick
// 44 = can receive end market for ticker snapshot
// 45 = can receive notHeld field in openOrder
// 46 = can receive contractMonth, industry, category, subcategory fields in contractDetails
// ; can receive timeZoneId, tradingHours, liquidHours fields in contractDetails
// 47 = can receive gamma, vega, theta, undPrice fields in TICK_OPTION_COMPUTATION
// 48 = can receive exemptCode in openOrder
// 49 = can receive hedgeType and hedgeParam in openOrder
// 50 = can receive optOutSmartRouting field in openOrder
// 51 = can receive smartComboRoutingParams in openOrder
// 52 = can receive deltaNeutralConId, deltaNeutralSettlingFirm, deltaNeutralClearingAccount and deltaNeutralClearingIntent in openOrder
// 53 = can receive orderRef in execution
// 54 = can receive scale order fields (PriceAdjustValue, PriceAdjustInterval, ProfitOffset, AutoReset,
// InitPosition, InitFillQty and RandomPercent) in openOrder
// 55 = can receive orderComboLegs (price) in openOrder
// 56 = can receive trailingPercent in openOrder
// 57 = can receive commissionReport message
// 58 = can receive CUSIP/ISIN/etc. in contractDescription/bondContractDescription
// 59 = can receive evRule, evMultiplier in contractDescription/bondContractDescription/executionDetails
// can receive multiplier in executionDetails
// 60 = can receive deltaNeutralOpenClose, deltaNeutralShortSale, deltaNeutralShortSaleSlot and deltaNeutralDesignatedLocation in openOrder
// 61 = can receive multiplier in openOrder
// can receive tradingClass in openOrder, updatePortfolio, execDetails and position
// 62 = can receive avgCost in position message
// 63 = can receive verifyMessageAPI, verifyCompleted, displayGroupList and displayGroupUpdated messages
let CLIENT_VERSION: Int = 63
let SERVER_VERSION: Int = 38
let EOL: [UInt8] = [0]
let BAG_SEC_TYPE: String = "BAG"
let GROUPS: Int = 1
let PROFILES: Int = 2
let ALIASES: Int = 3
open class EClientSocket {
class func faMsgTypeName(_ faDataType: Int) -> String {
switch (faDataType) {
case 1:
return "GROUPS"
case 2:
return "PROFILES"
case 3:
return "ALIASES"
default:
return ""
}
}
// outgoing msg id's
let REQ_MKT_DATA = 1
let CANCEL_MKT_DATA = 2
let PLACE_ORDER = 3
let CANCEL_ORDER = 4
let REQ_OPEN_ORDERS = 5
let REQ_ACCOUNT_DATA = 6
let REQ_EXECUTIONS = 7
let REQ_IDS = 8
let REQ_CONTRACT_DATA = 9
let REQ_MKT_DEPTH = 10
let CANCEL_MKT_DEPTH = 11
let REQ_NEWS_BULLETINS = 12
let CANCEL_NEWS_BULLETINS = 13
let SET_SERVER_LOGLEVEL = 14
let REQ_AUTO_OPEN_ORDERS = 15
let REQ_ALL_OPEN_ORDERS = 16
let REQ_MANAGED_ACCTS = 17
let REQ_FA = 18
let REPLACE_FA = 19
let REQ_HISTORICAL_DATA = 20
let EXERCISE_OPTIONS = 21
let REQ_SCANNER_SUBSCRIPTION = 22
let CANCEL_SCANNER_SUBSCRIPTION = 23
let REQ_SCANNER_PARAMETERS = 24
let CANCEL_HISTORICAL_DATA = 25
let REQ_CURRENT_TIME = 49
let REQ_REAL_TIME_BARS = 50
let CANCEL_REAL_TIME_BARS = 51
let REQ_FUNDAMENTAL_DATA = 52
let CANCEL_FUNDAMENTAL_DATA = 53
let REQ_CALC_IMPLIED_VOLAT = 54
let REQ_CALC_OPTION_PRICE = 55
let CANCEL_CALC_IMPLIED_VOLAT = 56
let CANCEL_CALC_OPTION_PRICE = 57
let REQ_GLOBAL_CANCEL = 58
let REQ_MARKET_DATA_TYPE = 59
let REQ_POSITIONS = 61
let REQ_ACCOUNT_SUMMARY = 62
let CANCEL_ACCOUNT_SUMMARY = 63
let CANCEL_POSITIONS = 64
let VERIFY_REQUEST = 65
let VERIFY_MESSAGE = 66
let QUERY_DISPLAY_GROUPS = 67
let SUBSCRIBE_TO_GROUP_EVENTS = 68
let UPDATE_DISPLAY_GROUP = 69
let UNSUBSCRIBE_FROM_GROUP_EVENTS = 70
let START_API = 71
let MIN_SERVER_VER_REAL_TIME_BARS = 34
let MIN_SERVER_VER_SCALE_ORDERS = 35
let MIN_SERVER_VER_SNAPSHOT_MKT_DATA = 35
let MIN_SERVER_VER_SSHORT_COMBO_LEGS = 35
let MIN_SERVER_VER_WHAT_IF_ORDERS = 36
let MIN_SERVER_VER_CONTRACT_CONID = 37
let MIN_SERVER_VER_PTA_ORDERS = 39
let MIN_SERVER_VER_FUNDAMENTAL_DATA = 40
let MIN_SERVER_VER_UNDER_COMP = 40
let MIN_SERVER_VER_CONTRACT_DATA_CHAIN = 40
let MIN_SERVER_VER_SCALE_ORDERS2 = 40
let MIN_SERVER_VER_ALGO_ORDERS = 41
let MIN_SERVER_VER_EXECUTION_DATA_CHAIN = 42
let MIN_SERVER_VER_NOT_HELD = 44
let MIN_SERVER_VER_SEC_ID_TYPE = 45
let MIN_SERVER_VER_PLACE_ORDER_CONID = 46
let MIN_SERVER_VER_REQ_MKT_DATA_CONID = 47
let MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT = 49
let MIN_SERVER_VER_REQ_CALC_OPTION_PRICE = 50
let MIN_SERVER_VER_CANCEL_CALC_IMPLIED_VOLAT = 50
let MIN_SERVER_VER_CANCEL_CALC_OPTION_PRICE = 50
let MIN_SERVER_VER_SSHORTX_OLD = 51
let MIN_SERVER_VER_SSHORTX = 52
let MIN_SERVER_VER_REQ_GLOBAL_CANCEL = 53
let MIN_SERVER_VER_HEDGE_ORDERS = 54
let MIN_SERVER_VER_REQ_MARKET_DATA_TYPE = 55
let MIN_SERVER_VER_OPT_OUT_SMART_ROUTING = 56
let MIN_SERVER_VER_SMART_COMBO_ROUTING_PARAMS = 57
let MIN_SERVER_VER_DELTA_NEUTRAL_CONID = 58
let MIN_SERVER_VER_SCALE_ORDERS3 = 60
let MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE = 61
let MIN_SERVER_VER_TRAILING_PERCENT = 62
let MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE = 66
let MIN_SERVER_VER_ACCT_SUMMARY = 67
let MIN_SERVER_VER_TRADING_CLASS = 68
let MIN_SERVER_VER_SCALE_TABLE = 69
let MIN_SERVER_VER_LINKING = 70
fileprivate var _eWrapper : EWrapper // msg handler
fileprivate var _anyWrapper : AnyWrapper // msg handler
fileprivate var dos : OutputStream? = nil // the socket output stream
fileprivate var connected : Bool = false // true if we are connected
fileprivate var _reader : EReader? = nil // thread which reads msgs from socket
fileprivate var _serverVersion : Int = 0
fileprivate var TwsTime : String = ""
fileprivate var clientId : Int = 0
fileprivate var extraAuth : Bool = false
func serverVersion() -> Int { return _serverVersion }
func TwsConnectionTime() -> String { return TwsTime }
func anyWrapper() -> AnyWrapper { return _anyWrapper }
func eWrapper() -> EWrapper { return _eWrapper }
func reader() -> EReader? { return _reader }
func isConnected() -> Bool { return connected }
func outputStream() -> OutputStream? { return dos }
public init(p_eWrapper: EWrapper, p_anyWrapper: AnyWrapper) {
_anyWrapper = p_anyWrapper
_eWrapper = p_eWrapper
}
open func setExtraAuth(_ p_extraAuth: Bool) {
extraAuth = p_extraAuth
}
open func eConnect(_ host: String, port: Int, clientId: Int) { // synchronized
self.eConnect(host, p_port: port, p_clientId: clientId, p_extraAuth: false)
}
open func eConnect(_ p_host: String, p_port: Int, p_clientId: Int, p_extraAuth: Bool) { // synchronized
// already connected?
let host = checkConnected(p_host)
var port : UInt32 = 0
if p_port > 0 { port = UInt32(p_port) }
clientId = p_clientId
extraAuth = p_extraAuth
if host.isEmpty {
return
}
self.eConnect(p_host, p_port: port)
// TODO: Handle errors here
// catch( Exception e) {
// eDisconnect()
// connectionError()
// }
}
func connectionError() {
_anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_CONNECT_FAIL.code,
errorMsg: EClientErrors_CONNECT_FAIL.msg)
_reader = nil
}
func checkConnected(_ host: String) -> String {
if connected {
_anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_ALREADY_CONNECTED.code,
errorMsg: EClientErrors_ALREADY_CONNECTED.msg)
return ""
}
if host.isEmpty {
return "127.0.0.1"
}
return host
}
func createReader(_ socket: EClientSocket, dis: InputStream) -> EReader {
return EReader(parent: socket, dis: dis)
}
open func eConnect(_ p_host: String, p_port: UInt32) { // synchronized
// create io streams
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let host: CFString = p_host as CFString
CFStreamCreatePairWithSocketToHost(nil, host, p_port, &readStream, &writeStream)
let dis : InputStream = readStream!.takeRetainedValue()
self.dos = writeStream!.takeRetainedValue()
// TODO: add delegates here
// self.inputStream.delegate = self
// self.outputStream.delegate = self
dis.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
dos?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
dis.open()
dos?.open()
// set client version
send(CLIENT_VERSION)
// start reader thread
_reader = createReader(self, dis: dis)
// check server version
_serverVersion = (_reader?.readInt())!
print("Server Version: \(_serverVersion)")
if _serverVersion >= 20 {
if let ttime = _reader?.readStr() {
TwsTime = ttime
}
print("TWS Time at connection: \(TwsTime)")
}
if (_serverVersion < SERVER_VERSION) {
eDisconnect()
_anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
// set connected flag
connected = true;
// Send the client id
if _serverVersion >= 3 {
if _serverVersion < MIN_SERVER_VER_LINKING {
send(clientId)
}
else if (!extraAuth){
startAPI()
}
}
_reader?.start()
}
open func eDisconnect() { // synchronized
// not connected?
if dos == nil {
return
}
connected = false
extraAuth = false
clientId = -1
_serverVersion = 0
TwsTime = ""
let pdos = dos
dos = nil
let preader = _reader
_reader = nil
// stop reader thread; reader thread will close input stream
if preader != nil {
preader?.cancel()
}
// close output stream
if preader != nil {
pdos?.close()
}
}
func startAPI() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
send(START_API)
send(VERSION)
send(clientId)
// TODO: Handle errors here
// catch( Exception e) {
// error( EClientErrors_NO_VALID_ID,
// EClientErrors_FAIL_SEND_STARTAPI, "" + e)
// close()
// }
}
open func cancelScannerSubscription(_ tickerId: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < 24 {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support API scanner subscription.")
return
}
let VERSION = 1
// send cancel mkt data msg
send(CANCEL_SCANNER_SUBSCRIPTION)
send(VERSION)
send(tickerId)
// TODO: Handle errors here
// catch( Exception e) {
// error( tickerId, EClientErrors_FAIL_SEND_CANSCANNER, "" + e)
// close()
// }
}
open func reqScannerParameters() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if (_serverVersion < 24) {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support API scanner subscription.")
return
}
let VERSION = 1
send(REQ_SCANNER_PARAMETERS)
send(VERSION)
// TODO: Handle errors here
// catch( Exception e) {
// error( EClientErrors_NO_VALID_ID,
// EClientErrors_FAIL_SEND_REQSCANNERPARAMETERS, "" + e)
// close()
// }
}
open func reqScannerSubscription(_ tickerId: Int, subscription: ScannerSubscription, scannerSubscriptionOptions: [TagValue]?) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < 24 {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support API scanner subscription.")
return
}
let VERSION = 4
send(REQ_SCANNER_SUBSCRIPTION)
send(VERSION)
send(tickerId)
sendMax(subscription.numberOfRows)
send(subscription.instrument)
send(subscription.locationCode)
send(subscription.scanCode)
sendMax(subscription.abovePrice)
sendMax(subscription.belowPrice)
sendMax(subscription.aboveVolume)
sendMax(subscription.marketCapAbove)
sendMax(subscription.marketCapBelow)
send(subscription.moodyRatingAbove)
send(subscription.moodyRatingBelow)
send(subscription.spRatingAbove)
send(subscription.spRatingBelow)
send(subscription.maturityDateAbove)
send(subscription.maturityDateBelow)
sendMax(subscription.couponRateAbove)
sendMax(subscription.couponRateBelow)
send(subscription.excludeConvertible)
if _serverVersion >= 25 {
sendMax(subscription.averageOptionVolumeAbove)
send(subscription.scannerSettingPairs)
}
if _serverVersion >= 27 {
send(subscription.stockTypeFilter)
}
// send scannerSubscriptionOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var scannerSubscriptionOptionsStr = ""
if scannerSubscriptionOptions != nil {
let scannerSubscriptionOptionsCount = scannerSubscriptionOptions!.count
if scannerSubscriptionOptionsCount > 0 {
for i in 1...scannerSubscriptionOptionsCount {
let tagValue = scannerSubscriptionOptions![i-1]
scannerSubscriptionOptionsStr += tagValue.tag
scannerSubscriptionOptionsStr += "="
scannerSubscriptionOptionsStr += tagValue.value
scannerSubscriptionOptionsStr += ";"
}
}
}
send( scannerSubscriptionOptionsStr )
}
// TODO: Handle errors here
// catch( Exception e) {
// error( tickerId, EClientErrors_FAIL_SEND_REQSCANNER, "" + e)
// close()
// }
}
open func reqMktData(_ tickerId: Int, contract: Contract, genericTickList: String, snapshot: Bool, mktDataOptions: [TagValue]?) { // synchronized
if !connected {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_NOT_CONNECTED, tail: "")
return
}
if _serverVersion < MIN_SERVER_VER_SNAPSHOT_MKT_DATA && snapshot {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support snapshot market data requests.")
return
}
if _serverVersion < MIN_SERVER_VER_UNDER_COMP {
if contract.underComp != nil {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support delta-neutral orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_REQ_MKT_DATA_CONID {
if contract.conId > 0 {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId parameter.")
return
}
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if !contract.tradingClass.isEmpty {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It ot support tradingClass parameter in reqMarketData.")
return
}
}
let VERSION = 11
// send req mkt data msg
send(REQ_MKT_DATA)
send(VERSION)
send(tickerId)
// send contract fields
if _serverVersion >= MIN_SERVER_VER_REQ_MKT_DATA_CONID {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
if _serverVersion >= 15 {
send(contract.multiplier)
}
send(contract.exchange)
if _serverVersion >= 14 {
send(contract.primaryExch)
}
send(contract.currency)
if _serverVersion >= 2 {
send(contract.localSymbol)
}
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
if _serverVersion >= 8 && caseInsensitiveEqual(contract.secType, BAG_SEC_TYPE) {
send(contract.comboLegs.count)
for i in 1...contract.comboLegs.count {
let comboLeg = contract.comboLegs[i]
send(comboLeg.conId)
send(comboLeg.ratio)
send(comboLeg.action)
send(comboLeg.exchange)
}
}
if _serverVersion >= MIN_SERVER_VER_UNDER_COMP {
if let underComp = contract.underComp {
send(true)
send(underComp.conId)
send(underComp.delta)
send(underComp.price)
}
else {
send( false)
}
}
if _serverVersion >= 31 {
/*
* Note: Even though SHORTABLE tick type supported only
* starting server version 33 it would be relatively
* expensive to expose this restriction here.
*
* Therefore we are relying on TWS doing validation.
*/
send( genericTickList)
}
if _serverVersion >= MIN_SERVER_VER_SNAPSHOT_MKT_DATA {
send (snapshot)
}
// send mktDataOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var mktDataOptionsStr = ""
if mktDataOptions != nil {
let mktDataOptionsCount = mktDataOptions!.count
for i in 1...mktDataOptionsCount {
let tagValue = mktDataOptions![i]
mktDataOptionsStr += tagValue.tag
mktDataOptionsStr += "="
mktDataOptionsStr += tagValue.value
mktDataOptionsStr += ";"
}
}
send( mktDataOptionsStr )
}
// TODO: Handle errors here
// catch( Exception e) {
// error( tickerId, EClientErrors_FAIL_SEND_REQMKT, "" + e)
// close()
// }
}
open func cancelHistoricalData(_ tickerId :Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < 24 {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support historical data query cancellation.")
return
}
let VERSION = 1
// send cancel mkt data msg
send(CANCEL_HISTORICAL_DATA)
send(VERSION)
send(tickerId)
// TODO: Handle errors here
// catch( Exception e) {
// error( tickerId, EClientErrors_FAIL_SEND_CANHISTDATA, "" + e)
// close()
// }
}
open func cancelRealTimeBars(_ tickerId: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REAL_TIME_BARS {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support realtime bar data query cancellation.")
return
}
let VERSION = 1
// send cancel mkt data msg
send( CANCEL_REAL_TIME_BARS)
send( VERSION)
send( tickerId)
// Handle errors here
// catch( Exception e) {
// error( tickerId, EClientErrors_FAIL_SEND_CANRTBARS, "" + e)
// close()
// }
}
/** Note that formatData parameter affects intra-day bars only; 1-day bars always return with date in YYYYMMDD format. */
open func reqHistoricalData(_ tickerId: Int, contract: Contract,
endDateTime: String, durationStr: String,
barSizeSetting: String, whatToShow: String,
useRTH: Int, formatDate: Int, chartOptions: [TagValue]?) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 6
if _serverVersion < 16 {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support historical data backfill.")
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId and tradingClass parameters in reqHistroricalData.")
return
}
}
send(REQ_HISTORICAL_DATA)
send(VERSION)
send(tickerId)
// send contract fields
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
send(contract.multiplier)
send(contract.exchange)
send(contract.primaryExch)
send(contract.currency)
send(contract.localSymbol)
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
if _serverVersion >= 31 {
send(contract.includeExpired ? 1 : 0)
}
if _serverVersion >= 20 {
send(endDateTime)
send(barSizeSetting)
}
send(durationStr)
send(useRTH)
send(whatToShow)
if _serverVersion > 16 {
send(formatDate)
}
if (caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType)) {
send(contract.comboLegs.count)
for i in 1...contract.comboLegs.count {
let comboLeg = contract.comboLegs[i - 1]
send(comboLeg.conId)
send(comboLeg.ratio)
send(comboLeg.action)
send(comboLeg.exchange)
}
}
// send chartOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var chartOptionsStr = ""
if chartOptions != nil {
let chartOptionsCount = chartOptions!.count
for i in 1...chartOptionsCount {
let tagValue = chartOptions![i]
chartOptionsStr += tagValue.tag
chartOptionsStr += "="
chartOptionsStr += tagValue.value
chartOptionsStr += ";"
}
}
send(chartOptionsStr)
}
// TODO: Handle errors here
// catch (Exception e) {
// error(tickerId, EClientErrors_FAIL_SEND_REQHISTDATA, "" + e)
// close()
// }
}
open func reqRealTimeBars(_ tickerId: Int, contract: Contract, barSize: Int, whatToShow: String, useRTH: Bool, realTimeBarsOptions: [TagValue]?) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REAL_TIME_BARS {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support real time bars.")
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId and tradingClass parameters in reqRealTimeBars.")
return
}
}
let VERSION = 3
// send req mkt data msg
send(REQ_REAL_TIME_BARS)
send(VERSION)
send(tickerId)
// send contract fields
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
send(contract.multiplier)
send(contract.exchange)
send(contract.primaryExch)
send(contract.currency)
send(contract.localSymbol)
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
send(barSize) // this parameter is not currently used
send(whatToShow)
send(useRTH)
// send realTimeBarsOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var realTimeBarsOptionsStr = ""
if realTimeBarsOptions != nil {
let realTimeBarsOptionsCount = realTimeBarsOptions!.count
for i in 1...realTimeBarsOptionsCount {
let tagValue = realTimeBarsOptions![i]
realTimeBarsOptionsStr += tagValue.tag
realTimeBarsOptionsStr += "="
realTimeBarsOptionsStr += tagValue.value
realTimeBarsOptionsStr += ";"
}
}
send(realTimeBarsOptionsStr)
}
// TODO: Handle errors here
//catch( Exception e) {
//error( tickerId, EClientErrors_FAIL_SEND_REQRTBARS, "" + e)
//close()
//}
}
open func reqContractDetails(_ reqId: Int, contract: Contract) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >=4
if (_serverVersion < 4) {
error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code,
errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
if (_serverVersion < MIN_SERVER_VER_SEC_ID_TYPE) {
if ((contract.secIdType.isEmpty == false) ||
(contract.secId.isEmpty == false)) {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support secIdType and secId parameters.")
return
}
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if (contract.tradingClass.isEmpty == false) {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support tradingClass parameter in reqContractDetails.")
return
}
}
let VERSION = 7
// send req mkt data msg
send(REQ_CONTRACT_DATA)
send(VERSION)
if _serverVersion >= MIN_SERVER_VER_CONTRACT_DATA_CHAIN {
send(reqId)
}
// send contract fields
if _serverVersion >= MIN_SERVER_VER_CONTRACT_CONID {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
if _serverVersion >= 15 {
send(contract.multiplier)
}
send(contract.exchange)
send(contract.currency)
send(contract.localSymbol)
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
if _serverVersion >= 31 {
send(contract.includeExpired)
}
if _serverVersion >= MIN_SERVER_VER_SEC_ID_TYPE {
send(contract.secIdType)
send(contract.secId)
}
// TODO: Handle errors here
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQCONTRACT, "" + e)
//close()
//}
}
open func reqMktDepth(_ tickerId: Int, contract: Contract, numRows: Int, mktDepthOptions: [TagValue]?) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >=6
if (_serverVersion < 6) {
error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code,
errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId and tradingClass parameters in reqMktDepth.")
return
}
}
let VERSION = 5
// send req mkt data msg
send(REQ_MKT_DEPTH)
send(VERSION)
send(tickerId)
// send contract fields
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
if _serverVersion >= 15 {
send(contract.multiplier)
}
send(contract.exchange)
send(contract.currency)
send(contract.localSymbol)
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
if _serverVersion >= 19 {
send(numRows)
}
// send mktDepthOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var mktDepthOptionsStr = ""
if mktDepthOptions != nil {
let mktDepthOptionsCount = mktDepthOptions!.count
for i in 1...mktDepthOptionsCount {
let tagValue = mktDepthOptions![i]
mktDepthOptionsStr += tagValue.tag
mktDepthOptionsStr += "="
mktDepthOptionsStr += tagValue.value
mktDepthOptionsStr += ";"
}
}
send(mktDepthOptionsStr)
}
// TODO: Handle errors here
//catch( Exception e) {
//error( tickerId, EClientErrors_FAIL_SEND_REQMKTDEPTH, "" + e)
//close()
//}
}
open func cancelMktData(_ tickerId: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send cancel mkt data msg
send(CANCEL_MKT_DATA)
send(VERSION)
send(tickerId)
// TODO: Handle errors here
//catch( Exception e) {
//error( tickerId, EClientErrors_FAIL_SEND_CANMKT, "" + e)
//close()
//}
}
open func cancelMktDepth(_ tickerId: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >=6
if (_serverVersion < 6) {
error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code,
errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
let VERSION = 1
// send cancel mkt data msg
send(CANCEL_MKT_DEPTH)
send(VERSION)
send(tickerId)
// TODO: Handle errors here
//catch( Exception e) {
//error( tickerId, EClientErrors_FAIL_SEND_CANMKTDEPTH, "" + e)
//close()
//}
}
func exerciseOptions(_ tickerId: Int, contract: Contract,
exerciseAction: Int, exerciseQuantity: Int,
account: String, override: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 2
if _serverVersion < 21 {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support options exercise from the API.")
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) {
error(tickerId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId and tradingClass parameters in exerciseOptions.")
return
}
}
send(EXERCISE_OPTIONS)
send(VERSION)
send(tickerId)
// send contract fields
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
send(contract.multiplier)
send(contract.exchange)
send(contract.currency)
send(contract.localSymbol)
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
send(exerciseAction)
send(exerciseQuantity)
send(account)
send(override)
// TODO: Handle errors here
//catch (Exception e) {
//error(tickerId, EClientErrors_FAIL_SEND_REQMKT, "" + e)
//close()
//}
}
func placeOrder(_ id: Int, contract: Contract, order: Order) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS {
if (order.scaleInitLevelSize != Int.max ||
order.scalePriceIncrement != Double.nan) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support Scale orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SSHORT_COMBO_LEGS {
if contract.comboLegs.count > 0 {
for i in 1...contract.comboLegs.count {
let comboLeg = contract.comboLegs[i]
if (comboLeg.shortSaleSlot != 0 ||
(comboLeg.designatedLocation.isEmpty == false)) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support SSHORT flag for combo legs.")
return
}
}
}
}
if _serverVersion < MIN_SERVER_VER_WHAT_IF_ORDERS {
if (order.whatIf) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support what-if orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_UNDER_COMP {
if (contract.underComp != nil) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support delta-neutral orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS2 {
if (order.scaleSubsLevelSize != Int.max) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support Subsequent Level Size for Scale orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_ALGO_ORDERS {
if order.algoStrategy.isEmpty == false {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support algo orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_NOT_HELD {
if (order.notHeld) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support notHeld parameter.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SEC_ID_TYPE {
if (contract.secIdType.isEmpty == false) ||
(contract.secId.isEmpty == false) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support secIdType and secId parameters.")
return
}
}
if _serverVersion < MIN_SERVER_VER_PLACE_ORDER_CONID {
if (contract.conId > 0) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId parameter.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SSHORTX {
if (order.exemptCode != -1) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support exemptCode parameter.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SSHORTX {
if contract.comboLegs.count > 0 {
for i in 1...contract.comboLegs.count {
let comboLeg = contract.comboLegs[i]
if (comboLeg.exemptCode != -1) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support exemptCode parameter.")
return
}
}
}
}
if _serverVersion < MIN_SERVER_VER_HEDGE_ORDERS {
if order.hedgeType.isEmpty == false {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support hedge orders.")
return
}
}
if _serverVersion < MIN_SERVER_VER_OPT_OUT_SMART_ROUTING {
if (order.optOutSmartRouting) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support optOutSmartRouting parameter.")
return
}
}
if _serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_CONID {
if (order.deltaNeutralConId > 0
|| !order.deltaNeutralSettlingFirm.isEmpty
|| !order.deltaNeutralClearingAccount.isEmpty
|| !order.deltaNeutralClearingIntent.isEmpty
) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent")
return
}
}
if _serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE {
if (!order.deltaNeutralOpenClose.isEmpty
|| !order.deltaNeutralShortSale
|| order.deltaNeutralShortSaleSlot > 0
|| !order.deltaNeutralDesignatedLocation.isEmpty
) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation")
return
}
}
if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS3 {
if (order.scalePriceIncrement > 0 && order.scalePriceIncrement != Double.nan) {
if (order.scalePriceAdjustValue != Double.nan ||
order.scalePriceAdjustInterval != Int.max ||
order.scaleProfitOffset != Double.nan ||
order.scaleAutoReset ||
order.scaleInitPosition != Int.max ||
order.scaleInitFillQty != Int.max ||
order.scaleRandomPercent) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, " +
"ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent")
return
}
}
}
if _serverVersion < MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) {
if order.orderComboLegs.count > 0 {
for i in 1...order.orderComboLegs.count {
let orderComboLeg = order.orderComboLegs[i]
if (orderComboLeg.price != Double.nan) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support per-leg prices for order combo legs.")
return
}
}
}
}
if _serverVersion < MIN_SERVER_VER_TRAILING_PERCENT {
if (order.trailingPercent != Double.nan) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support trailing percent parameter")
return
}
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if (contract.tradingClass.isEmpty == false) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support tradingClass parameters in placeOrder.")
return
}
}
if _serverVersion < MIN_SERVER_VER_SCALE_TABLE {
if (order.scaleTable.isEmpty == false || order.activeStartTime.isEmpty == false || order.activeStopTime.isEmpty == false) {
error(id, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support scaleTable, activeStartTime and activeStopTime parameters.")
return
}
}
let VERSION = (_serverVersion < MIN_SERVER_VER_NOT_HELD) ? 27 : 42
// send place order msg
send(PLACE_ORDER)
send(VERSION)
send(id)
// send contract fields
if (_serverVersion >= MIN_SERVER_VER_PLACE_ORDER_CONID) {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
if _serverVersion >= 15 {
send(contract.multiplier)
}
send(contract.exchange)
if (_serverVersion >= 14) {
send(contract.primaryExch)
}
send(contract.currency)
if (_serverVersion >= 2) {
send (contract.localSymbol)
}
if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
send(contract.tradingClass)
}
if (_serverVersion >= MIN_SERVER_VER_SEC_ID_TYPE){
send(contract.secIdType)
send(contract.secId)
}
// send main order fields
send(order.action)
send(order.totalQuantity)
send(order.orderType)
if _serverVersion < MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE {
send(order.lmtPrice == Double.nan ? 0 : order.lmtPrice)
}
else {
sendMax(order.lmtPrice)
}
if _serverVersion < MIN_SERVER_VER_TRAILING_PERCENT {
send(order.auxPrice == Double.nan ? 0 : order.auxPrice)
}
else {
sendMax(order.auxPrice)
}
// send extended order fields
send(order.tif)
send(order.ocaGroup)
send(order.account)
send(order.openClose)
send(order.origin)
send(order.orderRef)
send(order.transmit)
if (_serverVersion >= 4 ) {
send (order.parentId)
}
if (_serverVersion >= 5 ) {
send (order.blockOrder)
send (order.sweepToFill)
send (order.displaySize)
send (order.triggerMethod)
if _serverVersion < 38 {
// will never happen
send(/* order.ignoreRth */ false)
}
else {
send (order.outsideRth)
}
}
if _serverVersion >= 7 {
send(order.hidden)
}
// Send combo legs for BAG requests
if _serverVersion >= 8 && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) {
send(contract.comboLegs.count)
for i in 1...contract.comboLegs.count {
let comboLeg = contract.comboLegs[i]
send(comboLeg.conId)
send(comboLeg.ratio)
send(comboLeg.action)
send(comboLeg.exchange)
send(comboLeg.openClose)
if _serverVersion >= MIN_SERVER_VER_SSHORT_COMBO_LEGS {
send(comboLeg.shortSaleSlot)
send(comboLeg.designatedLocation)
}
if _serverVersion >= MIN_SERVER_VER_SSHORTX_OLD {
send(comboLeg.exemptCode)
}
}
}
// Send order combo legs for BAG requests
if _serverVersion >= MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) {
send(order.orderComboLegs.count)
for i in 1...order.orderComboLegs.count {
let orderComboLeg = order.orderComboLegs[i]
sendMax(orderComboLeg.price)
}
}
if _serverVersion >= MIN_SERVER_VER_SMART_COMBO_ROUTING_PARAMS && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) {
let smartComboRoutingParams = order.smartComboRoutingParams
let smartComboRoutingParamsCount = smartComboRoutingParams.count
send(smartComboRoutingParamsCount)
for i in 1...smartComboRoutingParamsCount {
let tagValue = smartComboRoutingParams[i]
send(tagValue.tag)
send(tagValue.value)
}
}
if ( _serverVersion >= 9 ) {
// send deprecated sharesAllocation field
send("")
}
if ( _serverVersion >= 10 ) {
send(order.discretionaryAmt)
}
if ( _serverVersion >= 11 ) {
send(order.goodAfterTime)
}
if ( _serverVersion >= 12 ) {
send(order.goodTillDate)
}
if ( _serverVersion >= 13 ) {
send(order.faGroup)
send(order.faMethod)
send(order.faPercentage)
send(order.faProfile)
}
if _serverVersion >= 18 { // institutional short sale slot fields.
send(order.shortSaleSlot) // 0 only for retail, 1 or 2 only for institution.
send(order.designatedLocation) // only populate when order.shortSaleSlot = 2.
}
if _serverVersion >= MIN_SERVER_VER_SSHORTX_OLD {
send(order.exemptCode)
}
if _serverVersion >= 19 {
send(order.ocaType)
if _serverVersion < 38 {
// will never happen
send(/* order.rthOnly */ false)
}
send(order.rule80A)
send(order.settlingFirm)
send(order.allOrNone)
sendMax(order.minQty)
sendMax(order.percentOffset)
send(order.eTradeOnly)
send(order.firmQuoteOnly)
sendMax(order.nbboPriceCap)
sendMax(order.auctionStrategy)
sendMax(order.startingPrice)
sendMax(order.stockRefPrice)
sendMax(order.delta)
// Volatility orders had specific watermark price attribs in server version 26
let lower = (_serverVersion == 26 && order.orderType == "VOL")
? Double.nan
: order.stockRangeLower
let upper = (_serverVersion == 26 && order.orderType == "VOL")
? Double.nan
: order.stockRangeUpper
sendMax(lower)
sendMax(upper)
}
if _serverVersion >= 22 {
send(order.overridePercentageConstraints)
}
if _serverVersion >= 26 { // Volatility orders
sendMax(order.volatility)
sendMax(order.volatilityType)
if _serverVersion < 28 {
send(caseInsensitiveEqual(order.deltaNeutralOrderType, "MKT"))
} else {
send(order.deltaNeutralOrderType)
sendMax(order.deltaNeutralAuxPrice)
if _serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL_CONID && order.deltaNeutralOrderType.isEmpty == false {
send(order.deltaNeutralConId)
send(order.deltaNeutralSettlingFirm)
send(order.deltaNeutralClearingAccount)
send(order.deltaNeutralClearingIntent)
}
if _serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE && order.deltaNeutralOrderType.isEmpty == false {
send(order.deltaNeutralOpenClose)
send(order.deltaNeutralShortSale)
send(order.deltaNeutralShortSaleSlot)
send(order.deltaNeutralDesignatedLocation)
}
}
send(order.continuousUpdate)
if _serverVersion == 26 {
// Volatility orders had specific watermark price attribs in server version 26
let lower = order.orderType == "VOL" ? order.stockRangeLower : Double.nan
let upper = order.orderType == "VOL" ? order.stockRangeUpper : Double.nan
sendMax(lower)
sendMax(upper)
}
sendMax(order.referencePriceType)
}
if _serverVersion >= 30 { // TRAIL_STOP_LIMIT stop price
sendMax(order.trailStopPrice)
}
if (_serverVersion >= MIN_SERVER_VER_TRAILING_PERCENT){
sendMax(order.trailingPercent)
}
if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS {
if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS2 {
sendMax (order.scaleInitLevelSize)
sendMax (order.scaleSubsLevelSize)
}
else {
send ("")
sendMax (order.scaleInitLevelSize)
}
sendMax (order.scalePriceIncrement)
}
if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS3 && order.scalePriceIncrement > 0.0 && order.scalePriceIncrement == Double.nan {
sendMax (order.scalePriceAdjustValue)
sendMax (order.scalePriceAdjustInterval)
sendMax (order.scaleProfitOffset)
send (order.scaleAutoReset)
sendMax (order.scaleInitPosition)
sendMax (order.scaleInitFillQty)
send (order.scaleRandomPercent)
}
if _serverVersion >= MIN_SERVER_VER_SCALE_TABLE {
send (order.scaleTable)
send (order.activeStartTime)
send (order.activeStopTime)
}
if _serverVersion >= MIN_SERVER_VER_HEDGE_ORDERS {
send (order.hedgeType)
if (order.hedgeType.isEmpty == false) {
send (order.hedgeParam)
}
}
if _serverVersion >= MIN_SERVER_VER_OPT_OUT_SMART_ROUTING {
send (order.optOutSmartRouting)
}
if _serverVersion >= MIN_SERVER_VER_PTA_ORDERS {
send (order.clearingAccount)
send (order.clearingIntent)
}
if _serverVersion >= MIN_SERVER_VER_NOT_HELD {
send (order.notHeld)
}
if _serverVersion >= MIN_SERVER_VER_UNDER_COMP {
if let underComp = contract.underComp {
send(true)
send(underComp.conId)
send(underComp.delta)
send(underComp.price)
}
else {
send(false)
}
}
if _serverVersion >= MIN_SERVER_VER_ALGO_ORDERS {
send(order.algoStrategy)
if (order.algoStrategy.isEmpty == false) {
let algoParams = order.algoParams
let algoParamsCount = algoParams.count
send(algoParamsCount)
for i in 1...algoParamsCount {
let tagValue = algoParams[i]
send(tagValue.tag)
send(tagValue.value)
}
}
}
if _serverVersion >= MIN_SERVER_VER_WHAT_IF_ORDERS {
send (order.whatIf)
}
// send orderMiscOptions parameter
if _serverVersion >= MIN_SERVER_VER_LINKING {
var orderMiscOptionsStr = ""
let orderMiscOptions = order.orderMiscOptions
let orderMiscOptionsCount = orderMiscOptions.count
for i in 1...orderMiscOptionsCount {
let tagValue = orderMiscOptions[i]
orderMiscOptionsStr += tagValue.tag
orderMiscOptionsStr += "="
orderMiscOptionsStr += tagValue.value
orderMiscOptionsStr += ";"
}
send(orderMiscOptionsStr)
}
// TODO: Handle errors here
//catch( Exception e) {
//error( id, EClientErrors_FAIL_SEND_ORDER, "" + e)
//close()
//}
}
open func reqAccountUpdates(_ subscribe: Bool, acctCode: String) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 2
// send cancel order msg
send(REQ_ACCOUNT_DATA )
send(VERSION)
send(subscribe)
// Send the account code. This will only be used for FA clients
if ( _serverVersion >= 9 ) {
send(acctCode)
}
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_ACCT, "" + e)
//close()
//}
}
open func reqExecutions(_ reqId: Int, filter: ExecutionFilter) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 3
// send cancel order msg
send(REQ_EXECUTIONS)
send(VERSION)
if _serverVersion >= MIN_SERVER_VER_EXECUTION_DATA_CHAIN {
send(reqId)
}
// Send the execution rpt filter data
if ( _serverVersion >= 9 ) {
send(filter.clientId)
send(filter.acctCode)
// Note that the valid format for m_time is "yyyymmdd-hh:mm:ss"
send(filter.time)
send(filter.symbol)
send(filter.secType)
send(filter.exchange)
send(filter.side)
}
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_EXEC, "" + e)
//close()
//}
}
open func cancelOrder(_ id: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send cancel order msg
send(CANCEL_ORDER)
send(VERSION)
send(id)
//catch( Exception e) {
//error( id, EClientErrors_FAIL_SEND_CORDER, "" + e)
//close()
//}
}
open func reqOpenOrders() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send cancel order msg
send(REQ_OPEN_ORDERS)
send(VERSION)
//catch( Exception e) {
//error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e)
//tail: close()
//}
}
open func reqIds(_ numIds: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
send(REQ_IDS)
send(VERSION)
send(numIds)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e)
//close()
//}
}
open func reqNewsBulletins(_ allMsgs: Bool) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
send(REQ_NEWS_BULLETINS)
send(VERSION)
send(allMsgs)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e)
//close()
//}
}
open func cancelNewsBulletins() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send cancel order msg
send(CANCEL_NEWS_BULLETINS)
send(VERSION)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e)
//close()
//}
}
func setServerLogLevel(_ logLevel: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send the set server logging level message
send(SET_SERVER_LOGLEVEL)
send(VERSION)
send(logLevel)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_SERVER_LOG_LEVEL, "" + e)
//close()
//}
}
open func reqAutoOpenOrders(_ bAutoBind: Bool) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send req open orders msg
send(REQ_AUTO_OPEN_ORDERS)
send(VERSION)
send(bAutoBind)
//catch( Exception e) {
//error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e)
//tail: close()
//}
}
open func reqAllOpenOrders() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send req all open orders msg
send(REQ_ALL_OPEN_ORDERS)
send(VERSION)
//catch( Exception e) {
//error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e)
//tail: close()
//}
}
open func reqManagedAccts() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
let VERSION = 1
// send req FA managed accounts msg
send(REQ_MANAGED_ACCTS)
send(VERSION)
//catch( Exception e) {
//error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e)
//tail: close()
//}
}
open func requestFA(_ faDataType: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >= 13
if (_serverVersion < 13) {
error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code,
errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
let VERSION = 1
send(REQ_FA )
send(VERSION)
send(faDataType)
//catch( Exception e) {
//error( faDataType, EClientErrors_FAIL_SEND_FA_REQUEST, "" + e)
//close()
//}
}
func replaceFA(_ faDataType: Int, xml: String) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >= 13
if (_serverVersion < 13) {
error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code,
errorMsg: EClientErrors_UPDATE_TWS.msg)
return
}
let VERSION = 1
send(REPLACE_FA )
send(VERSION)
send(faDataType)
send(xml)
//catch( Exception e) {
//error( faDataType, EClientErrors_FAIL_SEND_FA_REPLACE, "" + e)
//close()
//}
}
open func reqCurrentTime() { // synchronized
// not connected?
if !connected {
notConnected()
return
}
// This feature is only available for versions of TWS >= 33
if (_serverVersion < 33) {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support current time requests.")
return
}
let VERSION = 1
send(REQ_CURRENT_TIME )
send(VERSION)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQCURRTIME, "" + e)
//close()
//}
}
open func reqFundamentalData(_ reqId: Int, contract: Contract, reportType: String) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if (_serverVersion < MIN_SERVER_VER_FUNDAMENTAL_DATA) {
error( reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support fundamental data requests.")
return
}
if (_serverVersion < MIN_SERVER_VER_TRADING_CLASS) {
if( contract.conId > 0) {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support conId parameter in reqFundamentalData.")
return
}
}
let VERSION = 2
// send req fund data msg
send(REQ_FUNDAMENTAL_DATA)
send(VERSION)
send(reqId)
// send contract fields
if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) {
send(contract.conId)
}
send(contract.symbol)
send(contract.secType)
send(contract.exchange)
send(contract.primaryExch)
send(contract.currency)
send(contract.localSymbol)
send(reportType)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_REQFUNDDATA, "" + e)
//close()
//}
}
open func cancelFundamentalData(_ reqId: Int) { // synchronized
// not connected?
if !connected {
notConnected()
return
}
if (_serverVersion < MIN_SERVER_VER_FUNDAMENTAL_DATA) {
error( reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support fundamental data requests.")
return
}
let VERSION = 1
// send req mkt data msg
send(CANCEL_FUNDAMENTAL_DATA)
send(VERSION)
send(reqId)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_CANFUNDDATA, "" + e)
//close()
//}
}
// synchronized
func calculateImpliedVolatility(_ reqId: Int, contract: Contract,
optionPrice: Double, underPrice: Double) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support calculate implied volatility requests.")
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if contract.tradingClass.isEmpty == false {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support tradingClass parameter in calculateImpliedVolatility.")
return
}
}
let VERSION = 2
// send calculate implied volatility msg
send(REQ_CALC_IMPLIED_VOLAT)
send(VERSION)
send(reqId)
// send contract fields
send(contract.conId)
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
send(contract.multiplier)
send(contract.exchange)
send(contract.primaryExch)
send(contract.currency)
send(contract.localSymbol)
if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) {
send(contract.tradingClass)
}
send(optionPrice)
send(underPrice)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_REQCALCIMPLIEDVOLAT, "" + e)
//close()
//}
}
// synchronized
open func cancelCalculateImpliedVolatility(_ reqId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_CANCEL_CALC_IMPLIED_VOLAT {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support calculate implied volatility cancellation.")
return
}
let VERSION = 1
// send cancel calculate implied volatility msg
send(CANCEL_CALC_IMPLIED_VOLAT)
send(VERSION)
send(reqId)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_CANCALCIMPLIEDVOLAT, "" + e)
//close()
//}
}
// synchronized
func calculateOptionPrice(_ reqId: Int, contract: Contract,
volatility: Double, underPrice: Double) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REQ_CALC_OPTION_PRICE {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support calculate option price requests.")
return
}
if _serverVersion < MIN_SERVER_VER_TRADING_CLASS {
if contract.tradingClass.isEmpty == false {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support tradingClass parameter in calculateOptionPrice.")
return
}
}
let VERSION = 2
// send calculate option price msg
send(REQ_CALC_OPTION_PRICE)
send(VERSION)
send(reqId)
// send contract fields
send(contract.conId)
send(contract.symbol)
send(contract.secType)
send(contract.expiry)
send(contract.strike)
send(contract.right)
send(contract.multiplier)
send(contract.exchange)
send(contract.primaryExch)
send(contract.currency)
send(contract.localSymbol)
if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) {
send(contract.tradingClass)
}
send(volatility)
send(underPrice)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_REQCALCOPTIONPRICE, "" + e)
//close()
//}
}
// synchronized
open func cancelCalculateOptionPrice(_ reqId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_CANCEL_CALC_OPTION_PRICE {
error(reqId, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support calculate option price cancellation.")
return
}
let VERSION = 1
// send cancel calculate option price msg
send(CANCEL_CALC_OPTION_PRICE)
send(VERSION)
send(reqId)
//catch( Exception e) {
//error( reqId, EClientErrors_FAIL_SEND_CANCALCOPTIONPRICE, "" + e)
//close()
//}
}
// synchronized
open func reqGlobalCancel() {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REQ_GLOBAL_CANCEL {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support globalCancel requests.")
return
}
let VERSION = 1
// send request global cancel msg
send(REQ_GLOBAL_CANCEL)
send(VERSION)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQGLOBALCANCEL, "" + e)
//close()
//}
}
// synchronized
open func reqMarketDataType(_ marketDataType: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_REQ_MARKET_DATA_TYPE {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support marketDataType requests.")
return
}
let VERSION = 1
// send the reqMarketDataType message
send(REQ_MARKET_DATA_TYPE)
send(VERSION)
send(marketDataType)
//catch( Exception e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQMARKETDATATYPE, "" + e)
//close()
//}
}
// synchronized
open func reqPositions() {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support position requests.")
return
}
let VERSION = 1
let b = Builder()
b.send(REQ_POSITIONS)
b.send(VERSION)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQPOSITIONS, "" + e)
//}
}
// synchronized
open func cancelPositions() {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support position cancellation.")
return
}
let VERSION = 1
let b = Builder()
b.send(CANCEL_POSITIONS)
b.send(VERSION)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CANPOSITIONS, "" + e)
//}
}
// synchronized
open func reqAccountSummary(_ reqId: Int, group: String, tags: String) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support account summary requests.")
return
}
let VERSION = 1
let b = Builder()
b.send(REQ_ACCOUNT_SUMMARY)
b.send(VERSION)
b.send(reqId)
b.send(group)
b.send(tags)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQACCOUNTDATA, "" + e)
//}
}
// synchronized
open func cancelAccountSummary(_ reqId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support account summary cancellation.")
return
}
let VERSION = 1
let b = Builder()
b.send(CANCEL_ACCOUNT_SUMMARY)
b.send(VERSION)
b.send(reqId)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CANACCOUNTDATA, "" + e)
//}
}
// synchronized
func verifyRequest(_ apiName: String, apiVersion: String) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support verification request.")
return
}
if (!extraAuth) {
error( EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_VERIFYMESSAGE,
tail: " Intent to authenticate needs to be expressed during initial connect request.")
return
}
let VERSION = 1
let b = Builder()
b.send(VERIFY_REQUEST)
b.send(VERSION)
b.send(apiName)
b.send(apiVersion)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_VERIFYREQUEST, "" + e)
//}
}
// synchronized
func verifyMessage(_ apiData: String) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support verification message sending.")
return
}
let VERSION = 1
let b = Builder()
b.send(VERIFY_MESSAGE)
b.send(VERSION)
b.send(apiData)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_VERIFYMESSAGE, "" + e)
//}
}
// synchronized
func queryDisplayGroups(_ reqId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support queryDisplayGroups request.")
return
}
let VERSION = 1
let b = Builder()
b.send(QUERY_DISPLAY_GROUPS)
b.send(VERSION)
b.send(reqId)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_QUERYDISPLAYGROUPS, "" + e)
//}
}
// synchronized
func subscribeToGroupEvents(_ reqId: Int, groupId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support subscribeToGroupEvents request.")
return
}
let VERSION = 1
let b = Builder()
b.send(SUBSCRIBE_TO_GROUP_EVENTS)
b.send(VERSION)
b.send(reqId)
b.send(groupId)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_SUBSCRIBETOGROUPEVENTS, "" + e)
//}
}
// synchronized
func updateDisplayGroup(_ reqId: Int, contractInfo: String) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support updateDisplayGroup request.")
return
}
let VERSION = 1
let b = Builder()
b.send(UPDATE_DISPLAY_GROUP)
b.send(VERSION)
b.send(reqId)
b.send(contractInfo)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_UPDATEDISPLAYGROUP, "" + e)
//}
}
// synchronized
func unsubscribeFromGroupEvents(_ reqId: Int) {
// not connected?
if !connected {
notConnected()
return
}
if _serverVersion < MIN_SERVER_VER_LINKING {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS,
tail: " It does not support unsubscribeFromGroupEvents request.")
return
}
let VERSION = 1
let b = Builder()
b.send(UNSUBSCRIBE_FROM_GROUP_EVENTS)
b.send(VERSION)
b.send(reqId)
let bgb = b.bytes
dos?.write(bgb, maxLength: bgb.count)
//catch (IOException e) {
//error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_UNSUBSCRIBEFROMGROUPEVENTS, "" + e)
//}
}
func error(_ id: Int, errorCode: Int, errorMsg: String) { // synchronized
_anyWrapper.error(id, errorCode: errorCode, errorMsg: errorMsg)
}
open func close() {
eDisconnect()
eWrapper().connectionClosed()
}
func error(_ id: Int, pair: CodeMsgPair, tail: String) {
error(id, errorCode: pair.code, errorMsg: pair.msg + tail)
}
func send(_ str: String) {
// write string to data buffer; writer thread will
// write it to socket
if !str.isEmpty {
// TODO: Add comprehensive error handling here
if let dataBytes = str.data(using: String.Encoding.utf8, allowLossyConversion: false) {
var bytes = [UInt8](repeating: 0, count: dataBytes.count)
(dataBytes as NSData).getBytes(&bytes, length: dataBytes.count)
dos?.write(bytes, maxLength: dataBytes.count)
}
}
sendEOL()
}
func sendEOL() {
dos?.write(EOL, maxLength: 1)
}
func send(_ val: Int) {
send(itos(val))
}
func send(_ val: Character) {
let s = String(val)
send(s)
}
func send(_ val: Double) {
send(dtos(val))
}
func send(_ val: Int64) {
send(ltos(val))
}
func sendMax(_ val: Double) {
if (val == Double.nan) {
sendEOL()
}
else {
send(dtos(val))
}
}
func sendMax(_ val: Int) {
if (val == Int.max) {
sendEOL()
}
else {
send(itos(val))
}
}
func send(_ val: Bool) {
send( val ? 1 : 0)
}
func notConnected() {
error(EClientErrors_NO_VALID_ID, pair: EClientErrors_NOT_CONNECTED, tail: "")
}
}
// REMOVED METHOD
// public synchronized void eConnect(Socket socket, int clientId) throws IOException {
// m_clientId = clientId
// eConnect(socket)
// }
//
// private static boolean IsEmpty(String str) {
// return Util.StringIsEmpty(str)
// }
//
// private static boolean is( String str) {
// // return true if the string is not empty
// return str != null && str.length() > 0;
// }
//
// private static boolean isNull( String str) {
// // return true if the string is null or empty
// return !is( str)
// }
//
// /** @deprecated, never called. */
// protected synchronized void error( String err) {
// _anyWrapper.error( err)
// }
|
8a112162a37dd1e3ff415ffd93c3a84c
| 32.37281 | 166 | 0.54194 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.