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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rsaenzi/MyMoviesListApp
|
refs/heads/master
|
MyMoviesListApp/MyMoviesListApp/AuthModule.swift
|
mit
|
1
|
//
// AuthModule.swift
// MyMoviesListApp
//
// Created by Rigoberto Sáenz Imbacuán on 5/29/17.
// Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved.
//
import Foundation
class AuthModule {
var wireframe: AuthWireframe
var interactor: AuthInteractor
var presenter: AuthPresenter
init() {
wireframe = AuthWireframe()
interactor = AuthInteractor()
presenter = AuthPresenter()
presenter.wireframe = wireframe
presenter.interactor = interactor
}
}
|
3684486e9f2da815f41fc1183d51b651
| 19.740741 | 67 | 0.635714 | false | false | false | false |
tamanyan/UnlimitedScrollView
|
refs/heads/master
|
UnlimitedScrollViewExample/UnlimitedScrollViewExample/TextScrollView.swift
|
mit
|
1
|
//
// TextScrollView.swift
// UnlimitedScrollViewExample
//
// Created by tamanyan on 2015/10/26.
// Copyright © 2015年 tamanyan. All rights reserved.
//
import UIKit
class TextScrollView: UIScrollView, UIScrollViewDelegate {
var textLabel: UILabel?
var parantView: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
self.parantView = UIView(frame: frame)
self.textLabel = UILabel(frame: frame.insetBy(dx: 20, dy: 100))
self.textLabel?.textColor = UIColor.black
self.textLabel?.font = UIFont.boldSystemFont(ofSize: 30)
self.textLabel?.textAlignment = .center
self.textLabel?.layer.borderColor = UIColor.black.cgColor
self.textLabel?.layer.borderWidth = 2.0
self.addSubview(self.parantView!)
self.parantView?.addSubview(self.textLabel!)
self.clipsToBounds = false
self.minimumZoomScale = 1
self.maximumZoomScale = 4.0
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.contentSize = self.frame.size
self.delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.parantView
}
}
|
5c83af00adb890884f520baedc8809d7
| 30.595238 | 71 | 0.671439 | false | false | false | false |
ozgur/TestApp
|
refs/heads/master
|
TestApp/Models/Catalogue.swift
|
gpl-3.0
|
1
|
//
// Catalogue.swift
// TestApp
//
// Created by Ozgur on 15/02/2017.
// Copyright © 2017 Ozgur. All rights reserved.
//
import ObjectMapper
class Catalogue: Mappable {
var id: Int = NSNotFound
var name: String!
var companies: [Company] = []
required init?(map: Map) {}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
companies <- map["companies"]
}
}
// MARK: Equatable
extension Catalogue: Equatable {}
func ==(lhs: Catalogue, rhs: Catalogue) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
// MARK: CustomStringConvertible
extension Catalogue: CustomStringConvertible {
var description: String {
return "Catalogue <\(name)>"
}
}
|
97ec107019791b350b476a0bc1699f9b
| 16.585366 | 55 | 0.647712 | false | false | false | false |
BENMESSAOUD/yousign
|
refs/heads/master
|
YouSign/YouSign/BussinesObjects/Signature.swift
|
apache-2.0
|
1
|
//
// Signature.swift
// YouSign
//
// Created by Mahmoud Ben Messaoud on 05/06/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
@objc public class Token : NSObject{
public var token: String = kEmptyString
public var mail: String?
public var phone: String?
}
@objc public class FileInfo : NSObject{
public var id: String = kEmptyString
public var fileName: String = kEmptyString
public var sha1: String = kEmptyString
}
@objc public class Signature: NSObject {
public var id: String
var files = [FileInfo]()
var tokens = [Token]()
init(idDemand: String) {
self.id = idDemand
}
public func addFileInfo(fileInfo: FileInfo){
files.append(fileInfo)
}
public func addToken(token: Token){
tokens.append(token)
}
public func getToken(forSigner signer: Signer) -> Token {
let token = tokens.filter { (item: Token) -> Bool in
return signer.mail == item.mail && signer.phone == item.phone
}
return token.first ?? Token()
}
}
|
9c9f75ba78cdfee64303ccc46ca2227c
| 22.340426 | 73 | 0.640839 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS
|
refs/heads/develop
|
DuckDuckGo/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 18/01/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import UIKit
import Core
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private struct ShortcutKey {
static let search = "com.duckduckgo.mobile.ios.newsearch"
static let clipboard = "com.duckduckgo.mobile.ios.clipboard"
}
var window: UIWindow?
private lazy var groupData = GroupDataStore()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let shortcutItem = launchOptions?[.shortcutItem] {
handleShortCutItem(shortcutItem as! UIApplicationShortcutItem)
}
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
startOnboardingFlowIfNotSeenBefore()
}
private func startOnboardingFlowIfNotSeenBefore() {
var settings = OnboardingSettings()
if !settings.hasSeenOnboarding {
startOnboardingFlow()
settings.hasSeenOnboarding = true
}
}
private func startOnboardingFlow() {
guard let root = mainViewController() else { return }
let onboardingController = OnboardingViewController.loadFromStoryboard()
onboardingController.modalTransitionStyle = .flipHorizontal
root.present(onboardingController, animated: false, completion: nil)
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
handleShortCutItem(shortcutItem)
}
private func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) {
Logger.log(text: "Handling shortcut item: \(shortcutItem.type)")
if shortcutItem.type == ShortcutKey.search {
clearNavigationStack()
}
if shortcutItem.type == ShortcutKey.clipboard, let query = UIPasteboard.general.string {
mainViewController()?.loadQueryInNewWebTab(query: query)
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
Logger.log(text: "App launched with url \(url.absoluteString)")
clearNavigationStack()
if AppDeepLinks.isLaunch(url: url) {
return true
}
if AppDeepLinks.isQuickLink(url: url), let link = quickLink(from: url) {
loadQuickLink(link: link)
}
return true
}
private func quickLink(from url: URL) -> Link? {
guard let links = groupData.bookmarks else { return nil }
guard let host = url.host else { return nil }
guard let index = Int(host) else { return nil }
guard index < links.count else { return nil }
return links[index]
}
private func loadQuickLink(link: Link) {
mainViewController()?.loadUrlInNewWebTab(url: link.url)
}
private func mainViewController() -> MainViewController? {
return UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? MainViewController
}
private func clearNavigationStack() {
if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
navigationController.popToRootViewController(animated: false)
}
}
}
|
eb8957c27abc79baa773608e47004902
| 35.132653 | 155 | 0.672974 | false | false | false | false |
GuitarPlayer-Ma/Swiftweibo
|
refs/heads/master
|
weibo/weibo/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// weibo
//
// Created by mada on 15/9/27.
// Copyright © 2015年 MD. All rights reserved.
//
import UIKit
let JSJSwitchRootViewController = "JSJSwitchRootViewController"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 设置外观
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// 返回默认控制器
window?.rootViewController = defaultViewController()
window?.makeKeyAndVisible()
// 注册通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("switchRootViewController:"), name: JSJSwitchRootViewController, object: nil)
return true
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func switchRootViewController(notify: NSNotification) {
if notify.object != nil {
window?.rootViewController = WelcomeController()
}
window?.rootViewController = MainTabbarController()
}
/**
判断是不是新版本
*/
private func isNewUpdate() -> Bool {
// 获取当前版本号
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]! as! String
// 从沙盒中取出上次版本号(??作用:如果为nil则取??后面的值)
let lastVersion = NSUserDefaults.standardUserDefaults().valueForKey("version") ?? ""
// 比较两个版本
if currentVersion.compare(lastVersion as! String) == NSComparisonResult.OrderedDescending {
NSUserDefaults.standardUserDefaults().setValue(currentVersion, forKey: "version")
return true
}
return false
}
private func defaultViewController() -> UIViewController {
// 判断是否登录
if UserAccount.loadAccount() != nil {
return isNewUpdate() ? NewfeatureController() : WelcomeController()
}
// 保存当前版本
isNewUpdate()
return MainTabbarController()
}
}
/** 自定义打印输出*/
func JSJLog<T>(message: T, fileName: String = __FILE__, line: Int = __LINE__, method: String = __FUNCTION__) {
#if DEBUG
print("<\((fileName as NSString).lastPathComponent)>**\(line)**[\(method)]--\(message)")
#endif
}
|
27e818ce2c4adc65da713f89b49f944b
| 30.594937 | 159 | 0.642628 | false | false | false | false |
lavenderofme/MySina
|
refs/heads/master
|
Sina/Sina/Classes/Main/VisitorView.swift
|
apache-2.0
|
1
|
//
// VisitorView.swift
// Sina
//
// Created by shasha on 15/11/9.
// Copyright © 2015年 shasha. All rights reserved.
//
import UIKit
class VisitorView: UIView {
/** 中间的文字 */
@IBOutlet weak var titleLabel: UILabel!
/** 登录按钮 */
@IBOutlet weak var loginButton: UIButton!
/** 注册按钮 */
@IBOutlet weak var registerButton: UIButton!
/** 大图片 */
@IBOutlet weak var imageVIew: UIImageView!
/** 转盘 */
@IBOutlet weak var circleView: UIImageView!
// MARK: - 外部控制方法
func setupVisitorInfo(imageNamed: String?, title:String)
{
guard let name = imageNamed else {
starAnimation()
return
}
imageVIew.image = UIImage(named: name)
titleLabel.text = title
circleView.hidden = true
}
/** 快速创建方法 */
class func visitorView() -> VisitorView
{
return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).last as! VisitorView
}
// MARK: - 内部控制方法
func starAnimation(){
// 1.创建动画对象
let anim = CABasicAnimation(keyPath: "transform.rotation")
// 2.设置动画属性
anim.toValue = 2 * M_PI
anim.duration = 10.0
anim.repeatCount = MAXFLOAT
// 告诉系统不要随便给我移除动画, 只有当控件销毁的时候才需要移除
anim.removedOnCompletion = false
// 3.将动画添加到图层
circleView.layer.addAnimation(anim, forKey: nil)
}
}
|
52be094c1a420980d24be4ed0683c662
| 23.810345 | 111 | 0.584434 | false | false | false | false |
qinhaichuan/Microblog
|
refs/heads/master
|
microblog/microblog/Classes/OAuth/UserAccount.swift
|
mit
|
1
|
//
// UserAccount.swift
// microblog
//
// Created by QHC on 6/18/16.
// Copyright © 2016 秦海川. All rights reserved.
//
import UIKit
class UserAccount: NSObject, NSCoding {
/// 用于调用access_token,接口获取授权后的access token。
var access_token: String?
/// access_token的生命周期,单位是秒数。
var expires_in: NSNumber?
{
didSet{
expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
QHCLog("生命周期\(expires_Date)")
}
}
/// 当前授权用户的UID。
var uid: String?
/// 过期时间
var expires_Date: NSDate?
static var userAccount: UserAccount?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let proterty = ["access_token", "expires_in", "uid"]
let dict = dictionaryWithValuesForKeys(proterty)
return "\(dict)"
}
// MARK: ----- 保存模型到文件中
static let filePath = "userAccount.plist".cacheDirectory()
/**
* 保存模型
*/
func saveAccount() {
NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
}
/**
* 取出模型
*/
class func getUserAccount() -> UserAccount? {
if userAccount != nil {
return userAccount!
}
QHCLog("从文件中取出")
// 如果没有就取出
userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filePath) as? UserAccount
// 把刚登录时的时间取出了, 对比是否过期
guard let date = userAccount?.expires_Date where date.compare(NSDate()) == NSComparisonResult.OrderedDescending else {
QHCLog("已经过期\(userAccount)")
userAccount = nil
return userAccount
}
return userAccount!
}
/**
* 判断是否登录
*/
class func login() -> Bool {
return getUserAccount() != nil
}
// MARK: ----- NSCoding
/**
* 归档
*/
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_Date, forKey: "expires_Date")
}
/**
* 解档
*/
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
}
}
|
c1fee71ecc43e48100c7426b807e65e7
| 23 | 126 | 0.571225 | false | false | false | false |
tarunon/NotificationKit
|
refs/heads/master
|
NotificationKitTests/NotificationKitTests.swift
|
mit
|
1
|
//
// NotificationKitTests.swift
// NotificationKitTests
//
// Created by Nobuo Saito on 2015/08/04.
// Copyright © 2015年 tarunon. All rights reserved.
//
import XCTest
@testable import NotificationKit
class SampleNotification: Notification<NSObject, String> {
override var name: String {
return "SampleNotification"
}
}
class SampleNotification2: SimpleNotification<Int> {
override var name: String {
return "SampleNotification2"
}
}
class NotificationKitTests: 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 testPostNotification() {
let sampleNotification = SampleNotification()
let notificationObject = NSObject()
let notificationValue = "It is SampleNotification"
let observer = sampleNotification.addObserver(notificationObject, queue: nil) { object, value in
XCTAssertNotNil(object)
XCTAssertEqual(object!, notificationObject)
XCTAssertEqual(value, notificationValue)
}
sampleNotification.postNotification(notificationObject, value: notificationValue)
sampleNotification.postNotification(nil, value: "It is not observed at \(observer)")
}
func testPostNotification2() {
let sampleNotification = SampleNotification2()
let notificationValue = 1984
sampleNotification.addObserver(nil) { value in
XCTAssertEqual(value, notificationValue)
}
sampleNotification.postNotification(notificationValue)
}
func testRemoveNotification() {
var sampleNotification: SampleNotification!
autoreleasepool {
sampleNotification = SampleNotification()
let observer = sampleNotification.addObserver(nil, queue: nil) { object, value in
XCTFail()
}
sampleNotification.removeObserver(observer)
}
sampleNotification.postNotification(nil, value: "It is not observed.")
}
func testRemoveNotification2() {
var sampleNotification: SampleNotification2!
autoreleasepool {
sampleNotification = SampleNotification2()
let observer = sampleNotification.addObserver(nil, handler: { value in
XCTFail()
})
sampleNotification.removeObserver(observer)
}
sampleNotification.postNotification(1984)
}
}
|
efb822dfa79a629b13a782b65a389e50
| 29.265957 | 111 | 0.633392 | false | true | false | false |
Ryan-Vanderhoef/Antlers
|
refs/heads/master
|
AppIdea/ViewControllers/FriendsViewController.swift
|
mit
|
1
|
//
// FriendsViewController.swift
// AppIdea
//
// Created by Ryan Vanderhoef on 7/23/15.
// Copyright (c) 2015 Ryan Vanderhoef. All rights reserved.
//
import UIKit
import Parse
class FriendsViewController: UIViewController {
@IBOutlet weak var friendsTableView: UITableView!
var users: [PFUser] = []//? // All users
// var followingUsers: [PFUser]? {
// didSet {
// friendsTableView.reloadData()
// }
// }
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func segmentedControlAction(sender: AnyObject) {
viewDidAppear(true)
}
// @IBOutlet weak var segmentedControl: UISegmentedControl!
// @IBAction func segmentedControlAction(sender: AnyObject) {
//// println("seg pressed")
// viewDidAppear(true)
// }
override func viewDidLoad() {
super.viewDidLoad()
// self.friendsTableView.delegate = self
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//let friendPostQuery = PFQuery(className: "FriendRelation")
// if segmentedControl.selectedSegmentIndex == 0 {
// // Only want my friends
// let friendPostQuery = PFQuery(className: "FriendRelation")
//// println("first: \(friendPostQuery)")
// friendPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!)
//// println("second: \(friendPostQuery)")
// friendPostQuery.selectKeys(["toUser"])
//// println("thrid: \(friendPostQuery)")
// friendPostQuery.orderByAscending("fromUser")
//// println("fourth: \(friendPostQuery)")
// friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
//// println("results: \(result)")
// self.users = result as? [PFUser] ?? []
//// println("in here")
//// println("\(self.users)")
// self.friendsTableView.reloadData()
// }
//
// }
// else if segmentedControl.selectedSegmentIndex == 1 {
// Want all users
// if segmentedControl.selectedSegmentIndex == 1{
let friendPostQuery = PFUser.query()!
friendPostQuery.whereKey("username", notEqualTo: PFUser.currentUser()!.username!) // exclude the current user
friendPostQuery.orderByAscending("username") // Order first by username, alphabetically
friendPostQuery.addAscendingOrder("ObjectId") // Then order by ObjectId, alphabetically
friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
// println("qwerty: \(result)")
self.users = result as? [PFUser] ?? []
self.friendsTableView.reloadData()
println("\(self.users)")
}
// }
// else if segmentedControl.selectedSegmentIndex == 0 {
// println("my herd")
// let friendsPostQuery = PFQuery(className: "FriendRelation")
// friendsPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!)
// friendsPostQuery.selectKeys(["toUser"])
// friendsPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
// // println("qwerty: \(result)")
// var holding = result// as? [NSObject]
// println("holding : \(holding)")
//// var thing = holding![0]
//// println("thing : \(thing)")
//
// self.users = result as? [PFUser] ?? []
// self.friendsTableView.reloadData()
// println("\(self.users)")
// }
// }
// }
}
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.
println("preparing for segue")
println("segue is \(segue.identifier)")
if segue.identifier == "segueToSelectedFawn" {
let friendViewController = segue.destinationViewController as! SelectedFriendViewController
let indexPath = friendsTableView.indexPathForSelectedRow()
self.friendsTableView.deselectRowAtIndexPath(indexPath!, animated: false)
let selectedFriend = users[indexPath!.row]
friendViewController.friend = selectedFriend
}
}
}
extension FriendsViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users/*?*/.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell") as! FriendsTableViewCell
// cell.titleLabel!.text = "\(moviePosts[indexPath.row].Title)"
// cell.yearLabel!.text = "\(moviePosts[indexPath.row].Year)"
// cell.statusLabel!.text = "\(moviePosts[indexPath.row].Status)"
cell.friendsLabel!.text = "\(self.users/*!*/[indexPath.row].username!)"
//cell.friendsLabel!.text = "hello"
// let query = PFQuery(className: "FriendRelation")
// let test = PFQuery(className: "user")
// println("good1")
// var name = test.getObjectInBackgroundWithId(users![indexPath.row].objectId!) as! PFObject
// println("good2")
// query.whereKey("toUser", equalTo: name)
// println("good3")
// query.whereKey("fromUser", equalTo: PFUser.currentUser()!)
// println("good4")
// query.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
//// println("qwerty: \(result)")
//// self.users = result as? [PFUser] ?? []
//// self.friendsTableView.reloadData()
// println("toUser: \(self.users![indexPath.row].username!)")
// println(result)
//
// }
// if segmentedControl.selectedSegmentIndex == 0 {
// // Color To Watch movies as gray
// if moviePosts[indexPath.row].Status == "To Watch" {
// cell.backgroundColor = UIColor(red: 128/255, green: 128/255, blue: 128/255, alpha: 0.06)
// }
// // Color Have Watched movies as white
// else if moviePosts[indexPath.row].Status == "Have Watched" {
// cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16)
// }
// }
// else {
// // Color all movies white
// cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16)
// }
//
// if moviePosts[indexPath.row].Status == "Have Watched" {
// // If a movie has been watched, show rating
// var rate = moviePosts[indexPath.row].Rating
// if rate == 1 {cell.ratingLabel!.text = "Rating: ★☆☆☆☆"}
// else if rate == 2 {cell.ratingLabel!.text = "Rating: ★★☆☆☆"}
// else if rate == 3 {cell.ratingLabel!.text = "Rating: ★★★☆☆"}
// else if rate == 4 {cell.ratingLabel!.text = "Rating: ★★★★☆"}
// else if rate == 5 {cell.ratingLabel!.text = "Rating: ★★★★★"}
// else {cell.ratingLabel!.text = ""}
//
// }
// else {
// // If a movie has not been watched, don't show a rating
// cell.ratingLabel!.text = ""
// }
return cell
}
@IBAction func unwindToSegueFriends(segue: UIStoryboardSegue) {
if let identifier = segue.identifier {
println("indentifier is \(identifier)")
}
}
}
|
2416dbb733fb55d16dbdad3e5a68d987
| 39.365385 | 123 | 0.571701 | false | false | false | false |
nerdycat/Cupcake
|
refs/heads/master
|
Cupcake/Label.swift
|
mit
|
1
|
//
// Label.swift
// Cupcake
//
// Created by nerdycat on 2017/3/17.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
public var Label: UILabel {
cpk_swizzleMethodsIfNeed()
let label = UILabel()
return label
}
public extension UILabel {
/**
* Setting text or attributedText
* str can take any kind of value, even primitive type like Int.
* Usages:
.str(1024)
.str("hello world")
.str( AttStr("hello world").strikethrough() )
...
*/
@objc @discardableResult func str(_ any: Any?) -> Self {
if let attStr = any as? NSAttributedString {
self.attributedText = attStr
} else if let any = any {
self.text = String(describing: any)
} else {
self.text = nil
}
return self
}
/**
* Setting font
* font use Font() internally, so it can take any kind of values that Font() supported.
* See Font.swift for more information.
* Usages:
.font(15)
.font("20")
.font("body")
.font("Helvetica,15")
.font(someLabel.font)
...
**/
@objc @discardableResult func font(_ any: Any) -> Self {
self.font = Font(any)
return self
}
/**
* Setting textColor
* color use Color() internally, so it can take any kind of values that Color() supported.
* See Color.swift for more information.
* Usages:
.color(@"red")
.color(@"#F00")
.color(@"255,0,0")
.color(someLabel.textColor)
...
*/
@objc @discardableResult func color(_ any: Any) -> Self {
self.textColor = Color(any)
return self
}
/**
* Setting numberOfLines
* Usages:
.lines(2)
.lines(0) //multilines
.lines() //same as .lines(0)
*/
@objc @discardableResult func lines(_ numberOfLines: CGFloat = 0) -> Self {
self.numberOfLines = Int(numberOfLines)
return self
}
/**
* Setting lineSpacing
* Usages:
.lineGap(8)
*/
@objc @discardableResult func lineGap(_ lineSpacing: CGFloat) -> Self {
self.cpkLineGap = lineSpacing
return self
}
/**
* Setting textAlignment
* Usages:
.align(.center)
.align(.justified)
...
*/
@objc @discardableResult func align(_ textAlignment: NSTextAlignment) -> Self {
self.textAlignment = textAlignment
return self
}
/**
* Setup link handler.
* Use onLink in conjunction with AttStr's link method to make text clickable.
* This will automatically set isUserInteractionEnabled to true as well.
* Be aware of retain cycle when using this method.
* Usages:
.onLink({ text in print(text) })
.onLink({ [weak self] text in //capture self as weak reference when needed
print(text)
})
*/
@discardableResult func onLink(_ closure: @escaping (String)->()) -> Self {
self.isUserInteractionEnabled = true
self.cpkLinkHandler = closure
return self
}
}
|
393353974556e59253e8533d4ed0b2db
| 24.886179 | 94 | 0.556533 | false | false | false | false |
git-hushuai/MOMO
|
refs/heads/master
|
MMHSMeterialProject/UINavigationController/BusinessFile/简历库Item/TKOptimizeCell.swift
|
mit
|
1
|
//
// TKOptimizeCell.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/4/12.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class TKOptimizeCell: UITableViewCell {
var logoView:UIImageView = UIImageView();
var jobNameLabel:UILabel = UILabel();
var firstBaseInfoLabel:UILabel = UILabel();
var secondBaseInfoLabel:UILabel = UILabel();
var threeBaseInfoLabel :UILabel = UILabel();
var fourBaseInfoLabel:UILabel = UILabel();
var baseInfoLogoView:UIImageView = UIImageView();
var baseInfoPhoneView:UIImageView = UIImageView();
var baseInfoEmailView :UIImageView = UIImageView();
var baseInfoLogoLabel:UILabel = UILabel();
var baseInfoPhoneLabel:UILabel = UILabel();
var baseInfoEmailLabel:UILabel = UILabel.init();
var advisorContentButton:UIButton = UIButton.init(type:UIButtonType.Custom);
var CaverView:UILabel = UILabel.init();
var topCaverView:UILabel = UILabel.init();
var bottomCaverView: UILabel = UILabel.init();
var resumeModel:TKJobItemModel?{
didSet{
self.setCellSubInfoWithModle(resumeModel!);
}
}
func setCellSubInfoWithModle(resumeModel:TKJobItemModel){
self.logoView.sd_setImageWithURL(NSURL.init(string: resumeModel.logo), placeholderImage: UIImage.init(named: "缺X3"), options: SDWebImageOptions.RetryFailed);
self.jobNameLabel.text = resumeModel.expected_job;
self.jobNameLabel.sizeToFit();
if Int(resumeModel.sex) == 0{
self.firstBaseInfoLabel.text = "女";
}else if(Int(resumeModel.sex) == 1){
self.firstBaseInfoLabel.text = "男";
}else{
self.firstBaseInfoLabel.text = "";
}
self.secondBaseInfoLabel.text = resumeModel.position;
self.threeBaseInfoLabel.text = resumeModel.degree;
self.fourBaseInfoLabel.text = String.init(format: "%@年工作年限", resumeModel.year_work);
self.baseInfoLogoView.image = UIImage.init(named: "姓名@2x");
self.baseInfoLogoView.updateLayout();
self.baseInfoPhoneView.image = UIImage.init(named: "电话@2x");
self.baseInfoPhoneView.updateLayout();
self.baseInfoEmailView.image = UIImage.init(named: "邮箱@2x");
self.baseInfoEmailView.updateLayout();
self.baseInfoLogoLabel.text = resumeModel.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.name : "暂无";
let phoneStr = String.init(format: "%@", (resumeModel.phone)!);
if phoneStr != "<null>" && resumeModel.phone.intValue > 0{
self.baseInfoPhoneLabel.text = phoneStr;
}else{
self.baseInfoPhoneLabel.text = "暂无";
}
if resumeModel.email != nil{
self.baseInfoEmailLabel.text = resumeModel.email.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.email : "暂无";}else{
self.baseInfoEmailLabel.text = "暂无";
}
self.contentView.layoutSubviews();
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.contentView.addSubview(self.topCaverView);
self.topCaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.topCaverView.sd_layout()
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.heightIs(0.5)
.topEqualToView(self.contentView);
self.contentView.addSubview(self.logoView);
self.logoView.sd_layout()
.leftSpaceToView(self.contentView,14.0)
.topSpaceToView(self.contentView,10)
.widthIs(50)
.heightIs(50);
self.contentView.addSubview(self.jobNameLabel);
self.jobNameLabel.sd_layout()
.leftSpaceToView(self.logoView,14)
.topSpaceToView(self.contentView,10)
.heightIs(20);
self.jobNameLabel.setSingleLineAutoResizeWithMaxWidth(200);
self.jobNameLabel.textAlignment = .Left;
self.jobNameLabel.textColor = RGBA(0xff, g: 0x8a, b: 0x00, a: 1.0);
self.contentView.addSubview(self.firstBaseInfoLabel);
self.firstBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.firstBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.firstBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.firstBaseInfoLabel.sd_layout()
.leftEqualToView(self.jobNameLabel)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20.0);
self.firstBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(40);
self.firstBaseInfoLabel.isAttributedContent = false;
self.firstBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.secondBaseInfoLabel);
self.secondBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.secondBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.secondBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.secondBaseInfoLabel.sd_layout()
.leftSpaceToView(self.firstBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.secondBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.secondBaseInfoLabel.isAttributedContent = false;
self.secondBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.threeBaseInfoLabel);
self.threeBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.threeBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.threeBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.threeBaseInfoLabel.sd_layout()
.leftSpaceToView(self.secondBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.threeBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.threeBaseInfoLabel.isAttributedContent = false;
self.threeBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.fourBaseInfoLabel);
self.fourBaseInfoLabel.font = UIFont.systemFontOfSize(16.0);
self.fourBaseInfoLabel.textAlignment = NSTextAlignment.Left;
self.fourBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0);
self.fourBaseInfoLabel.sd_layout()
.leftSpaceToView(self.threeBaseInfoLabel,20)
.topSpaceToView(self.jobNameLabel,10)
.heightIs(20);
self.fourBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.fourBaseInfoLabel.isAttributedContent = false;
self.fourBaseInfoLabel.textAlignment = .Left;
self.contentView.addSubview(self.baseInfoLogoView);
self.baseInfoLogoView.sd_layout()
.leftSpaceToView(self.logoView,14.0)
.topSpaceToView(self.firstBaseInfoLabel,10)
.widthIs(16.0)
.heightIs(16.0);
self.contentView.addSubview(self.baseInfoLogoLabel);
self.baseInfoLogoLabel.sd_layout()
.leftSpaceToView(self.baseInfoLogoView,14)
.topEqualToView(self.baseInfoLogoView)
.heightIs(16)
self.baseInfoLogoLabel.setSingleLineAutoResizeWithMaxWidth(100);
self.baseInfoLogoLabel.textAlignment = .Left;
self.baseInfoLogoLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoLogoLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.baseInfoPhoneView);
self.baseInfoPhoneView.sd_layout()
.leftSpaceToView(self.baseInfoLogoView,100)
.topEqualToView(self.baseInfoLogoView)
.widthIs(16)
.heightIs(16);
self.contentView.addSubview(self.baseInfoPhoneLabel);
self.baseInfoPhoneLabel.sd_layout()
.leftSpaceToView(self.baseInfoPhoneView,14)
.topEqualToView(self.baseInfoLogoView)
.heightIs(16);
self.baseInfoPhoneLabel.setSingleLineAutoResizeWithMaxWidth(120);
self.baseInfoPhoneLabel.textAlignment = .Left;
self.baseInfoPhoneLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoPhoneLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.baseInfoEmailView);
self.baseInfoEmailView.sd_layout()
.leftEqualToView(self.baseInfoLogoView)
.topSpaceToView(self.baseInfoLogoView,10)
.widthIs(16.0)
.heightIs(16.0);
self.contentView.addSubview(self.baseInfoEmailLabel);
self.baseInfoEmailLabel.sd_layout()
.leftSpaceToView(self.baseInfoEmailView,14)
.topEqualToView(self.baseInfoEmailView)
.heightIs(16);
self.baseInfoEmailLabel.setSingleLineAutoResizeWithMaxWidth(240);
self.baseInfoEmailLabel.textAlignment = .Left;
self.baseInfoEmailLabel.font = UIFont.systemFontOfSize(12.0);
self.baseInfoEmailLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0);
self.contentView.addSubview(self.CaverView);
self.CaverView.sd_layout()
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.heightIs(0.5)
.topSpaceToView(self.baseInfoEmailView,6);
self.CaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.contentView.addSubview(self.advisorContentButton);
self.advisorContentButton.sd_layout()
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.topSpaceToView(self.CaverView,0)
.heightIs(44);
self.advisorContentButton.addTarget(self, action: "onClickCallPhoneBtn:", forControlEvents:.TouchUpInside)
self.advisorContentButton.setTitle("拨打电话", forState: .Normal);
self.advisorContentButton.titleLabel?.font = UIFont.systemFontOfSize(16);
self.advisorContentButton.titleLabel?.textAlignment = .Center;
self.advisorContentButton.setTitleColor(RGBA(0x3c, g: 0xb3, b: 0xec, a: 1.0), forState:.Normal);
self.contentView.addSubview(self.bottomCaverView);
self.bottomCaverView.backgroundColor = self.topCaverView.backgroundColor;
self.bottomCaverView.sd_layout()
.leftEqualToView(self.contentView)
.rightEqualToView(self.contentView)
.heightIs(0.5)
.topSpaceToView(self.advisorContentButton,0);
self.setupAutoHeightWithBottomView(self.bottomCaverView, bottomMargin: 0);
}
func onClickCallPhoneBtn(sender:UIButton){
print("onClickCallPhoneBtn");
let phoneInfo = String.init(format: "tel:%@", (self.resumeModel?.phone)!);
let webView = UIWebView.init();
webView.loadRequest(NSURLRequest.init(URL: NSURL.init(string: phoneInfo)!));
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.superview?.addSubview(webView);
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: rgb color
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
cae8caf3e6b5381cbc69aaee0ef42b7a
| 43.826923 | 165 | 0.665809 | false | false | false | false |
AkikoZ/PocketHTTP
|
refs/heads/master
|
PocketHTTP/PocketHTTP/Request/VariableEditingViewController.swift
|
gpl-3.0
|
1
|
//
// VariableEditingViewController.swift
// PocketHTTP
//
// Created by 朱子秋 on 2017/2/1.
// Copyright © 2017年 朱子秋. All rights reserved.
//
import UIKit
import CoreData
class VariableEditingViewController: UITableViewController {
@IBOutlet fileprivate weak var nameTextField: UITextField!
@IBOutlet fileprivate weak var valueTextField: UITextField!
@IBOutlet fileprivate weak var saveButton: UIBarButtonItem!
var managedObjectContext: NSManagedObjectContext!
var variable: PHVariable?
@IBAction private func save(_ sender: UIBarButtonItem) {
let variableToSave = variable == nil ? PHVariable(context: managedObjectContext) : variable!
variableToSave.name = nameTextField.text!
variableToSave.value = valueTextField.text!
do {
try managedObjectContext.save()
} catch {
let error = error as NSError
if error.code == 133021 {
let alert = UIAlertController(title: "Name Conflict", message: "Variable's name already existed, try another name.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
self.nameTextField.becomeFirstResponder()
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
return
} else {
fatalError("Could not save data: \(error)")
}
}
performSegue(withIdentifier: "EditedVariable", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
if let variable = variable {
title = "Edit Variable"
nameTextField.text = variable.name
valueTextField.text = variable.value
} else {
title = "Add Variable"
saveButton.isEnabled = false
}
}
}
extension VariableEditingViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
let newText = oldText.replacingCharacters(in: range, with: string) as NSString
if textField == nameTextField {
saveButton.isEnabled = newText.length > 0
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
valueTextField.becomeFirstResponder()
} else {
valueTextField.resignFirstResponder()
}
return true
}
}
|
d44a4339884aeda46a682044c6d67e3f
| 32.594937 | 156 | 0.623964 | false | false | false | false |
uwinkler/commons
|
refs/heads/master
|
commons/Array.swift
|
mit
|
1
|
//
// Array.swift
//
// Created by Ulrich Winkler on 09/01/2015.
// Copyright (c) 2015 Ulrich Winkler. All rights reserved.
//
import Foundation
extension Array {
mutating func removeObject(obj: NSObject) {
var idx = -1
for var i = 0; i < self.count; i++ {
if self[i] as! NSObject == obj {
idx = i
break
}
}
if idx > -1 {
self.removeAtIndex(idx)
}
}
mutating func appendAll(array: Array) {
for obj in array {
self.append(obj)
}
}
//
// Simulate simple FIFO and STACK queue operations
//
mutating func pop() -> T? {
return self.count > 0 ? self.removeAtIndex(0) : nil
}
mutating func push(obj: T) {
self.insert(obj, atIndex: 0)
}
mutating func add(obj: T) {
self.append(obj)
}
mutating func peek() -> T? {
return self.first
}
var nono: String {
get {
var ret = ""
for var i = 0; i < self.count; i++ {
if i % 4 == 0 {
ret += "\n\t\(i)\t"
}
ret += NSString(format: "0x%.2X ", self[i] as! UInt8) as String
}
return ret;
}
}
}
|
dbefaee97c8147f69150dd426a0b4c22
| 17.742857 | 79 | 0.450457 | false | false | false | false |
kumabook/FeedlyKit
|
refs/heads/master
|
Source/Entry.swift
|
mit
|
1
|
//
// Entry.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 12/23/14.
// Copyright (c) 2014 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import SwiftyJSON
public final class Entry: Equatable, Hashable,
ResponseObjectSerializable, ResponseCollectionSerializable,
ParameterEncodable {
public var id: String
public var title: String?
public var content: Content?
public var summary: Content?
public var author: String?
public var crawled: Int64 = 0
public var recrawled: Int64 = 0
public var published: Int64 = 0
public var updated: Int64?
public var alternate: [Link]?
public var origin: Origin?
public var keywords: [String]?
public var visual: Visual?
public var unread: Bool = true
public var tags: [Tag]?
public var categories: [Category] = []
public var engagement: Int?
public var actionTimestamp: Int64?
public var enclosure: [Link]?
public var fingerprint: String?
public var originId: String?
public var sid: String?
public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Entry]? {
let json = JSON(representation)
return json.arrayValue.map({ Entry(json: $0) })
}
@objc required public convenience init?(response: HTTPURLResponse, representation: Any) {
let json = JSON(representation)
self.init(json: json)
}
public static var instanceDidInitialize: ((Entry, JSON) -> Void)?
public init(id: String) {
self.id = id
}
public init(json: JSON) {
self.id = json["id"].stringValue
self.title = json["title"].string
self.content = Content(json: json["content"])
self.summary = Content(json: json["summary"])
self.author = json["author"].string
self.crawled = json["crawled"].int64Value
self.recrawled = json["recrawled"].int64Value
self.published = json["published"].int64Value
self.updated = json["updated"].int64
self.origin = Origin(json: json["origin"])
self.keywords = json["keywords"].array?.map({ $0.string! })
self.visual = Visual(json: json["visual"])
self.unread = json["unread"].boolValue
self.tags = json["tags"].array?.map({ Tag(json: $0) })
self.categories = json["categories"].arrayValue.map({ Category(json: $0) })
self.engagement = json["engagement"].int
self.actionTimestamp = json["actionTimestamp"].int64
self.fingerprint = json["fingerprint"].string
self.originId = json["originId"].string
self.sid = json["sid"].string
if let alternates = json["alternate"].array {
self.alternate = alternates.map({ Link(json: $0) })
} else {
self.alternate = nil
}
if let enclosures = json["enclosure"].array {
self.enclosure = enclosures.map({ Link(json: $0) })
} else {
self.enclosure = nil
}
Entry.instanceDidInitialize?(self, json)
}
public func hash(into hasher: inout Hasher) {
return id.hash(into: &hasher)
}
public func toParameters() -> [String : Any] {
var params: [String: Any] = ["published": NSNumber(value: published)]
if let title = title { params["title"] = title as AnyObject? }
if let content = content { params["content"] = content.toParameters() as AnyObject? }
if let summary = summary { params["summary"] = summary.toParameters() as AnyObject? }
if let author = author { params["author"] = author as AnyObject? }
if let enclosure = enclosure { params["enclosure"] = enclosure.map({ $0.toParameters() }) }
if let alternate = alternate { params["alternate"] = alternate.map({ $0.toParameters() }) }
if let keywords = keywords { params["keywords"] = keywords as AnyObject? }
if let tags = tags { params["tags"] = tags.map { $0.toParameters() }}
if let origin = origin { params["origin"] = origin.toParameters() as AnyObject? }
return params
}
public var thumbnailURL: URL? {
if let v = visual, let url = v.url.toURL() {
return url
}
if let links = enclosure {
for link in links {
if let url = link.href.toURL() {
if link.type.contains("image") { return url }
}
}
}
if let url = extractImgSrc() {
return url
}
return nil
}
func extractImgSrc() -> URL? {
if let html = content?.content {
let regex = try? NSRegularExpression(pattern: "<img.*src\\s*=\\s*[\"\'](.*?)[\"\'].*>",
options: NSRegularExpression.Options())
if let r = regex {
let range = NSRange(location: 0, length: html.count)
if let result = r.firstMatch(in: html, options: NSRegularExpression.MatchingOptions(), range: range) {
for i in 0...result.numberOfRanges - 1 {
let range = result.range(at: i)
let str = html as NSString
if let url = str.substring(with: range).toURL() {
return url
}
}
}
}
}
return nil
}
}
public func == (lhs: Entry, rhs: Entry) -> Bool {
return lhs.id == rhs.id
}
|
3c7dd8691ff875587fce202139267a97
| 39.047619 | 119 | 0.536776 | false | false | false | false |
bazelbuild/tulsi
|
refs/heads/master
|
src/TulsiGenerator/CommandLineSplitter.swift
|
apache-2.0
|
2
|
// Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Splits a string containing commandline arguments into an array of strings suitable for use by
/// Process.
class CommandLineSplitter {
let scriptPath: String
init() {
scriptPath = Bundle(for: type(of: self)).path(forResource: "command_line_splitter",
ofType: "sh")!
}
/// WARNING: This method utilizes a shell instance to evaluate the commandline and may have side
/// effects.
func splitCommandLine(_ commandLine: String) -> [String]? {
if commandLine.isEmpty { return [] }
var splitCommands: [String]? = nil
let semaphore = DispatchSemaphore(value: 0)
let process = ProcessRunner.createProcess(scriptPath, arguments: [commandLine]) {
completionInfo in
defer { semaphore.signal() }
guard completionInfo.terminationStatus == 0,
let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) else {
return
}
let split = stdout.components(separatedBy: CharacterSet.newlines)
splitCommands = [String](split.dropLast())
}
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return splitCommands
}
}
|
1a2061c4a79c708f4cf3b8a389561ceb
| 35.862745 | 110 | 0.681915 | false | false | false | false |
erolbaykal/EBColorEyes
|
refs/heads/master
|
EBColorEyes/EBImageColorAnalyser.swift
|
gpl-3.0
|
1
|
//
// EBImageColorAnalyser.swift
// EBColorEyes
//
// Created by beta on 18/04/16.
// Copyright © 2016 Baykal. All rights reserved.
//
import Foundation
import QuartzCore
import CoreImage
enum imageColorOrder:Int{
case rgb = 0
case bgr = 1
}
enum imageColorMode: Int{
case standard = 0
case increasedSaturation = 1
}
class EBImageColorAnalyser: NSObject {
var colorNamer = EBColorNamer()
func analayseImageColor(image: CGImage, colorOrder: imageColorOrder = imageColorOrder.rgb, colorMode:imageColorMode = imageColorMode.increasedSaturation)->String{
var theImage = image;
var theColorOrder = colorOrder;
//first apply color filters
if(colorMode == imageColorMode.increasedSaturation){
// Create an image object from the Quartz image
let filter = CIFilter(name: "CIColorControls")
filter!.setValue(CIImage(CGImage: theImage), forKey: kCIInputImageKey)
filter!.setValue(2.0, forKey: "inputSaturation")
theImage = convertCIImageToCGImage(filter!.outputImage!)
theColorOrder = imageColorOrder.bgr
}
//only then resize the image
let f:Int = 20
let width = CGImageGetWidth(image)
let height = CGImageGetHeight(image)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.NoneSkipFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let resizeContext = CGBitmapContextCreate(nil, width/f, height/f, 8, width/f*4, colorSpace, bitmapInfo.rawValue)
CGContextSetInterpolationQuality(resizeContext, CGInterpolationQuality.None)
CGContextDrawImage(resizeContext, CGRectMake(0, 0, CGFloat(width/f), CGFloat(height/f)), theImage)
theImage = CGBitmapContextCreateImage(resizeContext)!
//process pixels only after all tranformations and filters have been applied, as otherwise results may not be as expected
let rawData = CGDataProviderCopyData(CGImageGetDataProvider(theImage))
let buf:UnsafePointer<UInt8> = CFDataGetBytePtr(rawData)
let length:Int = CFDataGetLength(rawData)
var i:Int = 0
var c:Int = 0
var sumTable = [String:Int]()
//walk over the pixels in order to analyse then and populate the frequency table
while i < length {
var b:UInt8 = 0
var g:UInt8 = 0
var r:UInt8 = 0
if(theColorOrder == imageColorOrder.rgb){
r = buf.advancedBy(i+0).memory
g = buf.advancedBy(i+1).memory
b = buf.advancedBy(i+2).memory
} else if (theColorOrder == imageColorOrder.bgr){
b = buf.advancedBy(i+0).memory
g = buf.advancedBy(i+1).memory
r = buf.advancedBy(i+2).memory
}
c += 1
i = i+4
let colorName:EBColor = self.colorNamer.rgbToColorName(Float(r)/255, green: Float(g)/255, blue: Float(b)/255)
if((sumTable[colorName.rawValue]) != nil){
sumTable[colorName.rawValue] = (sumTable[colorName.rawValue]! + 1)
}else{
sumTable[colorName.rawValue] = 1
}
}
let sortedTable:Array = Array(sumTable).sort {$0.1 > $1.1}
var colorNameString = String()
if(sortedTable[0].1 > Int(Double(c)/1.7)){
colorNameString = "\(sortedTable[0].0)"
}else if(sortedTable[0].1 > c/2){
colorNameString = "mostly \(sortedTable[0].0)"
}else if (sortedTable[0].1 + sortedTable[0].1 > c/2){
colorNameString = "mostly \(sortedTable[0].0) and some \(sortedTable[1].0)"
}
return colorNameString
}
/* from http://wiki.hawkguide.com/wiki/Swift:_Convert_between_CGImage,_CIImage_and_UIImage*/
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage! {
let context = CIContext(options: nil)
return context.createCGImage(inputImage, fromRect: inputImage.extent)
}
}
|
aeb1cd8060c433c828047c7d12278772
| 36.4375 | 166 | 0.617844 | false | false | false | false |
pasmall/WeTeam
|
refs/heads/master
|
WeTools/WeTools/ViewController/Login/RegistViewController.swift
|
apache-2.0
|
1
|
//
// RegistViewController.swift
// WeTools
//
// Created by lhtb on 2016/11/17.
// Copyright © 2016年 lhtb. All rights reserved.
//
import UIKit
import Alamofire
class RegistViewController: BaseViewController {
let accTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 140, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入手机号码")
let psdTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入密码")
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "注册"
setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.navigationBar.isHidden = false
}
func setUI () {
view.addSubview(accTF)
view.addSubview(psdTF)
let line = UIView.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 0.4))
line.backgroundColor = backColor
view.addSubview(line)
psdTF.isSecureTextEntry = true
//登录
let logBtn = UIButton()
logBtn.frame = CGRect.init(x: 10, y: 248, width: SCREEN_WIDTH - 20, height: 44)
logBtn.backgroundColor = blueColor
logBtn.setTitle("注册", for: .normal)
logBtn.layer.cornerRadius = 4
logBtn.layer.masksToBounds = true
logBtn.addTarget(self, action: #selector(LoginViewController.tapLoginBtn), for: .touchUpInside)
view.addSubview(logBtn)
}
func tapLoginBtn() {
self.showSimpleHUD()
Alamofire.request( IP + "regist.php", method: .post, parameters: ["name":accTF.text!,"psd":psdTF.text!]).responseJSON { (data) in
if let json = data.result.value as? [String:Any]{
print(json)
if json["code"] as! Int == 200{
self.hidSimpleHUD()
_ = self.alert.showAlert("", subTitle: "注册成功", style: AlertStyle.success, buttonTitle: "返回登录", action: { (true) in
_ = self.navigationController?.popViewController(animated: true)
})
} else if json["code"] as! Int == 202{
_ = self.alert.showAlert("该账号已被注册")
}
}
}
}
}
|
6f6eac3f20171464cad65e2cd5e17fbd
| 29.275862 | 137 | 0.555049 | false | false | false | false |
bryancmiller/rockandmarty
|
refs/heads/master
|
Text Adventure/Text Adventure/CGFloatExtensions.swift
|
apache-2.0
|
1
|
//
// CGFloatExtensions.swift
// Text Adventure
//
// Created by Bryan Miller on 9/9/17.
// Copyright © 2017 Bryan Miller. All rights reserved.
//
import Foundation
import UIKit
extension CGFloat {
static func convertHeight(h: CGFloat, screenSize: CGRect) -> CGFloat {
// iPhone 5 height is 568 and designed on iPhone 5
let iPhone5Height: CGFloat = 568.0
let currentPhoneHeight: CGFloat = screenSize.height
// calculate ratio between iPhone 5 and current
let phoneRatio: CGFloat = currentPhoneHeight / iPhone5Height
return (h * phoneRatio)
}
static func convertWidth(w: CGFloat, screenSize: CGRect) -> CGFloat {
// iPhone 5 width is 320
let iPhone5Width: CGFloat = 320.0
let currentPhoneWidth: CGFloat = screenSize.width
// calculate ratio between iPhone 5 and current
let phoneRatio: CGFloat = currentPhoneWidth / iPhone5Width
return (w * phoneRatio)
}
}
|
2255423feb57df200b91fdd1b5abf5b1
| 31.633333 | 74 | 0.670072 | false | false | false | false |
aitim/XXWaterFlow
|
refs/heads/master
|
XXWaterFlow/XXCollectionViewLayout.swift
|
gpl-2.0
|
1
|
//
// XXCollectionViewLayout.swift
// XXWaterFlow
//
// Created by xin.xin on 3/12/15.
// Copyright (c) 2015 aitim. All rights reserved.
//
import UIKit
class XXCollectionViewLayout: UICollectionViewFlowLayout {
private var cellAttributes:[XXCollectionViewLayoutAttributes] = []
// private var columnHeights:[CGFloat] = [] //保存每一列的高度
override var collectionView:XXCollectionView?{
get{
return super.collectionView as? XXCollectionView
}
}
override func prepareLayout() {
NSLog("prepare")
super.prepareLayout()
//初始化各cell的attributes
var columnHeights:[CGFloat] = [] //记录每一列的高度
for i in 0..<self.collectionView!.columnCount{
columnHeights.append(0)
}
var section = 0
var itemCount = self.collectionView!.numberOfItemsInSection(section)
for i in 0..<itemCount{
var size:CGSize = (self.collectionView!.delegate! as XXCollectionViewDelegate).collectionView(self.collectionView!, sizeForItemAtIndexPath: NSIndexPath(forItem:i, inSection: section))
//找出高度最小的列
var minColumnHeight:CGFloat = CGFloat.max
var minColumnIndex:Int = 0
for j in 0..<self.collectionView!.columnCount{
if minColumnHeight > columnHeights[j]{
minColumnHeight = columnHeights[j]
minColumnIndex = j
}
}
columnHeights[minColumnIndex] = minColumnHeight + (size.height + self.collectionView!.margin)
//得到cell的frame
var frame = CGRectMake(CGFloat(minColumnIndex+1)*self.collectionView!.margin + CGFloat(minColumnIndex)*size.width, minColumnHeight + self.collectionView!.margin, size.width, size.height)
var attributes = XXCollectionViewLayoutAttributes(forCellWithIndexPath: NSIndexPath(forItem: i , inSection: section))
attributes.frame = frame
attributes.alpha = 1
// NSLog("cell \(i) frame:\(frame) heights:\(columnHeights)")
self.cellAttributes.append(attributes)
}
}
//返回collectionView的内容的尺寸
override func collectionViewContentSize() -> CGSize {
NSLog("返回contentSize")
var height:CGFloat = 0
for i in 0..<self.cellAttributes.count{
if (self.cellAttributes[i].frame.height+self.cellAttributes[i].frame.origin.y) > height {
height = (self.cellAttributes[i].frame.height + self.cellAttributes[i].frame.origin.y)
}
}
return CGSizeMake(self.collectionView!.frame.width, height + self.collectionView!.margin)
}
//返回rect中的所有的元素的布局属性
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
NSLog("返回rect中的所有的元素的布局属性")
var attributes:[UICollectionViewLayoutAttributes] = []
for i in 0..<self.cellAttributes.count{
if CGRectIntersectsRect(rect, self.cellAttributes[i].frame){
attributes.append(self.cellAttributes[i])
}
}
return attributes
}
//返回对应于indexPath的位置的cell的布局属性
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
NSLog("返回对应于indexPath的位置的cell的布局属性")
return self.cellAttributes[indexPath.item]
}
}
|
257fa041a82f90a978b351aa0957ab83
| 37.752809 | 198 | 0.632647 | false | false | false | false |
pigigaldi/Pock
|
refs/heads/develop
|
Pock/Widgets/WidgetsLoader.swift
|
mit
|
1
|
//
// WidgetsLoader.swift
// Pock
//
// Created by Pierluigi Galdi on 10/03/21.
//
import Foundation
import PockKit
// MARK: Notifications
extension NSNotification.Name {
static let didLoadWidgets = NSNotification.Name("didLoadWidgets")
}
// MARK: Helpers
private var kApplicationSupportPockFolder: String {
let prefix: String
if let path = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.path {
prefix = path
} else {
prefix = FileManager.default.homeDirectoryForCurrentUser.path + "/Library/Application Support"
}
return prefix + "/Pock"
}
internal let kWidgetsPath: String = kApplicationSupportPockFolder + "/Widgets"
internal let kWidgetsPathURL: URL = URL(fileURLWithPath: kWidgetsPath)
internal let kWidgetsTempPathURL: URL = URL(fileURLWithPath: kWidgetsPath + "/tmp")
// MARK: Loader
internal final class WidgetsLoader {
/// Typealias
typealias WidgetsLoaderHandler = ([PKWidgetInfo]) -> Void
/// File manager
private let fileManager = FileManager.default
/// Data
public static var loadedWidgets: [PKWidgetInfo] {
return installedWidgets.filter({ $0.loaded == true })
}
/// List of installed widgets (loaded or not)
public static var installedWidgets: [PKWidgetInfo] = []
init() {
/// Create support folders, if needed
guard createSupportFoldersIfNeeded() else {
AppController.shared.showMessagePanelWith(
title: "error.title.default".localized,
message: "error.message.cant_create_support_folders".localized,
style: .critical
)
return
}
}
/// Create support folders, if needed
private func createSupportFoldersIfNeeded() -> Bool {
return fileManager.createFolderIfNeeded(at: kApplicationSupportPockFolder) && fileManager.createFolderIfNeeded(at: kWidgetsPath)
}
/// Load installed widgets
internal func loadInstalledWidgets(_ completion: @escaping WidgetsLoaderHandler) {
WidgetsLoader.installedWidgets.removeAll()
let widgetURLs = fileManager.filesInFolder(kWidgetsPath, filter: {
$0.contains(".pock") && !$0.contains("disabled") && !$0.contains("/")
})
var widgets: [PKWidgetInfo] = []
for widgetFilePathURL in widgetURLs {
guard let widget = loadWidgetAtURL(widgetFilePathURL) else {
continue
}
widgets.append(widget)
}
completion(widgets)
NotificationCenter.default.post(name: .didLoadWidgets, object: nil)
}
/// Load single widget
private func loadWidgetAtURL(_ url: URL) -> PKWidgetInfo? {
do {
let info = try PKWidgetInfo(path: url)
if !WidgetsLoader.installedWidgets.contains(info) {
WidgetsLoader.installedWidgets.append(info)
}
return info
} catch let error1 {
do {
let info = try PKWidgetInfo(unloadableWidgetAtPath: url)
if !WidgetsLoader.installedWidgets.contains(info) {
WidgetsLoader.installedWidgets.append(info)
}
return info
} catch let error2 {
Roger.error(error2.localizedDescription)
}
Roger.error(error1.localizedDescription)
return nil
}
}
}
|
1d3cfbf625cadd1fce6bacf056c9b48c
| 28.018692 | 130 | 0.706924 | false | false | false | false |
carambalabs/Curt
|
refs/heads/master
|
Example/CurtTests/Tests.swift
|
mit
|
1
|
//
// Created by Sergi Gracia on 30/01/2017.
// Copyright © 2017 Caramba. All rights reserved.
//
import XCTest
import Quick
import Nimble
class CurtTests: QuickSpec {
override func spec() {
var view: UIView!
var viewA: UIView!
var viewB: UIView!
var viewC: UIView!
var cA: NSLayoutConstraint!
var cB: NSLayoutConstraint!
var constantFloat: CGFloat!
var constantNegativeFloat: CGFloat!
var constantInt: Int!
var multiplierFloat: CGFloat!
var multiplierInt: Int!
beforeEach {
view = UIView()
viewA = UIView()
viewB = UIView()
viewC = UIView()
[viewA, viewB, viewC].forEach { view.addSubview($0) }
constantFloat = 12
constantNegativeFloat = -constantFloat
constantInt = Int(constantFloat)
multiplierFloat = 2.0
multiplierInt = Int(multiplierFloat)
}
describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor)
cA.isActive = true
cB = viewA.topAnchor ~ viewB.topAnchor
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(greaterThanOrEqualTo: viewB.topAnchor)
cA.isActive = true
cB = viewA.topAnchor >~ viewB.topAnchor
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(lessThanOrEqualTo: viewB.topAnchor)
cA.isActive = true
cB = viewA.topAnchor <~ viewB.topAnchor
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantFloat)
cA.isActive = true
cB = viewA.topAnchor ~ viewB.topAnchor + constantFloat
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Negative Constant)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantNegativeFloat)
cA.isActive = true
cB = viewA.topAnchor ~ viewB.topAnchor - constantFloat
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Int)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantFloat)
cA.isActive = true
cB = viewA.topAnchor ~ viewB.topAnchor + constantInt
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Negative Int)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantNegativeFloat)
cA.isActive = true
cB = viewA.topAnchor ~ viewB.topAnchor - constantInt
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(greaterThanOrEqualTo: viewB.topAnchor, constant: constantFloat)
cA.isActive = true
cB = viewA.topAnchor >~ viewB.topAnchor + constantFloat
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.topAnchor.constraint(lessThanOrEqualTo: viewB.topAnchor, constant: constantFloat)
cA.isActive = true
cB = viewA.topAnchor <~ viewB.topAnchor + constantFloat
expect(cA) == cB
}
}
describe("constraint(equalToConstant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(equalToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor ~ constantFloat
expect(cA) == cB
}
}
describe("constraint(equalToConstant c: CGFloat) (Int)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(equalToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor ~ constantInt
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualToConstant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(greaterThanOrEqualToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor >~ constantFloat
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualToConstant c: CGFloat) (Int)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(greaterThanOrEqualToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor >~ constantInt
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualToConstant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(lessThanOrEqualToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor <~ constantFloat
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualToConstant c: CGFloat) (Int)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(lessThanOrEqualToConstant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor <~ constantInt
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat)
cA.isActive = true
cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierFloat
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat) (Int)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat)
cA.isActive = true
cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierInt
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(greaterThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat)
cA.isActive = true
cB = viewA.widthAnchor >~ viewB.widthAnchor * multiplierFloat
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(lessThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat)
cA.isActive = true
cB = viewA.widthAnchor <~ viewB.widthAnchor * multiplierFloat
expect(cA) == cB
}
}
describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierFloat + constantFloat
expect(cA) == cB
}
}
describe("constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(greaterThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor >~ viewB.widthAnchor * multiplierFloat + constantFloat
expect(cA) == cB
}
}
describe("constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") {
it("creates valid constraint") {
cA = viewA.widthAnchor.constraint(lessThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat)
cA.isActive = true
cB = viewA.widthAnchor <~ viewB.widthAnchor * multiplierFloat + constantFloat
expect(cA) == cB
}
}
// MARK: - Extra operations
describe("constrain to all X, Y anchors") {
it("creates valid constraint") {
let csA = [viewA.topAnchor.constraint(equalTo: viewB.topAnchor),
viewA.leadingAnchor.constraint(equalTo: viewB.leadingAnchor),
viewA.trailingAnchor.constraint(equalTo: viewB.trailingAnchor),
viewA.bottomAnchor.constraint(equalTo: viewB.bottomAnchor)]
NSLayoutConstraint.activate(csA)
let csB = viewA ~ viewB
for (coA, coB) in zip(csA, csB) {
expect(coA) == coB
}
}
}
}
}
|
e89b020df542cb635ea586467181fdb1
| 40.783465 | 144 | 0.570338 | false | false | false | false |
biohazardlover/ByTrain
|
refs/heads/master
|
ByTrain/Filter.swift
|
mit
|
1
|
import Foundation
class Filter: NSObject, NSCopying {
var fromStations: [FilterItem] = []
var toStations: [FilterItem] = []
var trainTypes: [FilterItem] = [
FilterItem(type: .gcTrain, name: "GC-高铁/城际", selected: true),
FilterItem(type: .dTrain, name: "D-动车", selected: true),
FilterItem(type: .zTrain, name: "Z-直达", selected: true),
FilterItem(type: .tTrain, name: "T-特快", selected: true),
FilterItem(type: .kTrain, name: "K-快速", selected: true),
FilterItem(type: .otherTrain, name: "其他", selected: true)
]
var timeRanges: [FilterItem] = [
FilterItem(type: .timeFrom00To24, name: "00:00--24:00", selected: true),
FilterItem(type: .timeFrom00To06, name: "00:00--06:00", selected: false),
FilterItem(type: .timeFrom06To12, name: "06:00--12:00", selected: false),
FilterItem(type: .timeFrom12To18, name: "12:00--18:00", selected: false),
FilterItem(type: .timeFrom18To24, name: "18:00--24:00", selected: false)
]
func copy(with zone: NSZone? = nil) -> Any {
let filter = Filter()
filter.fromStations = []
for fromStation in fromStations {
filter.fromStations.append(fromStation.copy() as! FilterItem)
}
filter.toStations = []
for toStation in toStations {
filter.toStations.append(toStation.copy() as! FilterItem)
}
filter.trainTypes = []
for trainType in trainTypes {
filter.trainTypes.append(trainType.copy() as! FilterItem)
}
filter.timeRanges = []
for timeRange in timeRanges {
filter.timeRanges.append(timeRange.copy() as! FilterItem)
}
return filter
}
}
|
f5a2be0a5928d8fd3ca85b51fbe6601b
| 33.226415 | 81 | 0.582139 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureCoin/Sources/FeatureCoinDomain/HistoricalPrice/Model/Series.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct Series: Hashable {
public let window: Interval
public let scale: Scale
}
extension Series {
public static let now = Self(window: ._15_minutes, scale: ._15_minutes)
public static let day = Self(window: .day, scale: ._15_minutes)
public static let week = Self(window: .week, scale: ._1_hour)
public static let month = Self(window: .month, scale: ._2_hours)
public static let year = Self(window: .year, scale: ._1_day)
public static let all = Self(window: .all, scale: ._5_days)
}
|
80699b322d5e1258652eed3d911cec92
| 34.764706 | 75 | 0.682566 | false | false | false | false |
lulee007/GankMeizi
|
refs/heads/master
|
GankMeizi/Splash/SplashViewController.swift
|
mit
|
1
|
//
// WelcomeViewController.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/19.
// Copyright © 2016年 lulee007. All rights reserved.
//
import UIKit
import EAIntroView
import CocoaLumberjack
class SplashViewController: UIViewController,EAIntroDelegate {
let pageTitles = [
"技术干货",
"精选妹纸美图",
"午间放松视频"
]
let pageDescriptions = [
"为大家精选的技术干货,充电充电充电",
"每天一张精选的美丽妹纸图,放空你的思绪",
"中午小憩一会儿,戴上耳机以免可能影响他人"
]
override func viewDidLoad() {
super.viewDidLoad()
buildAndShowIntroView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func introDidFinish(introView: EAIntroView!) {
DDLogDebug("欢迎页结束,进入主页")
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.setupRootVCWithNC(MainTabBarViewController.buildController())
}
func buildAndShowIntroView() {
self.view.backgroundColor = ThemeUtil.colorWithHexString(ThemeUtil.PRIMARY_COLOR)
var pages = [EAIntroPage]()
for pageIndex in 0..<3{
let page = EAIntroPage.init()
page.title = pageTitles[pageIndex]
page.desc = pageDescriptions[pageIndex]
pages.append(page)
}
let eaIntroView = EAIntroView.init(frame: (self.view.bounds), andPages: pages)
eaIntroView.titleView = UIImageView.init(image: scaleImage(UIImage(named: "SplashTitle")!, toSize: CGSize.init(width: 135, height: 135)))
eaIntroView.titleViewY = 90
eaIntroView.backgroundColor = ThemeUtil.colorWithHexString(ThemeUtil.PRIMARY_COLOR)
eaIntroView.skipButton.setTitle("跳过", forState: UIControlState.Normal)
eaIntroView.delegate = self
eaIntroView.showInView(self.view, animateDuration: 0.3)
DDLogDebug("初始化完成并显示欢迎页")
}
func scaleImage(image: UIImage, toSize newSize: CGSize) -> (UIImage) {
let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height))
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, .High)
let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)
CGContextConcatCTM(context, flipVertical)
CGContextDrawImage(context, newRect, image.CGImage)
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!)
UIGraphicsEndImageContext()
return newImage
}
// 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.
}
}
|
f618e4badc08c5e5a149d583a96666bd
| 32.55914 | 145 | 0.658122 | false | false | false | false |
orta/Tinker
|
refs/heads/master
|
Tinker/Library/Room.swift
|
mit
|
1
|
//
// Room.swift
// Relate
//
// Created by Orta on 8/23/14.
// Copyright (c) 2014 Orta. All rights reserved.
//
public class Room: TinkerObject {
public var roomDescription:String?
public var northRoom: Room?
public var eastRoom: Room?
public var westRoom: Room?
public var southRoom: Room?
public var items: [Item] = []
public var people: [Person] = []
var visited = false
public func connectNorth(room: Room) {
self.northRoom = room
room.southRoom = self
}
public func connectSouth(room:Room) {
self.southRoom = room
room.northRoom = self
}
public func connectEast(room: Room) {
self.eastRoom = room
room.westRoom = self
}
public func connectWest(room: Room) {
self.westRoom = room
room.eastRoom = self
}
func describeInsideRoom() {
for item in items {
TQ.print(item.descriptionInRoom);
}
}
public func addPerson(person: Person) {
people.append(person)
heldObjects.append(person)
}
public func addItem(item: Item) {
items.append(item)
heldObjects.append(item)
}
public func pickUpItem(itemID: String) {
if let item = itemForID(itemID) {
heldObjects.remove(item)
items.remove(item)
if item.onPickUp != nil {
item.onPickUp!()
}
Tinker.sharedInstance.player.addItem(item)
}
}
func itemForID(itemID: String) -> Item? {
for item in items {
if item.id == itemID {
return item
}
}
return nil
}
}
|
2195f85b5c66f1260db3ece8c24da0a2
| 21.15 | 54 | 0.534989 | false | false | false | false |
Cleverlance/Pyramid
|
refs/heads/master
|
Example/Tests/Scope Management/Injection/AssemblerScopeImplTests.swift
|
mit
|
1
|
//
// Copyright © 2016 Cleverlance. All rights reserved.
//
import XCTest
import Nimble
import Pyramid
import Swinject
class AssemblerScopeImplTests: XCTestCase {
func test_ItConformsToScopeProtocol() {
let _: Scope? = (nil as AssemblerScopeImpl<SpecDummy>?)
}
func testGetInstanceOf_GivenSpecWithInt42Assembly_WhenRequestingInt_ItShouldReturn42() {
let scope = AssemblerScopeImpl<SpecStubWithInt42Assembly>(parent: nil)
let result = scope.getInstance(of: Int.self)
expect(result) == 42
}
func test_GetInstanceOf_GivenParentWithSpecWithInt42_WhenRequestingInt_itShouldReturn42() {
let scope = AssemblerScopeImpl<SpecDummy>(parent: ScopeStubInt42(parent: nil))
let result = scope.getInstance(of: Int.self)
expect(result) == 42
}
}
private struct SpecDummy: AssemblerScopeSpec {
static var assemblies = [Assembly]()
}
private struct SpecStubWithInt42Assembly: AssemblerScopeSpec {
static var assemblies: [Assembly] = [AssemblyStubInt42()]
}
private struct AssemblyStubInt42: Assembly {
func assemble(container: Container) {
container.register(Int.self) { _ in 42 }
}
}
private typealias ScopeStubInt42 = AssemblerScopeImpl<SpecStubWithInt42Assembly>
|
b5b4206e9a3e0d5414feeef588412dd9
| 27.704545 | 95 | 0.729216 | false | true | false | false |
HipHipArr/PocketCheck
|
refs/heads/master
|
Cheapify 2.0/TaskManager.swift
|
mit
|
1
|
//
// TaskManager.swift
// Cheapify 2.0
//
// Created by Christine Wen on 7/1/15.
// Copyright (c) 2015 Your Friend. All rights reserved.
//
import UIKit
var taskMgr: TaskManager = TaskManager()
struct Task {
var event = "Name"
var category = "Description"
var price = "0.00"
var tax = "0.00"
var tip = "0.00"
}
class TaskManager: NSObject {
var tasks = [Task]()
func addTask(event: String, category: String, price: String, tax: String, tip: String){
tasks.append(Task(event: event, category: category, price: price, tax: tax, tip: tip))
}
func removeTask(index:Int){
tasks.removeAtIndex(index)
}
}
|
0959db76526e3e51ebe4f862e0b6ca9f
| 18.052632 | 94 | 0.578729 | false | false | false | false |
m-alani/contests
|
refs/heads/master
|
hackerrank/ClimbingTheLeaderboard.swift
|
mit
|
1
|
//
// ClimbingTheLeaderboard.swift
//
// Practice solution - Marwan Alani - 2021
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/climbing-the-leaderboard/
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
func climbingLeaderboard(ranked: [Int], player: [Int]) -> [Int] {
var output = [Int]()
var rankings = removeDuplicates(from: ranked)
for score in player {
while ((rankings.last ?? 0) <= score && !rankings.isEmpty) {
_ = rankings.popLast()
}
output.append((rankings.isEmpty) ? 1 : rankings.count + 1)
}
return output
}
func removeDuplicates(from arr: [Int]) -> [Int] {
var uniques = [Int]()
for score in arr {
if score != uniques.last {
uniques.append(score)
}
}
return uniques
}
|
85131e837ba3bd1a64b6652f11d36b85
| 27.030303 | 120 | 0.611892 | false | false | false | false |
Melon-IT/base-model-swift
|
refs/heads/master
|
MelonBaseModel/MelonBaseModel/MPropertyListData.swift
|
mit
|
1
|
//
// MBFBaseDataParser.swift
// MelonBaseModel
//
// Created by Tomasz Popis on 10/06/16.
// Copyright © 2016 Melon. All rights reserved.
//
import Foundation
/*
public protocol MBFDataParserProtocol {
var parserDataListener: MBFParserDataListener? {set get}
var resource: Any? {set get}
func load()
func save()
func clear()
func delete()
func parse(completionHandler: ((Bool) -> Void)?)
}
public protocol MBFParserDataListener {
func dataDidParse(success: Bool, type: UInt?)
}
*/
public class MPropertyList<Type> {
public var resourcesName: String?
fileprivate var resources: Type?
public init() {}
public init(resources: String) {
self.resourcesName = resources
}
fileprivate func readResourcesFromBundle() {
if let path = Bundle.main.path(forResource: resourcesName, ofType: "plist"),
let content = try? Data(contentsOf: URL(fileURLWithPath: path)) {
self.resources =
(try? PropertyListSerialization.propertyList(from: content,
options: [],
format: nil)) as? Type
}
}
fileprivate func cleanResources() {
self.resources = nil
}
}
public class MBundleDictionaryPropertyList<Type>: MPropertyList<Dictionary<String,Type>> {
public func read() {
self.readResourcesFromBundle();
}
public func clean() {
super.cleanResources()
}
public var numberOfItems: Int {
var result = 0;
if let counter = self.resources?.count {
result = counter
}
return result
}
public subscript(key: String) -> Type? {
return self.resources?[key]
}
}
public class MBundleArrayPropertyList<Type>: MPropertyList<Array<Type>> {
public func read() {
self.readResourcesFromBundle();
}
public func clean() {
super.cleanResources()
}
public var numberOfItems: Int {
var result = 0;
if let counter = self.resources?.count {
result = counter
}
return result
}
public subscript(index: Int) -> Type? {
var result: Type?
if let counter = self.resources?.count,
index >= 0 && index < counter {
result = self.resources?[index]
}
return result
}
}
/*
open class MBFBaseDataParser {
public init() {
}
open func loadData() {
}
open func saveData() {
}
open func parseData(data: AnyObject?) {
}
open func loadFromDefaults(key: String) -> AnyObject? {
let defaults = UserDefaults.standard
return defaults.object(forKey: key) as AnyObject?
}
open func saveToDefaults(key: String, object: AnyObject?) {
let defaults = UserDefaults.standard
defaults.set(object, forKey: key)
defaults.synchronize()
}
open func uniqueUserKey(userId: String,
separator: String,
suffix: String) -> String {
return "\(userId)\(separator)\(suffix)"
}
}
*/
|
cda29c1efe1073838fe1b1ae04a7545b
| 17.929487 | 91 | 0.624788 | false | false | false | false |
joshua7v/ResearchOL-iOS
|
refs/heads/master
|
ResearchOL/Class/Me/Controller/ROLEditController.swift
|
mit
|
1
|
//
// ROLEditController.swift
// ResearchOL
//
// Created by Joshua on 15/5/16.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
protocol ROLEditControllerDelegate: NSObjectProtocol {
func editControllerSaveButtonDidClicked(editController: ROLEditController, item: ROLEditItem, value: String)
}
class ROLEditController: SESettingViewController {
var delegate: ROLEditControllerDelegate?
var checkboxes: NSMutableArray = NSMutableArray()
var isSingleChoice = true
var textField = UITextField()
var indexPath = NSIndexPath()
var item: ROLEditItem = ROLEditItem() {
didSet {
self.title = item.title
if item.type == 2 {
var group = self.addGroup()
var i = SESettingTextFieldItem(placeholder: self.item.title)
self.textField = i.textField
group.items = [i]
group.header = "请输入"
} else if item.type == 1 {
var group = self.addGroup()
var items: NSMutableArray = NSMutableArray()
for i in 0 ..< item.choices.count {
// var cell = SESettingArrowItem(title: item.choices[i])
var cell = SESettingCheckboxItem(title: item.choices[i], checkState: false)
cell.checkbox.addTarget(self, action: "handleCheckboxTapped:", forControlEvents: UIControlEvents.TouchDown)
cell.checkbox.userInteractionEnabled = false
self.checkboxes.addObject(cell.checkbox)
items.addObject(cell)
}
group.items = items as [AnyObject]
group.header = "请选择"
}
}
}
@objc private func handleCheckboxTapped(sender: M13Checkbox) {
if self.isSingleChoice == false {
if sender.checkState.value == M13CheckboxStateChecked.value {
sender.checkState = M13CheckboxStateUnchecked
} else {
sender.checkState = M13CheckboxStateChecked
}
return
}
if sender.checkState.value == M13CheckboxStateChecked.value {
} else {
for i:M13Checkbox in self.checkboxes.copy() as! [M13Checkbox] {
if i == sender {
i.checkState = M13CheckboxStateChecked
} else {
i.checkState = M13CheckboxStateUnchecked
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "编辑信息"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnDidClicked")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: UIBarButtonItemStyle.Plain, target: self, action: "saveBtnDidClicked")
}
@objc private func saveBtnDidClicked() {
println(item.title)
var value = ""
if item.type == 1 {
if self.isSingleChoice {
for i in enumerate(self.checkboxes.copy() as! [M13Checkbox]) {
if i.element.checkState.value == M13CheckboxStateChecked.value {
value = self.item.choices[i.index]
}
}
} else {
for i in enumerate(self.checkboxes.copy() as! [M13Checkbox]) {
if i.element.checkState.value == M13CheckboxStateChecked.value {
value = value.stringByAppendingString("\(self.item.choices[i.index]), ")
}
}
var newValue: NSString = value
value = newValue.substringToIndex(newValue.length - 2)
}
} else if item.type == 2 {
value = self.textField.text
}
ROLUserInfoManager.sharedManager.saveAttributeForCurrentUser(item.title, value: value, success: { (finished) -> Void in
println("attribute set success")
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}) { (error) -> Void in
println("error \(error)")
if error.code == 127 {
SEProgressHUDTool.showError("请输入正确的手机号", toView: self.navigationController?.view)
}
}
// change text in superview
if (self.delegate?.respondsToSelector("editControllerSaveButtonDidClicked:") != nil) {
self.delegate?.editControllerSaveButtonDidClicked(self, item: self.item, value: value)
}
}
@objc private func cancelBtnDidClicked() {
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ROLEditController: UITabBarDelegate {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var checkbox = self.checkboxes[indexPath.row] as! M13Checkbox
self.handleCheckboxTapped(checkbox)
}
}
|
24c81ebc76414b03ac9dcd7f15b7a2d0
| 37.106383 | 157 | 0.579564 | false | false | false | false |
jovito-royeca/Cineko
|
refs/heads/master
|
Cineko/StartViewController.swift
|
apache-2.0
|
1
|
//
// LoginViewController.swift
// Cineko
//
// Created by Jovit Royeca on 04/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import UIKit
import JJJUtils
import MBProgressHUD
import MMDrawerController
class StartViewController: UIViewController {
// MARK: Actions
@IBAction func loginAction(sender: UIButton) {
do {
if let requestToken = try TMDBManager.sharedInstance.getAvailableRequestToken() {
let urlString = "\(TMDBConstants.AuthenticateURL)/\(requestToken)"
performSegueWithIdentifier("presentLoginFromStart", sender: urlString)
} else {
let completion = { (error: NSError?) in
if let error = error {
performUIUpdatesOnMain {
MBProgressHUD.hideHUDForView(self.view, animated: true)
JJJUtil.alertWithTitle("Error", andMessage:"\(error.userInfo[NSLocalizedDescriptionKey]!)")
}
} else {
do {
if let requestToken = try TMDBManager.sharedInstance.getAvailableRequestToken() {
performUIUpdatesOnMain {
let urlString = "\(TMDBConstants.AuthenticateURL)/\(requestToken)"
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.performSegueWithIdentifier("presentLoginFromStart", sender: urlString)
}
}
} catch {}
}
}
MBProgressHUD.showHUDAddedTo(view, animated: true)
try TMDBManager.sharedInstance.authenticationTokenNew(completion)
}
} catch {}
}
@IBAction func skipLoginAction(sender: UIButton) {
performSegueWithIdentifier("presentDrawerFromStart", sender: sender)
}
// MARK: Overrides
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "presentLoginFromStart" {
if let vc = segue.destinationViewController as? LoginViewController {
vc.authenticationURLString = sender as? String
vc.delegate = self
}
} else if segue.identifier == "presentDrawerFromStart" {
// no op
}
}
}
// MARK: LoginViewControllerDelegate
extension StartViewController : LoginViewControllerDelegate {
func loginSuccess(viewController: UIViewController) {
if TMDBManager.sharedInstance.hasSessionID() {
if let controller = self.storyboard!.instantiateViewControllerWithIdentifier("DrawerController") as? MMDrawerController {
viewController.presentViewController(controller, animated: true, completion: nil)
}
} else {
viewController.dismissViewControllerAnimated(true, completion: nil)
}
}
}
|
48cb4391a3c0a2b4408fa8e5672e5f67
| 38.135802 | 133 | 0.564669 | false | false | false | false |
mcudich/TemplateKit
|
refs/heads/master
|
Examples/Twitter/Source/App.swift
|
mit
|
1
|
//
// App.swift
// TwitterClientExample
//
// Created by Matias Cudich on 10/27/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
import TemplateKit
import CSSLayout
struct AppState: State {
var tweets = [Tweet]()
}
func ==(lhs: AppState, rhs: AppState) -> Bool {
return lhs.tweets == rhs.tweets
}
class App: Component<AppState, DefaultProperties, UIView> {
override func didBuild() {
TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump") { tweets in
self.updateState { state in
state.tweets = tweets
}
}
}
override func render() -> Template {
var properties = DefaultProperties()
properties.core.layout = self.properties.core.layout
var tree: Element!
if state.tweets.count > 0 {
tree = box(properties, [
renderTweets()
])
} else {
properties.core.layout.alignItems = CSSAlignCenter
properties.core.layout.justifyContent = CSSJustifyCenter
tree = box(properties, [
activityIndicator(ActivityIndicatorProperties(["activityIndicatorViewStyle": UIActivityIndicatorViewStyle.gray]))
])
}
return Template(tree)
}
@objc func handleEndReached() {
guard let maxId = state.tweets.last?.id else {
return
}
TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump", maxId: maxId) { tweets in
self.updateState { state in
state.tweets.append(contentsOf: tweets.dropFirst())
}
}
}
private func renderTweets() -> Element {
var properties = TableProperties()
properties.core.layout.flex = 1
properties.tableViewDataSource = self
properties.items = [TableSection(items: state.tweets, hashValue: 0)]
properties.onEndReached = #selector(App.handleEndReached)
properties.onEndReachedThreshold = 700
return table(properties)
}
}
extension App: TableViewDataSource {
func tableView(_ tableView: TableView, elementAtIndexPath indexPath: IndexPath) -> Element {
var properties = TweetProperties()
properties.tweet = state.tweets[indexPath.row]
properties.core.layout.width = self.properties.core.layout.width
return component(TweetItem.self, properties)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return state.tweets.count
}
}
|
eac16b392d0815e73c333bbd621b9770
| 26.694118 | 121 | 0.697111 | false | false | false | false |
rbailoni/SOSHospital
|
refs/heads/master
|
SOSHospital/SOSHospital/Hospital.swift
|
mit
|
1
|
//
// Hospital.swift
// SOSHospital
//
// Created by William kwong huang on 27/10/15.
// Copyright © 2015 Quaddro. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class Hospital: NSManagedObject {
private let entityName = "Hospital"
private enum jsonEnum: String {
case id = "id"
case name = "nome"
case state = "estado"
case coordinates = "coordinates"
case latitude = "lat"
case longitude = "long"
case category = "categoria"
}
lazy var Location: CLLocation = {
return CLLocation(latitude: self.latitude, longitude: self.longitude)
}()
var distance: Double = 0
// MARK: - Create
func createHospital(context: NSManagedObjectContext) -> Hospital {
let item = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! Hospital
return item
}
// MARK: - Find
func findHospitals(context: NSManagedObjectContext, name: String? = nil, state: String? = nil) -> [Hospital] {
// cria a request
let fetchRequest = NSFetchRequest(entityName: entityName)
// faz algum filtro
if let n = name, s = state {
fetchRequest.predicate = NSPredicate(format: "name contains %@ and state contains %@", n, s)
}
if let s = state {
fetchRequest.predicate = NSPredicate(format: "state contains %@", s)
}
if let n = name {
fetchRequest.predicate = NSPredicate(format: "name contains %@", n)
}
//fetchRequest.predicate = NSPredicate(format: "id == %@", username)
var result = [Hospital]()
do {
// busca a informação
result = try context.executeFetchRequest(fetchRequest) as! [Hospital]
} catch {
print("Erro ao consultar: \(error)")
}
return result
}
func findHospitals(context: NSManagedObjectContext, origin: CLLocation, maxDistance: Double) -> [Hospital] {
var result = [Hospital]()
for item in findHospitals(context) {
let meters = origin.distanceFromLocation(item.Location)
if meters <= maxDistance {
item.distance = meters
result.append(item)
}
}
return result
}
func findHospital(context: NSManagedObjectContext, id: Int) -> Hospital? {
// cria a request
let fetchRequest = NSFetchRequest(entityName: entityName)
// faz algum filtro
fetchRequest.predicate = NSPredicate(format: "id == %d", id)
var result : Hospital?
do {
// busca a informação
result = try (context.executeFetchRequest(fetchRequest) as! [Hospital]).first
} catch {
print("Erro ao consultar id(\(id)): \(error)")
}
return result
}
// MARK: - Save
func save(context: NSManagedObjectContext, data: JSON) {
// Verifica se a categoria e um hospital
if data[jsonEnum.category.rawValue].intValue != 1 {
return
}
// Cria uma variavel de controle
let hospital : Hospital
// Verifica se já existe hospital cadastrado
// - se existir, deverá atribuir na variavel hospital
// - se não existir, deverá:
// - criar o objeto Hospital a partir do CoreData
// - atribuir o id
if let founded = findHospital(context, id: Int(data["id"].intValue)) {
hospital = founded
}
else {
hospital = createHospital(context)
hospital.id = Int64(data[jsonEnum.id.rawValue].intValue)
}
hospital.name = data[jsonEnum.name.rawValue].stringValue
hospital.state = data[jsonEnum.state.rawValue].stringValue
hospital.latitude = data[jsonEnum.coordinates.rawValue][jsonEnum.latitude.rawValue].doubleValue
hospital.longitude = data[jsonEnum.coordinates.rawValue][jsonEnum.longitude.rawValue].doubleValue
// if let c = data["coordinates"] as? [String: AnyObject],
// lat = c["lat"] as? String,
// long = c["long"] as? String {
//
// hospital.latitude = NSDecimalNumber(string: lat)
// hospital.longitude = NSDecimalNumber(string: long)
// }
// Validação
if ((hospital.name?.isEmpty) != nil) {
}
if ((hospital.state?.isEmpty) != nil) {
}
if hospital.latitude.isZero {
}
if hospital.longitude.isZero {
}
// Inserir | Atualizar no CoreData
do {
try context.save()
//print(hospital)
} catch {
print("Erro ao salvar hospital \(hospital.name)): \n\n \(error)")
}
}
}
|
9171688b3b3ed23f66049392d1be22b8
| 28.455056 | 128 | 0.536143 | false | false | false | false |
tobias/vertx-swift-eventbus
|
refs/heads/master
|
Sources/EventBus.swift
|
apache-2.0
|
1
|
/**
* Copyright Red Hat, Inc 2016
*
* 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 Dispatch
import Foundation
import Socket
import SwiftyJSON
/// Provides a connection to a remote [TCP EventBus Bridge](https://github.com/vert-x3/vertx-tcp-eventbus-bridge).
public class EventBus {
private let host: String
private let port: Int32
private let pingInterval: Int
private let readQueue = DispatchQueue(label: "read")
private let workQueue = DispatchQueue(label: "work", attributes: [.concurrent])
private var socket: Socket?
private var errorHandler: ((Error) -> ())? = nil
private var handlers = [String: [String: Registration]]()
private var replyHandlers = [String: (Response) -> ()]()
private let replyHandlersMutex = Mutex(recursive: true)
func readLoop() {
if connected() {
readQueue.async(execute: {
self.readMessage()
self.readLoop()
})
}
}
func pingLoop() {
if connected() {
DispatchQueue.global()
.asyncAfter(deadline: DispatchTime.now()
+ DispatchTimeInterval.milliseconds(self.pingInterval),
execute: {
self.ping()
self.pingLoop()
})
}
}
func readMessage() {
guard let socket = self.socket else {
handleError(Error.disconnected(cause: nil))
return
}
do {
if let msg = try Util.read(from: socket) {
dispatch(msg)
}
} catch let error {
disconnect()
handleError(Error.disconnected(cause: error))
}
}
func handleError(_ error: Error) {
if let h = self.errorHandler {
h(error)
}
}
func dispatch(_ json: JSON) {
guard let address = json["address"].string else {
if let type = json["type"].string,
type == "err" {
handleError(Error.serverError(message: json["message"].string!))
}
// ignore unknown messages
return
}
let msg = Message(basis: json, eventBus: self)
if let handlers = self.handlers[address] {
if (msg.isSend) {
if let registration = handlers.values.first {
workQueue.async(execute: { registration.handler(msg) })
}
} else {
for registration in handlers.values {
workQueue.async(execute: { registration.handler(msg) })
}
}
} else if let handler = self.replyHandlers[address] {
workQueue.async(execute: { handler(Response(message: msg)) })
}
}
func send(_ message: JSON) throws {
guard let m = message.rawString() else {
throw Error.invalidData(data: message)
}
try send(m)
}
func send(_ message: String) throws {
guard let socket = self.socket else {
throw Error.disconnected(cause: nil)
}
do {
try Util.write(from: message, to: socket)
} catch let error {
disconnect()
throw Error.disconnected(cause: error)
}
}
func ping() {
do {
try send(JSON(["type": "ping"]))
} catch let error {
if let e = error as? Error {
handleError(e)
}
// else won't happen
}
}
func uuid() -> String {
return NSUUID().uuidString
}
// public API
/// Creates a new EventBus instance.
///
/// Note: a new EventBus instance *isn't* connected to the bridge automatically. See `connect()`.
///
/// - parameter host: address of host running the bridge
/// - parameter port: port the bridge is listening on
/// - parameter pingEvery: interval (in ms) to ping the bridge to ensure it is still up (default: `5000`)
/// - returns: a new EventBus
public init(host: String, port: Int, pingEvery: Int = 5000) {
self.host = host
self.port = Int32(port)
self.pingInterval = pingEvery
}
/// Connects to the remote bridge.
///
/// Any already registered message handlers will be (re)connected.
///
/// - throws: `Socket.Error` if connecting fails
public func connect() throws {
self.socket = try Socket.create()
try self.socket!.connect(to: self.host, port: self.port)
readLoop()
ping() // ping once to get this party started
pingLoop()
for handlers in self.handlers.values {
for registration in handlers.values {
let _ = try register(address: registration.address,
id: registration.id,
headers: registration.headers,
handler: registration.handler)
}
}
}
/// Disconnects from the remote bridge.
public func disconnect() {
if let s = self.socket {
for handlers in self.handlers.values {
for registration in handlers.values {
// We don't care about errors here, since we're
// not going to be receiving messages anyway. We
// unregister as a convenience to the bridge.
let _ = try? unregister(address: registration.address,
id: registration.id,
headers: registration.headers)
}
}
s.close()
self.socket = nil
}
}
/// Signals the current state of the connection.
///
/// - returns: `true` if connected to the remote bridge, `false` otherwise
public func connected() -> Bool {
if let _ = self.socket {
return true
}
return false
}
/// Sends a message to an EventBus address.
///
/// If the remote handler will reply, you can provide a callback
/// to handle that reply. If no reply is received within the
/// specified timeout, a `Response` that responds with `false` to
/// `timeout()` will be passed.
///
/// - parameter to: the address to send the message to
/// - parameter body: the body of the message
/// - parameter headers: headers to send with the message (default: `[String: String]()`)
/// - parameter replyTimeout: the timeout (in ms) to wait for a reply if a reply callback is provided (default: `30000`)
/// - parameter callback: the callback to handle the reply or timeout `Response` (default: `nil`)
/// - throws: `Error.invalidData(data:)` if the given `body` can't be converted to JSON
/// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge
public func send(to address: String,
body: [String: Any],
headers: [String: String]? = nil,
replyTimeout: Int = 30000, // 30 seconds
callback: ((Response) -> ())? = nil) throws {
var msg: [String: Any] = ["type": "send", "address": address, "body": body, "headers": headers ?? [String: String]()]
if let cb = callback {
let replyAddress = uuid()
let timeoutAction = DispatchWorkItem() {
self.replyHandlersMutex.lock()
defer {
self.replyHandlersMutex.unlock()
}
if let _ = self.replyHandlers.removeValue(forKey: replyAddress) {
cb(Response.timeout())
}
}
replyHandlers[replyAddress] = {[unowned self] (r) in
self.replyHandlersMutex.lock()
defer {
self.replyHandlersMutex.unlock()
}
if let _ = self.replyHandlers.removeValue(forKey: replyAddress) {
timeoutAction.cancel()
cb(r)
}
}
msg["replyAddress"] = replyAddress
DispatchQueue.global()
.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(replyTimeout),
execute: timeoutAction)
}
try send(JSON(msg))
}
/// Publishes a message to the EventBus.
///
/// - parameter to: the address to send the message to
/// - parameter body: the body of the message
/// - parameter headers: headers to send with the message (default: `[String: String]()`)
/// - throws: `Error.invalidData(data:)` if the given `body` can't be converted to JSON
/// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge
public func publish(to address: String,
body: [String: Any],
headers: [String: String]? = nil) throws {
try send(JSON(["type": "publish",
"address": address,
"body": body,
"headers": headers ?? [String: String]()] as [String: Any]))
}
/// Registers a closure to receive messages for the given address.
///
/// - parameter address: the address to listen to
/// - parameter id: the id for the registration (default: a random uuid)
/// - parameter headers: headers to send with the register request (default: `[String: String]()`)
/// - parameter handler: the closure to handle each `Message`
/// - returns: an id for the registration that can be used to unregister it
/// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge
public func register(address: String,
id: String? = nil,
headers: [String: String]? = nil,
handler: @escaping (Message) -> ()) throws -> String {
let _id = id ?? uuid()
let _headers = headers ?? [String: String]()
let registration = Registration(address: address, id: _id, handler: handler, headers: _headers)
if let _ = self.handlers[address] {
self.handlers[address]![_id] = registration
} else {
self.handlers[address] = [_id : registration]
try send(JSON(["type": "register", "address": address, "headers": _headers]))
}
return _id
}
/// Registers a closure to receive messages for the given address.
///
/// - parameter address: the address to remove the registration from
/// - parameter id: the id for the registration
/// - parameter headers: headers to send with the unregister request (default: `[String: String]()`)
/// - returns: `true` if something was actually unregistered
/// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge
public func unregister(address: String, id: String, headers: [String: String]? = nil) throws -> Bool {
guard var handlers = self.handlers[address],
let _ = handlers[id] else {
return false
}
handlers.removeValue(forKey: id)
if handlers.isEmpty {
try send(JSON(["type": "unregister", "address": address, "headers": headers ?? [String: String]()]))
}
return true
}
/// Registers an error handler that will be passed any errors that occur in async operations.
///
/// Operations that can trigger this error handler are:
/// - handling messages received from the remote bridge (can trigger `Error.disconnected(cause:)` or `Error.serverError(message:)`)
/// - the ping operation discovering the bridge connection has closed (can trigger `Error.disconnected(cause:)`)
///
/// - parameter errorHandler: a closure that will be passed an `Error` when an error occurs
public func register(errorHandler: @escaping (Error) -> ()) {
self.errorHandler = errorHandler
}
/// Represents error types thrown or passed by EventBus methods.
public enum Error : Swift.Error {
/// Indicates that a given `JSON` object can't be converted to json text.
///
/// - parameter data: the offending data object
case invalidData(data: JSON)
/// Indicates an error from the bridge server
///
/// - parameter message: the error message returned by the server
case serverError(message: String)
/// Indicates that the client is now in a disconnected state
///
/// - parameter cause: the (optional) underlying cause for the disconnect
case disconnected(cause: Swift.Error?)
}
struct Registration {
let address: String
let id: String
let handler: (Message) -> ()
let headers: [String: String]
}
}
|
475ac45fb787231e5b49133df787bb4d
| 36.361644 | 135 | 0.556134 | false | false | false | false |
mrackwitz/Commandant
|
refs/heads/master
|
Commandant/Errors.swift
|
mit
|
1
|
//
// Errors.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-10-24.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Box
import Result
/// Possible errors that can originate from Commandant.
///
/// `ClientError` should be the type of error (if any) that can occur when
/// running commands.
public enum CommandantError<ClientError> {
/// An option was used incorrectly.
case UsageError(description: String)
/// An error occurred while running a command.
case CommandError(Box<ClientError>)
}
extension CommandantError: Printable {
public var description: String {
switch self {
case let .UsageError(description):
return description
case let .CommandError(error):
return toString(error)
}
}
}
/// Used to represent that a ClientError will never occur.
internal enum NoError {}
/// Constructs an `InvalidArgument` error that indicates a missing value for
/// the argument by the given name.
internal func missingArgumentError<ClientError>(argumentName: String) -> CommandantError<ClientError> {
let description = "Missing argument for \(argumentName)"
return .UsageError(description: description)
}
/// Constructs an error by combining the example of key (and value, if applicable)
/// with the usage description.
internal func informativeUsageError<ClientError>(keyValueExample: String, usage: String) -> CommandantError<ClientError> {
let lines = usage.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
return .UsageError(description: reduce(lines, keyValueExample) { previous, value in
return previous + "\n\t" + value
})
}
/// Constructs an error that describes how to use the option, with the given
/// example of key (and value, if applicable) usage.
internal func informativeUsageError<T, ClientError>(keyValueExample: String, option: Option<T>) -> CommandantError<ClientError> {
if option.defaultValue != nil {
return informativeUsageError("[\(keyValueExample)]", option.usage)
} else {
return informativeUsageError(keyValueExample, option.usage)
}
}
/// Constructs an error that describes how to use the option.
internal func informativeUsageError<T: ArgumentType, ClientError>(option: Option<T>) -> CommandantError<ClientError> {
var example = ""
if let key = option.key {
example += "--\(key) "
}
var valueExample = ""
if let defaultValue = option.defaultValue {
valueExample = "\(defaultValue)"
}
if valueExample.isEmpty {
example += "(\(T.name))"
} else {
example += valueExample
}
return informativeUsageError(example, option)
}
/// Constructs an error that describes how to use the given boolean option.
internal func informativeUsageError<ClientError>(option: Option<Bool>) -> CommandantError<ClientError> {
precondition(option.key != nil)
let key = option.key!
if let defaultValue = option.defaultValue {
return informativeUsageError((defaultValue ? "--no-\(key)" : "--\(key)"), option)
} else {
return informativeUsageError("--(no-)\(key)", option)
}
}
/// Combines the text of the two errors, if they're both `UsageError`s.
/// Otherwise, uses whichever one is not (biased toward the left).
internal func combineUsageErrors<ClientError>(lhs: CommandantError<ClientError>, rhs: CommandantError<ClientError>) -> CommandantError<ClientError> {
switch (lhs, rhs) {
case let (.UsageError(left), .UsageError(right)):
let combinedDescription = "\(left)\n\n\(right)"
return .UsageError(description: combinedDescription)
case (.UsageError, _):
return rhs
case (_, .UsageError), (_, _):
return lhs
}
}
|
ef3bda04a8f56315fe7855cc0cf497f3
| 29.905172 | 149 | 0.735565 | false | false | false | false |
samodom/TestableMapKit
|
refs/heads/master
|
TestableMapKit/MKUserLocation/MKUserLocation.swift
|
mit
|
1
|
//
// MKUserLocation.swift
// TestableMapKit
//
// Created by Sam Odom on 12/25/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import MapKit
public class MKUserLocation: MapKit.MKUserLocation {
/*!
Exposed initializer.
*/
public init(location: CLLocation, heading: CLHeading, updating: Bool) {
super.init()
self.location = location
self.heading = heading
self.updating = updating
}
/*!
Mutable override of the `location` property.
*/
public override var location: CLLocation {
get {
if locationOverride != nil {
return locationOverride!
}
else {
return super.location
}
}
set {
locationOverride = newValue
}
}
/*!
Mutable override of the `heading` property.
*/
public override var heading: CLHeading {
get {
if headingOverride != nil {
return headingOverride!
}
else {
return super.heading
}
}
set {
headingOverride = newValue
}
}
/*!
Mutable override of the `updating` property.
*/
public override var updating: Bool {
get {
if updatingOverride != nil {
return updatingOverride!
}
else {
return super.updating
}
}
set {
updatingOverride = newValue
}
}
private var locationOverride: CLLocation?
private var headingOverride: CLHeading?
private var updatingOverride: Bool?
}
|
efddc23b54d743f5c374b31f6c82b313
| 20.708861 | 75 | 0.516035 | false | false | false | false |
vimeo/VimeoUpload
|
refs/heads/develop
|
VimeoUpload/Descriptor System/KeyedArchiver.swift
|
mit
|
1
|
//
// KeyedArchiver.swift
// VimeoUpload
//
// Created by Hanssen, Alfie on 10/23/15.
// Copyright © 2015 Vimeo. 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
public class KeyedArchiver: ArchiverProtocol
{
private struct Constants
{
static let ArchiveExtension = "archive"
static let UnderscoreText = "_"
}
private let basePath: String
private let prefix: String?
public init(basePath: String, archivePrefix: String? = nil)
{
assert(FileManager.default.fileExists(atPath: basePath, isDirectory: nil), "Invalid basePath")
self.basePath = basePath
self.prefix = archivePrefix
}
public func loadObject(for key: String) -> Any?
{
let path = self.archivePath(key: self.key(withPrefix: self.prefix, key: key))
return NSKeyedUnarchiver.unarchiveObject(withFile: path)
}
public func save(object: Any, key: String)
{
let path = self.archivePath(key: self.key(withPrefix: self.prefix, key: key))
NSKeyedArchiver.archiveRootObject(object, toFile: path)
}
// MARK: Utilities
func archivePath(key: String) -> String
{
var url = URL(string: self.basePath)!
url = url.appendingPathComponent(key)
url = url.appendingPathExtension(Constants.ArchiveExtension)
return url.absoluteString as String
}
private func key(withPrefix prefix: String?, key: String) -> String
{
guard let prefix = prefix else
{
return key
}
return prefix + Constants.UnderscoreText + key
}
}
|
05ea08f33191b8c8c4ac600febf5a20c
| 32.204819 | 102 | 0.671988 | false | false | false | false |
raymondshadow/SwiftDemo
|
refs/heads/master
|
SwiftApp/SwiftApp/RxSwift/Demo1/Service/SearchService.swift
|
apache-2.0
|
1
|
//
// SearchService.swift
// SwiftApp
//
// Created by wuyp on 2017/7/4.
// Copyright © 2017年 raymond. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class SearchService {
static let shareInstance = SearchService()
private init() {}
func getHeros() -> Observable<[Hero]> {
let herosString = Bundle.main.path(forResource: "heros", ofType: "plist")
let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]>
var heros = [Hero]()
for heroDic in herosArray {
let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!)
heros.append(hero)
}
return Observable.just(heros)
.observeOn(MainScheduler.instance)
}
func getHeros(withName name: String) -> Observable<[Hero]> {
if name == "" {
return getHeros()
}
let herosString = Bundle.main.path(forResource: "heros", ofType: "plist")
let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]>
var heros = [Hero]()
for heroDic in herosArray {
if heroDic["name"]!.contains(name) {
let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!)
heros.append(hero)
}
}
return Observable.just(heros)
.observeOn(MainScheduler.instance)
}
}
|
6b1a60f2564f7eca58da59fb24c4e741
| 28.490196 | 104 | 0.575798 | false | false | false | false |
tlax/GaussSquad
|
refs/heads/master
|
GaussSquad/Model/LinearEquations/Plot/MLinearEquationsPlotRenderCartesian.swift
|
mit
|
1
|
import UIKit
import MetalKit
class MLinearEquationsPlotRenderCartesian:MetalRenderableProtocol
{
private let axisX:MTLBuffer
private let axisY:MTLBuffer
private let color:MTLBuffer
private let kAxisWidth:Float = 1
private let kBoundaries:Float = 10000
private let texture:MTLTexture
init(
device:MTLDevice,
texture:MTLTexture)
{
let vectorStartX:float2 = float2(-kBoundaries, 0)
let vectorEndX:float2 = float2(kBoundaries, 0)
let vectorStartY:float2 = float2(0, -kBoundaries)
let vectorEndY:float2 = float2(0, kBoundaries)
self.texture = texture
axisX = MetalSpatialLine.vertex(
device:device,
vectorStart:vectorStartX,
vectorEnd:vectorEndX,
lineWidth:kAxisWidth)
axisY = MetalSpatialLine.vertex(
device:device,
vectorStart:vectorStartY,
vectorEnd:vectorEndY,
lineWidth:kAxisWidth)
color = MetalColor.color(
device:device,
originalColor:UIColor.black)
}
//MARK: renderable Protocol
func render(renderEncoder:MTLRenderCommandEncoder)
{
renderEncoder.render(
vertex:axisX,
color:color,
texture:texture)
renderEncoder.render(
vertex:axisY,
color:color,
texture:texture)
}
}
|
902382e56286a5fef67e40386a31a7b1
| 26.092593 | 65 | 0.603554 | false | false | false | false |
weareopensource/Sample-TVOS_Swift_Instagram
|
refs/heads/master
|
tabbar/ApiController.swift
|
mit
|
1
|
//
// ApiController.swift
// Benestar
//
// Created by RYPE on 21/05/2015.
// Copyright (c) 2015 Yourcreation. All rights reserved.
//
import Foundation
/**************************************************************************************************/
// Protocol
/**************************************************************************************************/
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
}
/**************************************************************************************************/
// Class
/**************************************************************************************************/
class APIController {
/*************************************************/
// Main
/*************************************************/
// Var
/*************************/
var delegate: APIControllerProtocol
// init
/*************************/
init(delegate: APIControllerProtocol) {
self.delegate = delegate
}
/*************************************************/
// Functions
/*************************************************/
func get(path: String) {
let url = NSURL(string: path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
//print(jsonResult["data"])
if let results = jsonResult["data"] as? NSArray {
self.delegate.didReceiveAPIResults(results)
}
} catch let error as NSError {
print(error.description)
}
})
task.resume()
}
func instagram() {
get("https://api.instagram.com/v1/users/\(GlobalConstants.TwitterInstaUserId)/media/recent/?access_token=\(GlobalConstants.TwitterInstaAccessToken)")
}
}
|
481630fa6ba54309343cea1059852164
| 33 | 157 | 0.416522 | false | false | false | false |
RCacheaux/BitbucketKit
|
refs/heads/develop
|
Bike 2 Work/Pods/Nimble/Nimble/Matchers/SatisfyAnyOf.swift
|
apache-2.0
|
15
|
import Foundation
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
public func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: U...) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(matchers)
}
internal func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: [U]) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc<T> { actualExpression, failureMessage in
var fullPostfixMessage = "match one of: "
var matches = false
for var i = 0; i < matchers.count && !matches; ++i {
fullPostfixMessage += "{"
let matcher = matchers[i]
matches = try matcher.matches(actualExpression, failureMessage: failureMessage)
fullPostfixMessage += "\(failureMessage.postfixMessage)}"
if i < (matchers.count - 1) {
fullPostfixMessage += ", or "
}
}
failureMessage.postfixMessage = fullPostfixMessage
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "\(actualValue)"
}
return matches
}
}
public func ||<T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
public func ||<T>(left: FullMatcherFunc<T>, right: FullMatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
public func ||<T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
extension NMBObjCMatcher {
public class func satisfyAnyOfMatcher(matchers: [NMBObjCMatcher]) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
if matchers.isEmpty {
failureMessage.stringValue = "satisfyAnyOf must be called with at least one matcher"
return false
}
var elementEvaluators = [NonNilMatcherFunc<NSObject>]()
for matcher in matchers {
let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = {
expression, failureMessage in
return matcher.matches(
{try! expression.evaluate()}, failureMessage: failureMessage, location: actualExpression.location)
}
elementEvaluators.append(NonNilMatcherFunc(elementEvaluator))
}
return try! satisfyAnyOf(elementEvaluators).matches(actualExpression, failureMessage: failureMessage)
}
}
}
|
24cbb9c35f2fb7f763008dea637e19cd
| 39.833333 | 122 | 0.629314 | false | false | false | false |
sdhzwm/QQMusic
|
refs/heads/master
|
QQMusic/Classes/Controller/WMMusicController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// QQMusic
//
// Created by 王蒙 on 15/8/27.
// Copyright © 2015年 王蒙. All rights reserved.
//
import UIKit
import AVFoundation
//MARK: 基本属性定义及初始化方法加载
class WMMusicController: UIViewController {
/**Xcode7的注释,使用‘/// ’mark down注释语法*/
/// 进度条
@IBOutlet weak var sliderTime: UISlider!
/// 中间的View
@IBOutlet weak var iconView: UIView!
/// 最大时间label
@IBOutlet weak var maxTime: UILabel!
/// 最小时间的label
@IBOutlet weak var minTime: UILabel!
/// 歌词展示的label
@IBOutlet weak var lrcLabel: WMLrcLabel!
/// 演唱者的名字
@IBOutlet weak var singer: UILabel!
/// 歌名
@IBOutlet weak var songName: UILabel!
/// 头像
@IBOutlet weak var iconImageView: UIImageView!
/// 是否选中了按钮--》是否播放
@IBOutlet weak var playerBtn: UIButton!
/// 背景图
@IBOutlet weak var backGroudView: UIImageView!
/// 当前播放歌曲
private var currentSong = AVAudioPlayer()
/// slider的定时器
private var progressTimer:Timer?
/// 歌词的定时器
private var lrcTimer:CADisplayLink?
/// scrollView ->歌词的展示view
@IBOutlet weak var lrcView: WMLrcView!
//MARK: 初始化设置
override func viewDidLoad() {
super.viewDidLoad()
//播放歌曲
setingPlaySong()
lrcView.lrcLabel = lrcLabel
}
}
//MARK:滑块的播放操作
extension WMMusicController {
/**添加定时器*/
private func addSliedTimer() {
updateMuneInfo()
progressTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(WMMusicController.updateMuneInfo), userInfo: nil, repeats: true)
RunLoop.main.add(progressTimer!, forMode: .commonModes)
}
/**移除滑块的定时器*/
private func removeSliderTimer() {
progressTimer?.invalidate()
progressTimer = nil
}
/**更新页面的信息*/
@objc private func updateMuneInfo() {
minTime.text = currentSong.currentTime.lrcTimeString
sliderTime.value = Float(currentSong.currentTime / currentSong.duration)
}
//MARK:设置滑块的状态
@IBAction func startSlide() {
removeSliderTimer()
}
@IBAction func sliderValueChange() {
// 设置当前播放的时间Label
minTime.text = (currentSong.duration * Double(sliderTime.value)).lrcTimeString
}
@IBAction func endSlide() {
// 设置歌曲的播放时间
currentSong.currentTime = currentSong.duration * Double(sliderTime.value)
// 添加定时器
addSliedTimer()
}
//MARK:滑块的点击事件
@objc private func sliderClick(tap:UITapGestureRecognizer) {
//获取点击的位置
let point = tap.location(in: sliderTime)
//获取点击的在slider长度中占据的比例
let ratio = point.x / sliderTime.bounds.size.width
//改变歌曲播放的时间
currentSong.currentTime = Double(ratio) * currentSong.duration
//更新进度信息
updateMuneInfo()
}
//MARK:歌词的定时器设置
//添加歌词的定时器
private func addLrcTimer() {
lrcTimer = CADisplayLink(target: self, selector: #selector(WMMusicController.updateLrcTimer))
lrcTimer?.add(to: .main, forMode: .commonModes)
}
//删除歌词的定时器
private func removeLrcTimer() {
lrcTimer?.invalidate()
lrcTimer = nil
}
//更新歌词的时间
@objc private func updateLrcTimer() {
lrcView.currentTime = currentSong.currentTime
}
}
//MARK: 歌曲播放
extension WMMusicController {
//MARK: 上一首歌曲
@IBAction func preSong() {
let previousMusic = WMMusicTool.shared.previousMusic()
//播放
playingMusicWithMusic(music: previousMusic)
}
//MARK: 播放歌曲
@IBAction func playSong() {
playerBtn.isSelected = !playerBtn.isSelected
if currentSong.isPlaying {
currentSong.pause()
//删除滑块的定时器
removeSliderTimer()
//移除歌词的定时器
removeLrcTimer()
//暂停头像的动画
iconImageView.layer.pauseAnimate()
}else {
currentSong.play()
//添加上滑块的定时器
addSliedTimer()
//歌词的定时器
removeLrcTimer()
//恢复动画
iconImageView.layer.resumeAnimate()
}
}
//MARK: 下一首歌曲
@IBAction func nextSong() {
let nextSong = WMMusicTool.shared.nextMusic()
//播放
playingMusicWithMusic(music: nextSong)
}
//播放歌曲,根据传来的歌曲名字
private func playingMusicWithMusic(music: WMMusic) {
//停掉之前的
let playerMusic = WMMusicTool.shared.playerMusic()
WMAudioTool.stopMusic(with: playerMusic.filename!)
lrcLabel.text = ""
lrcView.currentTime = 0
//播放现在的
WMAudioTool.playMusic(with: music.filename!)
WMMusicTool.shared.setPlayingMusic(playingMusic: music)
setingPlaySong()
}
//MARK: 设置播放的加载项
private func setingPlaySong() {
//取出当前的播放歌曲
let currentMusic = WMMusicTool.shared.playerMusic()
//设置当前的界面信息
backGroudView.image = UIImage(named: currentMusic.icon!)
iconImageView.image = UIImage(named: currentMusic.icon!)
songName.text = currentMusic.name
singer.text = currentMusic.singer
//设置歌曲播放
let currentAudio = WMAudioTool.playMusic(with: currentMusic.filename!)
currentAudio.delegate = self
//设置时间
minTime.text = currentAudio.currentTime.lrcTimeString
maxTime.text = currentAudio.duration.lrcTimeString
currentSong = currentAudio
//播放按钮状态的改变
playerBtn.isSelected = currentSong.isPlaying
sliderTime.value = 0
//设置歌词内容
lrcView.lrcName = currentMusic.lrcname
lrcView.duration = currentSong.duration
lrcLabel.text = ""
//移除以前的定时器
removeSliderTimer()
//添加定时器
addSliedTimer()
removeLrcTimer()
addLrcTimer()
startIconViewAnimate()
}
}
//MARK: 播放器的代理以及ScrollView的代理
extension WMMusicController: AVAudioPlayerDelegate,UIScrollViewDelegate{
//自动播放下一曲
@objc internal func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
nextSong()
}
}
//随着ScrollView的偏移,头像view隐藏
@objc internal func scrollViewDidScroll(_ scrollView: UIScrollView) {
//获取到滑动的偏移
let point = scrollView.contentOffset
//计算偏移的比例
let ratio = 1 - point.x / scrollView.bounds.size.width
// 设置存放歌词和头像的view的透明度
iconView.alpha = ratio
}
//监听远程事件
override func remoteControlReceived(with event: UIEvent?) {
switch(event!.subtype) {
case .remoteControlPlay:
playSong()
case .remoteControlPause:
playSong()
case .remoteControlNextTrack:
nextSong()
case .remoteControlPreviousTrack:
preSong()
default:
break
}
}
}
// MARK: 动画及基本设置
extension WMMusicController {
//MARK: 内部的子空间的设置
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
iconImageView.layer.cornerRadius = iconImageView.bounds.width * 0.5
iconImageView.layer.masksToBounds = true
iconImageView.layer.borderWidth = 8
iconImageView.layer.borderColor = UIColor(red: 36/255.0, green: 36/255.0, blue: 36/255.0, alpha: 1.0).cgColor
sliderTime.setThumbImage(UIImage(named: "player_slider_playback_thumb"), for: .normal)
lrcView.contentSize = CGSize(width: view.bounds.width * 2, height: 0)
}
//MARK: 设置状态栏的透明
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
//MARK:设置动画
private func startIconViewAnimate() {
let rotateAnim = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnim.fromValue = 0
rotateAnim.toValue = Double.pi * 2
rotateAnim.repeatCount = Float(NSIntegerMax)
rotateAnim.duration = 15
iconImageView.layer.add(rotateAnim, forKey: nil)
let tapSlider = UITapGestureRecognizer()
tapSlider.addTarget(self, action: #selector(WMMusicController.sliderClick(tap:)))
sliderTime.addGestureRecognizer(tapSlider)
}
}
|
b76a7e4404e0592cbb3fdabaaa567c17
| 29.267658 | 160 | 0.626259 | false | false | false | false |
OatmealCode/Oatmeal
|
refs/heads/master
|
Carlos/NetworkFetcher.swift
|
mit
|
2
|
import Foundation
import PiedPiper
public enum NetworkFetcherError: ErrorType {
/// Used when the status code of the network response is not included in the range 200..<300
case StatusCodeNotOk
/// Used when the network response had an invalid size
case InvalidNetworkResponse
/// Used when the network request didn't manage to retrieve data
case NoDataRetrieved
}
/// This class is a network cache level, mostly acting as a fetcher (meaning that calls to the set method won't have any effect). It internally uses NSURLSession to retrieve values from the internet
public class NetworkFetcher: Fetcher {
private static let ValidStatusCodes = 200..<300
private let lock: ReadWriteLock = PThreadReadWriteLock()
/// The network cache accepts only NSURL keys
public typealias KeyType = NSURL
/// The network cache returns only NSData values
public typealias OutputType = NSData
private func validate(response: NSHTTPURLResponse, withData data: NSData) -> Bool {
var responseIsValid = true
let expectedContentLength = response.expectedContentLength
if expectedContentLength > -1 {
responseIsValid = Int64(data.length) >= expectedContentLength
}
return responseIsValid
}
private func startRequest(URL: NSURL) -> Future<NSData> {
let result = Promise<NSData>()
let task = NSURLSession.sharedSession().dataTaskWithURL(URL) { [weak self] (data, response, error) in
guard let strongSelf = self else { return }
if let error = error {
if error.domain != NSURLErrorDomain || error.code != NSURLErrorCancelled {
GCD.main {
result.fail(error)
}
}
} else if let httpResponse = response as? NSHTTPURLResponse {
if !NetworkFetcher.ValidStatusCodes.contains(httpResponse.statusCode) {
GCD.main {
result.fail(NetworkFetcherError.StatusCodeNotOk)
}
} else if let data = data where !strongSelf.validate(httpResponse, withData: data) {
GCD.main {
result.fail(NetworkFetcherError.InvalidNetworkResponse)
}
} else if let data = data {
GCD.main {
result.succeed(data)
}
} else {
GCD.main {
result.fail(NetworkFetcherError.NoDataRetrieved)
}
}
}
}
result.onCancel {
task.cancel()
}
task.resume()
return result.future
}
private var pendingRequests: [Future<OutputType>] = []
private func addPendingRequest(request: Future<OutputType>) {
lock.withWriteLock {
self.pendingRequests.append(request)
}
}
private func removePendingRequests(request: Future<OutputType>) {
if let idx = lock.withReadLock({ self.pendingRequests.indexOf({ $0 === request }) }) {
lock.withWriteLock {
self.pendingRequests.removeAtIndex(idx)
}
}
}
/**
Initializes a new instance of a NetworkFetcher
*/
public init() {}
/**
Asks the cache to get a value for the given key
- parameter key: The key for the value. It represents the URL to fetch the value
- returns: A Future that you can use to get the asynchronous results of the network fetch
*/
public func get(key: KeyType) -> Future<OutputType> {
let result = startRequest(key)
result
.onSuccess { _ in
Logger.log("Fetched \(key) from the network fetcher")
self.removePendingRequests(result)
}
.onFailure { _ in
Logger.log("Failed fetching \(key) from the network fetcher", .Error)
self.removePendingRequests(result)
}
.onCancel {
Logger.log("Canceled request for \(key) on the network fetcher", .Info)
self.removePendingRequests(result)
}
self.addPendingRequest(result)
return result
}
}
|
7e948cfe4d371fa08fe9f3a74df6ac16
| 29.68254 | 198 | 0.656662 | false | false | false | false |
hhsolar/MemoryMaster-iOS
|
refs/heads/master
|
MemoryMaster/Controller/TabLibrary/ReadNoteViewController.swift
|
mit
|
1
|
//
// ReadNoteViewController.swift
// MemoryMaster
//
// Created by apple on 11/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
import CoreData
private let cellReuseIdentifier = "ReadCollectionViewCell"
class ReadNoteViewController: EnlargeImageViewController {
// public api
var passedInNoteInfo: MyBasicNoteInfo?
var passedInNotes = [CardContent]()
var startCardIndexPath: IndexPath?
@IBOutlet weak var progressBarView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var addBookmarkButton: UIButton!
let barFinishedPart = UIView()
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
var currentCardIndex: Int {
return Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.setNeedsLayout()
if let indexPath = startCardIndexPath {
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if var dict = UserDefaults.standard.dictionary(forKey: UserDefaultsKeys.lastReadStatus) {
dict.updateValue((passedInNoteInfo?.id)!, forKey: UserDefaultsDictKey.id)
dict.updateValue(currentCardIndex, forKey: UserDefaultsDictKey.cardIndex)
dict.updateValue(ReadType.read.rawValue, forKey: UserDefaultsDictKey.readType)
dict.updateValue("", forKey: UserDefaultsDictKey.cardStatus)
UserDefaults.standard.set(dict, forKey: UserDefaultsKeys.lastReadStatus)
}
}
override func setupUI() {
super.setupUI()
super.titleLabel.text = passedInNoteInfo?.name
self.automaticallyAdjustsScrollViewInsets = false
addBookmarkButton.setTitleColor(UIColor.white, for: .normal)
view.bringSubview(toFront: addBookmarkButton)
progressBarView.layer.cornerRadius = 4
progressBarView.layer.masksToBounds = true
progressBarView.layer.borderWidth = 1
progressBarView.layer.borderColor = CustomColor.medianBlue.cgColor
progressBarView.backgroundColor = UIColor.white
barFinishedPart.backgroundColor = CustomColor.medianBlue
let startIndex = startCardIndexPath?.row ?? 0
let barFinishedPartWidth = progressBarView.bounds.width / CGFloat(passedInNotes.count) * CGFloat(startIndex + 1)
barFinishedPart.frame = CGRect(x: 0, y: 0, width: barFinishedPartWidth, height: progressBarView.bounds.height)
progressBarView.addSubview(barFinishedPart)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = CGSize(width: (collectionView?.bounds.width)!, height: (collectionView?.bounds.height)!)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView.collectionViewLayout = layout
let nib = UINib(nibName: cellReuseIdentifier, bundle: Bundle.main)
collectionView?.register(nib, forCellWithReuseIdentifier: cellReuseIdentifier)
}
@IBAction func addBookmarkAction(_ sender: UIButton) {
playSound.playClickSound(SystemSound.buttonClick)
let placeholder = String(format: "%@-%@-%@-%d", (passedInNoteInfo?.name)!, (passedInNoteInfo?.type)!, ReadType.read.rawValue, currentCardIndex + 1)
let alert = UIAlertController(title: "Bookmark", message: "Give a name for the bookmark.", preferredStyle: .alert)
alert.addTextField { textFiled in
textFiled.placeholder = placeholder
}
let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak self] action in
self?.playSound.playClickSound(SystemSound.buttonClick)
var text = placeholder
if alert.textFields![0].text! != "" {
text = alert.textFields![0].text!
}
let isNameUsed = try? BookMark.find(matching: text, in: (self?.container?.viewContext)!)
if isNameUsed! {
self?.showAlert(title: "Error!", message: "Name already used, please give another name.")
} else {
let bookmark = MyBookmark(name: text, id: (self?.passedInNoteInfo?.id)!, time: Date(), readType: ReadType.read.rawValue, readPage: (self?.currentCardIndex)!, readPageStatus: nil)
self?.container?.performBackgroundTask({ (context) in
BookMark.findOrCreate(matching: bookmark, in: context)
DispatchQueue.main.async {
self?.showSavedPrompt()
}
})
}
})
let cancel = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
// MARK: draw prograss bar
private func updatePrograssLing(readingIndex: CGFloat) {
let width = progressBarView.bounds.width * (readingIndex + 1) / CGFloat(passedInNotes.count)
UIView.animate(withDuration: 0.3, delay: 0.02, options: [], animations: {
self.barFinishedPart.frame.size.width = width
}, completion: nil)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updatePrograssLing(readingIndex: CGFloat(currentCardIndex))
}
}
extension ReadNoteViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return passedInNotes.count
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let newCell = cell as! ReadCollectionViewCell
newCell.updateUI(noteType: (passedInNoteInfo?.type)!, title: passedInNotes[indexPath.row].title, body: passedInNotes[indexPath.row].body, index: indexPath.row)
newCell.delegate = self
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)
}
}
|
36ec63790a6a5f3cc7484ddb5fb3f2b1
| 43.402597 | 194 | 0.676806 | false | false | false | false |
alecchyi/SwiftDemos
|
refs/heads/master
|
SwiftDemos/MapsViewController.swift
|
mit
|
1
|
//
// MapsViewController.swift
// SwiftDemos
//
// Created by dst-macpro1 on 15/10/22.
// Copyright (c) 2015年 ibm. All rights reserved.
//
import UIKit
import MapKit
class MapsViewController: UIViewController {
@IBOutlet weak var picImageView: UIImageView!
@IBOutlet weak var moveBtn: UIButton!
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let center:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 40.029915, longitude: 116.347082)
let span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: center, span: span)
// self.mapView.setRegion(region, animated: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.fetchLocationCities()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clickMoveBtnEvent(sender: AnyObject) {
UIView.animateWithDuration(2.0,
delay: 0.0,
options: UIViewAnimationOptions.BeginFromCurrentState,
animations: {() -> Void in
var btnFrame = self.moveBtn.frame
var frame = self.view.bounds
var imgFrame = self.picImageView.frame
if imgFrame.origin.x + imgFrame.size.width < frame.size.width {
imgFrame.origin.x = frame.size.width - imgFrame.size.width
}else {
imgFrame.origin.x = btnFrame.origin.x + btnFrame.size.width + 5
}
self.picImageView.frame = imgFrame
}, completion: {[weak self](let b) -> Void in
if let weakSelf = self {
weakSelf.moveToEnd()
}
})
}
func moveToEnd() {
UIView.animateKeyframesWithDuration(2.0, delay: 0.0, options: UIViewKeyframeAnimationOptions.CalculationModeCubic, animations: {() -> Void in
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0/2.0, animations: {() -> Void in
var frame = self.picImageView.frame
frame.origin.y = self.view.frame.size.height
self.picImageView.frame = frame
})
UIView.addKeyframeWithRelativeStartTime(1.0/2.0, relativeDuration: 1.0/2.0, animations: {() -> Void in
var frame = self.picImageView.frame
var btnFrame = self.moveBtn.center
self.picImageView.center = CGPointMake(btnFrame.x + frame.size.width, btnFrame.y)
})
}, completion: nil)
}
func fetchLocationCities() {
var res = NSBundle.mainBundle().pathForResource("locations", ofType: "plist")
if let resources = res {
if let citiesData = NSMutableArray(contentsOfFile: resources) {
if (citiesData.count > 0) {
for c in citiesData {
if let city = c as? Dictionary<String,AnyObject> {
self.addAnchorPoint(city)
}
}
}
}
}
}
func addAnchorPoint(city:Dictionary<String, AnyObject>) {
var pointAnnotation = MKPointAnnotation()
let point = city["coordinate"] as! Dictionary<String, AnyObject>
if let lat = point["lat"] as? Double, lng = point["lng"] as? Double {
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: lat , longitude: lng )
}
pointAnnotation.title = city["location"] as! String
pointAnnotation.subtitle = ""
self.mapView.addAnnotation(pointAnnotation)
}
}
extension MapsViewController:MKMapViewDelegate {
}
|
e1534b2b8b20f59e6ae8e1f79da43211
| 34.035088 | 149 | 0.588883 | false | false | false | false |
cseduardorangel/Cantina
|
refs/heads/master
|
Cantina/Class/ViewController/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// Cantina
//
// Created by Eduardo Rangel on 10/25/15.
// Copyright © 2015 Concrete Solutions. All rights reserved.
//
import UIKit
import Google
class LoginViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {
//////////////////////////////////////////////////////////////////////
// MARK: IBOutlet
@IBOutlet weak var indicatorView: UIActivityIndicatorView!
//////////////////////////////////////////////////////////////////////
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupGoogleSignIn()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//////////////////////////////////////////////////////////////////////
// MARK: - Instance Methods
func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
}
//////////////////////////////////////////////////////////////////////
// MARK: - IBAction
@IBAction func login(sender: AnyObject) {
self.indicatorView.startAnimating()
GIDSignIn.sharedInstance().signIn()
}
//////////////////////////////////////////////////////////////////////
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
//////////////////////////////////////////////////////////////////////
// MARK: - GIDSignInDelegate
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
CredentialsService.logInUser(user, completion: { (success, error) -> Void in
self.indicatorView.stopAnimating()
if(success){
self.performSegueWithIdentifier("SegueToPurchases", sender: self)
}else {
let alertController = UIAlertController.init(title: ":(", message: error as String, preferredStyle: .Alert)
let okBtn = UIAlertAction.init(title: "Ok", style: .Cancel, handler: nil)
alertController.addAction(okBtn)
self.presentViewController(alertController, animated: true, completion: nil)
}
})
}
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!, withError error: NSError!) {
print(">>>>>>>>>> signIn:didDisconnectWithUser:withError")
// NSNotificationCenter.defaultCenter().postNotificationName("ToggleAuthUINotification", object: nil, userInfo: ["statusText": "Usuário disconectado."])
}
}
|
d2059842a02fae65dadecc968c37614d
| 28.606061 | 159 | 0.506143 | false | false | false | false |
Cezar2005/SuperChat
|
refs/heads/master
|
SuperChat/MyChatViewController.swift
|
lgpl-3.0
|
1
|
import UIKit
import Alamofire
import SwiftWebSocket
import SwiftyJSON
import RealmSwift
//The ViewController of available chat rooms.
class MyChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
/* ViewController properties.
'currUser' - it's a dictionary for a current session.
'availableUserRooms' - it's a dictionary for the list of available user room for a current user.
'selectedRoom' - it's an implementation of chat room object in the list that was selected by the user.
'tavleView' - it's an UI TableView. It contains the list of chat rooms.
*/
var currUser:[String: String] = [:]
var availableUserRooms: [ChatRoomsService.Room] = []
var selectedRoom = ChatRoomsService.Room()
@IBOutlet weak var tableView: UITableView!
//The function gets information about current user and then gets information about available chat rooms for him.
override func viewDidLoad() {
super.viewDidLoad()
InfoUserService().infoAboutUser( {(result1: [String: String]) -> Void in
self.currUser = result1
ChatRoomsService().availableRooms( {(result2: [ChatRoomsService.Room]) -> Void in
self.availableUserRooms = result2
self.tableView.reloadData()
})
})
}
//The function sends the entity of selected chat room from the list into the segue between screens.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "MyChatToRoom" {
let roomVC = segue.destinationViewController as! RoomViewController
roomVC.currentRoom = self.selectedRoom
}
}
//This is a line treatment of choice in tavleView.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if !self.availableUserRooms.isEmpty {
self.selectedRoom = self.availableUserRooms[indexPath.row]
self.performSegueWithIdentifier("MyChatToRoom", sender: self)
}
}
//The function returns a number of rows in tableView that will be displayed on the screen.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !self.availableUserRooms.isEmpty {
return self.availableUserRooms.count
} else {
return 0
}
}
//The function returns the cell of tableView. The cells contain the login of the users.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestSwiftCell")
if !self.availableUserRooms.isEmpty {
for user in self.availableUserRooms[indexPath.row].users {
if String(user.id) != self.currUser["id"] {
cell.textLabel!.text = user.login
break
} else {
cell.textLabel!.text = "error"
}
}
}
return cell
}
}
|
f7bb7218f2182ab42c00fb51e52c5e8e
| 38.469136 | 125 | 0.651126 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Test/VideoTranscriptTests.swift
|
apache-2.0
|
2
|
//
// VideoTranscriptTests.swift
// edX
//
// Created by Danial Zahid on 1/11/17.
// Updated by Salman on 05/03/2018.
// Copyright © 2017 edX. All rights reserved.
//
import XCTest
@testable import edX
class VideoTranscriptTests: XCTestCase {
func testTranscriptLoaded() {
let environment = TestRouterEnvironment()
let transcriptView = VideoTranscript(environment: environment)
XCTAssertEqual(transcriptView.transcriptTableView.numberOfRows(inSection: 0), 0)
XCTAssertTrue(transcriptView.transcriptTableView.isHidden)
let transcriptParser = TranscriptParser()
transcriptParser.parse(transcript: TranscriptDataFactory.validTranscriptString) { (success, error) in
if success {
transcriptView.updateTranscript(transcript: transcriptParser.transcripts)
}
}
XCTAssertEqual(transcriptView.transcriptTableView.numberOfRows(inSection: 0), 11)
XCTAssertFalse(transcriptView.transcriptTableView.isHidden)
}
func testTranscriptSeek() {
let environment = TestRouterEnvironment()
let transcriptView = VideoTranscript(environment: environment)
let transcriptParser = TranscriptParser()
transcriptParser.parse(transcript: TranscriptDataFactory.validTranscriptString) { (success, error) in
if success {
transcriptView.updateTranscript(transcript: transcriptParser.transcripts)
}
}
transcriptView.highlightSubtitle(for: 4.83)
XCTAssertEqual(transcriptView.highlightedIndex, 1)
transcriptView.highlightSubtitle(for: 10.0)
XCTAssertEqual(transcriptView.highlightedIndex, 2)
transcriptView.highlightSubtitle(for: 12.93)
XCTAssertEqual(transcriptView.highlightedIndex, 3)
}
}
|
ce14040db7d8906cafb4d088c9b22fd4
| 34.226415 | 109 | 0.693091 | false | true | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Managers/Call/CallPresenter.swift
|
apache-2.0
|
1
|
//
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// swiftlint:disable file_length
#if canImport(JitsiMeetSDK)
import JitsiMeetSDK
import CallKit
#endif
/// The number of milliseconds in one second.
private let MSEC_PER_SEC: TimeInterval = 1000
@objcMembers
/// Service to manage call screens and call bar UI management.
class CallPresenter: NSObject {
private enum Constants {
static let pipAnimationDuration: TimeInterval = 0.25
static let groupCallInviteLifetime: TimeInterval = 30
}
/// Utilized sessions
private var sessions: [MXSession] = []
/// Call view controllers map. Keys are callIds.
private var callVCs: [String: CallViewController] = [:]
/// Call background tasks map. Keys are callIds.
private var callBackgroundTasks: [String: MXBackgroundTask] = [:]
/// Actively presented direct call view controller.
private weak var presentedCallVC: UIViewController? {
didSet {
updateOnHoldCall()
}
}
private weak var pipCallVC: UIViewController?
/// UI operation queue for various UI operations
private var uiOperationQueue: OperationQueue = .main
/// Flag to indicate whether the presenter is active.
private var isStarted: Bool = false
#if canImport(JitsiMeetSDK)
private var widgetEventsListener: Any?
/// Jitsi calls map. Keys are CallKit call UUIDs, values are corresponding widgets.
private var jitsiCalls: [UUID: Widget] = [:]
/// The current Jitsi view controller being displayed or not.
private(set) var jitsiVC: JitsiViewController? {
didSet {
updateOnHoldCall()
}
}
#endif
private var isCallKitEnabled: Bool {
MXCallKitAdapter.callKitAvailable() && MXKAppSettings.standard()?.isCallKitEnabled == true
}
private var activeCallVC: UIViewController? {
return callVCs.values.filter { (callVC) -> Bool in
guard let call = callVC.mxCall else {
return false
}
return !call.isOnHold
}.first ?? jitsiVC
}
private var onHoldCallVCs: [CallViewController] {
return callVCs.values.filter { (callVC) -> Bool in
guard let call = callVC.mxCall else {
return false
}
return call.isOnHold
}
}
private var numberOfPausedCalls: UInt {
return UInt(callVCs.values.filter { (callVC) -> Bool in
guard let call = callVC.mxCall else {
return false
}
return call.isOnHold
}.count)
}
// MARK: - Public
/// Maximum number of concurrent calls allowed.
let maximumNumberOfConcurrentCalls: UInt = 2
/// Delegate object
weak var delegate: CallPresenterDelegate?
func addMatrixSession(_ session: MXSession) {
sessions.append(session)
}
func removeMatrixSession(_ session: MXSession) {
if let index = sessions.firstIndex(of: session) {
sessions.remove(at: index)
}
}
/// Start the service
func start() {
MXLog.debug("[CallPresenter] start")
addCallObservers()
}
/// Stop the service
func stop() {
MXLog.debug("[CallPresenter] stop")
removeCallObservers()
}
// MARK - Group Calls
/// Open the Jitsi view controller from a widget.
/// - Parameter widget: the jitsi widget
func displayJitsiCall(withWidget widget: Widget) {
MXLog.debug("[CallPresenter] displayJitsiCall: for widget: \(widget.widgetId)")
#if canImport(JitsiMeetSDK)
let createJitsiBlock = { [weak self] in
guard let self = self else { return }
self.jitsiVC = JitsiViewController()
self.jitsiVC?.openWidget(widget, withVideo: true, success: { [weak self] in
guard let self = self else { return }
if let jitsiVC = self.jitsiVC {
jitsiVC.delegate = self
self.presentCallVC(jitsiVC)
self.startJitsiCall(withWidget: widget)
}
}, failure: { [weak self] (error) in
guard let self = self else { return }
self.jitsiVC = nil
AppDelegate.theDelegate().showAlert(withTitle: nil,
message: VectorL10n.callJitsiError)
})
}
if let jitsiVC = jitsiVC {
if jitsiVC.widget.widgetId == widget.widgetId {
self.presentCallVC(jitsiVC)
} else {
// end previous Jitsi call first
endActiveJitsiCall()
createJitsiBlock()
}
} else {
createJitsiBlock()
}
#else
AppDelegate.theDelegate().showAlert(withTitle: nil,
message: VectorL10n.notSupportedYet)
#endif
}
private func startJitsiCall(withWidget widget: Widget) {
MXLog.debug("[CallPresenter] startJitsiCall")
if let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key {
// this Jitsi call is already managed by this class, no need to report the call again
MXLog.debug("[CallPresenter] startJitsiCall: already managed with id: \(uuid.uuidString)")
return
}
guard let roomId = widget.roomId else {
MXLog.debug("[CallPresenter] startJitsiCall: no roomId on widget")
return
}
guard let session = sessions.first else {
MXLog.debug("[CallPresenter] startJitsiCall: no active session")
return
}
guard let room = session.room(withRoomId: roomId) else {
MXLog.debug("[CallPresenter] startJitsiCall: unknown room: \(roomId)")
return
}
let newUUID = UUID()
let handle = CXHandle(type: .generic, value: roomId)
let startCallAction = CXStartCallAction(call: newUUID, handle: handle)
let transaction = CXTransaction(action: startCallAction)
MXLog.debug("[CallPresenter] startJitsiCall: new call with id: \(newUUID.uuidString)")
JMCallKitProxy.request(transaction) { (error) in
MXLog.debug("[CallPresenter] startJitsiCall: JMCallKitProxy returned \(String(describing: error))")
if error == nil {
JMCallKitProxy.reportCallUpdate(with: newUUID,
handle: roomId,
displayName: room.summary.displayname,
hasVideo: true)
JMCallKitProxy.reportOutgoingCall(with: newUUID, connectedAt: nil)
self.jitsiCalls[newUUID] = widget
}
}
}
func endActiveJitsiCall() {
MXLog.debug("[CallPresenter] endActiveJitsiCall")
guard let jitsiVC = jitsiVC else {
// there is no active Jitsi call
MXLog.debug("[CallPresenter] endActiveJitsiCall: no active Jitsi call")
return
}
if pipCallVC == jitsiVC {
// this call currently in the PiP mode,
// first present it by exiting PiP mode and then dismiss it
exitPipCallVC(jitsiVC)
}
dismissCallVC(jitsiVC)
jitsiVC.hangup()
self.jitsiVC = nil
guard let widget = jitsiVC.widget else {
MXLog.debug("[CallPresenter] endActiveJitsiCall: no Jitsi widget for the active call")
return
}
guard let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key else {
// this Jitsi call is not managed by this class
MXLog.debug("[CallPresenter] endActiveJitsiCall: Not managed Jitsi call: \(widget.widgetId)")
return
}
let endCallAction = CXEndCallAction(call: uuid)
let transaction = CXTransaction(action: endCallAction)
MXLog.debug("[CallPresenter] endActiveJitsiCall: ended call with id: \(uuid.uuidString)")
JMCallKitProxy.request(transaction) { (error) in
MXLog.debug("[CallPresenter] endActiveJitsiCall: JMCallKitProxy returned \(String(describing: error))")
if error == nil {
self.jitsiCalls.removeValue(forKey: uuid)
}
}
}
func processWidgetEvent(_ event: MXEvent, inSession session: MXSession) {
MXLog.debug("[CallPresenter] processWidgetEvent")
guard let widget = Widget(widgetEvent: event, inMatrixSession: session) else {
MXLog.debug("[CallPresenter] processWidgetEvent: widget couldn't be created")
return
}
guard JMCallKitProxy.isProviderConfigured() else {
// CallKit proxy is not configured, no benefit in parsing the event
MXLog.debug("[CallPresenter] processWidgetEvent: JMCallKitProxy not configured")
hangupUnhandledCallIfNeeded(widget)
return
}
if widget.isActive {
if let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key {
// this Jitsi call is already managed by this class, no need to report the call again
MXLog.debug("[CallPresenter] processWidgetEvent: Jitsi call already managed with id: \(uuid.uuidString)")
return
}
guard widget.type == kWidgetTypeJitsiV1 || widget.type == kWidgetTypeJitsiV2 else {
// not a Jitsi widget, ignore
MXLog.debug("[CallPresenter] processWidgetEvent: not a Jitsi widget")
return
}
if let jitsiVC = jitsiVC,
jitsiVC.widget.widgetId == widget.widgetId {
// this is already the Jitsi call we have atm
MXLog.debug("[CallPresenter] processWidgetEvent: ongoing Jitsi call")
return
}
if TimeInterval(event.age)/MSEC_PER_SEC > Constants.groupCallInviteLifetime {
// too late to process the event
MXLog.debug("[CallPresenter] processWidgetEvent: expired call invite")
return
}
// an active Jitsi widget
let newUUID = UUID()
// assume this Jitsi call will survive
self.jitsiCalls[newUUID] = widget
if event.sender == session.myUserId {
// outgoing call
MXLog.debug("[CallPresenter] processWidgetEvent: Report outgoing call with id: \(newUUID.uuidString)")
JMCallKitProxy.reportOutgoingCall(with: newUUID, connectedAt: nil)
} else {
// incoming call
guard RiotSettings.shared.enableRingingForGroupCalls else {
// do not ring for Jitsi calls
return
}
let user = session.user(withUserId: event.sender)
let displayName = NSString.localizedUserNotificationString(forKey: "GROUP_CALL_FROM_USER",
arguments: [user?.displayname as Any])
MXLog.debug("[CallPresenter] processWidgetEvent: Report new incoming call with id: \(newUUID.uuidString)")
JMCallKitProxy.reportNewIncomingCall(UUID: newUUID,
handle: widget.roomId,
displayName: displayName,
hasVideo: true) { (error) in
MXLog.debug("[CallPresenter] processWidgetEvent: JMCallKitProxy returned \(String(describing: error))")
if error != nil {
self.jitsiCalls.removeValue(forKey: newUUID)
}
}
}
} else {
guard let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key else {
// this Jitsi call is not managed by this class
MXLog.debug("[CallPresenter] processWidgetEvent: not managed Jitsi call: \(widget.widgetId)")
hangupUnhandledCallIfNeeded(widget)
return
}
MXLog.debug("[CallPresenter] processWidgetEvent: ended call with id: \(uuid.uuidString)")
JMCallKitProxy.reportCall(with: uuid, endedAt: nil, reason: .remoteEnded)
self.jitsiCalls.removeValue(forKey: uuid)
}
}
// MARK: - Private
private func updateOnHoldCall() {
guard let presentedCallVC = presentedCallVC as? CallViewController else {
return
}
if onHoldCallVCs.isEmpty {
// no on hold calls, clear the call
presentedCallVC.mxCallOnHold = nil
} else {
for callVC in onHoldCallVCs where callVC != presentedCallVC {
// do not set the same call (can happen in case of two on hold calls)
presentedCallVC.mxCallOnHold = callVC.mxCall
break
}
}
}
private func shouldHandleCall(_ call: MXCall) -> Bool {
return callVCs.count < maximumNumberOfConcurrentCalls
}
private func callHolded(withCallId callId: String) {
updateOnHoldCall()
}
private func endCall(withCallId callId: String) {
guard let callVC = callVCs[callId] else {
return
}
let completion = { [weak self] in
guard let self = self else {
return
}
self.updateOnHoldCall()
self.callVCs.removeValue(forKey: callId)
callVC.destroy()
self.callBackgroundTasks[callId]?.stop()
self.callBackgroundTasks.removeValue(forKey: callId)
// if still have some calls and there is no present operation in the queue
if let oldCallVC = self.callVCs.values.first,
self.presentedCallVC == nil,
!self.uiOperationQueue.containsPresentCallVCOperation,
!self.uiOperationQueue.containsEnterPiPOperation,
let oldCall = oldCallVC.mxCall,
oldCall.state != .ended {
// present the call screen after dismissing this one
self.presentCallVC(oldCallVC)
}
}
if pipCallVC == callVC {
// this call currently in the PiP mode,
// first present it by exiting PiP mode and then dismiss it
exitPipCallVC(callVC) {
self.dismissCallVC(callVC, completion: completion)
}
return
}
if callVC.isDisplayingAlert {
completion()
} else {
dismissCallVC(callVC, completion: completion)
}
}
private func logCallVC(_ callVC: UIViewController, log: String) {
if let callVC = callVC as? CallViewController {
MXLog.debug("[CallPresenter] \(log): Matrix call: \(String(describing: callVC.mxCall?.callId))")
} else if let callVC = callVC as? JitsiViewController {
MXLog.debug("[CallPresenter] \(log): Jitsi call: \(callVC.widget.widgetId)")
}
}
// MARK: - Observers
private func addCallObservers() {
guard !isStarted else {
return
}
NotificationCenter.default.addObserver(self,
selector: #selector(newCall(_:)),
name: NSNotification.Name(rawValue: kMXCallManagerNewCall),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(callStateChanged(_:)),
name: NSNotification.Name(rawValue: kMXCallStateDidChange),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(callTileTapped(_:)),
name: .RoomCallTileTapped,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(groupCallTileTapped(_:)),
name: .RoomGroupCallTileTapped,
object: nil)
isStarted = true
#if canImport(JitsiMeetSDK)
JMCallKitProxy.addListener(self)
guard let session = sessions.first else {
return
}
widgetEventsListener = session.listenToEvents([
MXEventType(identifier: kWidgetMatrixEventTypeString),
MXEventType(identifier: kWidgetModularEventTypeString)
]) { (event, direction, _) in
if direction == .backwards {
// ignore backwards events
return
}
self.processWidgetEvent(event, inSession: session)
}
#endif
}
private func removeCallObservers() {
guard isStarted else {
return
}
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name(rawValue: kMXCallManagerNewCall),
object: nil)
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name(rawValue: kMXCallStateDidChange),
object: nil)
NotificationCenter.default.removeObserver(self,
name: .RoomCallTileTapped,
object: nil)
NotificationCenter.default.removeObserver(self,
name: .RoomGroupCallTileTapped,
object: nil)
isStarted = false
#if canImport(JitsiMeetSDK)
JMCallKitProxy.removeListener(self)
guard let session = sessions.first else {
return
}
if let widgetEventsListener = widgetEventsListener {
session.removeListener(widgetEventsListener)
}
widgetEventsListener = nil
#endif
}
@objc
private func newCall(_ notification: Notification) {
guard let call = notification.object as? MXCall else {
return
}
if !shouldHandleCall(call) {
return
}
guard let newCallVC = CallViewController(call) else {
return
}
newCallVC.playRingtone = !isCallKitEnabled
newCallVC.delegate = self
if !call.isIncoming {
// put other native calls on hold
callVCs.values.forEach({ $0.mxCall.hold(true) })
// terminate Jitsi calls
endActiveJitsiCall()
}
callVCs[call.callId] = newCallVC
if UIApplication.shared.applicationState == .background && call.isIncoming {
// Create backgound task.
// Without CallKit this will allow us to play vibro until the call was ended
// With CallKit we'll inform the system when the call is ended to let the system terminate our app to save resources
let handler = MXSDKOptions.sharedInstance().backgroundModeHandler
let callBackgroundTask = handler.startBackgroundTask(withName: "[CallPresenter] addMatrixCallObserver", expirationHandler: nil)
callBackgroundTasks[call.callId] = callBackgroundTask
}
if call.isIncoming && isCallKitEnabled {
return
} else {
presentCallVC(newCallVC)
}
}
@objc
private func callStateChanged(_ notification: Notification) {
guard let call = notification.object as? MXCall else {
return
}
switch call.state {
case .createAnswer:
MXLog.debug("[CallPresenter] callStateChanged: call created answer: \(call.callId)")
if call.isIncoming, isCallKitEnabled, let callVC = callVCs[call.callId] {
presentCallVC(callVC)
}
case .connected:
MXLog.debug("[CallPresenter] callStateChanged: call connected: \(call.callId)")
case .onHold:
MXLog.debug("[CallPresenter] callStateChanged: call holded: \(call.callId)")
callHolded(withCallId: call.callId)
case .remotelyOnHold:
MXLog.debug("[CallPresenter] callStateChanged: call remotely holded: \(call.callId)")
callHolded(withCallId: call.callId)
case .ended:
MXLog.debug("[CallPresenter] callStateChanged: call ended: \(call.callId)")
endCall(withCallId: call.callId)
default:
break
}
}
@objc
private func callTileTapped(_ notification: Notification) {
MXLog.debug("[CallPresenter] callTileTapped")
guard let bubbleData = notification.object as? RoomBubbleCellData else {
return
}
guard let randomEvent = bubbleData.allLinkedEvents().randomElement() else {
return
}
guard let callEventContent = MXCallEventContent(fromJSON: randomEvent.content) else {
return
}
MXLog.debug("[CallPresenter] callTileTapped: for call: \(callEventContent.callId)")
guard let session = sessions.first else { return }
guard let call = session.callManager.call(withCallId: callEventContent.callId) else {
return
}
if call.state == .ended {
return
}
guard let callVC = callVCs[call.callId] else {
return
}
if callVC == pipCallVC {
exitPipCallVC(callVC)
} else {
presentCallVC(callVC)
}
}
@objc
private func groupCallTileTapped(_ notification: Notification) {
MXLog.debug("[CallPresenter] groupCallTileTapped")
guard let bubbleData = notification.object as? RoomBubbleCellData else {
return
}
guard let randomEvent = bubbleData.allLinkedEvents().randomElement() else {
return
}
guard randomEvent.eventType == .custom,
(randomEvent.type == kWidgetMatrixEventTypeString ||
randomEvent.type == kWidgetModularEventTypeString) else {
return
}
guard let session = sessions.first else { return }
guard let widget = Widget(widgetEvent: randomEvent, inMatrixSession: session) else {
return
}
MXLog.debug("[CallPresenter] groupCallTileTapped: for call: \(widget.widgetId)")
guard let jitsiVC = jitsiVC,
jitsiVC.widget.widgetId == widget.widgetId else {
return
}
if jitsiVC == pipCallVC {
exitPipCallVC(jitsiVC)
} else {
presentCallVC(jitsiVC)
}
}
// MARK: - Call Screens
private func presentCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) {
logCallVC(callVC, log: "presentCallVC")
// do not use PiP transitions here, as we really want to present the screen
callVC.transitioningDelegate = nil
if let presentedCallVC = presentedCallVC {
dismissCallVC(presentedCallVC)
}
let operation = CallVCPresentOperation(presenter: self, callVC: callVC) { [weak self] in
self?.presentedCallVC = callVC
if callVC == self?.pipCallVC {
self?.pipCallVC = nil
}
completion?()
}
uiOperationQueue.addOperation(operation)
}
private func dismissCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) {
logCallVC(callVC, log: "dismissCallVC")
// do not use PiP transitions here, as we really want to dismiss the screen
callVC.transitioningDelegate = nil
let operation = CallVCDismissOperation(presenter: self, callVC: callVC) { [weak self] in
if callVC == self?.presentedCallVC {
self?.presentedCallVC = nil
}
completion?()
}
uiOperationQueue.addOperation(operation)
}
private func enterPipCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) {
logCallVC(callVC, log: "enterPipCallVC")
// assign self as transitioning delegate
callVC.transitioningDelegate = self
let operation = CallVCEnterPipOperation(presenter: self, callVC: callVC) { [weak self] in
self?.pipCallVC = callVC
if callVC == self?.presentedCallVC {
self?.presentedCallVC = nil
}
completion?()
}
uiOperationQueue.addOperation(operation)
}
private func exitPipCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) {
logCallVC(callVC, log: "exitPipCallVC")
// assign self as transitioning delegate
callVC.transitioningDelegate = self
let operation = CallVCExitPipOperation(presenter: self, callVC: callVC) { [weak self] in
if callVC == self?.pipCallVC {
self?.pipCallVC = nil
}
self?.presentedCallVC = callVC
completion?()
}
uiOperationQueue.addOperation(operation)
}
/// Hangs up current Jitsi call, if it is inactive and associated with given widget.
/// Should be used for calls that are not handled through JMCallKitProxy,
/// as these should be removed regardless.
private func hangupUnhandledCallIfNeeded(_ widget: Widget) {
guard !widget.isActive, widget.widgetId == jitsiVC?.widget.widgetId else { return }
MXLog.debug("[CallPresenter] hangupUnhandledCallIfNeeded: ending call with Widget id: %@", widget.widgetId)
endActiveJitsiCall()
}
}
// MARK: - MXKCallViewControllerDelegate
extension CallPresenter: MXKCallViewControllerDelegate {
func dismiss(_ callViewController: MXKCallViewController!, completion: (() -> Void)!) {
guard let callVC = callViewController as? CallViewController else {
// this call screen is not handled by this service
completion?()
return
}
if callVC.mxCall == nil || callVC.mxCall.state == .ended {
// wait for the call state changes, will be handled there
return
} else {
// go to pip mode here
enterPipCallVC(callVC, completion: completion)
}
}
func callViewControllerDidTap(onHoldCall callViewController: MXKCallViewController!) {
guard let callOnHold = callViewController.mxCallOnHold else {
return
}
guard let onHoldCallVC = callVCs[callOnHold.callId] else {
return
}
if callOnHold.state == .onHold {
// call is on hold locally, switch calls
callViewController.mxCall.hold(true)
callOnHold.hold(false)
}
// switch screens
presentCallVC(onHoldCallVC)
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension CallPresenter: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PiPAnimator(animationDuration: Constants.pipAnimationDuration,
animationType: .exit,
pipViewDelegate: nil)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PiPAnimator(animationDuration: Constants.pipAnimationDuration,
animationType: .enter,
pipViewDelegate: self)
}
}
// MARK: - PiPViewDelegate
extension CallPresenter: PiPViewDelegate {
func pipViewDidTap(_ view: PiPView) {
guard let pipCallVC = pipCallVC else { return }
exitPipCallVC(pipCallVC)
}
}
// MARK: - OperationQueue Extension
extension OperationQueue {
var containsPresentCallVCOperation: Bool {
return containsOperation(ofType: CallVCPresentOperation.self)
}
var containsEnterPiPOperation: Bool {
return containsOperation(ofType: CallVCEnterPipOperation.self)
}
private func containsOperation(ofType type: Operation.Type) -> Bool {
return operations.contains { (operation) -> Bool in
return operation.isKind(of: type.self)
}
}
}
#if canImport(JitsiMeetSDK)
// MARK: - JMCallKitListener
extension CallPresenter: JMCallKitListener {
func providerDidReset() {
}
func performAnswerCall(UUID: UUID) {
guard let widget = jitsiCalls[UUID] else {
return
}
displayJitsiCall(withWidget: widget)
}
func performEndCall(UUID: UUID) {
guard let widget = jitsiCalls[UUID] else {
return
}
if let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId {
// hangup an active call
dismissCallVC(jitsiVC)
endActiveJitsiCall()
} else {
// decline incoming call
JitsiService.shared.declineWidget(withId: widget.widgetId)
}
}
func performSetMutedCall(UUID: UUID, isMuted: Bool) {
guard let widget = jitsiCalls[UUID] else {
return
}
if let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId {
// mute the active Jitsi call
jitsiVC.setAudioMuted(isMuted)
}
}
func performStartCall(UUID: UUID, isVideo: Bool) {
}
func providerDidActivateAudioSession(session: AVAudioSession) {
}
func providerDidDeactivateAudioSession(session: AVAudioSession) {
}
func providerTimedOutPerformingAction(action: CXAction) {
}
}
// MARK: - JitsiViewControllerDelegate
extension CallPresenter: JitsiViewControllerDelegate {
func jitsiViewController(_ jitsiViewController: JitsiViewController!, dismissViewJitsiController completion: (() -> Void)!) {
if jitsiViewController == jitsiVC {
endActiveJitsiCall()
}
}
func jitsiViewController(_ jitsiViewController: JitsiViewController!, goBackToApp completion: (() -> Void)!) {
if jitsiViewController == jitsiVC {
enterPipCallVC(jitsiViewController, completion: completion)
}
}
}
#endif
|
defd1efbebae9f4a37ba9941bfbd7947
| 35.052922 | 170 | 0.566758 | false | false | false | false |
BrianSemiglia/Cycle.swift
|
refs/heads/master
|
Sources/Core/Cycle.swift
|
mit
|
1
|
//
// Cycle.swift
// Cycle
//
// Created by Brian Semiglia on 1/2/17.
// Copyright © 2017 Brian Semiglia. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import RxSwift
open class CycledApplicationDelegate<T: IORouter>: UIResponder, UIApplicationDelegate {
private var cycle: Cycle<T>
public var window: UIWindow?
public override init() {
fatalError("CycledApplicationDelegate must be instantiated with a router.")
}
public init(router: T) {
cycle = Cycle(router: router)
super.init()
}
public func application(
_ application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds, root: cycle.root)
window?.makeKeyAndVisible()
return cycle.delegate.application!(
application,
willFinishLaunchingWithOptions: launchOptions
)
}
override open func forwardingTarget(for input: Selector!) -> Any? { return
cycle.delegate
}
override open func responds(to input: Selector!) -> Bool { return
cycle.delegate.responds(to: input)
}
}
extension UIWindow {
convenience init(frame: CGRect, root: UIViewController) {
self.init(frame: frame)
rootViewController = root
}
}
#elseif os(watchOS)
import WatchKit
import RxSwift
open class CycledApplicationDelegate<T: IORouter>: NSObject, WKExtensionDelegate {
private var cycle: Cycle<T>
public override init() {
fatalError("CycledApplicationDelegate must be instantiated with a router.")
}
public init(router: T) {
cycle = Cycle(router: router)
super.init()
}
override open func forwardingTarget(for input: Selector!) -> Any? { return
cycle.delegate
}
override open func responds(to input: Selector!) -> Bool { return
cycle.delegate.responds(to: input)
}
}
#elseif os(macOS)
import AppKit
import RxSwift
open class CycledApplicationDelegate<T: IORouter>: NSObject, NSApplicationDelegate {
private var cycle: Cycle<T>
public var main: NSWindowController? // <-- change to (NSWindow, NSViewController) combo to avoid internal storyboard use below
public override init() {
fatalError("CycledApplicationDelegate must be instantiated with a router.")
}
public init(router: T) {
cycle = Cycle(router: router)
super.init()
}
public func applicationWillFinishLaunching(_ notification: Notification) {
main = NSStoryboard(
name: "Main",
bundle: nil
)
.instantiateController(
withIdentifier: "MainWindow"
)
as? NSWindowController
main?.window?.contentViewController = cycle.root
main?.window?.makeKeyAndOrderFront(nil)
}
override open func forwardingTarget(for input: Selector!) -> Any? { return
cycle.delegate
}
override open func responds(to input: Selector!) -> Bool {
if input == #selector(applicationWillFinishLaunching(_:)) {
applicationWillFinishLaunching(
Notification(
name: Notification.Name(
rawValue: ""
)
)
)
}
return cycle.delegate.responds(
to: input
)
}
}
#endif
public final class Cycle<E: IORouter> {
private var output: Observable<E.Frame>?
private var inputProxy: ReplaySubject<E.Frame>?
private let cleanup = DisposeBag()
private let drivers: E.Drivers
fileprivate let delegate: AppDelegate
fileprivate let root: AppView
public required init(router: E) {
inputProxy = ReplaySubject.create(
bufferSize: 1
)
drivers = router.driversFrom(seed: E.seed)
root = drivers.screen.root
delegate = drivers.application
output = router.effectsOfEventsCapturedAfterRendering(
incoming: inputProxy!,
to: drivers
)
// `.startWith` is redundant, but necessary to kickoff cycle
// Possibly removed if `output` was BehaviorSubject?
// Not sure how to `merge` observables to single BehaviorSubject though.
output?
.startWith(E.seed)
.subscribe(self.inputProxy!.on)
.disposed(by: cleanup)
}
}
public protocol IORouter {
/*
Defines schema and initial values of application model.
*/
associatedtype Frame
static var seed: Frame { get }
/*
Defines drivers that handle effects, produce events. Requires two default drivers:
1. let application: UIApplicationDelegateProviding - can serve as UIApplicationDelegate
2. let screen: ScreenDrivable - can provide a root UIViewController
A default UIApplicationDelegateProviding driver, RxUIApplicationDelegate, is included with Cycle.
*/
associatedtype Drivers: MainDelegateProviding, ScreenDrivable
/*
Instantiates drivers with initial model. Necessary to for drivers that require initial values.
*/
func driversFrom(seed: Frame) -> Drivers
/*
Returns a stream of Models created by rendering the incoming stream of effects to Drivers and then capturing and transforming Driver events into the Model type.
*/
func effectsOfEventsCapturedAfterRendering(
incoming: Observable<Frame>,
to drivers: Drivers
) -> Observable<Frame>
}
public protocol ScreenDrivable {
associatedtype Driver: RootViewProviding
var screen: Driver { get }
}
public protocol RootViewProviding {
#if os(macOS)
var root: NSViewController { get }
#elseif os(iOS) || os(tvOS)
var root: UIViewController { get }
#elseif os(watchOS)
var root: WKInterfaceController { get }
#endif
}
public protocol MainDelegateProviding {
#if os(macOS)
associatedtype Delegate: NSApplicationDelegate
#elseif os(iOS) || os(tvOS)
associatedtype Delegate: UIApplicationDelegate
#elseif os(watchOS)
associatedtype Delegate: WKExtensionDelegate
#endif
var application: Delegate { get }
}
#if os(macOS)
typealias AppDelegate = NSApplicationDelegate
#elseif os(iOS) || os(tvOS)
typealias AppDelegate = UIApplicationDelegate
#elseif os(watchOS)
typealias AppDelegate = WKExtensionDelegate
#endif
#if os(macOS)
typealias AppView = NSViewController
#elseif os(iOS) || os(tvOS)
typealias AppView = UIViewController
#elseif os(watchOS)
typealias AppView = WKInterfaceController
#endif
|
6984cd3815072e9bc3ef63c47433a26c
| 24.90795 | 163 | 0.710433 | false | false | false | false |
abellono/IssueReporter
|
refs/heads/master
|
IssueReporter/Core/ViewController/ReporterViewController.swift
|
mit
|
1
|
//
// ReporterViewController.swift
// IssueReporter
//
// Created by Hakon Hanesand on 10/6/16.
// Copyright © 2017 abello. All rights reserved.
//
//
import Foundation
import UIKit
import CoreGraphics
internal class ReporterViewController: UIViewController {
private static let kABETextFieldInset = 14
private static let kABEdescriptionTextViewCornerRadius: CGFloat = 4
private static let kABEdescriptionTextViewBorderWidth: CGFloat = 0.5
private static let kABETableName = "IssueReporter-Localizable"
@IBOutlet private var descriptionTextView: UITextView!
@IBOutlet private var titleTextField: UITextField!
@IBOutlet private var placeHolderLabel: UILabel!
private var imageCollectionViewController: ImageCollectionViewController!
var issueManager: IssueManager! {
didSet {
issueManager.delegate = self
}
}
class func instance(withIssueManager manager: IssueManager) -> ReporterViewController {
let storyboard = UIStoryboard(name: String(describing: self), bundle: Bundle.bundleForLibrary())
let reporterViewController = storyboard.instantiateInitialViewController() as! ReporterViewController
reporterViewController.issueManager = manager
return reporterViewController
}
override func viewDidLoad() {
super.viewDidLoad()
configureTextView()
setupLocalization()
navigationController?.navigationBar.barTintColor = UIColor.blueNavigationBarColor()
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
// navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
}
private func configureTextView() {
let spacerView = UIView(frame: CGRect(x: 0, y: 0, width: ReporterViewController.kABETextFieldInset, height: ReporterViewController.kABETextFieldInset))
titleTextField.leftViewMode = .always
titleTextField.leftView = spacerView
descriptionTextView.layer.borderColor = UIColor.greyBorderColor().cgColor
descriptionTextView.layer.cornerRadius = ReporterViewController.kABEdescriptionTextViewCornerRadius
descriptionTextView.layer.borderWidth = ReporterViewController.kABEdescriptionTextViewBorderWidth
let textFieldInset = CGFloat(ReporterViewController.kABETextFieldInset)
descriptionTextView.textContainerInset = UIEdgeInsets(top: textFieldInset, left: textFieldInset, bottom: 0, right: textFieldInset)
descriptionTextView.delegate = self
}
private func setupLocalization() {
titleTextField.placeholder = NSLocalizedString(titleTextField.placeholder!,
tableName: ReporterViewController.kABETableName,
bundle: Bundle.bundleForLibrary(),
comment: "title of issue")
placeHolderLabel.text = NSLocalizedString(placeHolderLabel.text!,
tableName: ReporterViewController.kABETableName,
bundle: Bundle.bundleForLibrary(),
comment: "placeholder for description")
title = NSLocalizedString(navigationItem.title!,
tableName: ReporterViewController.kABETableName,
bundle: Bundle.bundleForLibrary(),
comment: "title")
}
@IBAction func cancelIssueReporting(_ sender: AnyObject) {
dismissIssueReporter(success: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier, identifier == "embed_segue" {
imageCollectionViewController = segue.destination as? ImageCollectionViewController
imageCollectionViewController.issueManager = issueManager
}
}
@objc func saveIssue() {
if let name = UserDefaults.standard.string(forKey: "tester_name") {
return saveIssueInternal(name: name)
}
if (Reporter.shouldPresentNameAlert()) {
return presentNameAlertBeforeSave()
} else {
saveIssueInternal(name: "No Name")
}
}
private func saveIssueInternal(name: String) {
UserDefaults.standard.set(name, forKey: "tester_name")
issueManager.issue.title = titleTextField.text ?? ""
issueManager.issue.issueDescription = descriptionTextView.text
issueManager.saveIssue(completion: { [weak self] in
guard let strongSelf = self else { return }
DispatchQueue.main.async {
strongSelf.dismissIssueReporter(success: true)
}
})
}
func dismissIssueReporter(success: Bool) {
view.endEditing(false)
Reporter.dismissReporterView(with: success)
}
// Name Dialoge
func presentNameAlertBeforeSave() {
let alert = UIAlertController(title: "What is your first name?",
message: "So we can shoot you a message to further investigate, if need be.",
preferredStyle: .alert)
alert.addTextField(configurationHandler: nil)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { [weak self] _ in
guard let name = alert.textFields?.first?.text else {
return
}
self?.saveIssueInternal(name: name)
}))
present(alert, animated: true)
}
}
extension ReporterViewController: IssueManagerDelegate {
static let spinner = UIActivityIndicatorView(style: .white)
internal func issueManagerUploadingStateDidChange(issueManager: IssueManager) {
imageCollectionViewController?.collectionView?.reloadData()
if issueManager.isUploading == ReporterViewController.spinner.isAnimating {
return
}
if issueManager.isUploading {
let spinner = UIActivityIndicatorView(style: .white)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinner)
navigationItem.rightBarButtonItem?.isEnabled = false
ReporterViewController.spinner.startAnimating()
} else {
ReporterViewController.spinner.stopAnimating()
navigationItem.rightBarButtonItem = UIBarButtonItem.saveButton(self, action: #selector(ReporterViewController.saveIssue))
navigationItem.rightBarButtonItem?.isEnabled = true
}
}
internal func issueManager(_ issueManager: IssueManager, didFailToUploadImage image: Image, error: IssueReporterError) {
if issueManager.images.index(of: image) != nil {
let alert = UIAlertController(error: error)
present(alert, animated: true)
}
}
internal func issueManager(_ issueManager: IssueManager, didFailToUploadFile file: File, error: IssueReporterError) {
let alert = UIAlertController(error: error)
present(alert, animated: true)
}
internal func issueManager(_ issueManager: IssueManager, didFailToUploadIssueWithError error: IssueReporterError) {
let alert = UIAlertController(error: error)
alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.saveIssue()
})
present(alert, animated: true)
}
}
extension ReporterViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let length = textView.text?.count ?? 0
let shouldHide = length > 0
placeHolderLabel.isHidden = shouldHide
}
}
|
35be8e7d58a51dac9f31f3abbbf0c6b4
| 37.21028 | 159 | 0.645469 | false | false | false | false |
KrishMunot/swift
|
refs/heads/master
|
test/SILGen/import_as_member.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s 2>&1 | FileCheck --check-prefix=SIL %s
// REQUIRES: objc_interop
import ImportAsMember.A
import ImportAsMember.Proto
import ImportAsMember.Class
public func returnGlobalVar() -> Double {
return Struct1.globalVar
}
// SIL-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double {
// SIL: %0 = global_addr @IAMStruct1GlobalVar : $*Double
// SIL: %2 = load %0 : $*Double
// SIL: return %2 : $Double
// SIL-NEXT: }
// SIL-LABEL: sil {{.*}}useProto{{.*}} (@owned IAMProto) -> () {
// TODO: Add in body checks
public func useProto(p: IAMProto) {
p.mutateSomeState()
let v = p.someValue
p.someValue = v+1
}
// SIL-LABEL: sil {{.*}}anchor{{.*}} () -> () {
func anchor() {}
// SIL-LABEL: sil {{.*}}useClass{{.*}}
// SIL: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options):
public func useClass(d: Double, opts: SomeClass.Options) {
// SIL: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass
// SIL: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]])
let o = SomeClass(value: d)
// SIL: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> ()
// SIL: apply [[APPLY_FN]]([[OBJ]], [[OPTS]])
o.applyOptions(opts)
}
extension SomeClass {
// SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_
// SIL: bb0([[DOUBLE:%[0-9]+]] : $Double
// SIL-NOT: value_metatype
// SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// SIL: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
|
e115f6c019437172e0f2aaab6951ee12
| 33.854167 | 126 | 0.620442 | false | false | false | false |
Goro-Otsubo/GPaperTrans
|
refs/heads/master
|
GPaperTrans/GCollectionView Base/GCollectionView.swift
|
mit
|
1
|
//
// GCollectionView.swift
// GPaperTrans
//
// Created by 大坪五郎 on 2015/02/03.
// Copyright (c) 2015年 demodev. All rights reserved.
//
import UIKit
//subclass of UICollectionView
//which has "guard"to prevent from unexpected contentOffset change
class GCollectionView: UICollectionView{
var offsetAccept:Bool
var oldOffset:CGPoint = CGPointZero
override var contentOffset:CGPoint{
willSet{
oldOffset = contentOffset
}
didSet{
if !self.offsetAccept{
super.contentOffset = oldOffset
}
}
}
required override init(frame:CGRect,collectionViewLayout:UICollectionViewLayout){
offsetAccept = true
super.init(frame:frame, collectionViewLayout:collectionViewLayout)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// func setContentOffset(contentOffset: CGPoint) {
//
// if self.offsetAccept{
// super.contentOffset = contentOffset
// }
// }
override func finishInteractiveTransition() {
self.offsetAccept = false
super.finishInteractiveTransition()
// self.offsetAccept = true //will be restored in viewController finish block
}
}
|
6e0057a53fa1e53a11fa7a322f4d6a42
| 23.690909 | 85 | 0.647275 | false | false | false | false |
FindGF/_BiliBili
|
refs/heads/master
|
WTBilibili/Other-其他/Login-登陆/Controller/WTLoginViewController.swift
|
apache-2.0
|
1
|
//
// WTLoginViewController.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/5/30.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
// 登陆控制器
import UIKit
class WTLoginViewController: UIViewController
{
// MARK: - 拖线的属性
@IBOutlet weak var loginHeaderImageV: UIImageView!
/// 手机或邮箱
@IBOutlet weak var phoneTextF: UITextField!
/// 密码
@IBOutlet weak var passwordTextF: UITextField!
/// 注册按钮
@IBOutlet weak var registerBtn: UIButton!
/// 登陆按钮
@IBOutlet weak var loginBtn: UIButton!
// MARK: - 懒加载
/// 手机或邮箱左侧的View
lazy var phoneLeftView: UIImageView = {
let phoneLeftView = UIImageView()
phoneLeftView.image = UIImage(named: "ictab_me")
phoneLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45)
phoneLeftView.contentMode = .Center
return phoneLeftView
}()
/// 密码左侧的View
lazy var passwordLeftView: UIImageView = {
let passwordLeftView = UIImageView()
passwordLeftView.image = UIImage(named: "pws_icon")
passwordLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45)
passwordLeftView.contentMode = .Center
return passwordLeftView
}()
// MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI
setupUI()
}
}
// MARK: - 自定义函数
extension WTLoginViewController
{
// MARK: 设置UI
private func setupUI()
{
// 0、设置导航栏
setupNav()
// 1、手机或邮箱
setupCommonTextField(phoneTextF, leftView: phoneLeftView)
// 2、密码
setupCommonTextField(passwordTextF, leftView: passwordLeftView)
// 3、注册按钮
self.registerBtn.layer.cornerRadius = 3
self.registerBtn.layer.borderColor = WTColor(r: 231, g: 231, b: 231).CGColor
self.registerBtn.layer.borderWidth = 1
// 4、登陆按钮
self.loginBtn.layer.cornerRadius = 3
}
// MARK: 设置导航栏
private func setupNav()
{
title = "登录"
// 关闭按钮
navigationItem.leftBarButtonItem = UIBarButtonItem.createCloseItem(self, action: #selector(closeBtnClick))
// 忘记密码
let forgetPasswordBtn = UIButton(type: .Custom)
forgetPasswordBtn.titleLabel?.font = UIFont.setQIHeiFontWithSize(14)
forgetPasswordBtn.setTitle("忘记密码", forState: .Normal)
forgetPasswordBtn.addTarget(self, action: #selector(forgetPasswordBtnClick), forControlEvents: .TouchUpInside)
forgetPasswordBtn.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: forgetPasswordBtn)
}
// MARK: 设置textField公共属性
private func setupCommonTextField(textField: UITextField, leftView: UIImageView)
{
textField.tintColor = WTMainColor
textField.leftView = leftView
textField.leftViewMode = .Always
}
}
// MARK: - 事件
extension WTLoginViewController
{
// MARK: 关闭按钮
func closeBtnClick()
{
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: 忘记密码
func forgetPasswordBtnClick()
{
}
// MARK: 注册按钮
@IBAction func registerBtnClick()
{
}
// MARK: 登陆按钮
@IBAction func loginBtnClick()
{
}
}
// MARK: - UITextFieldDelegate
extension WTLoginViewController: UITextFieldDelegate
{
func textFieldDidBeginEditing(textField: UITextField)
{
if textField.tag == 1
{
self.phoneLeftView.image = UIImage(named: "ictab_me_selected")
}
else if textField.tag == 2
{
self.loginHeaderImageV.image = UIImage(named: "login_header_cover_eyes")
self.passwordLeftView.image = UIImage(named: "pws_icon_hover")
}
}
func textFieldDidEndEditing(textField: UITextField)
{
if textField.tag == 1
{
self.phoneLeftView.image = UIImage(named: "ictab_me")
}
else if textField.tag == 2
{
self.loginHeaderImageV.image = UIImage(named: "login_header")
self.passwordLeftView.image = UIImage(named: "pws_icon")
}
}
}
|
19e9330e5776ae5a8d1f13a3299b2adb
| 25.175 | 118 | 0.614136 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Style/CommaRule.swift
|
mit
|
1
|
import Foundation
import SourceKittenFramework
import SwiftSyntax
struct CommaRule: CorrectableRule, ConfigurationProviderRule, SourceKitFreeRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "comma",
name: "Comma Spacing",
description: "There should be no space before and one after any comma.",
kind: .style,
nonTriggeringExamples: [
Example("func abc(a: String, b: String) { }"),
Example("abc(a: \"string\", b: \"string\""),
Example("enum a { case a, b, c }"),
Example("func abc(\n a: String, // comment\n bcd: String // comment\n) {\n}\n"),
Example("func abc(\n a: String,\n bcd: String\n) {\n}\n"),
Example("#imageLiteral(resourceName: \"foo,bar,baz\")"),
Example("""
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
"""),
Example("""
public indirect enum ExpectationMessage {
/// appends after an existing message ("<expectation> (use beNil() to match nils)")
case appends(ExpectationMessage, /* Appended Message */ String)
}
""", excludeFromDocumentation: true)
],
triggeringExamples: [
Example("func abc(a: String↓ ,b: String) { }"),
Example("func abc(a: String↓ ,b: String↓ ,c: String↓ ,d: String) { }"),
Example("abc(a: \"string\"↓,b: \"string\""),
Example("enum a { case a↓ ,b }"),
Example("let result = plus(\n first: 3↓ , // #683\n second: 4\n)\n"),
Example("""
Foo(
parameter: a.b.c,
tag: a.d,
value: a.identifier.flatMap { Int64($0) }↓ ,
reason: Self.abcd()
)
"""),
Example("""
return Foo(bar: .baz, title: fuzz,
message: My.Custom.message↓ ,
another: parameter, doIt: true,
alignment: .center)
""")
],
corrections: [
Example("func abc(a: String↓,b: String) {}\n"): Example("func abc(a: String, b: String) {}\n"),
Example("abc(a: \"string\"↓,b: \"string\"\n"): Example("abc(a: \"string\", b: \"string\"\n"),
Example("abc(a: \"string\"↓ , b: \"string\"\n"): Example("abc(a: \"string\", b: \"string\"\n"),
Example("enum a { case a↓ ,b }\n"): Example("enum a { case a, b }\n"),
Example("let a = [1↓,1]\nlet b = 1\nf(1, b)\n"): Example("let a = [1, 1]\nlet b = 1\nf(1, b)\n"),
Example("let a = [1↓,1↓,1↓,1]\n"): Example("let a = [1, 1, 1, 1]\n"),
Example("""
Foo(
parameter: a.b.c,
tag: a.d,
value: a.identifier.flatMap { Int64($0) }↓ ,
reason: Self.abcd()
)
"""): Example("""
Foo(
parameter: a.b.c,
tag: a.d,
value: a.identifier.flatMap { Int64($0) },
reason: Self.abcd()
)
"""),
Example("""
return Foo(bar: .baz, title: fuzz,
message: My.Custom.message↓ ,
another: parameter, doIt: true,
alignment: .center)
"""): Example("""
return Foo(bar: .baz, title: fuzz,
message: My.Custom.message,
another: parameter, doIt: true,
alignment: .center)
""")
]
)
func validate(file: SwiftLintFile) -> [StyleViolation] {
return violationRanges(in: file).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0.0.location))
}
}
private func violationRanges(in file: SwiftLintFile) -> [(ByteRange, shouldAddSpace: Bool)] {
let syntaxTree = file.syntaxTree
return syntaxTree
.windowsOfThreeTokens()
.compactMap { previous, current, next -> (ByteRange, shouldAddSpace: Bool)? in
if current.tokenKind != .comma {
return nil
} else if !previous.trailingTrivia.isEmpty && !previous.trailingTrivia.containsBlockComments() {
let start = ByteCount(previous.endPositionBeforeTrailingTrivia)
let end = ByteCount(current.endPosition)
let nextIsNewline = next.leadingTrivia.containsNewlines()
return (ByteRange(location: start, length: end - start), shouldAddSpace: !nextIsNewline)
} else if !current.trailingTrivia.starts(with: [.spaces(1)]), !next.leadingTrivia.containsNewlines() {
return (ByteRange(location: ByteCount(current.position), length: 1), shouldAddSpace: true)
} else {
return nil
}
}
}
func correct(file: SwiftLintFile) -> [Correction] {
let initialNSRanges = Dictionary(
uniqueKeysWithValues: violationRanges(in: file)
.compactMap { byteRange, shouldAddSpace in
file.stringView
.byteRangeToNSRange(byteRange)
.flatMap { ($0, shouldAddSpace) }
}
)
let violatingRanges = file.ruleEnabled(violatingRanges: Array(initialNSRanges.keys), for: self)
guard violatingRanges.isNotEmpty else { return [] }
let description = Self.description
var corrections = [Correction]()
var contents = file.contents
for range in violatingRanges.sorted(by: { $0.location > $1.location }) {
let contentsNSString = contents.bridge()
let shouldAddSpace = initialNSRanges[range] ?? true
contents = contentsNSString.replacingCharacters(in: range, with: ",\(shouldAddSpace ? " " : "")")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
private extension Trivia {
func containsBlockComments() -> Bool {
contains { piece in
if case .blockComment = piece {
return true
} else {
return false
}
}
}
}
|
edbb67b1dff5e9f54940b59688fb59f7
| 41.810127 | 118 | 0.509905 | false | false | false | false |
bitboylabs/selluv-ios
|
refs/heads/master
|
selluv-ios/selluv-ios/Classes/Controller/UI/Product/SLVProductPhotoViewer.swift
|
mit
|
1
|
//
// SLVProductPhotoViewer.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 9..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
/*
판매 사진편집
*/
import Foundation
import UIKit
class SLVProductPhotoViewer: SLVBaseStatusHiddenController {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var horizontalView: PagedHorizontalView!
@IBOutlet weak var productButton: UIButton!
var photos: [String]?
var items: [SLVDetailProduct]?
var type: ProductPhotoType = .none
var viewerBlock: ((_ path: IndexPath, _ image: UIImage?,_ type: ProductPhotoType,_ item: SLVDetailProduct?) -> ())?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabController.animationTabBarHidden(true)
tabController.hideFab()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
self.setupCollectionLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupCollectionLayout() {
// horizontalView.addObserver(self, forKeyPath: "currentIndex", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
self.horizontalView.collectionView.register(UINib(nibName: "SLVProductPhotoViewerCell", bundle: nil), forCellWithReuseIdentifier: "SLVProductPhotoViewerCell")
self.horizontalView.collectionView.dataSource = self
}
deinit {
// horizontalView.removeObserver(self, forKeyPath: "currentIndex")
}
func setupData(type: ProductPhotoType, photos: [String], items: [SLVDetailProduct] ) {
self.type = type
self.items = items
self.photos = photos
}
func moveIndex(index: Int) {
self.horizontalView.moveToPage(index, animated: false)
}
func setupViewer(block: @escaping ((_ path: IndexPath, _ image: UIImage? ,_ type: ProductPhotoType,_ item: SLVDetailProduct?) -> ()) ) {
self.viewerBlock = block
}
func move(path: IndexPath, item: SLVDetailProduct?) {
if self.viewerBlock != nil {
let cell = self.horizontalView.collectionView.cellForItem(at: path) as? SLVProductPhotoViewerCell
let image = cell?.photo.image
self.viewerBlock!(path, image, type, item)
}
}
func imageDomain() -> String {
var domain = dnProduct
switch self.type {
case .style :
domain = dnStyle
break
case .damage :
domain = dnDamage
break
case .accessory :
domain = dnAccessory
break
default:
break
}
return domain
}
//MARK: Event
func dismiss() {
self.dismiss(animated: true) {
}
}
@IBAction func touchBack(_ sender: Any) {
self.dismiss()
}
@IBAction func touchProductDetail(_ sender: Any) {
let index = horizontalView.currentIndex
var item: SLVDetailProduct?
if self.items != nil && self.items!.count >= index + 1 {
item = self.items![index]
}
self.dismiss(animated: true) {
let path = IndexPath(row: index, section: 0)
self.move(path: path, item: item)
}
}
}
extension SLVProductPhotoViewer : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVProductPhotoViewerCell", for: indexPath) as! SLVProductPhotoViewerCell
if let list = self.photos {
let name = list[indexPath.row]
if name != "" {
let urlString = self.imageDomain()
let from = URL(string: "\(urlString)\(name)")
let dnModel = SLVDnImageModel.shared
dnModel.setupImageView(view: cell.photo!, from: from!)
}
}
return cell
}
}
|
3bd7f4e2352078e77734101de36551ab
| 30 | 166 | 0.617901 | false | false | false | false |
slepcat/mint
|
refs/heads/release
|
MINT/MintIOs.swift
|
gpl-3.0
|
1
|
//
// MintIOs.swift
// mint
//
// Created by NemuNeko on 2015/10/11.
// Copyright © 2015年 Taizo A. All rights reserved.
//
import Foundation
/*
class Display: Primitive {
let port : Mint3DPort
init(port: Mint3DPort) {
self.port = port
}
override func apply(var args: [SExpr]) -> SExpr {
var acc: [Double] = []
var acc_normal: [Double] = []
var acc_color: [Float] = []
var portid = 0
if args.count > 0 {
if let p = args.removeAtIndex(0) as? MInt {
portid = p.value
}
}
for arg in args {
let polys = delayed_list_of_values(arg)
for poly in polys {
if let p = poly as? MPolygon {
let vertices = p.value.vertices
if vertices.count == 3 {
for vertex in vertices {
acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z]
acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z]
acc_color += vertex.color
}
} else if vertices.count > 3 {
// if polygon is not triangle, split it to triangle polygons
//if polygon.checkIfConvex() {
let triangles = p.value.triangulationConvex()
for tri in triangles {
for vertex in tri.vertices {
acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z]
acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z]
acc_color += vertex.color
}
}
//} else {
//}
}
} else {
print("display take only polygons", terminator: "\n")
return MNull()
}
}
}
port.write(IOMesh(mesh: acc, normal: acc_normal, color: acc_color), port: portid)
return MNull()
}
override var category : String {
get {return "3D Primitives"}
}
override func params_str() -> [String] {
return ["portid", "poly."]
}
private func delayed_list_of_values(_opds :SExpr) -> [SExpr] {
if let atom = _opds as? Atom {
return [atom]
} else {
return tail_delayed_list_of_values(_opds, acc: [])
}
}
private func tail_delayed_list_of_values(_opds :SExpr, var acc: [SExpr]) -> [SExpr] {
if let pair = _opds as? Pair {
acc.append(pair.car)
return tail_delayed_list_of_values(pair.cdr, acc: acc)
} else {
return acc
}
}
}
*/
|
3c3af48aa980ed4741ccc2890baf3ad8
| 28.771429 | 97 | 0.41248 | false | false | false | false |
joaoSakai/torpedo-saude
|
refs/heads/master
|
GrupoFlecha/GrupoFlecha/ConfigViewController.swift
|
gpl-2.0
|
1
|
//
// ConfigViewController.swift
// GrupoFlecha
//
// Created by Davi Rodrigues on 05/03/16.
// Copyright © 2016 Davi Rodrigues. All rights reserved.
//
import UIKit
class ConfigViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate {
let defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var ageTextField: UITextField!
@IBOutlet weak var gestanteLabel: UILabel!
@IBOutlet weak var gestanteSwitch: UISwitch!
@IBOutlet weak var greenView: UIView!
//var keyboard: CGSize = CGSize(width: 0, height: 0)
@IBOutlet var tapGestureRecognizer: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
greenView.layer.cornerRadius = 50
}
///Popula informações do usuário na tela
override func viewWillAppear(animated: Bool) {
if(UserInfo.userAge >= 0) {
self.ageTextField.text = String(UserInfo.userAge)
}
self.gestanteSwitch.on = UserInfo.gestante
}
override func viewWillDisappear(animated: Bool) {
//Faz a persistencia de dados do usuário em NSUserDefaults ao deixar a tela
UserInfo.gestante = self.gestanteSwitch.on
self.defaults.setBool(self.gestanteSwitch.on, forKey: "gestante")
if(self.ageTextField.text != "") {
UserInfo.userAge = Int(self.ageTextField.text!)!
self.defaults.setInteger(Int(self.ageTextField.text!)!, forKey: "age")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Keyboard
/*
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.ageTextField.resignFirstResponder()
return true
}
func registerForKeyboardNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self,
selector: "keyboardWillBeShown:",
name: UIKeyboardWillShowNotification,
object: nil)
notificationCenter.addObserver(self,
selector: "keyboardWillBeHidden:",
name: UIKeyboardWillHideNotification,
object: nil)
}
// Called when the UIKeyboardDidShowNotification is sent.
func keyboardWillBeShown(sender: NSNotification) {
let info: NSDictionary = sender.userInfo!
let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue
let keyboardSize: CGSize = value.CGRectValue().size
self.keyboard = keyboardSize
if(ageTextField.isFirstResponder()) {
self.view.center.y -= keyboardSize.height
}
}
*/
//Recolhe teclado ao fim da edição do campo de texto
@IBAction func tapGestureRecognizerHandler(sender: AnyObject) {
self.ageTextField.resignFirstResponder()
}
}
|
060c617248fd67b42925836d0db3cd8a
| 29.35 | 96 | 0.6514 | false | false | false | false |
duliodenis/cs193p-Spring-2016
|
refs/heads/master
|
democode/Cassini-L8/Cassini/CassiniViewController.swift
|
mit
|
1
|
//
// CassiniViewController.swift
// Cassini
//
// Created by CS193p Instructor.
// Copyright © 2016 Stanford University. All rights reserved.
//
import UIKit
class CassiniViewController: UIViewController, UISplitViewControllerDelegate
{
// this is just our normal "put constants in a struct" thing
// but we call it Storyboard, because all the constants in it
// are strings in our Storyboard
private struct Storyboard {
static let ShowImageSegue = "Show Image"
}
// prepare for segue is called
// even if we invoke the segue from code using performSegue (see below)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Storyboard.ShowImageSegue {
if let ivc = segue.destinationViewController.contentViewController as? ImageViewController {
let imageName = (sender as? UIButton)?.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName)
ivc.title = imageName
}
}
}
// we changed the buttons to this target/action method
// so that we could either
// a) just set our imageURL in the detail if we're in a split view, or
// b) cause the segue to happen from code with performSegue
// to make the latter work, we had to create a segue in our storyboard
// that was ctrl-dragged from the view controller icon (orange one at the top)
@IBAction func showImage(sender: UIButton) {
if let ivc = splitViewController?.viewControllers.last?.contentViewController as? ImageViewController {
let imageName = sender.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName)
ivc.title = imageName
} else {
performSegueWithIdentifier(Storyboard.ShowImageSegue, sender: sender)
}
}
// if we are in a split view, we set ourselves as its delegate
// this is so we can prevent an empty detail from collapsing on top of our master
// see split view delegate method below
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
}
// this method lets the split view's delegate
// collapse the detail on top of the master when it's the detail's time to appear
// this method returns whether we (the delegate) handled doing this
// we don't want an empty detail to collapse on top of our master
// so if the detail is an empty ImageViewController, we return true
// (which tells the split view controller that we handled the collapse)
// of course, we didn't actually handle it, we did nothing
// but that's exactly what we want (i.e. no collapse if the detail ivc is empty)
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool
{
if primaryViewController.contentViewController == self {
if let ivc = secondaryViewController.contentViewController as? ImageViewController where ivc.imageURL == nil {
return true
}
}
return false
}
}
// a little helper extension
// which either returns the view controller you send it to
// or, if you send it to a UINavigationController,
// it returns its visibleViewController
// (if any, otherwise the UINavigationController itself)
extension UIViewController {
var contentViewController: UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController ?? self
} else {
return self
}
}
}
|
eb52e44fe4a1edbce2cf4f9b7501efc4
| 39 | 222 | 0.688032 | false | false | false | false |
seongkyu-sim/BaseVCKit
|
refs/heads/master
|
BaseVCKit/Classes/extensions/UITableViewExtensions.swift
|
mit
|
1
|
//
// UITableViewExtensions.swift
// BaseVCKit
//
// Created by frank on 2015. 11. 10..
// Copyright © 2016년 colavo. All rights reserved.
//
import UIKit
public extension UITableView {
func isLastRow(at indexPath: IndexPath) -> Bool {
let lastSectionIndex:Int = self.numberOfSections-1
let lastRowIndex:Int = self.numberOfRows(inSection: lastSectionIndex)-1
return (indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex)
}
func isSelectedCell(at indexPath: IndexPath) -> Bool {
guard let selectedRows = self.indexPathsForSelectedRows else {
return false
}
return selectedRows.contains(indexPath)
}
}
|
4a2660508d11f8594577f24130006212
| 26 | 87 | 0.678063 | false | false | false | false |
mikewxk/DYLiveDemo_swift
|
refs/heads/master
|
DYLiveDemo/DYLiveDemo/Classes/Main/View/PageTitleView.swift
|
unlicense
|
1
|
//
// PageTitleView.swift
// DYLiveDemo
//
// Created by xiaokui wu on 12/16/16.
// Copyright © 2016 wxk. All rights reserved.
//
import UIKit
//MARK: - 协议
protocol PageTitleViewDelegate : class {// : class 表明代理只能被类遵守
func pageTitleView(titleView : PageTitleView ,selectedIndex index: Int)
}
//MARK: - 常量
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) // 元组定义rgb颜色
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // 元组定义rgb颜色
private let kScrollLineHeight: CGFloat = 2
class PageTitleView: UIView {
//MARK: - 属性
private var titles: [String]
private var currentIndex = 0
weak var delegate : PageTitleViewDelegate?// 代理指明weak
//MARK: - 懒加载
private lazy var titleLabels: [UILabel] = [UILabel]()
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.pagingEnabled = false
scrollView.bounces = false
return scrollView
}()
private lazy var scrollLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orangeColor()
return scrollLine
}()
//MARK: - 自定义构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView{
private func setupUI(){
// 滚动视图
addSubview(scrollView)
scrollView.frame = bounds
// 标题label
setupTitleLabels()
// 底线
setupBottomAndScrollLine()
}
private func setupTitleLabels() {
let labelW: CGFloat = frame.width / CGFloat(titles.count)
let labelH: CGFloat = frame.height - kScrollLineHeight
let labelY: CGFloat = 0
for (index, title) in titles.enumerate(){
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(16.0)
label.textColor = UIColor.darkGrayColor()
label.textAlignment = .Center
//frame
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
// 添加到scrollView中,让label能随着scrollView滚动
scrollView.addSubview(label)
// 添加到titleLabels数组里
titleLabels.append(label)
// 给label添加手势
label.userInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelTap(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomAndScrollLine(){
// 底部分隔线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGrayColor()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: (frame.height - lineH), width: frame.width, height: lineH)
addSubview(bottomLine)
// 拿到第一个label
guard let firstLabel = titleLabels.first else{return}
firstLabel.textColor = UIColor.orangeColor()
// scrollLine滚动指示线
scrollView.addSubview(scrollLine)
// 参照第一个label,设置frame
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineHeight, width: firstLabel.frame.size.width, height: kScrollLineHeight)
}
}
//MARK: - 内部事件回调
extension PageTitleView{
@objc private func titleLabelTap(tapGes: UITapGestureRecognizer) {
// 当前选中的label
guard let currentLabel = tapGes.view as? UILabel else{return}
// 上一个label
let previousLabel = titleLabels[currentIndex]
// 改变颜色
previousLabel.textColor = UIColor.darkGrayColor()
currentLabel.textColor = UIColor.orangeColor()
// 最新选中label的tag值,就是索引值
currentIndex = currentLabel.tag
// 移动滚动条
UIView.animateWithDuration(0.15) {
self.scrollLine.frame.origin.x = currentLabel.frame.origin.x
}
// 通知代理
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
//MARK: - 外部方法
extension PageTitleView{
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
// 记录最新选中的索引
currentIndex = targetIndex
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 滑块滑动
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 颜色渐变
// 变化范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 选中颜色变为普通颜色
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 普通颜色变为选中颜色
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
}
}
|
8ab2e268199121fd1b39de170d7a5804
| 24.371681 | 174 | 0.603767 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Kickstarter-iOS/Features/ProjectPage/Views/ProjectPageNavigationBarView.swift
|
apache-2.0
|
1
|
import KsApi
import Library
import PassKit
import Prelude
import UIKit
protocol ProjectPageNavigationBarViewDelegate: AnyObject {
func configureSharing(with context: ShareContext)
func configureWatchProject(with context: WatchProjectValue)
func viewDidLoad()
}
private enum Layout {
enum Button {
static let height: CGFloat = 15
}
}
final class ProjectPageNavigationBarView: UIView {
// MARK: - Properties
private let shareViewModel: ShareViewModelType = ShareViewModel()
private let watchProjectViewModel: WatchProjectViewModelType = WatchProjectViewModel()
private lazy var navigationShareButton: UIButton = { UIButton(type: .custom) }()
private lazy var navigationCloseButton: UIButton = {
let buttonView = UIButton(type: .custom)
|> UIButton.lens.title(for: .normal) .~ nil
|> UIButton.lens.image(for: .normal) .~ image(named: "icon--cross")
|> UIButton.lens.tintColor .~ .ksr_support_700
|> UIButton.lens.accessibilityLabel %~ { _ in Strings.accessibility_projects_buttons_close() }
|> UIButton.lens.accessibilityHint %~ { _ in Strings.Closes_project() }
return buttonView
}()
private lazy var navigationSaveButton: UIButton = { UIButton(type: .custom) }()
private lazy var rootStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var spacer: UIView = {
UIView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
weak var delegate: ProjectPageViewControllerDelegate?
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureSubviews()
self.setupConstraints()
self.setupNotifications()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self |> \.backgroundColor .~ .ksr_white
_ = self.rootStackView
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.insetsLayoutMarginsFromSafeArea .~ true
|> \.spacing .~ Styles.grid(0)
_ = self.navigationShareButton
|> shareButtonStyle
|> UIButton.lens.accessibilityLabel %~ { _ in Strings.dashboard_accessibility_label_share_project() }
_ = self.navigationSaveButton
|> saveButtonStyle
|> UIButton.lens.accessibilityLabel %~ { _ in Strings.Toggle_saving_this_project() }
}
// MARK: - View Model
override func bindViewModel() {
super.bindViewModel()
self.bindSharingViewModel()
self.bindWatchViewModel()
}
private func bindSharingViewModel() {
self.shareViewModel.outputs.showShareSheet
.observeForControllerAction()
.observeValues { [weak self] controller, _ in
self?.delegate?.showShareSheet(controller, sourceView: self?.navigationShareButton)
}
}
private func bindWatchViewModel() {
self.navigationSaveButton.rac.accessibilityValue = self.watchProjectViewModel.outputs
.saveButtonAccessibilityValue
self.navigationSaveButton.rac.selected = self.watchProjectViewModel.outputs.saveButtonSelected
self.watchProjectViewModel.outputs.generateImpactFeedback
.observeForUI()
.observeValues { generateImpactFeedback() }
self.watchProjectViewModel.outputs.generateNotificationSuccessFeedback
.observeForUI()
.observeValues { generateNotificationSuccessFeedback() }
self.watchProjectViewModel.outputs.generateSelectionFeedback
.observeForUI()
.observeValues { generateSelectionFeedback() }
self.watchProjectViewModel.outputs.showProjectSavedAlert
.observeForControllerAction()
.observeValues { [weak self] in
self?.delegate?.displayProjectStarredPrompt()
}
self.watchProjectViewModel.outputs.goToLoginTout
.observeForControllerAction()
.observeValues { [weak self] in
self?.delegate?.goToLogin()
}
self.watchProjectViewModel.outputs.postNotificationWithProject
.observeForUI()
.observeValues { project in
NotificationCenter.default.post(
name: Notification.Name.ksr_projectSaved,
object: nil,
userInfo: ["project": project]
)
}
}
// MARK: Helpers
private func setupConstraints() {
_ = (self.rootStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (
[
self.navigationCloseButton,
self.spacer,
self.navigationShareButton,
self.navigationSaveButton
],
self.rootStackView
)
|> ksr_addArrangedSubviewsToStackView()
NSLayoutConstraint
.activate([
self.navigationShareButton.widthAnchor
.constraint(equalTo: self.navigationShareButton.heightAnchor),
self.navigationSaveButton.widthAnchor
.constraint(equalTo: self.navigationSaveButton.heightAnchor),
self.navigationCloseButton.widthAnchor
.constraint(equalTo: self.navigationCloseButton.heightAnchor)
])
}
private func setupNotifications() {
NotificationCenter.default
.addObserver(
self,
selector: #selector(ProjectPageNavigationBarView.userSessionStarted),
name: .ksr_sessionStarted,
object: nil
)
NotificationCenter.default
.addObserver(
self,
selector: #selector(ProjectPageNavigationBarView.userSessionEnded),
name: .ksr_sessionEnded,
object: nil
)
}
private func configureSubviews() {
self.addTargetAction(
buttonItem: self.navigationCloseButton,
targetAction: #selector(ProjectPageNavigationBarView.closeButtonTapped),
event: .touchUpInside
)
self.addTargetAction(
buttonItem: self.navigationShareButton,
targetAction: #selector(ProjectPageNavigationBarView.shareButtonTapped),
event: .touchUpInside
)
self.addTargetAction(
buttonItem: self.navigationSaveButton,
targetAction: #selector(ProjectPageNavigationBarView.saveButtonTapped(_:)),
event: .touchUpInside
)
self.addTargetAction(
buttonItem: self.navigationSaveButton,
targetAction: #selector(ProjectPageNavigationBarView.saveButtonPressed),
event: .touchDown
)
}
private func addTargetAction(
buttonItem: UIButton,
targetAction: Selector,
event: UIControl.Event
) {
buttonItem.addTarget(
self,
action: targetAction,
for: event
)
}
// MARK: Selectors
@objc private func shareButtonTapped() {
self.shareViewModel.inputs.shareButtonTapped()
}
@objc private func userSessionStarted() {
self.watchProjectViewModel.inputs.userSessionStarted()
}
@objc private func userSessionEnded() {
self.watchProjectViewModel.inputs.userSessionEnded()
}
@objc private func closeButtonTapped() {
self.delegate?.dismissPage(animated: true, completion: nil)
}
@objc private func saveButtonTapped(_ button: UIButton) {
self.watchProjectViewModel.inputs.saveButtonTapped(selected: button.isSelected)
}
@objc private func saveButtonPressed() {
self.watchProjectViewModel.inputs.saveButtonTouched()
}
}
extension ProjectPageNavigationBarView: ProjectPageNavigationBarViewDelegate {
func viewDidLoad() {
self.watchProjectViewModel.inputs.viewDidLoad()
}
func configureSharing(with context: ShareContext) {
self.shareViewModel.inputs.configureWith(shareContext: context, shareContextView: nil)
}
func configureWatchProject(with context: WatchProjectValue) {
self.watchProjectViewModel.inputs
.configure(with: context)
}
}
|
3a7e6efa5c5e98dd5f23313d9f7b0317
| 27.88764 | 107 | 0.706859 | false | false | false | false |
SwiftStudies/OysterKit
|
refs/heads/master
|
Tests/OysterKitTests/HomegenousASTTests.swift
|
bsd-2-clause
|
1
|
//
// HomegenousASTTests.swift
// PerformanceTests
//
// Created by Nigel Hughes on 30/01/2018.
//
import XCTest
import OysterKit
//
// XML Parser
//
enum XMLGenerated : Int, TokenType {
typealias T = XMLGenerated
// Cache for compiled regular expressions
private static var regularExpressionCache = [String : NSRegularExpression]()
/// Returns a pre-compiled pattern from the cache, or if not in the cache builds
/// the pattern, caches and returns the regular expression
///
/// - Parameter pattern: The pattern the should be built
/// - Returns: A compiled version of the pattern
///
private static func regularExpression(_ pattern:String)->NSRegularExpression{
if let cached = regularExpressionCache[pattern] {
return cached
}
do {
let new = try NSRegularExpression(pattern: pattern, options: [])
regularExpressionCache[pattern] = new
return new
} catch {
fatalError("Failed to compile pattern /\(pattern)/\n\(error)")
}
}
/// The tokens defined by the grammar
case `ws`, `identifier`, `singleQuote`, `doubleQuote`, `value`, `attribute`, `attributes`, `data`, `openTag`, `closeTag`, `inlineTag`, `nestingTag`, `tag`, `contents`, `xml`
/// The rule for the token
var rule : Rule {
switch self {
/// ws
case .ws:
return -[
CharacterSet.whitespacesAndNewlines.require(.one)
].sequence
/// identifier
case .identifier:
return [
[
CharacterSet.letters.require(.one),
[
CharacterSet.letters.require(.one),
[
"-".require(.one),
CharacterSet.letters.require(.one)].sequence
].choice
].sequence
].sequence.parse(as: self)
/// singleQuote
case .singleQuote:
return [
"\'".require(.one)
].sequence.parse(as: self)
/// doubleQuote
case .doubleQuote:
return [
"\\\"".require(.one)
].sequence.parse(as: self)
/// value
case .value:
return [
[
[
-T.singleQuote.rule.require(.one),
!T.singleQuote.rule.require(.zeroOrMore),
-T.singleQuote.rule.require(.one)].sequence
,
[
-T.doubleQuote.rule.require(.one),
!T.doubleQuote.rule.require(.zeroOrMore),
-T.doubleQuote.rule.require(.one)].sequence
].choice
].sequence.parse(as: self)
/// attribute
case .attribute:
return [
[
T.ws.rule.require(.oneOrMore),
T.identifier.rule.require(.one),
[
T.ws.rule.require(.zeroOrMore),
-"=".require(.one),
T.ws.rule.require(.zeroOrMore),
T.value.rule.require(.one)].sequence
].sequence
].sequence.parse(as: self)
/// attributes
case .attributes:
return [
T.attribute.rule.require(.oneOrMore)
].sequence.parse(as: self)
/// data
case .data:
return [
!"<".require(.oneOrMore)
].sequence.parse(as: self)
/// openTag
case .openTag:
return [
[
T.ws.rule.require(.zeroOrMore),
-"<".require(.one),
T.identifier.rule.require(.one),
[
T.attributes.rule.require(.one),
T.ws.rule.require(.zeroOrMore)].choice
,
-">".require(.one)].sequence
].sequence.parse(as: self)
/// closeTag
case .closeTag:
return -[
[
T.ws.rule.require(.zeroOrMore),
-"</".require(.one),
T.identifier.rule.require(.one),
T.ws.rule.require(.zeroOrMore),
-">".require(.one)].sequence
].sequence
/// inlineTag
case .inlineTag:
return [
[
T.ws.rule.require(.zeroOrMore),
-"<".require(.one),
T.identifier.rule.require(.one),
[
T.attribute.rule.require(.oneOrMore),
T.ws.rule.require(.zeroOrMore)].choice
,
-"/>".require(.one)].sequence
].sequence.parse(as: self)
/// nestingTag
case .nestingTag:
return [
[
~T.openTag.rule.require(.one),
T.contents.rule.require(.one),
T.closeTag.rule.require(.one)].sequence
].sequence.parse(as: self)
/// tag
case .tag:
return [
[
~T.nestingTag.rule.require(.one),
~T.inlineTag.rule.require(.one)].choice
].sequence.parse(as: self)
/// contents
case .contents:
return [
[
T.data.rule.require(.one),
T.tag.rule.require(.one)].choice
].sequence.parse(as: self)
/// xml
case .xml:
return [
T.tag.rule.require(.one)
].sequence.parse(as: self)
}
}
/// Create a language that can be used for parsing etc
public static var grammar: [Rule] {
return [T.xml.rule]
}
}
class HomegenousASTTests: 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 testCache() {
let astConstructor = AbstractSyntaxTreeConstructor()
astConstructor.initializeCache(depth: 3, breadth: 3)
}
}
|
a8d1597e8cfded9959272928e43afdb7
| 30.285714 | 177 | 0.438213 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Plans/PlanComparisonViewController.swift
|
gpl-2.0
|
2
|
import UIKit
import Gridicons
import WordPressShared
class PlanComparisonViewController: PagedViewController {
let initialPlan: Plan
let plans: [Plan]
let features: [PlanFeature]
// Keep a more specific reference to the view controllers rather than force
// downcast viewControllers.
fileprivate let detailViewControllers: [PlanDetailViewController]
lazy fileprivate var cancelXButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: .gridicon(.cross), style: .plain, target: self, action: #selector(PlanComparisonViewController.closeTapped))
button.accessibilityLabel = NSLocalizedString("Close", comment: "Dismiss the current view")
return button
}()
init(plans: [Plan], initialPlan: Plan, features: [PlanFeature]) {
self.initialPlan = initialPlan
self.plans = plans
self.features = features
let controllers: [PlanDetailViewController] = plans.map({ plan in
let controller = PlanDetailViewController.controllerWithPlan(plan, features: features)
return controller
})
self.detailViewControllers = controllers
let initialIndex = plans.firstIndex { plan in
return plan == initialPlan
}
super.init(viewControllers: controllers, initialIndex: initialIndex!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func closeTapped() {
dismiss(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = cancelXButton
}
}
|
58196941c44aed1e7a9fb1c1dafe939d
| 30.339623 | 152 | 0.686334 | false | false | false | false |
eugeneego/utilities-ios
|
refs/heads/master
|
Sources/UI/NetworkImageView.swift
|
mit
|
1
|
//
// GradientView
// Legacy
//
// Copyright (c) 2016 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
open class NetworkImageView: UIImageView {
open var imageLoader: ImageLoader?
open var resizeMode: ResizeMode = .fill
open var placeholder: UIImage?
open var imageUrl: URL? {
didSet {
if oldValue != imageUrl {
update()
}
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if task == nil && image == nil {
update()
}
}
private var task: Task<Void, Never>?
private func update() {
task?.cancel()
task = nil
image = placeholder
guard bounds.width > 0.1 && bounds.height > 0.1 else { return }
guard let imageLoader = imageLoader, let imageUrl = imageUrl else { return }
task = Task {
let result = await imageLoader.load(url: imageUrl, size: frame.size, mode: resizeMode)
task = nil
guard let image = result.value?.1 else { return }
addFadeTransition()
self.image = image
}
}
}
#endif
|
f085cb88a43c93c0b1b0a6a56ba945f1
| 21.321429 | 98 | 0.5664 | false | false | false | false |
evermeer/EVWordPressAPI
|
refs/heads/master
|
EVWordPressAPI/EVWordPressAPI_Stats.swift
|
bsd-3-clause
|
1
|
//
// EVWordPressAPI_Stats.swift
// EVWordPressAPI
//
// Created by Edwin Vermeer on 11/24/15.
// Copyright © 2015 evict. All rights reserved.
//
import Alamofire
import AlamofireOauth2
import AlamofireJsonToObjects
import EVReflection
public extension EVWordPressAPI {
// MARK: - Stats
/**
Get a site's stats (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
:param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the Stats object
:return: No return value
*/
public func stats(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Stats?) -> Void) {
genericOauthCall(.Stats(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's summarized views, visitors, likes and comments (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/summary/
:param: parameters an array of statsSummaryParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsSummary object
:return: No return value
*/
public func statsSummary(_ parameters:[statsSummaryParameters]? = nil, completionHandler: @escaping (StatsSummary?) -> Void) {
genericOauthCall(.StatsSummary(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's top posts and pages by views (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-posts/
:param: parameters an array of statsSummaryParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsTopTasks object
:return: No return value
*/
public func statsTopPosts(_ parameters:[statsSummaryParameters]? = nil, completionHandler: @escaping (StatsTopTasks?) -> Void) {
genericOauthCall(.StatsTopTasks(pdict(parameters)), completionHandler: completionHandler)
}
/**
View the details of a single video (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video/%24post_id/
:param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsVideo object
:return: No return value
*/
public func statsVideo(_ parameters:[basicContextParameters]? = nil, videoId: String, completionHandler: @escaping (StatsVideo?) -> Void) {
genericOauthCall(.StatsVideo(pdict(parameters), videoId), completionHandler: completionHandler)
}
/**
View a site's referrers (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/referrers/
:param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsReferrer object
:return: No return value
*/
public func statsReferrers(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsReferrer?) -> Void) {
genericOauthCall(.StatsReferrers(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's outbound clicks (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/clicks/
:param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsClicks object
:return: No return value
*/
public func statsClicks(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsClicks?) -> Void) {
genericOauthCall(.StatsClicks(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's views by tags and categories (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/tags/
:param: parameters an array of statsTagsParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsTags object
:return: No return value
*/
public func statsTags(_ parameters:[statsTagsParameters]? = nil, completionHandler: @escaping (StatsTags?) -> Void) {
genericOauthCall(.StatsTags(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's top authors (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-authors/
:param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsAuthors object
:return: No return value
*/
public func statsAuthors(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsAuthors?) -> Void) {
genericOauthCall(.StatsAuthors(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's top comment authors and most-commented posts (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/comments/
:param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsComments object
:return: No return value
*/
public func statsComments(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (StatsComments?) -> Void) {
genericOauthCall(.StatsComments(pdict(parameters)), completionHandler: completionHandler)
}
/**
View a site's video plays (authentication is required)
See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video-plays/
:param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation
:param: completionHandler A code block that will be called with the StatsVideoPlays object
:return: No return value
*/
public func statsVideoPlays(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsVideoPlays?) -> Void) {
genericOauthCall(.StatsVideoPlays(pdict(parameters)), completionHandler: completionHandler)
}
public func statsPost(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (StatsPost?) -> Void) {
genericOauthCall(.StatsPost(pdict(parameters)), completionHandler: completionHandler)
}
}
|
4d19a898c9fa0372c7fbbbbbea3f84c1
| 47.208054 | 143 | 0.728943 | false | false | false | false |
hryk224/IPhotoBrowser
|
refs/heads/master
|
IPhotoBrowserExample/IPhotoBrowserExample/Sources/View/Controller/Table/ImageUrlViewController.swift
|
mit
|
1
|
//
// ColorViewController.swift
// IPhotoBrowserExample
//
// Created by hryk224 on 2017/02/15.
// Copyright © 2017年 hryk224. All rights reserved.
//
import UIKit
import IPhotoBrowser
final class ImageUrlViewController: UITableViewController {
static func makeFromStoryboard() -> ImageUrlViewController {
let storyboard = UIStoryboard(name: "ImageUrlViewController", bundle: nil)
return storyboard.instantiateInitialViewController() as! ImageUrlViewController
}
fileprivate var imageUrls: Assets.ImageURL {
return Assets.ImageURL.share
}
fileprivate var indexPathForSelectedRow: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(WebImageTableViewCell.nib, forCellReuseIdentifier: WebImageTableViewCell.identifier)
tableView.separatorInset = .zero
title = MainViewController.Row.imageUrl.title
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension ImageUrlViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageUrls.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WebImageTableViewCell.identifier, for: indexPath) as! WebImageTableViewCell
cell.configure(imageUrl: imageUrls.objects[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let photoBrowser = IPhotoBrowser(imageUrls: imageUrls.objects, start: indexPath.item)
photoBrowser.delegate = self
DispatchQueue.main.async {
self.present(photoBrowser, animated: true, completion: nil)
}
indexPathForSelectedRow = indexPath
tableView.deselectRow(at: indexPath, animated: false)
}
}
// MARK: - IPhotoBrowserAnimatedTransitionProtocol
extension ImageUrlViewController: IPhotoBrowserAnimatedTransitionProtocol {
var iPhotoBrowserSelectedImageViewCopy: UIImageView? {
guard let indexPath = indexPathForSelectedRow, let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell else {
return nil
}
let sourceImageView = UIImageView(image: cell.webImageView.image)
sourceImageView.contentMode = cell.webImageView.contentMode
sourceImageView.clipsToBounds = true
sourceImageView.frame = cell.contentView.convert(cell.webImageView.frame, to: navigationController?.view)
sourceImageView.layer.cornerRadius = cell.webImageView.layer.cornerRadius
return sourceImageView
}
var iPhotoBrowserDestinationImageViewSize: CGSize? {
guard let indexPath = indexPathForSelectedRow else {
return nil
}
let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell
return cell?.webImageView.frame.size
}
var iPhotoBrowserDestinationImageViewCenter: CGPoint? {
guard let indexPath = indexPathForSelectedRow, let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell else {
return nil
}
return cell.contentView.convert(cell.webImageView.center, to: navigationController?.view)
}
func iPhotoBrowserTransitionWillBegin() {
guard let indexPath = indexPathForSelectedRow else {
return
}
let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell
cell?.webImageView.isHidden = true
}
func iPhotoBrowserTransitionDidEnded() {
guard let indexPath = indexPathForSelectedRow else {
return
}
let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell
cell?.webImageView.isHidden = false
}
}
// MARK: - IPhotoBrowserDelegate
extension ImageUrlViewController: IPhotoBrowserDelegate {
func iPhotoBrowser(_ iPhotoBrowser: IPhotoBrowser, didChange index: Int) {
let indexPath = IndexPath(item: index, section: 0)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .top)
indexPathForSelectedRow = indexPath
}
func iPhotoBrowserDidDismissing(_ iPhotoBrowser: IPhotoBrowser) {
guard let indexPath = indexPathForSelectedRow else {
return
}
let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell
cell?.webImageView.isHidden = true
}
func iPhotoBrowserDidCanceledDismiss(_ iPhotoBrowser: IPhotoBrowser) {
guard let indexPath = indexPathForSelectedRow else {
return
}
let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell
cell?.webImageView.isHidden = false
}
}
|
d3dbbfc2086476e0759745dfdb78c872
| 41.707965 | 140 | 0.716743 | false | false | false | false |
googlecodelabs/automl-vision-edge-in-mlkit
|
refs/heads/master
|
ios/mlkit-automl/MLVisionExample/ViewController.swift
|
apache-2.0
|
1
|
//
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate {
/// An image picker for accessing the photo library or camera.
private var imagePicker = UIImagePickerController()
/// Image counter.
private var currentImage = 0
/// AutoML image classifier wrapper.
private lazy var classifier = ImageClassifer()
// MARK: - IBOutlets
@IBOutlet fileprivate weak var imageView: UIImageView!
@IBOutlet fileprivate weak var photoCameraButton: UIBarButtonItem!
@IBOutlet fileprivate weak var videoCameraButton: UIBarButtonItem!
@IBOutlet fileprivate weak var resultsLabelView: UILabel!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
let isCameraAvailable = UIImagePickerController.isCameraDeviceAvailable(.front) ||
UIImagePickerController.isCameraDeviceAvailable(.rear)
if isCameraAvailable {
// `CameraViewController` uses `AVCaptureDevice.DiscoverySession` which is only supported for
// iOS 10 or newer.
if #available(iOS 10.0, *) {
videoCameraButton.isEnabled = true
}
} else {
photoCameraButton.isEnabled = false
}
// Set up image view and classify the first image in the bundle.
imageView.image = UIImage(named: Constant.images[currentImage])
classifyImage()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isHidden = false
}
// MARK: - IBActions
@IBAction func openPhotoLibrary(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true)
}
@IBAction func openCamera(_ sender: Any) {
guard UIImagePickerController.isCameraDeviceAvailable(.front) ||
UIImagePickerController.isCameraDeviceAvailable(.rear)
else {
return
}
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
@IBAction func changeImage(_ sender: Any) {
nextImageAndClassify()
}
// MARK: - Private
/// Clears the results text view and removes any frames that are visible.
private func clearResults() {
resultsLabelView.text = ""
imageView.image = nil
}
/// Update the results text view with classification result.
private func showResult(_ resultText: String) {
self.resultsLabelView.text = resultText
}
/// Change to the next image available in app's bundle, and run image classification.
private func nextImageAndClassify() {
clearResults()
currentImage = (currentImage + 1) % Constant.images.count
imageView.image = UIImage(named: Constant.images[currentImage])
classifyImage()
}
/// Run image classification on the image currently display in imageView.
private func classifyImage() {
guard let image = imageView.image else {
print("Error: Attempted to run classification on a nil object")
showResult("Error: invalid image")
return
}
classifier.classifyImage(image) { resultText, error in
// Handle classification error
guard error == nil else {
self.showResult(error!.localizedDescription)
return
}
// We don't expect resultText and error to be both nil, so this is just a safeguard.
guard resultText != nil else {
self.showResult("Error: Unknown error occured")
return
}
self.showResult(resultText!)
}
}
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController: UIImagePickerControllerDelegate {
public func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
if let pickedImage = info[.originalImage] as? UIImage {
clearResults()
imageView.image = pickedImage
classifyImage()
}
dismiss(animated: true)
}
}
// MARK: - Constants
private enum Constant {
static let images = ["sunflower_1627193_640.jpg", "sunflower_3292932_640.jpg",
"dandelion_4110356_640.jpg", "dandelion_2817950_640.jpg",
"rose_1463562_640.jpg", "rose_3063284_640.jpg"]
}
|
21bc1bf981ceabdfdb771929269dfbe9
| 28.270588 | 99 | 0.705587 | false | false | false | false |
elkanaoptimove/OptimoveSDK
|
refs/heads/master
|
OptimoveSDK/Tenant Config/FirebaseKeys/FirebaseProjectKeys.swift
|
mit
|
1
|
//
// FirebaseProjectKeys.swift
// WeAreOptimove
//
// Created by Elkana Orbach on 10/05/2018.
// Copyright © 2018 Optimove. All rights reserved.
//
import Foundation
class FirebaseProjectKeys:FirebaseKeys
{
var appid:String
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let appIds = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .appIds )
let ios = try appIds.nestedContainer(keyedBy: CK.self, forKey: .ios)
let key = Bundle.main.bundleIdentifier!
appid = try ios.decode(String.self, forKey: CK(stringValue:key)!)
try super.init(from: decoder)
}
}
|
02e142338aaf3e6a74a2a1927efc9311
| 28.208333 | 91 | 0.68331 | false | false | false | false |
takayoshiotake/SevenSegmentSampler_swift
|
refs/heads/master
|
SevenSegmentViewSampler/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SevenSegmentViewSampler
//
// Created by Takayoshi Otake on 2015/11/08.
// Copyright © 2015 Takayoshi Otake. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
let valueMap: [Int: Int16] = [
0:0x3f,
1:0x06,
2:0x5b,
3:0x4f,
4:0x66,
5:0x6d,
6:0x7d,
7:0x07,
8:0x7f,
9:0x6f,
]
var value: Int = 0 {
didSet {
if let temp_view = stackView.subviews[0] as? BBSevenSegmentView {
temp_view.pinBits = valueMap[(value / 100) % 10]!
}
if let temp_view = stackView.subviews[1] as? BBSevenSegmentView {
temp_view.pinBits = valueMap[(value / 10) % 10]! | 0x80
}
if let temp_view = stackView.subviews[2] as? BBSevenSegmentView {
temp_view.pinBits = valueMap[(value / 1) % 10]!
}
}
}
var timer: NSTimer?
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResignActive:", name: UIApplicationWillResignActiveNotification, object: nil)
}
func applicationDidBecomeActive(notification: NSNotification) {
start()
}
func applicationWillResignActive(notification: NSNotification) {
stop()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
start()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
stop()
}
private func start() {
if let timer = timer {
if timer.valid {
return
}
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerDidTick:", userInfo: nil, repeats: true)
}
private func stop() {
if let timer = timer {
timer.invalidate()
}
timer = nil
}
func timerDidTick(timer: NSTimer) {
dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
if let selfVC = self {
if (selfVC.value < 1000) {
selfVC.value += 1
}
else {
selfVC.value = 0
}
}
}
}
}
|
87e0e6a2677bee78cc43fcfec51e5d41
| 25.881188 | 166 | 0.554328 | false | false | false | false |
lucasmpaim/GuizionCardView
|
refs/heads/master
|
guizion-card-view/Classes/MaskLabel.swift
|
mit
|
1
|
//
// MaskLabel.swift
// guizion-card-view
//
// Created by Lucas Paim on 13/11/2017.
//
import Foundation
import UIKit
class MaskLabel: UILabel {
var textMask: String = "#### #### #### ####"
fileprivate var applyingMask = false
override var text: String? {
didSet {
if !applyingMask {
applyMask(text)
}
}
}
fileprivate func applyMask(_ _value: String?) {
//Remove spaces
applyingMask = true
guard let value = _value?.replacingOccurrences(of: " ", with: "") else { return }
var maskedValue = ""
var currentTextIndex = 0
textMask.forEach {
if currentTextIndex < value.count {
if $0 == "#" {
maskedValue += value[currentTextIndex]
currentTextIndex += 1
} else {
maskedValue += "\($0)"
}
}
}
text = maskedValue
applyingMask = false
}
}
|
744e488b60ed7a7402a449bd525afb73
| 20.115385 | 89 | 0.456284 | false | false | false | false |
piscoTech/GymTracker
|
refs/heads/master
|
Gym Tracker iOS/CurrentWorkoutVC.swift
|
mit
|
1
|
//
// CurrentWorkoutViewController.swift
// Gym Tracker
//
// Created by Marco Boschi on 08/04/2017.
// Copyright © 2017 Marco Boschi. All rights reserved.
//
import UIKit
import MBLibrary
import GymTrackerCore
class CurrentWorkoutViewController: UIViewController {
@IBOutlet private var cancelBtn: UIBarButtonItem!
@IBOutlet private var endNowBtn: UIBarButtonItem!
@IBOutlet private weak var manageFromWatchLbl: UILabel!
@IBOutlet private weak var noWorkoutLabel: UIView!
@IBOutlet private weak var workoutInfo: UIStackView!
@IBOutlet private weak var workoutTitleLbl: UILabel!
@IBOutlet private weak var bpmLbl: UILabel!
@IBOutlet private weak var timerLbl: UILabel!
@IBOutlet private weak var currentExerciseInfo: UIStackView!
@IBOutlet private weak var exerciseNameLbl: UILabel!
@IBOutlet private weak var currentSetInfoLbl: UILabel!
@IBOutlet private weak var otherSetsLbl: UILabel!
@IBOutlet private weak var setDoneBtn: UIButton!
@IBOutlet private weak var restInfo: UIStackView!
@IBOutlet private weak var restTimerLbl: UILabel!
@IBOutlet private weak var restDoneBtn: UIButton!
@IBOutlet private weak var workoutDoneInfo: UIStackView!
@IBOutlet private weak var workoutDoneLbl: UILabel!
@IBOutlet private weak var workoutDoneBtn: UIButton!
@IBOutlet private weak var nextUpInfo: UIView!
@IBOutlet private weak var nextUpLbl: UILabel!
@IBOutlet private weak var tipView: UIView!
private var workoutController: ExecuteWorkoutController? {
return appDelegate.workoutController
}
override func viewDidLoad() {
super.viewDidLoad()
appDelegate.currentWorkout = self
for b in [setDoneBtn, restDoneBtn] {
b?.clipsToBounds = true
b?.layer.cornerRadius = 5
}
for l in [bpmLbl, timerLbl, restTimerLbl] {
l?.font = l?.font?.makeMonospacedDigit()
}
// This method is always called during app launch by the app delegate and as soon as the view is loaded it also updates it as appropriate
if #available(iOS 13, *) {} else {
self.navigationController?.navigationBar.barStyle = .black
self.view.backgroundColor = .black
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setWorkoutTitle(_ text: String) {
workoutTitleLbl.text = text
}
func askForChoices(_ choices: [GTChoice]) {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "askChoices", sender: choices)
}
}
func setBPM(_ text: String) {
bpmLbl.text = text
}
private var timerDate: Date!
private var timerUpdater: Timer? {
didSet {
DispatchQueue.main.async {
oldValue?.invalidate()
}
}
}
func startTimer(at date: Date) {
timerDate = date
let update = {
self.timerLbl.text = Date().timeIntervalSince(self.timerDate).rawDuration()
}
DispatchQueue.main.async {
self.timerUpdater = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
update()
}
RunLoop.main.add(self.timerUpdater!, forMode: .common)
}
update()
}
func stopTimer() {
timerUpdater?.invalidate()
timerUpdater = nil
}
private var currentExerciseInfoSpacing: CGFloat?
func setCurrentExerciseViewHidden(_ hidden: Bool) {
if hidden {
currentExerciseInfoSpacing = currentExerciseInfo.isHidden
? currentExerciseInfoSpacing
: currentExerciseInfo.spacing
currentExerciseInfo.spacing = 0
} else {
currentExerciseInfo.spacing = currentExerciseInfoSpacing ?? 0
}
currentExerciseInfo.isHidden = hidden
}
func setExerciseName(_ name: String) {
exerciseNameLbl.text = name
}
func setCurrentSetViewHidden(_ hidden: Bool) {
currentSetInfoLbl.isHidden = hidden
}
func setCurrentSetText(_ text: NSAttributedString) {
if #available(iOS 13, *) {
// In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string
} else {
currentSetInfoLbl.textColor = UIColor(named: "Text Color")
}
currentSetInfoLbl.attributedText = text
}
func setOtherSetsViewHidden(_ hidden: Bool) {
otherSetsLbl.isHidden = hidden
}
func setOtherSetsText(_ text: NSAttributedString) {
if #available(iOS 13, *) {
// In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string
} else {
otherSetsLbl.textColor = UIColor(named: "Text Color")
}
otherSetsLbl.attributedText = text
}
func setSetDoneButtonHidden(_ hidden: Bool) {
setDoneBtn.isHidden = hidden
}
private var restTimerDate: Date!
private var restTimerUpdater: Timer? {
didSet {
DispatchQueue.main.async {
oldValue?.invalidate()
}
}
}
func startRestTimer(to date: Date) {
restTimerDate = date
let update = {
let time = max(self.restTimerDate.timeIntervalSince(Date()), 0)
self.restTimerLbl.text = time.rawDuration(hidingHours: true)
if time == 0 {
self.stopRestTimer()
}
}
DispatchQueue.main.async {
self.restTimerUpdater = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
update()
}
RunLoop.main.add(self.restTimerUpdater!, forMode: .common)
}
update()
}
func stopRestTimer() {
restTimerUpdater?.invalidate()
restTimerUpdater = nil
}
private var restInfoSpacing: CGFloat?
func setRestViewHidden(_ hidden: Bool) {
if hidden {
restInfoSpacing = restInfo.isHidden
? restInfoSpacing
: restInfo.spacing
restInfo.spacing = 0
} else {
restInfo.spacing = restInfoSpacing ?? 0
}
restInfo.isHidden = hidden
}
func setRestEndButtonHidden(_ hidden: Bool) {
restDoneBtn.isHidden = hidden
}
private var workoutDoneInfoSpacing: CGFloat?
func setWorkoutDoneViewHidden(_ hidden: Bool) {
if hidden {
workoutDoneInfoSpacing = workoutDoneInfo.isHidden
? workoutDoneInfoSpacing
: workoutDoneInfo.spacing
workoutDoneInfo.spacing = 0
} else {
workoutDoneInfo.spacing = workoutDoneInfoSpacing ?? 0
}
workoutDoneInfo.isHidden = hidden
}
func setWorkoutDoneText(_ text: String) {
workoutDoneLbl.text = text
}
func setWorkoutDoneButtonEnabled(_ enabled: Bool) {
workoutDoneBtn.isEnabled = enabled
}
func disableGlobalActions() {
DispatchQueue.main.async {
self.cancelBtn.isEnabled = false
self.endNowBtn.isEnabled = false
}
}
func setNextUpTextHidden(_ hidden: Bool) {
nextUpInfo.isHidden = hidden
}
func setNextUpText(_ text: NSAttributedString) {
if #available(iOS 13, *) {
// In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string
} else {
nextUpLbl.textColor = UIColor(named: "Text Color")
}
nextUpLbl.attributedText = text
}
var skipAskUpdate = false
func askUpdateSecondaryInfo(with data: UpdateSecondaryInfoData) {
if !skipAskUpdate {
self.performSegue(withIdentifier: "updateWeight", sender: data)
}
skipAskUpdate = false
}
@IBAction func endRest() {
workoutController?.endRest()
}
@IBAction func endSet() {
workoutController?.endSet()
}
@IBAction func endWorkout() {
let alert = UIAlertController(title: GTLocalizedString("WORKOUT_END", comment: "End"), message: GTLocalizedString("WORKOUT_END_TXT", comment: "End?"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: GTLocalizedString("YES", comment: "Yes"), style: .default) { _ in
self.workoutController?.endWorkout()
})
alert.addAction(UIAlertAction(title: GTLocalizedString("NO", comment: "No"), style: .cancel, handler: nil))
self.present(alert, animated: true)
}
@IBAction func cancelWorkout() {
let alert = UIAlertController(title: GTLocalizedString("WORKOUT_CANCEL", comment: "Cancel"), message: GTLocalizedString("WORKOUT_CANCEL_TXT", comment: "Cancel??"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: GTLocalizedString("YES", comment: "Yes"), style: .destructive) { _ in
self.workoutController?.cancelWorkout()
})
alert.addAction(UIAlertAction(title: GTLocalizedString("NO", comment: "No"), style: .cancel, handler: nil))
self.present(alert, animated: true)
}
func workoutHasStarted() {
skipAskUpdate = false
let isWatch = workoutController?.isMirroring ?? false
cancelBtn.isEnabled = true
endNowBtn.isEnabled = true
navigationItem.leftBarButtonItem = isWatch ? nil : cancelBtn
navigationItem.rightBarButtonItem = isWatch ? nil : endNowBtn
manageFromWatchLbl.isHidden = !isWatch
tipView.isHidden = isWatch
noWorkoutLabel.isHidden = true
workoutInfo.isHidden = false
}
@IBAction func workoutDoneButton() {
appDelegate.exitWorkoutTracking()
}
func exitWorkoutTracking() {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
noWorkoutLabel.isHidden = false
workoutInfo.isHidden = true
appDelegate.refreshData()
}
func exitWorkoutTrackingIfAppropriate() {
if workoutController?.isCompleted ?? false {
appDelegate.exitWorkoutTracking()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueID = segue.identifier else {
return
}
let dest = segue.destination
PopoverController.preparePresentation(for: dest)
dest.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
dest.popoverPresentationController?.sourceView = self.view
dest.popoverPresentationController?.canOverlapSourceViewRect = true
switch segueID {
case "updateWeight":
guard let updateSec = dest as? UpdateSecondaryInfoViewController, let data = sender as? UpdateSecondaryInfoData else {
break
}
updateSec.secondaryInfoData = data
updateSec.popoverPresentationController?.backgroundColor = updateSec.backgroundColor
case "askChoices":
guard let ask = (dest as? UINavigationController)?.viewControllers.first as? AskChoiceTableViewController, let choices = sender as? [GTChoice] else {
break
}
ask.choices = choices
ask.n = 0
default:
break
}
}
}
|
cd2e9611da5704ef2d9416c3cae3e739
| 26.075676 | 189 | 0.72759 | false | false | false | false |
ainopara/Stage1st-Reader
|
refs/heads/master
|
Stage1st/Manager/SentryBreadcrumbsLogger.swift
|
bsd-3-clause
|
1
|
//
// SentryBreadcrumbsLogger.swift
// Stage1st
//
// Created by Zheng Li on 2020/2/9.
// Copyright © 2020 Renaissance. All rights reserved.
//
import CocoaLumberjack
import Sentry
private extension DDLoggerName {
static let sentryBreadcrumbs = DDLoggerName("com.ainopara.sentryBreadcrumbsLogger")
}
class SentryBreadcrumbsLogger: DDAbstractLogger {
@objc public static let shared = SentryBreadcrumbsLogger()
override var loggerName: DDLoggerName {
return .sentryBreadcrumbs
}
override func log(message logMessage: DDLogMessage) {
let message: String?
if let formatter = value(forKey: "_logFormatter") as? DDLogFormatter {
message = formatter.format(message: logMessage)
} else {
message = logMessage.message
}
guard let finalMessage = message else {
// Log Formatter decided to drop this message.
return
}
let level: SentryLevel = {
switch logMessage.level {
case .debug: return .debug
case .info: return .info
case .warning: return .warning
case .error: return .error
default: return .debug
}
}()
let rawCategory = (logMessage.tag as? S1LoggerTag)?.category.description ?? "default"
let category: String = "log / \(rawCategory)"
let breadcrumb = Breadcrumb(level: level, category: category)
breadcrumb.message = finalMessage
breadcrumb.timestamp = logMessage.timestamp
breadcrumb.level = level
SentrySDK.addBreadcrumb(crumb: breadcrumb)
}
}
|
124a89e2158565c96088e5e9dd346ea4
| 28.303571 | 93 | 0.636807 | false | false | false | false |
ZeeQL/ZeeQL3
|
refs/heads/develop
|
Tests/ZeeQLTests/AdaptorActiveRecordTestCase.swift
|
apache-2.0
|
1
|
//
// AdaptorActiveRecordTestCase.swift
// ZeeQL3
//
// Created by Helge Hess on 18/05/17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import Foundation
import XCTest
@testable import ZeeQL
class AdapterActiveRecordTests: XCTestCase {
// Is there a better way to share test cases?
var adaptor : Adaptor! {
XCTAssertNotNil(nil, "override in subclass")
return nil
}
let verbose = true
let model = ActiveRecordContactsDBModel.model
func testSnapshotting() throws {
let db = Database(adaptor: adaptor)
let entity : Entity! = model[entity: "Person"]
XCTAssert(entity != nil, "did not find person entity ...")
guard entity != nil else { return } // tests continue to run
let ds = ActiveDataSource<ActiveRecord>(database: db, entity: entity)
let dagobert = try ds.findBy(matchingAll: [ "firstname": "Dagobert" ])
XCTAssert(dagobert != nil)
XCTAssertFalse(dagobert!.isNew, "fetched object marked as new!")
XCTAssertNotNil(dagobert!.snapshot, "missing snapshot")
XCTAssertFalse(dagobert!.hasChanges, "marked as having changes")
}
func testSimpleChange() throws {
let db = Database(adaptor: adaptor)
let entity : Entity! = model[entity: "Person"]
XCTAssert(entity != nil, "did not find person entity ...")
guard entity != nil else { return } // tests continue to run
let ds = ActiveDataSource<ActiveRecordContactsDBModel.Person>(database: db)
let dagobert = try ds.findBy(matchingAll: [ "firstname": "Dagobert" ])
XCTAssert(dagobert != nil)
XCTAssertFalse(dagobert!.isNew, "fetched object marked as new!")
XCTAssertNotNil(dagobert!.snapshot, "missing snapshot")
XCTAssertFalse(dagobert!.hasChanges, "marked as having changes")
dagobert!["firstname"] = "Bobby"
XCTAssertTrue(dagobert!.hasChanges, "marked as not having changes")
let changes = dagobert!.changesFromSnapshot(dagobert!.snapshot!)
XCTAssertEqual(changes.count, 1)
XCTAssert(changes["firstname"] != nil)
XCTAssert((changes["firstname"] as EquatableType).isEqual(to: "Bobby"))
}
func testInsertAndDelete() throws {
let db = Database(adaptor: adaptor)
let ds = db.datasource(ActiveRecordContactsDBModel.Person.self)
// clear
try adaptor.performSQL("DELETE FROM person WHERE firstname = 'Ronald'")
// create object
let person = ds.createObject() // this attaches to the DB/entity
person["firstname"] = "Ronald"
person["lastname"] = "McDonald"
XCTAssertTrue(person.isNew, "new object not marked as new!")
if verbose {print("before save: \(person)") }
do {
try person.save()
}
catch {
XCTFail("save failed: \(error)")
}
if verbose { print("after save: \(person)") }
XCTAssertFalse(person.isNew, "object still marked as new after save!")
XCTAssertNotNil(person.snapshot, "missing snapshot after save")
XCTAssertFalse(person.hasChanges, "marked as having changes after save")
// TODO: check for primary key ...
XCTAssertNotNil(person["id"], "got no primary key!")
// refetch object
let refetch = try ds.findBy(matchingAll: [ "firstname": "Ronald" ])
XCTAssert(refetch != nil, "did not find new Ronald")
if verbose { print("Ronald: \(refetch as Optional)") }
guard refetch != nil else { return } // keep tests running
XCTAssertFalse(refetch!.isNew, "fetched object marked as new!")
XCTAssertNotNil(refetch!.snapshot, "missing snapshot")
XCTAssertFalse(refetch!.hasChanges, "marked as having changes")
XCTAssert(refetch?["firstname"] != nil)
XCTAssert(refetch?["lastname"] != nil)
XCTAssert((refetch!["firstname"] as EquatableType).isEqual(to: "Ronald"))
XCTAssert((refetch!["lastname"] as EquatableType).isEqual(to: "McDonald"))
// delete object
do {
// try person.delete() // only works when the pkey is assigned ..
try refetch?.delete()
}
catch {
XCTFail("delete failed: \(error)")
}
}
static var sharedTests = [
( "testSnapshotting", testSnapshotting ),
( "testSimpleChange", testSimpleChange ),
( "testInsertAndDelete", testInsertAndDelete ),
]
}
|
47639eba05395fe7a7f4cb7268751245
| 32.734375 | 79 | 0.657249 | false | true | false | false |
ShezHsky/Countdown
|
refs/heads/master
|
CountdownTouchTests/Test Cases/EventDetailViewControllerShould.swift
|
mit
|
1
|
//
// EventDetailViewControllerShould.swift
// Countdown
//
// Created by Thomas Sherwood on 27/01/2017.
// Copyright © 2017 ShezHsky. All rights reserved.
//
@testable import CountdownTouch
import XCTest
class CapturingPresentationBinder: PresentationBinder {
// MARK: PresentationBinder
private var scenes = [Any]()
func bind<Scene>(_ scene: Scene) {
scenes.append(scene)
}
// MARK: Convenience Functions
func boundScene<T>(ofType type: T.Type = T.self) -> T? {
return scenes.flatMap({ $0 as? T }).first
}
}
class EventDetailViewControllerShould: XCTestCase {
// MARK: Properties
var detailViewController: EventDetailViewController!
var scene: EventDetailScene!
// MARK: Overrides
override func setUp() {
super.setUp()
detailViewController = UIStoryboard.main.instantiateViewController(EventDetailViewController.self)
_ = detailViewController.view
let binder = CapturingPresentationBinder()
detailViewController.presentationBinder = binder
detailViewController.viewWillAppear(true)
scene = binder.boundScene()
}
// MARK: Tests
func testShowThePlaceholderByDefault() {
XCTAssertFalse(detailViewController.placeholderView.isHidden)
}
func testHideThePlaceholderWhenToldTo() {
detailViewController.placeholderView.isHidden = false
scene.hidePlaceholder()
XCTAssertTrue(detailViewController.placeholderView.isHidden)
}
func testShowThePlaceholderWhenToldTo() {
detailViewController.placeholderView.isHidden = true
scene.showPlaceholder()
XCTAssertFalse(detailViewController.placeholderView.isHidden)
}
}
|
d4a3366777ee3bc32a83c52d2710d0a2
| 24.130435 | 106 | 0.704152 | false | true | false | false |
slimane-swift/Hanger
|
refs/heads/master
|
Sources/Request.swift
|
mit
|
1
|
//
// Request.swift
// Hanger
//
// Created by Yuki Takei on 5/2/16.
//
//
let CRLF = "\r\n"
extension Request {
public mutating func serialize() throws -> Data {
var requestData = "\(method) \(path ?? "/") HTTP/\(version.major).\(version.minor)\(CRLF)"
if headers["Host"].first == nil {
var host = uri.host!
let port = uri.port ?? 80
if port != 80 {
host+=":\(port)"
}
headers["Host"] = Header(host)
}
if headers["Accept"].first == nil {
headers["Accept"] = Header("*/*")
}
if headers["User-Agent"].first == nil {
headers["User-Agent"] = Header("Hanger HTTP Client")
}
requestData += headers.filter({ _, v in v.first != nil }).map({ k, v in "\(k): \(v)" }).joined(separator: CRLF)
let data = try body.becomeBuffer()
requestData += CRLF + CRLF
if !data.isEmpty {
return requestData.data + data
}
return requestData.data
}
}
|
3445e1bc13226f5059536489fe84fb58
| 24.568182 | 119 | 0.464 | false | false | false | false |
wwu-pi/md2-framework
|
refs/heads/master
|
de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2IsNumberValidator.swift
|
apache-2.0
|
1
|
//
// MD2IsNumberValidator.swift
// md2-ios-library
//
// Created by Christoph Rieger on 05.08.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
/**
Validator to check for a numeric value.
*/
class MD2IsNumberValidator: MD2Validator {
/// Unique identification string.
let identifier: MD2String
/// Custom message to display.
var message: (() -> MD2String)?
/// Default message to display.
var defaultMessage: MD2String {
get {
return MD2String("This value must be a valid number!")
}
}
/**
Default initializer.
:param: identifier The unique validator identifier.
:param: message Closure of the custom method to display.
*/
init(identifier: MD2String, message: (() -> MD2String)?) {
self.identifier = identifier
self.message = message
}
/**
Validate a value.
:param: value The value to check.
:return: Validation result
*/
func isValid(value: MD2Type) -> Bool {
if value is MD2NumericType {
return true
}
// Try to parse
if MD2Float(MD2String(value.toString())).toString() == value.toString()
|| MD2Integer(MD2String(value.toString())).toString() == value.toString() {
return true
}
return false
}
/**
Return the message to display on wrong validation.
Use custom method if set or else use default message.
*/
func getMessage() -> MD2String {
if let _ = message {
return message!()
} else {
return defaultMessage
}
}
}
|
25b203998385cae7b7bfea825c5e7e3a
| 23.43662 | 87 | 0.5594 | false | false | false | false |
ifeherva/HSTracker
|
refs/heads/master
|
HSTracker/Importers/Handlers/Hearthstonetopdecks.swift
|
mit
|
1
|
//
// Hearthstonetopdecks.swift
// HSTracker
//
// Created by Istvan Fehervari on 29/08/16.
// Copyright © 2016 Istvan Fehervari. All rights reserved.
//
import Foundation
import Kanna
import RegexUtil
struct HearthstoneTopDecks: HttpImporter {
var siteName: String {
return "Hearthstonetopdecks"
}
var handleUrl: RegexPattern {
return "hearthstonetopdecks\\.com\\/decks"
}
var preferHttps: Bool {
return true
}
func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? {
guard let nameNode = doc.at_xpath("//h1[contains(@class, 'entry-title')]"),
let deckName = nameNode.text else {
logger.error("Deck name not found")
return nil
}
logger.verbose("Got deck name \(deckName)")
let xpath = "//div[contains(@class, 'deck-import-code')]/input[@type='text']"
guard let deckStringNode = doc.at_xpath(xpath),
let deckString = deckStringNode["value"]?.trim(),
let (playerClass, cardList) = DeckSerializer.deserializeDeckString(deckString: deckString) else {
logger.error("Card list not found")
return nil
}
let deck = Deck()
deck.name = deckName
deck.playerClass = playerClass
return (deck, cardList)
}
}
|
0cb72ee72b03ae3c5c922165fcaf95ac
| 26.632653 | 109 | 0.604136 | false | false | false | false |
psoamusic/PourOver
|
refs/heads/master
|
PourOver/POUserDocumentsTableViewController.swift
|
gpl-3.0
|
1
|
//
// PieceTableViewController.swift
// PourOver
//
// Created by labuser on 11/5/14.
// Copyright (c) 2014 labuser. All rights reserved.
//
import UIKit
class POUserDocumentsTableViewController: POPieceTableViewController {
//===================================================================================
//MARK: Private Properties
//===================================================================================
override var reminderTextViewText: String {
get {
return "No user documents present\n\nCopy your files into iTunes > \(UIDevice.currentDevice().name) > Apps > PourOver > File Sharing\n\n Supported file types: .pd, .aif, .wav, .txt"
}
}
//===================================================================================
//MARK: Refresh
//===================================================================================
override func refreshPieces() {
cellDictionaries.removeAll(keepCapacity: false)
if let availablePatches = POPdFileLoader.sharedPdFileLoader.availablePatchesInDocuments() {
cellDictionaries = availablePatches
}
//add spacer cells to the top and bottom for correct scrolling behavior
cellDictionaries.insert(Dictionary(), atIndex: 0)
cellDictionaries.append(Dictionary())
checkForNoDocuments()
}
}
|
5b263029856af69753410d975a06ae54
| 36.236842 | 193 | 0.49894 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios
|
refs/heads/master
|
Source/Phone/Call/CallInfoSequence.swift
|
mit
|
1
|
// Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class CallInfoSequence {
enum OverwriteResult {
// the value passed in is newer than the current CallInfo
case `true`
// the value passed in is older than or equal to the current CallInfo
case `false`
// there are inconsistencies between the two versions - they both contain overlapping unique values
case deSync
}
enum CompareResult {
case greaterThan
case lessThan
case equal
case deSync
}
// calculate "only in a's" list and "only in b's" list
static func populateSets(_ a: Sequence, _ b: Sequence) -> ([UInt64], [UInt64]) {
var aOnly = [UInt64]()
var bOnly = [UInt64]()
var aArray = a.getEntries()
var bArray = b.getEntries()
var atEndOfA = false
var atEndOfB = false
var indexOfA = 0
var indexOfB = 0
while (indexOfA < aArray.count && indexOfB < bArray.count) {
var aVal = aArray[indexOfA]
var bVal = bArray[indexOfB]
indexOfA += 1
indexOfB += 1
while (aVal != bVal && !atEndOfA && !atEndOfB) {
while (aVal > bVal) {
if !a.inRange(bVal) {
bOnly.append(bVal)
}
if indexOfB < bArray.count {
bVal = bArray[indexOfB]
indexOfB += 1
} else {
atEndOfB = true
break
}
}
while (bVal > aVal) {
if !b.inRange(aVal) {
aOnly.append(aVal)
}
if indexOfA < aArray.count {
aVal = aArray[indexOfA]
indexOfA += 1
} else {
atEndOfA = true
break
}
}
}
if (atEndOfA && !atEndOfB) {
if (!a.inRange(bVal)) {
bOnly.append(bVal)
}
}
if ( !atEndOfA && atEndOfB) {
if (!b.inRange(aVal)) {
aOnly.append(aVal)
}
}
}
while (indexOfA < aArray.count) {
let aVal = aArray[indexOfA]
indexOfA += 1
if (!b.inRange(aVal)) {
aOnly.append(aVal)
}
}
while (indexOfB < bArray.count) {
let bVal = bArray[indexOfB]
indexOfB += 1
if (!a.inRange(bVal)) {
bOnly.append(bVal)
}
}
return (aOnly, bOnly)
}
static func compare(_ a: Sequence, _ b: Sequence) -> CompareResult {
var aOnly = [UInt64]()
var bOnly = [UInt64]()
// if all of a's values are less than b's, b is newer
if a.getCompareLastValue() < b.getCompareFirstValue() {
return CompareResult.lessThan
}
// if all of a's values are greater than b's, a is newer
if a.getCompareFirstValue() > b.getCompareLastValue() {
return CompareResult.greaterThan
}
// calculate "only in a's" list and "only in b's" list
(aOnly, bOnly) = populateSets(a, b)
if aOnly.isEmpty && bOnly.isEmpty {
// both sets are completely empty, use range to figure out order
if a.getRangeEnd() > b.getRangeEnd() {
return CompareResult.greaterThan
} else if a.getRangeEnd() < b.getRangeEnd() {
return CompareResult.lessThan
} else if a.getRangeStart() < b.getRangeStart() {
return CompareResult.greaterThan
} else if a.getRangeStart() > b.getRangeStart() {
return CompareResult.lessThan
} else {
return CompareResult.equal
}
}
// If b has nothing unique and a does, then a is newer
if !aOnly.isEmpty && bOnly.isEmpty {
return CompareResult.greaterThan
}
// if I have nothing unique but b does, then b is newer
if !bOnly.isEmpty && aOnly.isEmpty {
return CompareResult.lessThan
}
// both have unique entries...
// if a unique value in one list is within the min and max value in the others list then we are desync'd
for i in aOnly {
if i > b.getCompareFirstValue() && i < b.getCompareLastValue() {
return CompareResult.deSync
}
}
for i in bOnly {
if i > a.getCompareFirstValue() && i < a.getCompareLastValue() {
return CompareResult.deSync
}
}
// aOnly and bOnly are 2 non-overlapping sets. compare first item in both
if aOnly[0] > bOnly[0] {
return CompareResult.greaterThan
} else {
return CompareResult.lessThan
}
}
static func overwrite(oldValue: Sequence, newValue: Sequence) -> OverwriteResult {
// special case the empty sequence. If you are currently empty then say update no matter what
if oldValue.isEmpty() || newValue.isEmpty() {
return OverwriteResult.true
} else {
let compareResult = compare(oldValue, newValue)
switch (compareResult) {
case CompareResult.greaterThan:
return OverwriteResult.false
case CompareResult.lessThan:
return OverwriteResult.true
case CompareResult.equal:
return OverwriteResult.false
case CompareResult.deSync:
return OverwriteResult.deSync
}
}
}
}
|
2f7b685d4187daac64f5c7e275df398d
| 34.147059 | 112 | 0.524686 | false | false | false | false |
AbidHussainCom/HackingWithSwift
|
refs/heads/master
|
project13/Project13/ViewController.swift
|
unlicense
|
20
|
//
// ViewController.swift
// Project13
//
// Created by Hudzilla on 22/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var intensity: UISlider!
var currentImage: UIImage!
var context: CIContext!
var currentFilter: CIFilter!
override func viewDidLoad() {
super.viewDidLoad()
// Yet Another Core Image Filters Program
title = "YACIFP"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "importPicture")
context = CIContext(options: nil)
currentFilter = CIFilter(name: "CISepiaTone")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func importPicture() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject: AnyObject]) {
var newImage: UIImage
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
} else {
return
}
dismissViewControllerAnimated(true, completion: nil)
currentImage = newImage
let beginImage = CIImage(image: currentImage)
currentFilter.setValue(beginImage, forKey: kCIInputImageKey)
applyProcessing()
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func applyProcessing() {
let inputKeys = currentFilter.inputKeys() as! [NSString]
if contains(inputKeys, kCIInputIntensityKey) { currentFilter.setValue(intensity.value, forKey: kCIInputIntensityKey) }
if contains(inputKeys, kCIInputRadiusKey) { currentFilter.setValue(intensity.value * 200, forKey: kCIInputRadiusKey) }
if contains(inputKeys, kCIInputScaleKey) { currentFilter.setValue(intensity.value * 10, forKey: kCIInputScaleKey) }
if contains(inputKeys, kCIInputCenterKey) { currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey) }
let cgimg = context.createCGImage(currentFilter.outputImage, fromRect: currentFilter.outputImage.extent())
let processedImage = UIImage(CGImage: cgimg)
imageView.image = processedImage
}
@IBAction func intensityChanged(sender: AnyObject) {
applyProcessing()
}
@IBAction func changeFilter(sender: AnyObject) {
let ac = UIAlertController(title: "Choose filter", message: nil, preferredStyle: .ActionSheet)
ac.addAction(UIAlertAction(title: "CIBumpDistortion", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIGaussianBlur", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIPixellate", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CISepiaTone", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CITwirlDistortion", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIUnsharpMask", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIVignette", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
@IBAction func save(sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imageView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func setFilter(action: UIAlertAction!) {
currentFilter = CIFilter(name: action.title)
let beginImage = CIImage(image: currentImage)
currentFilter.setValue(beginImage, forKey: kCIInputImageKey)
applyProcessing()
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
}
|
6f521797998c45342211d4d2cd5fbdc1
| 37.211382 | 172 | 0.765957 | false | false | false | false |
wilfreddekok/Antidote
|
refs/heads/master
|
Antidote/OCTSubmanagerObjectsExtension.swift
|
mpl-2.0
|
1
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
extension OCTSubmanagerObjects {
func friends(predicate predicate: NSPredicate? = nil) -> Results<OCTFriend> {
let rlmResults = objectsForType(.Friend, predicate: predicate)
return Results(results: rlmResults)
}
func friendRequests(predicate predicate: NSPredicate? = nil) -> Results<OCTFriendRequest> {
let rlmResults = objectsForType(.FriendRequest, predicate: predicate)
return Results(results: rlmResults)
}
func chats(predicate predicate: NSPredicate? = nil) -> Results<OCTChat> {
let rlmResults = objectsForType(.Chat, predicate: predicate)
return Results(results: rlmResults)
}
func calls(predicate predicate: NSPredicate? = nil) -> Results<OCTCall> {
let rlmResults = objectsForType(.Call, predicate: predicate)
return Results(results: rlmResults)
}
func messages(predicate predicate: NSPredicate? = nil) -> Results<OCTMessageAbstract> {
let rlmResults = objectsForType(.MessageAbstract, predicate: predicate)
return Results(results: rlmResults)
}
func getProfileSettings() -> ProfileSettings {
guard let data = self.genericSettingsData else {
return ProfileSettings()
}
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
let settings = ProfileSettings(coder: unarchiver)
unarchiver.finishDecoding()
return settings
}
func saveProfileSettings(settings: ProfileSettings) {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
settings.encodeWithCoder(archiver)
archiver.finishEncoding()
self.genericSettingsData = data.copy() as! NSData
}
}
|
f131252cd082a29622ef3b5070e534c2
| 35.388889 | 95 | 0.691603 | false | false | false | false |
ByteriX/BxInputController
|
refs/heads/master
|
BxInputController/Sources/Common/View/Selector/BxInputSelectorRowBinder.swift
|
mit
|
1
|
/**
* @file BxInputSelectorRowBinder.swift
* @namespace BxInputController
*
* @details Binder for a selector row
* @date 06.03.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
#warning("change BxInputBaseFieldRowBinder to BxInputBaseRowBinder")
/// Binder for a selector row
open class BxInputSelectorRowBinder<Row: BxInputSelectorRow, Cell: BxInputSelectorCell>: BxInputBaseFieldRowBinder<Row, Cell>
{
/// call when user selected this cell
override open func didSelected()
{
super.didSelected()
row.isOpened = !row.isOpened
refreshOpened(animated: true)
if row.isOpened {
//owner?.beginUpdates() init crash
owner?.addRows(row.children, after: row)
if let owner = owner, owner.settings.isAutodissmissSelector {
owner.dissmissAllRows(exclude: row)
}
//owner?.endUpdates()
if row.children.count > 1 {
owner?.scrollRow(row, at: .top, animated: true)
} else if let firstItem = row.children.first {
owner?.selectRow(firstItem, at: .middle, animated: true)
} else {
owner?.scrollRow(row, at: .middle, animated: true)
}
owner?.activeRow = row
} else {
owner?.deleteRows(row.children)
}
}
/// update cell from model data
override open func update()
{
super.update()
//
cell?.arrowImage.image = BxInputUtils.getImage(resourceId: "bx_arrow_to_bottom")
//
refreshOpened(animated: false)
}
/// event of change isEnabled
override open func didSetEnabled(_ value: Bool)
{
super.didSetEnabled(value)
guard let cell = cell else {
return
}
// UI part
if needChangeDisabledCell {
if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler {
changeViewEnableHandler(cell.arrowImage, isEnabled)
} else {
cell.arrowImage.alpha = value ? 1 : alphaForDisabledView
}
} else {
cell.arrowImage.isHidden = !value
}
}
/// visual updating of state from opened/closed
open func refreshOpened(animated: Bool) {
if animated {
UIView.beginAnimations(nil, context: nil)
}
if row.isOpened {
cell?.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
} else {
cell?.arrowImage.transform = CGAffineTransform.identity
}
checkValue()
if animated {
UIView.commitAnimations()
}
}
/// visual updating of value && separator that depends on type of the row
open func checkValue() {
// all string changing of value
if let row = row as? BxInputString{
cell?.valueTextField.text = row.stringValue
} else {
cell?.valueTextField.text = ""
}
}
/// If selector is closed just will open
public func toOpen() {
if row.isOpened == false {
didSelected()
}
}
/// If selector is opened just will close
public func toClose() {
if row.isOpened == true {
didSelected()
}
}
}
|
c8f57b422b7233bf390c0f1bc4c7dd08
| 28.710744 | 125 | 0.574965 | false | false | false | false |
marcusellison/Yelply
|
refs/heads/master
|
Yelp/Filters.swift
|
mit
|
1
|
//
// Filters.swift
// Yelp
//
// Created by Marcus J. Ellison on 5/16/15.
// Copyright (c) 2015 Marcus J. Ellison. All rights reserved.
//
import UIKit
class Category: NSObject {
let title = "Category"
let categories = {
return [
["name" : "African", "code": "african"],
["name" : "Brazilian", "code": "brazilian"],
["name" : "Burgers", "code": "burgers"],
["name" : "American, New", "code": "newamerican"]
]
}
}
class Sort: NSObject {
let title = "Sort"
let categories = ["match", "distance", "rating"]
}
class Radius: NSObject {
let title = "Radius"
var radius = 0
}
class Deals: NSObject {
let title = "Deals"
var on = false
}
|
6172c7958eb2f3f5f971ef23579664b2
| 18.1 | 62 | 0.527487 | false | false | false | false |
rain2540/RGNetwork
|
refs/heads/master
|
RGNetwork/RGNetwork/RGDataRequest.swift
|
mpl-2.0
|
1
|
//
// RGDataRequest.swift
// RGNetwork
//
// Created by Rain on 2020/3/6.
// Copyright © 2020 Smartech. All rights reserved.
//
import Foundation
import Alamofire
class RGDataRequest {
public var tag: Int = 0
public private(set) var config: RGDataRequestConfig
// MARK: - Lifecycle
/// create network request
/// - Parameters:
/// - urlString: string of URL path
/// - method: HTTP method
/// - parameters: request parameters
/// - encoding: parameter encoding
/// - headers: HTTP headers
/// - timeoutInterval: 超时时长
init(
urlString: String,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
timeoutInterval: TimeInterval = 30.0,
isShowLog: Bool = true
) {
self.config = RGDataRequestConfig(
urlString: urlString,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
timeoutInterval: timeoutInterval,
isShowLog: isShowLog
)
}
}
// MARK: - Public
extension RGDataRequest {
/// 执行请求
/// - Parameters:
/// - queue: 执行请求的队列
/// - showIndicator: 是否显示 Indicator
/// - responseType: 返回数据格式类型
/// - success: 请求成功的 Task
/// - failure: 请求失败的 Task
public func task(
queue: DispatchQueue = DispatchQueue.global(),
showIndicator: Bool = false,
responseType: ResponseType = .json,
success: @escaping SuccessTask,
failure: @escaping FailureTask
) {
RGNetwork.request(
config: config,
queue: queue,
showIndicator: showIndicator,
responseType: responseType,
success: success,
failure: failure
)
}
}
|
7189660b4c305f5a91d257b01d77dd7c
| 22.925 | 58 | 0.575235 | false | true | false | false |
luizlopezm/ios-Luis-Trucking
|
refs/heads/master
|
Pods/Charts/Charts/Classes/Data/Implementations/Standard/PieChartDataSet.swift
|
mit
|
1
|
//
// PieChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class PieChartDataSet: ChartDataSet, IPieChartDataSet
{
private func initialize()
{
self.valueTextColor = NSUIColor.whiteColor()
self.valueFont = NSUIFont.systemFontOfSize(17.0)
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Styling functions and accessors
private var _sliceSpace = CGFloat(0.0)
/// the space in pixels between the pie-slices
/// **default**: 0
/// **maximum**: 20
public var sliceSpace: CGFloat
{
get
{
return _sliceSpace
}
set
{
var space = newValue
if (space > 20.0)
{
space = 20.0
}
if (space < 0.0)
{
space = 0.0
}
_sliceSpace = space
}
}
/// indicates the selection distance of a pie slice
public var selectionShift = CGFloat(18.0)
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! PieChartDataSet
copy._sliceSpace = _sliceSpace
copy.selectionShift = selectionShift
return copy
}
}
|
3557721acf035d5ed8285fa4cf454153
| 21.294872 | 66 | 0.558688 | false | false | false | false |
grimbolt/BaseSwiftProject
|
refs/heads/master
|
BaseSwiftProject/Sources/Types/ConnectionManager.swift
|
mit
|
1
|
//
// ConnectionManager.swift
// BaseSwiftProject
//
// Created by Grimbolt on 07.01.2017.
//
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
public class ConnectionManager {
enum PareseError: Error {
case invalid
}
static let lock = NSLock()
static var _sessionManager: SessionManager?
public static var sessionManager: SessionManager {
get {
if let sessionManager = ConnectionManager._sessionManager {
return sessionManager;
} else {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 20
configuration.timeoutIntervalForResource = 20
configuration.urlCache = nil
ConnectionManager._sessionManager = SessionManager(configuration: configuration)
return ConnectionManager._sessionManager!
}
}
set {
ConnectionManager._sessionManager = newValue
}
}
public static func request<T: BaseMappable> (
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
preloaderType: PreloaderType = .small,
withSaveContext: Bool = true,
beforeMapping: ((DefaultDataResponse) -> Void)? = nil,
completionHandler: ((DataResponse<T>) -> Void)? = nil
) {
let request = sessionManager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
let uuid = UUID().uuidString
showPreloader(uuid, type: preloaderType)
request
.response { response in
beforeMapping?(response)
}
.responseObject { (response: DataResponse<T>) in
commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext)
}
.validate { request, response, data in
return validate(request: request, response: response, data: data)
}
}
public static func requestArray<T: BaseMappable> (
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
preloaderType: PreloaderType = .small,
withSaveContext: Bool = true,
beforeMapping: ((DefaultDataResponse) -> Void)? = nil,
completionHandler: ((DataResponse<[T]>) -> Void)? = nil
) {
let request = sessionManager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
let uuid = UUID().uuidString
showPreloader(uuid, type: preloaderType)
request
.response { response in
beforeMapping?(response)
}
.responseArray { (response: DataResponse<[T]>) in
commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext)
}
.validate { request, response, data in
return validate(request: request, response: response, data: data)
}
}
public static func simpleRequestWithHttpBody<T: BaseMappable> (
url:URL,
httpBody:Data?,
method: HTTPMethod = .get,
headers: HTTPHeaders? = nil,
preloaderType: PreloaderType = .small,
withSaveContext: Bool = true,
beforeMapping: ((DefaultDataResponse) -> Void)? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void
) {
var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
urlRequest.httpBody = httpBody
urlRequest.httpMethod = method.rawValue
if let _ = headers {
for header in headers! {
urlRequest.setValue(header.value, forHTTPHeaderField: header.key)
}
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let request = sessionManager.request(urlRequest)
let uuid = UUID().uuidString
showPreloader(uuid, type: preloaderType)
request
.response { response in
beforeMapping?(response)
}
.responseArray { (response: DataResponse<[T]>) in
commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext)
}
.validate { (requst, response, data) -> Request.ValidationResult in
return validate(request: requst, response: response, data: data)
}
}
public static func simpleRequestWithHttpBody<T: BaseMappable> (
url:URL,
httpBody:Data?,
method: HTTPMethod = .get,
headers: HTTPHeaders? = nil,
preloaderType: PreloaderType = .small,
withSaveContext: Bool = true,
beforeMapping: ((DefaultDataResponse) -> Void)? = nil,
completionHandler: @escaping (DataResponse<T>) -> Void
) {
var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
urlRequest.httpBody = httpBody
urlRequest.httpMethod = method.rawValue
if let _ = headers {
for header in headers! {
urlRequest.setValue(header.value, forHTTPHeaderField: header.key)
}
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let request = sessionManager.request(urlRequest)
let uuid = UUID().uuidString
showPreloader(uuid, type: preloaderType)
request
.response { response in
beforeMapping?(response)
}
.responseObject { (response: DataResponse<T>) in
commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext)
}
.validate { (requst, response, data) -> Request.ValidationResult in
return validate(request: requst, response: response, data: data)
}
}
public static func cancelAllTasks(whiteList: [String] = []) {
sessionManager.session.getTasksWithCompletionHandler { (sessionDataTask, sessionUploadTask, sessionDownloadTask) in
func forEach(_ task: URLSessionTask) {
if let url = task.currentRequest?.url?.absoluteString {
var onWhiteList = false;
whiteList.forEach({
if url.hasPrefix($0) {
onWhiteList = true
}
})
if !onWhiteList {
task.cancel()
}
} else {
task.cancel()
}
}
sessionDataTask.forEach({ forEach($0) })
sessionUploadTask.forEach({ forEach($0) })
sessionDownloadTask.forEach({ forEach($0) })
}
}
private static func commonResponse<T>(
preloader uuid: String,
preloaderType: PreloaderType,
response: DataResponse<T>,
completionHandler: ((DataResponse<T>) -> Void)?, withSaveContext: Bool
) {
hidePreloader(uuid, type: preloaderType)
switch response.result {
case .failure(let error):
print("error \(error)")
if (error as NSError).code == NSURLErrorCancelled {
// nothing
} else {
completionHandler?(response)
}
break
default:
completionHandler?(response)
}
if withSaveContext {
switch response.result {
case .success:
DatabaseHelper.sharedInstance.saveContext()
case .failure: break
}
}
}
private static func validate(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> DataRequest.ValidationResult {
if
let data = data,
response.statusCode >= 200,
response.statusCode < 300
{
do {
try JSONSerialization.jsonObject(with: data, options: [])
return DataRequest.ValidationResult.success
} catch {
}
}
return DataRequest.ValidationResult.failure(PareseError.invalid)
}
}
|
34a2e80ded0bc6b5d071dcbf62759752
| 35.86 | 169 | 0.580901 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/Countdown/View/ConventionCountdownTableViewDataSource.swift
|
mit
|
1
|
import Combine
import ComponentBase
import UIKit
public class ConventionCountdownTableViewDataSource<
ViewModel: ConventionCountdownViewModel
>: NSObject, TableViewMediator {
private let viewModel: ViewModel
private var subscriptions = Set<AnyCancellable>()
init(viewModel: ViewModel) {
self.viewModel = viewModel
super.init()
viewModel
.publisher(for: \.showCountdown)
.sink { [weak self] (_) in
if let self = self {
self.delegate?.dataSourceContentsDidChange(self)
}
}
.store(in: &subscriptions)
}
public var delegate: TableViewMediatorDelegate?
public func registerReusableViews(into tableView: UITableView) {
tableView.registerConventionBrandedHeader()
tableView.register(NewsConventionCountdownTableViewCell.self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewModel.showCountdown ? 1 : 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(NewsConventionCountdownTableViewCell.self)
viewModel
.publisher(for: \.countdownDescription)
.map({ $0 ?? "" })
.sink { [weak cell] (countdownDescription) in
cell?.setTimeUntilConvention(countdownDescription)
}
.store(in: &subscriptions)
return cell
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueConventionBrandedHeader()
headerView.textLabel?.text = .daysUntilConvention
return headerView
}
}
|
ab45482a333ab2efade5c804f1db72c8
| 31.206897 | 107 | 0.631156 | false | false | false | false |
Appstax/appstax-ios
|
refs/heads/master
|
Appstax/AppstaxTests/RealtimeTests.swift
|
mit
|
1
|
import Foundation
import XCTest
@testable import Appstax
@objc class RealtimeTests: XCTestCase {
private var realtimeService: AXRealtimeService!
private var appKeyHeader: String?
private var websocketUrl: NSURL?
private var serverReceived: [[String:AnyObject]] = []
private var sessionRequestShouldFail = false
private var websocketRequestShouldFail = false
override func setUp() {
super.setUp()
OHHTTPStubs.setEnabled(true)
OHHTTPStubs.removeAllStubs()
Appstax.setAppKey("testappkey", baseUrl:"http://localhost:3000/");
Appstax.setLogLevel("debug");
realtimeService = Appstax.defaultContext.realtimeService
appKeyHeader = nil
websocketUrl = nil
serverReceived = []
sessionRequestShouldFail = false
websocketRequestShouldFail = false
AXStubs.method("POST", urlPath: "/messaging/realtime/sessions") { request in
self.appKeyHeader = request.allHTTPHeaderFields?["x-appstax-appkey"]
if self.sessionRequestShouldFail {
return OHHTTPStubsResponse(JSONObject: ["":""], statusCode: 422, headers: [:])
} else {
return OHHTTPStubsResponse(JSONObject: ["realtimeSessionId":"testrsession"], statusCode: 200, headers: [:])
}
}
realtimeService.webSocketFactory = {
self.websocketUrl = $0
let webSocket = MockWebSocket(self.realtimeService, fail: self.websocketRequestShouldFail) {
self.serverReceived.append($0)
}
return webSocket
}
}
override func tearDown() {
super.tearDown()
OHHTTPStubs.setEnabled(false)
}
func serverSend(dict: [String:AnyObject]) {
realtimeService.webSocketDidReceiveMessage(dict)
}
func testShouldGetRealtimeSessionAndConnectToWebsocket() {
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
channel.on("open") { _ in
async.fulfill()
}
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(self.appKeyHeader, "testappkey")
AXAssertNotNil(self.websocketUrl)
AXAssertEqual(self.websocketUrl?.absoluteString, "ws://localhost:3000/messaging/realtime?rsession=testrsession")
}
}
func testShouldReconnectIfDisconnected() {
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
var channelOpen = 0
channel.on("open") { _ in
channelOpen += 1
}
delay(2) {
self.realtimeService.webSocketDidDisconnect(nil)
delay(2) {
channel.send("Message!")
delay(2, async.fulfill)
}
}
waitForExpectationsWithTimeout(10) { error in
AXAssertEqual(channelOpen, 2)
AXAssertEqual(self.serverReceived.count, 2)
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
AXAssertEqual(self.serverReceived[1]["command"], "publish")
AXAssertEqual(self.serverReceived[1]["message"], "Message!")
}
}
func testShouldSendSubscribeCommandToServerAndOpenEventToClient() {
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
var channelOpen = false
channel.on("open") { _ in
channelOpen = true
}
delay(1, async.fulfill)
waitForExpectationsWithTimeout(3) { error in
XCTAssertTrue(channelOpen)
AXAssertEqual(self.serverReceived.count, 1)
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
AXAssertEqual(self.serverReceived[0]["channel"], "public/chat")
}
}
func testShouldGetErrorEventWhenSessionRequestFails() {
sessionRequestShouldFail = true
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
var channelOpen = false
var channelError = false
channel.on("open") { _ in
channelOpen = true
}
channel.on("error") { _ in
channelError = true
}
delay(1, async.fulfill)
waitForExpectationsWithTimeout(3) { error in
XCTAssertFalse(channelOpen)
XCTAssertTrue(channelError)
}
}
func testShouldGetErrorEventWhenWebSocketRequestFails() {
websocketRequestShouldFail = true
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
var channelOpen = false
var channelError = false
channel.on("open") { _ in
channelOpen = true
}
channel.on("error") { _ in
channelError = true
}
delay(1, async.fulfill)
waitForExpectationsWithTimeout(3) { error in
XCTAssertFalse(channelOpen)
XCTAssertTrue(channelError)
}
}
func testShouldSendMessagesWithIdToServer() {
let async = expectationWithDescription("async")
let channel = AXChannel("public/chat")
channel.send("This is my first message!")
channel.send("This is my second message!")
delay(1, async.fulfill)
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(self.serverReceived.count, 3)
AXAssertEqual(self.serverReceived[1]["command"], "publish")
AXAssertEqual(self.serverReceived[1]["channel"], "public/chat")
AXAssertEqual(self.serverReceived[1]["message"], "This is my first message!")
AXAssertEqual(self.serverReceived[2]["command"], "publish")
AXAssertEqual(self.serverReceived[2]["channel"], "public/chat")
AXAssertEqual(self.serverReceived[2]["message"], "This is my second message!")
AXAssertNotNil(self.serverReceived[0]["id"])
AXAssertNotNil(self.serverReceived[1]["id"])
AXAssertNotNil(self.serverReceived[2]["id"])
let id1 = self.serverReceived[0]["id"] as! NSString
let id2 = self.serverReceived[1]["id"] as! String
XCTAssertFalse(id1.isEqualToString(id2))
}
}
func testShouldMapServerEventsToChannels() {
let async = expectationWithDescription("async")
let chat = AXChannel("public/chat")
var chatReceived: [AXChannelEvent] = []
chat.on("message") { chatReceived.append($0) }
chat.on("error") { chatReceived.append($0) }
let stocks = AXChannel("public/stocks")
var stocksReceived: [AXChannelEvent] = []
stocks.on("message") { stocksReceived.append($0) }
stocks.on("error") { stocksReceived.append($0) }
delay(0.2) {
self.serverSend(["channel":"public/chat", "event":"message", "message":"Hello World!"])
self.serverSend(["channel":"public/chat", "event":"error", "error":"Bad dog!"])
self.serverSend(["channel":"public/stocks", "event":"message", "message":["AAPL": 127.61]])
self.serverSend(["channel":"public/stocks", "event":"error", "error":"Bad stock!"])
delay(0.1, async.fulfill)
}
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(chatReceived.count, 2)
AXAssertEqual(stocksReceived.count, 2)
AXAssertEqual(chatReceived[0].channel, "public/chat")
AXAssertEqual(chatReceived[0].message, "Hello World!")
AXAssertNil(chatReceived[0].error)
AXAssertEqual(chatReceived[1].channel, "public/chat")
AXAssertEqual(chatReceived[1].error, "Bad dog!")
AXAssertNil(chatReceived[1].message)
AXAssertEqual(stocksReceived[0].channel, "public/stocks")
AXAssertEqual(stocksReceived[0].message?["AAPL"], 127.61)
AXAssertNil(stocksReceived[0].error)
AXAssertEqual(stocksReceived[1].channel, "public/stocks")
AXAssertEqual(stocksReceived[1].error, "Bad stock!")
AXAssertNil(stocksReceived[1].message)
}
}
func testShouldMapServerEventsToWildcardChannels() {
let async = expectationWithDescription("async")
let a1 = AXChannel("public/a/1")
let a2 = AXChannel("public/a/2")
let aw = AXChannel("public/a/*")
let b1 = AXChannel("public/b/1")
let b2 = AXChannel("public/b/2")
let bw = AXChannel("public/b/*")
var received: [String:[AXChannelEvent]] = ["a1":[],"a2":[],"aw":[],"b1":[],"b2":[],"bw":[]]
a1.on("message") { received["a1"]?.append($0) }
a2.on("message") { received["a2"]?.append($0) }
aw.on("message") { received["aw"]?.append($0) }
b1.on("message") { received["b1"]?.append($0) }
b2.on("message") { received["b2"]?.append($0) }
bw.on("message") { received["bw"]?.append($0) }
delay(0.2) {
self.serverSend(["channel":"public/a/1", "event":"message", "message":"A1"])
self.serverSend(["channel":"public/a/2", "event":"message", "message":"A2"])
self.serverSend(["channel":"public/b/1", "event":"message", "message":"B1"])
self.serverSend(["channel":"public/b/2", "event":"message", "message":"B2"])
delay(0.1, async.fulfill)
}
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(received["a1"]?.count, 1)
AXAssertEqual(received["a2"]?.count, 1)
AXAssertEqual(received["aw"]?.count, 2)
AXAssertEqual(received["b1"]?.count, 1)
AXAssertEqual(received["b2"]?.count, 1)
AXAssertEqual(received["bw"]?.count, 2)
}
}
func testShouldMapServerEventsToWildcardEventHandlers() {
let async = expectationWithDescription("async")
let a1 = AXChannel("public/a/1")
let a2 = AXChannel("public/a/2")
let aw = AXChannel("public/a/*")
let b1 = AXChannel("public/b/1")
let b2 = AXChannel("public/b/2")
let bw = AXChannel("public/b/*")
var received: [String:[AXChannelEvent]] = ["a1":[],"a2":[],"aw":[],"b1":[],"b2":[],"bw":[]]
a1.on("*") { received["a1"]?.append($0) }
a2.on("*") { received["a2"]?.append($0) }
aw.on("*") { received["aw"]?.append($0) }
b1.on("*") { received["b1"]?.append($0) }
b2.on("*") { received["b2"]?.append($0) }
bw.on("*") { received["bw"]?.append($0) }
delay(1.0) {
self.serverSend(["channel":"public/a/1", "event":"message", "message":"A1"])
self.serverSend(["channel":"public/a/2", "event":"message", "message":"A2"])
self.serverSend(["channel":"public/b/1", "event":"message", "message":"B1"])
self.serverSend(["channel":"public/b/2", "event":"message", "message":"B2"])
delay(0.1, async.fulfill)
}
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(received["a1"]?[0].type, "status")
AXAssertEqual(received["a2"]?[0].type, "status")
AXAssertEqual(received["aw"]?[0].type, "status")
AXAssertEqual(received["b1"]?[0].type, "status")
AXAssertEqual(received["b2"]?[0].type, "status")
AXAssertEqual(received["bw"]?[0].type, "status")
AXAssertEqual(received["a1"]?[1].type, "open")
AXAssertEqual(received["a2"]?[1].type, "open")
AXAssertEqual(received["aw"]?[1].type, "open")
AXAssertEqual(received["b1"]?[1].type, "open")
AXAssertEqual(received["b2"]?[1].type, "open")
AXAssertEqual(received["bw"]?[1].type, "open")
AXAssertEqual(received["a1"]?[2].type, "message")
AXAssertEqual(received["a2"]?[2].type, "message")
AXAssertEqual(received["aw"]?[2].type, "message")
AXAssertEqual(received["b1"]?[2].type, "message")
AXAssertEqual(received["b2"]?[2].type, "message")
AXAssertEqual(received["bw"]?[2].type, "message")
AXAssertEqual(received["a1"]?[2].channel, "public/a/1")
AXAssertEqual(received["a2"]?[2].channel, "public/a/2")
AXAssertEqual(received["aw"]?[2].channel, "public/a/1")
AXAssertEqual(received["aw"]?[3].channel, "public/a/2")
AXAssertEqual(received["b1"]?[2].channel, "public/b/1")
AXAssertEqual(received["b2"]?[2].channel, "public/b/2")
AXAssertEqual(received["bw"]?[2].channel, "public/b/1")
AXAssertEqual(received["bw"]?[3].channel, "public/b/2")
}
}
func testShouldSubscribeToAPrivateChannel() {
let async = expectationWithDescription("async")
let _ = AXChannel("private/mychannel")
delay(1, async.fulfill)
waitForExpectationsWithTimeout(3) { error in
AXAssertEqual(self.serverReceived.count, 1)
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
AXAssertEqual(self.serverReceived[0]["channel"], "private/mychannel")
}
}
func testShouldGrantPermissionsOnPrivateChannels() {
let async = expectationWithDescription("async")
let channel = AXChannel("private/mychannel")
channel.grant("buddy", permissions:["read"])
channel.grant("friend", permissions:["read", "write"])
channel.revoke("buddy", permissions:["read", "write"])
channel.revoke("friend", permissions:["write"])
delay(1, async.fulfill)
waitForExpectationsWithTimeout(8) { error in
AXAssertEqual(self.serverReceived.count, 8)
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
AXAssertEqual(self.serverReceived[0]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[1]["command"], "channel.create")
AXAssertEqual(self.serverReceived[1]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[2]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[2]["command"], "grant.read")
AXAssertEqual((self.serverReceived[2]["data"] as! [String])[0], "buddy")
AXAssertEqual(self.serverReceived[3]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[3]["command"], "grant.read")
AXAssertEqual((self.serverReceived[3]["data"] as! [String])[0], "friend")
AXAssertEqual(self.serverReceived[4]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[4]["command"], "grant.write")
AXAssertEqual((self.serverReceived[4]["data"] as! [String])[0], "friend")
AXAssertEqual(self.serverReceived[5]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[5]["command"], "revoke.read")
AXAssertEqual((self.serverReceived[5]["data"] as! [String])[0], "buddy")
AXAssertEqual(self.serverReceived[6]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[6]["command"], "revoke.write")
AXAssertEqual((self.serverReceived[6]["data"] as! [String])[0], "buddy")
AXAssertEqual(self.serverReceived[7]["channel"], "private/mychannel")
AXAssertEqual(self.serverReceived[7]["command"], "revoke.write")
AXAssertEqual((self.serverReceived[7]["data"] as! [String])[0], "friend")
}
}
func testShouldSubscribeToObjectChannel() {
let async = expectationWithDescription("async")
let _ = AXChannel("objects/mycollection")
delay(1, async.fulfill)
waitForExpectationsWithTimeout(8) { error in
AXAssertEqual(self.serverReceived.count, 1)
AXAssertEqual(self.serverReceived[0]["channel"], "objects/mycollection")
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
}
}
func testShouldSubscribeToObjectChannelWithFilter() {
let async = expectationWithDescription("async")
let _ = AXChannel("objects/mycollection", filter: "text like Hello%")
delay(1, async.fulfill)
waitForExpectationsWithTimeout(8) { error in
AXAssertEqual(self.serverReceived.count, 1)
AXAssertEqual(self.serverReceived[0]["channel"], "objects/mycollection")
AXAssertEqual(self.serverReceived[0]["command"], "subscribe")
AXAssertEqual(self.serverReceived[0]["filter"], "text like Hello%")
}
}
func testShouldConvertReceivedDataToAppstaxObjects() {
let async = expectationWithDescription("async")
let channel = AXChannel("objects/mycollection3")
var receivedObjects: [AXObject?] = []
channel.on("object.created") { receivedObjects.append($0.object) }
channel.on("object.updated") { receivedObjects.append($0.object) }
channel.on("object.deleted") { receivedObjects.append($0.object) }
delay(1) {
self.serverSend([
"channel": "objects/mycollection3",
"event": "object.created",
"data": ["sysObjectId":"id1", "prop1":"value1"]
])
self.serverSend([
"channel": "objects/mycollection3",
"event": "object.updated",
"data": ["sysObjectId":"id2", "prop2":"value2"]
])
self.serverSend([
"channel": "objects/mycollection3",
"event": "object.deleted",
"data": ["sysObjectId":"id3", "prop3":"value3"]
])
delay(0.1, async.fulfill)
}
waitForExpectationsWithTimeout(8) { error in
AXAssertEqual(receivedObjects.count, 3)
AXAssertEqual(receivedObjects[0]?.objectID, "id1")
AXAssertEqual(receivedObjects[0]?.collectionName, "mycollection3")
AXAssertEqual(receivedObjects[0]?.string("prop1"), "value1")
AXAssertEqual(receivedObjects[1]?.objectID, "id2")
AXAssertEqual(receivedObjects[1]?.collectionName, "mycollection3")
AXAssertEqual(receivedObjects[1]?.string("prop2"), "value2")
AXAssertEqual(receivedObjects[2]?.objectID, "id3")
AXAssertEqual(receivedObjects[2]?.collectionName, "mycollection3")
AXAssertEqual(receivedObjects[2]?.string("prop3"), "value3")
}
}
func testShouldTriggerStatusEventsThrougoutConnectionLifecycle() {
let async = expectationWithDescription("async")
var statusChanges: [[String:AnyObject]] = []
realtimeService.on("status") { event in
let status = self.realtimeService.status
statusChanges.append(["eventType": event.type, "status": status.rawValue])
}
AXAssertEqual(realtimeService.status.rawValue, AXRealtimeServiceStatus.Disconnected.rawValue)
let channel = AXChannel("public/foo")
channel.send("foo")
delay(1) {
AXAssertEqual(statusChanges.count, 2)
self.realtimeService.webSocketDidDisconnect(nil)
delay(3) {
AXAssertEqual(statusChanges.count, 4)
async.fulfill()
}
}
waitForExpectationsWithTimeout(10) { error in
AXAssertEqual(statusChanges[0]["status"], AXRealtimeServiceStatus.Connecting.rawValue)
AXAssertEqual(statusChanges[1]["status"], AXRealtimeServiceStatus.Connected.rawValue)
AXAssertEqual(statusChanges[2]["status"], AXRealtimeServiceStatus.Connecting.rawValue)
AXAssertEqual(statusChanges[3]["status"], AXRealtimeServiceStatus.Connected.rawValue)
}
}
}
private class MockWebSocket: AXWebSocketAdapter {
private var realtimeService: AXRealtimeService!
private var received: ([String:AnyObject])->()
init(_ realtimeService: AXRealtimeService, fail: Bool, received: ([String:AnyObject])->()) {
self.realtimeService = realtimeService
self.received = received
delay(0.5) {
if fail {
self.realtimeService.webSocketDidDisconnect(NSError(domain: "webSocketDidDisconnect", code: 0, userInfo: nil))
} else {
self.realtimeService.webSocketDidConnect()
}
}
}
func send(message:AnyObject) {
if let packet = message as? [String:AnyObject] {
received(packet)
}
}
}
|
809c6ddb7f073ed0f023035efe45a89d
| 41.659229 | 126 | 0.588797 | false | false | false | false |
asbhat/stanford-ios9-apps
|
refs/heads/master
|
Calculator/Calculator/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// Calculator
//
// Created by Aditya Bhat on 5/2/2016.
// Copyright © 2016 Aditya Bhat. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class ViewController: UIViewController {
// implicitly (automatically) unwraps display
@IBOutlet fileprivate weak var display: UILabel!
@IBOutlet fileprivate weak var history: UILabel!
fileprivate let displayFormatter = NumberFormatter()
fileprivate var userIsInTheMiddleOfTyping = false
@IBAction fileprivate func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping {
let textCurrentlyInDisplay = display.text!
if digit != "." || textCurrentlyInDisplay.range(of: ".") == nil {
display.text = textCurrentlyInDisplay + digit
}
} else {
display.text = (digit == "." ? "0." : digit)
}
userIsInTheMiddleOfTyping = true
}
// computed propery
fileprivate var displayValue: Double? {
get {
return Double(display.text!)
}
set {
displayFormatter.maximumFractionDigits = (newValue ?? 0).truncatingRemainder(dividingBy: 1) == 0 ? 0 : 6
display.text = displayFormatter.string(from: newValue as NSNumber? ?? 0)
}
}
// initializing CalculatorBrain with the default initializer (takes no arguments)
fileprivate var brain = CalculatorBrain()
@IBAction fileprivate func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.enter(operand: displayValue!)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(symbol: mathematicalSymbol)
}
displayValue = brain.result
history.text = brain.description + (brain.isPartialResult ? "..." : "=")
}
@IBAction fileprivate func allClear() {
displayValue = 0
history.text = " "
userIsInTheMiddleOfTyping = false
brain.allClear()
}
@IBAction func backspace() {
if userIsInTheMiddleOfTyping {
if display.text!.characters.count > 1 {
display.text!.remove(at: display.text!.characters.index(before: display.text!.endIndex))
} else {
displayValue = 0
userIsInTheMiddleOfTyping = false
}
}
}
}
|
76aa2cdfd4a2253eb617c9f99bfd3ae6
| 33.066667 | 116 | 0.630137 | false | false | false | false |
piscoTech/MBLibrary
|
refs/heads/master
|
Shared/HealthKit.swift
|
mit
|
1
|
//
// HealthKit.swift
// MBLibrary
//
// Created by Marco Boschi on 05/03/2017.
// Copyright © 2017 Marco Boschi. All rights reserved.
//
import Foundation
import MBLibrary
import HealthKit
extension HKWorkoutActivityType {
public var name: String {
let wType: Int
switch self {
case .americanFootball:
wType = 1
case .archery:
wType = 2
case .australianFootball:
wType = 3
case .badminton:
wType = 4
case .baseball:
wType = 5
case .basketball:
wType = 6
case .bowling:
wType = 7
case .boxing:
wType = 8
case .climbing:
wType = 9
case .cricket:
wType = 10
case .crossTraining:
wType = 11
case .curling:
wType = 12
case .cycling:
wType = 13
case .dance:
wType = 14
case .danceInspiredTraining:
wType = 15
case .elliptical:
wType = 16
case .equestrianSports:
wType = 17
case .fencing:
wType = 18
case .fishing:
wType = 19
case .functionalStrengthTraining:
wType = 20
case .golf:
wType = 21
case .gymnastics:
wType = 22
case .handball:
wType = 23
case .hiking:
wType = 24
case .hockey:
wType = 25
case .hunting:
wType = 26
case .lacrosse:
wType = 27
case .martialArts:
wType = 28
case .mindAndBody:
wType = 29
case .mixedMetabolicCardioTraining:
wType = 30
case .paddleSports:
wType = 31
case .play:
wType = 32
case .preparationAndRecovery:
wType = 33
case .racquetball:
wType = 34
case .rowing:
wType = 35
case .rugby:
wType = 36
case .running:
wType = 37
case .sailing:
wType = 38
case .skatingSports:
wType = 39
case .snowSports:
wType = 40
case .soccer:
wType = 41
case .softball:
wType = 42
case .squash:
wType = 43
case .stairClimbing:
wType = 44
case .surfingSports:
wType = 45
case .swimming:
wType = 46
case .tableTennis:
wType = 47
case .tennis:
wType = 48
case .trackAndField:
wType = 49
case .traditionalStrengthTraining:
wType = 50
case .volleyball:
wType = 51
case .walking:
wType = 52
case .waterFitness:
wType = 53
case .waterPolo:
wType = 54
case .waterSports:
wType = 55
case .wrestling:
wType = 56
case .yoga:
wType = 57
case .barre:
wType = 58
case .coreTraining:
wType = 59
case .crossCountrySkiing:
wType = 60
case .downhillSkiing:
wType = 61
case .flexibility:
wType = 62
case .highIntensityIntervalTraining:
wType = 63
case .jumpRope:
wType = 64
case .kickboxing:
wType = 65
case .pilates:
wType = 66
case .snowboarding:
wType = 67
case .stairs:
wType = 68
case .stepTraining:
wType = 69
case .wheelchairWalkPace:
wType = 70
case .wheelchairRunPace:
wType = 71
case .taiChi:
wType = 72
case .mixedCardio:
wType = 73
case .handCycling:
wType = 74
case .discSports:
wType = 75
case .fitnessGaming:
wType = 76
case .cardioDance:
wType = 77
case .socialDance:
wType = 78
case .pickleball:
wType = 79
case .cooldown:
wType = 80
case .other:
fallthrough
@unknown default:
wType = 0
}
return MBLocalizedString("WORKOUT_NAME_\(wType)", comment: "Workout")
}
}
|
e30ddff9346d9d7bd7015fc37ac3fe25
| 16.069149 | 71 | 0.631973 | false | false | false | false |
skylib/SnapImagePicker
|
refs/heads/master
|
SnapImagePicker_Snapshot_Tests/SnapImagePickerAlbumTest.swift
|
bsd-3-clause
|
1
|
@testable import SnapImagePicker
import SnapFBSnapshotBase
class SnapImagePickerAlbumTest: SnapFBSnapshotBase {
override func setUp() {
super.setUp()
let bundle = NSBundle(identifier: "com.snapsale.SnapImagePicker")
let storyboard = UIStoryboard(name: "SnapImagePicker", bundle: bundle)
if let viewController = storyboard.instantiateViewControllerWithIdentifier("Image Picker View Controller") as? SnapImagePickerViewController {
sutBackingViewController = viewController
sut = viewController.view
setup(viewController)
recordMode = super.recordAll || true
}
}
override func tearDown() {
super.tearDown()
}
}
extension SnapImagePickerAlbumTest {
private func setup(vc: SnapImagePickerViewController) {
if let image = UIImage(named: "dress.jpg", inBundle: NSBundle(forClass: SnapImagePickerAlbumTest.self), compatibleWithTraitCollection: nil) {
vc.eventHandler = self
let mainImage = SnapImagePickerImage(image: image, localIdentifier: "localIdentifier", createdDate: NSDate())
vc.display(SnapImagePickerViewModel(albumTitle: "Title", mainImage: mainImage, selectedIndex: 0, isLoading: false))
}
}
}
extension SnapImagePickerAlbumTest: SnapImagePickerEventHandlerProtocol {
func viewWillAppearWithCellSize(cellSize: CGFloat) {
}
func albumImageClicked(index: Int) -> Bool {
return false
}
func albumTitleClicked(destinationViewController: UIViewController) {
}
func selectButtonPressed(image: UIImage, withImageOptions: ImageOptions) {
}
func numberOfSectionsForNumberOfColumns(columns: Int) -> Int {
return 40
}
func numberOfItemsInSection(section: Int, withColumns: Int) -> Int {
return withColumns
}
func presentCell(cell: ImageCell, atIndex: Int) -> ImageCell {
cell.imageView?.image = UIImage(named: "dress.jpg", inBundle: NSBundle(forClass: SnapImagePickerAlbumTest.self), compatibleWithTraitCollection: nil)
if atIndex == 0 {
cell.backgroundColor = SnapImagePicker.Theme.color
cell.spacing = 2
}
return cell
}
func scrolledToCells(cells: Range<Int>, increasing: Bool, fromOldRange: Range<Int>?) { }
}
|
4b5d0fd87ff02754c3404b37b10ad563
| 35.784615 | 156 | 0.676151 | false | true | false | false |
hstdt/GodEye
|
refs/heads/master
|
Carthage/Checkouts/Log4G/Log4G/Classes/Log4G.swift
|
mit
|
1
|
//
// Log4G.swift
// Pods
//
// Created by zixun on 17/1/10.
//
//
import Foundation
//--------------------------------------------------------------------------
// MARK: - Log4gDelegate
//--------------------------------------------------------------------------
public protocol Log4GDelegate: NSObjectProtocol {
func log4gDidRecord(with model:LogModel)
}
//--------------------------------------------------------------------------
// MARK: - WeakLog4gDelegate
// DESCRIPTION: Weak wrap of delegate
//--------------------------------------------------------------------------
class WeakLog4GDelegate: NSObject {
weak var delegate : Log4GDelegate?
init (delegate: Log4GDelegate) {
super.init()
self.delegate = delegate
}
}
//--------------------------------------------------------------------------
// MARK: - Log4G
// DESCRIPTION: Simple, lightweight logging framework written in Swift
// 4G means for GodEye, it was development for GodEye at the beginning of the time
//--------------------------------------------------------------------------
open class Log4G: NSObject {
//--------------------------------------------------------------------------
// MARK: OPEN FUNCTION
//--------------------------------------------------------------------------
/// record a log type message
///
/// - Parameters:
/// - message: log message
/// - file: file which call the api
/// - line: line number at file which call the api
/// - function: function name which call the api
open class func log(_ message: Any = "",
file: String = #file,
line: Int = #line,
function: String = #function) {
self.shared.record(type: .log,
thread: Thread.current,
message: "\(message)",
file: file,
line: line,
function: function)
}
/// record a warning type message
///
/// - Parameters:
/// - message: warning message
/// - file: file which call the api
/// - line: line number at file which call the api
/// - function: function name which call the api
open class func warning(_ message: Any = "",
file: String = #file,
line: Int = #line,
function: String = #function) {
self.shared.record(type: .warning,
thread: Thread.current,
message: "\(message)",
file: file,
line: line,
function: function)
}
/// record an error type message
///
/// - Parameters:
/// - message: error message
/// - file: file which call the api
/// - line: line number at file which call the api
/// - function: function name which call the api
open class func error(_ message: Any = "",
file: String = #file,
line: Int = #line,
function: String = #function) {
self.shared.record(type: .error,
thread: Thread.current,
message: "\(message)",
file: file,
line: line,
function: function)
}
//--------------------------------------------------------------------------
// MARK: PRIVATE FUNCTION
//--------------------------------------------------------------------------
/// record message base function
///
/// - Parameters:
/// - type: log type
/// - thread: thread which log the messsage
/// - message: log message
/// - file: file which call the api
/// - line: line number at file which call the api
/// - function: function name which call the api
private func record(type:Log4gType,
thread:Thread,
message: String,
file: String,
line: Int,
function: String) {
self.queue.async {
let model = LogModel(type: type,
thread: thread,
message: message,
file: self.name(of: file),
line: line,
function: function)
print(message)
for delegate in self.delegates {
delegate.delegate?.log4gDidRecord(with: model)
}
}
}
/// get the name of file in filepath
///
/// - Parameter file: path of file
/// - Returns: filename
private func name(of file:String) -> String {
return URL(fileURLWithPath: file).lastPathComponent
}
//MARK: - Private Variable
/// singleton for Log4g
fileprivate static let shared = Log4G()
/// log queue
private let queue = DispatchQueue(label: "Log4g")
/// weak delegates
fileprivate var delegates = [WeakLog4GDelegate]()
}
//--------------------------------------------------------------------------
// MARK: - Log4gDelegate Fucntion Extension
//--------------------------------------------------------------------------
extension Log4G {
open class var delegateCount: Int {
get {
return self.shared.delegates.count
}
}
open class func add(delegate:Log4GDelegate) {
let log4g = self.shared
// delete null week delegate
log4g.delegates = log4g.delegates.filter {
return $0.delegate != nil
}
// judge if contains the delegate from parameter
let contains = log4g.delegates.contains {
return $0.delegate?.hash == delegate.hash
}
// if not contains, append it with weak wrapped
if contains == false {
let week = WeakLog4GDelegate(delegate: delegate)
self.shared.delegates.append(week)
}
}
open class func remove(delegate:Log4GDelegate) {
let log4g = self.shared
log4g.delegates = log4g.delegates.filter {
// filter null weak delegate
return $0.delegate != nil
}.filter {
// filter the delegate from parameter
return $0.delegate?.hash != delegate.hash
}
}
}
|
0849573dbdb48a465aaff9e273d0e679
| 32.766497 | 95 | 0.428593 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox
|
refs/heads/master
|
nRF Toolbox/Profiles/UART/NewCommand/UARTNewCommandViewController.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
protocol UARTNewCommandDelegate: AnyObject {
func createdNewCommand(_ viewController: UARTNewCommandViewController, command: UARTCommandModel, index: Int)
}
class UARTNewCommandViewController: UIViewController {
@IBOutlet private var createButton: NordicButton!
@IBOutlet private var deleteButton: NordicButton!
@IBOutlet private var collectionView: UICollectionView!
@IBOutlet private var valueTextField: UITextField!
@IBOutlet private var typeSegmentControl: UISegmentedControl!
@IBOutlet private var textView: AutoReszableTextView!
@IBOutlet private var eolLabel: UILabel!
@IBOutlet private var eolSegment: UISegmentedControl!
weak var delegate: UARTNewCommandDelegate?
private var command: UARTCommandModel?
private var index: Int
init(command: UARTCommandModel?, index: Int) {
self.command = command
self.index = index
super.init(nibName: "UARTNewCommandViewController", bundle: .main)
}
required init?(coder: NSCoder) {
SystemLog(category: .app, type: .fault).fault("required init?(coder: NSCoder) is not implemented for UARTNewCommandViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
}
setupTextField()
setupTextView()
createButton.style = .mainAction
navigationItem.title = "Create new command"
collectionView.register(type: ImageCollectionViewCell.self)
command.map { self.setupUI(with: $0) }
if #available(iOS 13, *) {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(dismsiss))
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .done, target: self, action: #selector(dismsiss))
}
}
@IBAction func typeChanged(_ sender: UISegmentedControl) {
// textField.isHidden, textView.isHidden, eolLabel.isHidden, eolSegment.isHidden
let hiddenOptions: (Bool, Bool, Bool, Bool)
if sender.selectedSegmentIndex == 0 {
hiddenOptions = (true, false, false, false )
} else {
hiddenOptions = (false, true, true, true )
}
valueTextField.isHidden = hiddenOptions.0
textView.isHidden = hiddenOptions.1
eolLabel.isHidden = hiddenOptions.2
eolSegment.isHidden = hiddenOptions.3
createButton.isEnabled = readyForCreate()
textView.resignFirstResponder()
valueTextField.resignFirstResponder()
}
@IBAction func textChanged(_ sender: Any) {
createButton.isEnabled = readyForCreate()
}
@IBAction func createCommand() {
let command: UARTCommandModel
let selectedItem = (collectionView.indexPathsForSelectedItems?.first?.item)!
let image = CommandImage.allCases[selectedItem]
if typeSegmentControl.selectedSegmentIndex == 0 {
let slices = textView.text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
let text = slices.joined(separator: eolSymbol())
command = TextCommand(text: text, image: image, eol: self.eolSymbol())
} else {
command = DataCommand(data: Data(valueTextField.text!.hexa), image: image)
}
delegate?.createdNewCommand(self, command: command, index: index)
}
@IBAction func deleteBtnPressed() {
delegate?.createdNewCommand(self, command: EmptyModel(), index: index)
}
}
extension UARTNewCommandViewController {
private func setupUI(with command: UARTCommandModel) {
let typeIndex: Int
let title: String
switch command {
case let tCommand as TextCommand:
typeIndex = 0
title = tCommand.title
textView.text = title
updateEOLSegment(eol: tCommand.eol)
case is DataCommand:
typeIndex = 1
title = command.data.hexEncodedString().uppercased()
valueTextField.text = title
default:
return
}
typeSegmentControl.selectedSegmentIndex = typeIndex
typeChanged(typeSegmentControl)
CommandImage.allCases.enumerated()
.first(where: { $0.element.name == command.image.name })
.map { self.collectionView.selectItem(at: IndexPath(item: $0.offset, section: 0), animated: false, scrollPosition: .top) }
deleteButton.isHidden = false
deleteButton.style = .destructive
createButton.setTitle("Save", for: .normal)
}
private func updateButtonState() {
createButton.isEnabled = !(valueTextField.text?.isEmpty ?? true) && collectionView.indexPathsForSelectedItems?.first != nil
}
private func setupTextView() {
let accessoryToolbar = UIToolbar()
accessoryToolbar.autoresizingMask = .flexibleHeight
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: textView, action: #selector(resignFirstResponder))
accessoryToolbar.items = [doneBtn]
textView.inputAccessoryView = accessoryToolbar
textView.didChangeText = { [weak self] _ in
self?.createButton.isEnabled = self?.readyForCreate() == true
}
}
private func updateEOLSegment(eol: String) {
let symbols = ["\n", "\r", "\n\r"]
eolSegment.selectedSegmentIndex = symbols.enumerated().first(where: { eol == $0.element })?.offset ?? 0
}
private func setupTextField() {
let accessoryToolbar = UIToolbar()
accessoryToolbar.autoresizingMask = .flexibleHeight
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: valueTextField, action: #selector(resignFirstResponder))
accessoryToolbar.items = [doneBtn]
let hexLabel = UILabel()
hexLabel.text = " 0x"
hexLabel.font = valueTextField.font
hexLabel.textColor = UIColor.Text.secondarySystemText
hexLabel.textAlignment = .center
valueTextField.leftView = hexLabel
valueTextField.leftViewMode = .always
valueTextField.inputAccessoryView = accessoryToolbar
}
private func readyForCreate() -> Bool {
let selectedItem = collectionView.indexPathsForSelectedItems?.first != nil
let dataIsReady = typeSegmentControl.selectedSegmentIndex == 0
? !textView.text.isEmpty
: valueTextField.text?.isEmpty == false
return selectedItem && dataIsReady
}
private func eolSymbol() -> String {
switch eolSegment.selectedSegmentIndex {
case 0: return "\n"
case 1: return "\r"
case 2: return "\n\r"
default:
return ""
}
}
}
extension UARTNewCommandViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
createButton.isEnabled = readyForCreate()
valueTextField.resignFirstResponder()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let side = collectionView.frame.size.width / 3 - 6
return CGSize(width: side, height: side)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
8
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
8
}
}
extension UARTNewCommandViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
CommandImage.allCases.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let img = CommandImage.allCases[indexPath.item]
let cell = collectionView.dequeueCell(ofType: ImageCollectionViewCell.self, for: indexPath)
cell.imageView.image = img.image?.withRenderingMode(.alwaysTemplate)
return cell
}
}
extension UARTNewCommandViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return CharacterSet(charactersIn: "0123456789abcdefABCDEF").isSuperset(of: CharacterSet(charactersIn: string))
}
}
|
fb5290255713fc64d70a68d0b1e9fcee
| 38.805243 | 175 | 0.68169 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/IRGen/Inputs/metadata2.swift
|
apache-2.0
|
29
|
import resilient_struct
struct Item {
var d: ResilientInt? = nil
}
struct InternalContainer {
fileprivate enum SomeEnumType {
case none
case single(Item)
init(item: [Item]) {
if item.count >= 1 {
self = .single(item.first!)
} else {
self = .none
}
}
}
private var type: SomeEnumType
init(item: [Item]) {
self.type = SomeEnumType(item: item)
}
}
struct InternalContainer2 {
fileprivate enum SomeEnumType {
case none
case single(Item)
init(item: [Item]) {
if item.count >= 1 {
self = .single(item.first!)
} else {
self = .none
}
}
}
private var type: (SomeEnumType, SomeEnumType)
init(item: [Item]) {
self.type = SomeEnumType(item: item)
}
}
enum InternalSingletonEnum {
fileprivate enum SomeEnumType {
case none
case single(Item)
init(item: [Item]) {
if item.count >= 1 {
self = .single(item.first!)
} else {
self = .none
}
}
}
case first(SomeEnumType)
init() {
return .first(.none)
}
}
enum InternalSingletonEnum2 {
fileprivate enum SomeEnumType {
case none
case single(Item)
init(item: [Item]) {
if item.count >= 1 {
self = .single(item.first!)
} else {
self = .none
}
}
}
case first(SomeEnumType, SomeEnumType)
init() {
return .first(.none, .none)
}
}
|
c16a62441c30384570e6e8b8c9d9551e
| 17.404494 | 50 | 0.490842 | false | false | false | false |
psoamusic/PourOver
|
refs/heads/master
|
PourOver/POCoreMotionGenerator.swift
|
gpl-3.0
|
1
|
//
// POCoreMotionGenerator.swift
// LibraryLoader
//
// Created by kevin on 6/15/15.
// Copyright (c) 2015 labuser. All rights reserved.
//
import Foundation
import UIKit
import CoreMotion
//constants for controller names:
//note: case-insensitive compared for lookup
let kPitchController = "CMMotionManager.deviceMotion.attitude.pitch"
let kRollController = "CMMotionManager.deviceMotion.attitude.roll"
let kYawController = "CMMotionManager.deviceMotion.attitude.yaw"
let kGravityXController = "CMMotionManager.deviceMotion.gravity.x"
let kGravityYController = "CMMotionManager.deviceMotion.gravity.y"
let kGravityZController = "CMMotionManager.deviceMotion.gravity.z"
let kUserAccelerationXController = "CMMotionManager.deviceMotion.userAcceleration.x"
let kUserAccelerationYController = "CMMotionManager.deviceMotion.userAcceleration.y"
let kUserAccelerationZController = "CMMotionManager.deviceMotion.userAcceleration.z"
let kRotationRateXController = "CMMotionManager.deviceMotion.rotationRate.x"
let kRotationRateYController = "CMMotionManager.deviceMotion.rotationRate.y"
let kRotationRateZController = "CMMotionManager.deviceMotion.rotationRate.z"
class POCoreMotionGenerator: POControllerUpdating {
//===================================================================================
//MARK: Properties
//===================================================================================
//framework objects should be lazy loaded, not instantiated during init()
lazy final var motionManager = CMMotionManager()
//===================================================================================
//MARK: Initialization
//===================================================================================
deinit {
endUpdating()
}
//===================================================================================
//MARK: POControllerUpdating
//===================================================================================
static var controllers: [String : POController] = [
kPitchController : POController(name: kPitchController, min: -M_PI_2, max: M_PI_2),
kRollController : POController(name: kRollController, min: -M_PI, max: M_PI),
kYawController : POController(name: kYawController, min: -M_PI, max: M_PI),
kGravityXController : POController(name: kGravityXController, min: -M_PI, max: M_PI),
kGravityYController : POController(name: kGravityYController, min: -M_PI, max: M_PI),
kGravityZController : POController(name: kGravityZController, min: -M_PI, max: M_PI),
kUserAccelerationXController : POController(name: kUserAccelerationXController, min: -M_PI, max: M_PI),
kUserAccelerationYController : POController(name: kUserAccelerationYController, min: -M_PI, max: M_PI),
kUserAccelerationZController : POController(name: kUserAccelerationZController, min: -M_PI, max: M_PI),
kRotationRateXController : POController(name: kRotationRateXController, min: -M_PI, max: M_PI),
kRotationRateYController : POController(name: kRotationRateYController, min: -M_PI, max: M_PI),
kRotationRateZController : POController(name: kRotationRateZController, min: -M_PI, max: M_PI),
]
static var requiresTimer: Bool = true
func update() {
if let deviceMotion = motionManager.deviceMotion {
updateValue(deviceMotion.attitude.pitch, forControllerNamed: kPitchController)
updateValue(deviceMotion.attitude.roll, forControllerNamed: kRollController)
updateValue(deviceMotion.attitude.yaw, forControllerNamed: kYawController)
updateValue(deviceMotion.gravity.x, forControllerNamed: kGravityXController)
updateValue(deviceMotion.gravity.y, forControllerNamed: kGravityYController)
updateValue(deviceMotion.gravity.z, forControllerNamed: kGravityZController)
updateValue(deviceMotion.userAcceleration.x, forControllerNamed: kUserAccelerationXController)
updateValue(deviceMotion.userAcceleration.y, forControllerNamed: kUserAccelerationYController)
updateValue(deviceMotion.userAcceleration.z, forControllerNamed: kUserAccelerationZController)
updateValue(deviceMotion.rotationRate.x, forControllerNamed: kRotationRateXController)
updateValue(deviceMotion.rotationRate.y, forControllerNamed: kRotationRateYController)
updateValue(deviceMotion.rotationRate.z, forControllerNamed: kRotationRateZController)
}
}
func beginUpdating() {
if motionManager.gyroAvailable {
motionManager.startDeviceMotionUpdates()
}
}
func endUpdating() {
motionManager.stopDeviceMotionUpdates()
}
}
|
6b3158096a158bd6cec4660221edf3ca
| 49.645833 | 111 | 0.657548 | false | false | false | false |
TG908/iOS
|
refs/heads/master
|
TUM Campus App/TumOnlineLoginRequestManager.swift
|
gpl-3.0
|
1
|
//
// TumOnlineLoginRequestManager.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/5/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import Sweeft
import Alamofire
import SWXMLHash
class TumOnlineLoginRequestManager {
init(delegate:AccessTokenReceiver?) {
self.delegate = delegate
}
var token = ""
let defaults = UserDefaults.standard
var delegate: AccessTokenReceiver?
var lrzID : String?
func newId(_ newId: String) {
lrzID = newId
}
func getLoginURL() -> String {
let version = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String) ?? "1"
let base = TUMOnlineWebServices.BaseUrl.rawValue + TUMOnlineWebServices.TokenRequest.rawValue
if let id = lrzID {
return base + "?pUsername=" + id + "&pTokenName=TumCampusApp-" + version
}
return ""
}
func getConfirmationURL() -> String {
return TUMOnlineWebServices.BaseUrl.rawValue + TUMOnlineWebServices.TokenConfirmation.rawValue + "?" + TUMOnlineWebServices.TokenParameter.rawValue + "=" + token
}
func fetch() {
let url = getLoginURL()
print(url)
Alamofire.request(url).responseString() { (response) in
if let data = response.result.value {
let tokenData = SWXMLHash.parse(data)
if let token = tokenData["token"].element?.text {
self.token = token
}
}
}
}
func confirmToken() {
let url = getConfirmationURL()
print(url)
Alamofire.request(url).responseString() { (response) in
if let data = response.result.value {
let tokenData = SWXMLHash.parse(data)
print(tokenData)
if let confirmed = tokenData["confirmed"].element?.text {
if confirmed == "true" {
self.delegate?.receiveToken(self.token)
} else {
self.delegate?.tokenNotConfirmed()
}
} else {
self.delegate?.tokenNotConfirmed()
}
} else {
self.delegate?.tokenNotConfirmed()
}
}
}
func loginSuccesful(_ user: User) {
PersistentUser.value = .some(lrzID: (user.lrzID).?, token: user.token)
User.shared = user
}
func logOut() {
PersistentUser.reset()
User.shared = nil
}
}
|
e2a2b2144a433e64e2a8775341d33597
| 27.7 | 169 | 0.546264 | false | false | false | false |
Mazy-ma/DemoBySwift
|
refs/heads/master
|
ComplexLoadingAnimation/ComplexLoadingAnimation/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// ComplexLoadingAnimation
//
// Created by Mazy on 2017/6/30.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var holderView = HolderView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addHolderView()
}
func addHolderView() {
let boxSize: CGFloat = 100
holderView.frame = CGRect(x: view.bounds.width/2 - boxSize/2, y: view.bounds.height/2-boxSize/2, width: boxSize, height: boxSize)
holderView.parentFrame = view.frame
holderView.delegate = self
holderView.addOval()
view.addSubview(holderView)
}
func addButton() {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
func buttonPressed() {
view.backgroundColor = Colors.white
_ = view.subviews.map{ $0.removeFromSuperview()}
holderView = HolderView(frame: CGRect.zero)
addHolderView()
}
}
extension ViewController: HolderViewDelegate {
func animationLabel() {
// 1
holderView.removeFromSuperview()
view.backgroundColor = Colors.blue
// 2
let label: UILabel = UILabel(frame: view.frame)
label.textColor = Colors.white
label.font = UIFont(name: "HelveticaNeue-Thin", size: 170)
label.textAlignment = .center
label.text = "S"
label.transform = label.transform.scaledBy(x: 0.25, y: 0.25)
view.addSubview(label)
// 3
UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: .curveEaseInOut, animations: {
label.transform = label.transform.scaledBy(x: 4.0, y: 4.0)
}) { (_) in
self.addButton()
}
}
}
|
19133d127cb18172f4a939d3b083c0bd
| 28.219178 | 151 | 0.614158 | false | false | false | false |
iosliutingxin/DYVeideoVideo
|
refs/heads/master
|
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
|
mit
|
1
|
//
// HomeViewController.swift
// DYZB
//
// Created by 北京时代华擎 on 17/4/30.
// Copyright © 2017年 iOS _Liu. All rights reserved.
//
import UIKit
private let titleViewH:CGFloat=40
class HomeViewController: UIViewController {
public var currentIndex : Int = 0{
didSet{
setCurrentIndex(index: currentIndex)
}
}
//懒加载属性
fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in
let titleFrame=CGRect(x: 0, y: stateBarH+NavigationBar, width:screenW, height: titleViewH)
let titles=["推荐","游戏","娱乐","趣玩"]
let titleView=PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate=self
return titleView
}()
//内容部分
fileprivate lazy var pageContentView : PageContentView = {[weak self]in
//1、确定frame
let contentH = screenH - stateBarH - NavigationBar - titleViewH - tabBarH
let contentFrame = CGRect(x: 0, y: stateBarH + NavigationBar + titleViewH, width: screenW, height: contentH)
//2、确定所有子控制器
var childVc = [UIViewController]()
//(1--推荐控制器
childVc.append(RecommeViewController())
//(2--游戏控制器
childVc.append(gameController())
//3、游戏界面
childVc.append(AmuseController())
for _ in 0..<1{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVc.append(vc)
}
let contentView = PageContentView(frame: contentFrame, chilVcs: childVc, parentViewController: self)
contentView.ContentCurrentPage = {[weak self] (index)in
guard let strongSelf = self else {
return
}
strongSelf.currentIndex = index
}
return contentView
}()
//系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
}
//设置UI界面
extension HomeViewController{
fileprivate func setUpUI(){
//不需要调整UIscrollView的内边距
automaticallyAdjustsScrollViewInsets=false
//1、设置导航栏
setUpNavigationBar()
//2、添加titlview
view.addSubview(pageTitleView)
//3、添加contentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.purple
}
fileprivate func setUpNavigationBar(){
let btn=UIButton()
btn.setImage(UIImage (named: "homeLogoIcon"), for:UIControlState() )
btn.sizeToFit()
navigationItem.leftBarButtonItem=UIBarButtonItem(customView: btn)
let size=CGSize(width: 40, height: 40)
let historyItem=UIBarButtonItem(imageName: "btn_close_danmu", highImage: "btn_close_danmu", size: size)
let searchItem=UIBarButtonItem(imageName: "home_newSeacrhcon", highImage: "home_newSaoicon", size: size)
let qrcodeItem=UIBarButtonItem(imageName: "home_newSaoicon", highImage: "home_newSeacrhcon", size: size)
navigationItem.rightBarButtonItems=[historyItem,searchItem,qrcodeItem]
}
}
extension HomeViewController{
func setCurrentIndex(index : Int) {
pageTitleView.setCurrentId(index)
}
}
//pageTitleDelegate
extension HomeViewController : pageTitleDelegate {
func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) {
pageContentView.setCurrentIndex(index)
}
}
|
c0bbbb3fd340c1b2aac97bee187cf192
| 24.811594 | 156 | 0.629141 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.