repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
drewfish/ios-vetcrash | vetcrash/ViewControllers/ScheduleViewController.swift | 1 | 1196 | //
// ScheduleViewController.swift
// vetcrash
//
// Created by Andrew Folta on 10/31/14.
// Copyright (c) 2014 Andrew Folta. All rights reserved.
//
import UIKit
class ScheduleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 58.0
}
override func viewDidAppear(animated: Bool) {
navigationController?.navigationBar.topItem?.title = tabBarItem.title!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CRASH_SCHEDULE.count
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 58.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var drug = CRASH_SCHEDULE[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier("drugCell") as DrugCell
cell.setDrug(drug)
return cell
}
}
| cc0-1.0 | 52478c315f83abcf194ee0d77b90daec | 26.813953 | 112 | 0.702341 | 4.784 | false | false | false | false |
admaiorastudio/bugghy | packages/.xbcache/GCr-3.0.3/Samples/signin/SignInExampleSwift/ViewController.swift | 6 | 3308 | //
// Copyright (c) Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
// Match the ObjC symbol name inside Main.storyboard.
@objc(ViewController)
// [START viewcontroller_interfaces]
class ViewController: UIViewController, GIDSignInUIDelegate {
// [END viewcontroller_interfaces]
// [START viewcontroller_vars]
@IBOutlet weak var signInButton: GIDSignInButton!
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var statusText: UILabel!
// [END viewcontroller_vars]
// [START viewdidload]
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
// Uncomment to automatically sign in the user.
//GIDSignIn.sharedInstance().signInSilently()
// TODO(developer) Configure the sign-in button look/feel
// [START_EXCLUDE]
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(ViewController.receiveToggleAuthUINotification(_:)),
name: "ToggleAuthUINotification",
object: nil)
statusText.text = "Initialized Swift app..."
toggleAuthUI()
// [END_EXCLUDE]
}
// [END viewdidload]
// [START signout_tapped]
@IBAction func didTapSignOut(sender: AnyObject) {
GIDSignIn.sharedInstance().signOut()
// [START_EXCLUDE silent]
statusText.text = "Signed out."
toggleAuthUI()
// [END_EXCLUDE]
}
// [END signout_tapped]
// [START disconnect_tapped]
@IBAction func didTapDisconnect(sender: AnyObject) {
GIDSignIn.sharedInstance().disconnect()
// [START_EXCLUDE silent]
statusText.text = "Disconnecting."
// [END_EXCLUDE]
}
// [END disconnect_tapped]
// [START toggle_auth]
func toggleAuthUI() {
if (GIDSignIn.sharedInstance().hasAuthInKeychain()){
// Signed in
signInButton.hidden = true
signOutButton.hidden = false
disconnectButton.hidden = false
} else {
signInButton.hidden = false
signOutButton.hidden = true
disconnectButton.hidden = true
statusText.text = "Google Sign in\niOS Demo"
}
}
// [END toggle_auth]
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: "ToggleAuthUINotification",
object: nil)
}
@objc func receiveToggleAuthUINotification(notification: NSNotification) {
if (notification.name == "ToggleAuthUINotification") {
self.toggleAuthUI()
if notification.userInfo != nil {
let userInfo:Dictionary<String,String!> =
notification.userInfo as! Dictionary<String,String!>
self.statusText.text = userInfo["statusText"]
}
}
}
}
| mit | c3b8886b58226d5dc456d6f63ca9ff90 | 29.348624 | 80 | 0.695889 | 4.531507 | false | false | false | false |
adamdahan/GraphKit | Tests/SessionTests.swift | 1 | 2942 | //
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import XCTest
import GraphKit
class SessionTests: XCTestCase, SessionDelegate {
lazy var session: Session = Session()
var callbackExpectation: XCTestExpectation?
var delegateExpectation: XCTestExpectation?
override func setUp() {
super.setUp()
session.delegate = self
}
override func tearDown() {
session.delegate = nil
super.tearDown()
}
func testGet() {
// if let u1: NSURL = NSURL(string: "http://graph.sandbox.local:5000/key/1/graph/test") {
// session.get(u1) { (json: JSON?, error: NSError?) in
// if nil != json && nil == error {
// self.callbackExpectation?.fulfill()
// }
// }
// }
// callbackExpectation = expectationWithDescription("Test failed.")
// delegateExpectation = expectationWithDescription("Test failed.")
//
// waitForExpectationsWithTimeout(5, handler: nil)
//
// if let u1: NSURL = NSURL(string: "http://graph.sandbox.local:5000/key/1/graph") {
// session.get(u1) { (json: JSON?, error: NSError?) in
// if nil != error && nil == json {
// self.callbackExpectation?.fulfill()
// }
// }
// }
//
// callbackExpectation = expectationWithDescription("Test failed.")
// delegateExpectation = expectationWithDescription("Test failed.")
//
// waitForExpectationsWithTimeout(5, handler: nil)
}
func testPost() {
// if let u1: NSURL = NSURL(string: "http://graph.sandbox.local:5000/index") {
// session.post(u1, json: JSON(value: [["type": "User", "nodeClass": 1]])) { (json: JSON?, error: NSError?) in
// if nil != json && nil == error {
// self.callbackExpectation?.fulfill()
// }
// }
// }
// callbackExpectation = expectationWithDescription("Test failed.")
// delegateExpectation = expectationWithDescription("Test failed.")
//
// waitForExpectationsWithTimeout(5, handler: nil)
}
func sessionDidReceiveGetResponse(session: Session, json: JSON?, error: NSError?) {
delegateExpectation?.fulfill()
}
func sessionDidReceivePOSTResponse(session: Session, json: JSON?, error: NSError?) {
delegateExpectation?.fulfill()
}
func testPerformance() {
self.measureBlock() {}
}
}
| agpl-3.0 | 520b1e343321602269fe5fc094d37960 | 31.32967 | 112 | 0.693406 | 3.668329 | false | true | false | false |
alldne/PolarKit | PolarKit/Classes/CircularScrollView.swift | 1 | 6552 | //
// CircularScrollView.swift
// PolarKit
//
// Created by Yonguk Jeong on 2016. 4. 19..
// Copyright © 2016년 Yonguk Jeong. All rights reserved.
//
import UIKit
func makeBoundFunction(lower: Double, upper: Double, margin: Double) -> (bound: (Double) -> Double, inverse: (Double) -> Double) {
return (
{ (input) in
if lower <= input && input <= upper {
return input
}
if input < lower {
let limit = lower - margin
return limit + pow(margin, 2) / (lower - input + margin)
}
let limit = upper + margin
return limit - pow(margin, 2) / (input - upper + margin)
}, { (input) in
if lower <= input && input <= upper {
return input
}
if input < lower {
let limit = lower - margin
return lower + margin - pow(margin, 2) / (input - limit)
}
let limit = upper + margin
return upper - margin - pow(margin, 2) / (input - limit)
}
)
}
func getTangentialVelocity(center: CGPoint, point: CGPoint, velocity: CGPoint) -> CGVector {
let r = point - center
let v = CGVector(dx: velocity.x, dy: velocity.y)
let length = (r.dx*v.dy - r.dy*v.dx) / r.length
let tangentialUnit = CGVector(dx: -r.dy/r.length, dy: r.dx/r.length)
return tangentialUnit * length
}
func getAngularVelocity(center: CGPoint, point: CGPoint, velocity: CGPoint) -> Double {
let t = getTangentialVelocity(center: center, point: point, velocity: velocity)
if t.length == 0 {
return 0
}
let r = point - center
if r.dx*t.dy - r.dy*t.dx > 0 {
return Double(t.length / point.length)
}
return Double(-t.length / point.length)
}
open class CircularScrollView: RotatableView {
override open class var layerClass : AnyClass {
return RotatableScrollLayer.self
}
override open var layer: RotatableScrollLayer {
return super.layer as! RotatableScrollLayer
}
override public init(frame: CGRect) {
super.init(frame: frame)
let draggingGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(CircularScrollView.dragging(_:)))
self.addGestureRecognizer(draggingGestureRecognizer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate var bound = makeBoundFunction(lower: 0, upper: 0, margin: .pi / 4)
open var contentLength: Double = 0 {
didSet {
self.bound = makeBoundFunction(lower: 0, upper: self.contentLength, margin: .pi / 4)
}
}
override open var offset: Double {
willSet {
if self.layer.animation(forKey: CircularScrollView.kAnimationKey) != nil {
self.cancelAnimation()
}
}
didSet {
self._dragOffset = self.bound.inverse(offset)
}
}
fileprivate var _dragOffset: Double = 0
fileprivate var dragOffset: Double {
get {
return self._dragOffset
}
set {
self._dragOffset = newValue
self.offset = self.bound.bound(newValue)
}
}
fileprivate struct TouchInfo {
var initialPoint: CGVector
var initialDragOffset: Double
var offsetFromInitialPoint: Double
}
fileprivate var touchInfo: TouchInfo!
static let kInertiaThreshhold = 0.8
static let kInertiaAnimationDuration = 2.5
static let kAnimationKey = "scroll-to-offset"
func dragging(_ recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .began:
self._dragOffset = self.bound.inverse(offset)
let initialPoint = recognizer.location(in: self) - self.center
self.touchInfo = TouchInfo(initialPoint: initialPoint, initialDragOffset: self.dragOffset, offsetFromInitialPoint: 0)
case .changed:
let v = recognizer.location(in: self) - self.center
self.touchInfo.offsetFromInitialPoint = v.getNearbyAngle(self.touchInfo.initialPoint, hint: self.touchInfo.offsetFromInitialPoint)
self.dragOffset = self.touchInfo.initialDragOffset + self.touchInfo.offsetFromInitialPoint
case .ended:
self.touchInfo = nil
if self.offset < 0 {
self.scrollToOffset(0, animate: true)
} else if self.offset > self.contentLength {
self.scrollToOffset(self.contentLength, animate: true)
} else {
let w = getAngularVelocity(center: self.center, point: recognizer.location(in: self), velocity: recognizer.velocity(in: self))
if abs(w) > CircularScrollView.kInertiaThreshhold {
let t = CircularScrollView.kInertiaAnimationDuration
let endPoint = self.offset - w*t - 0.5*(-w)*t
self.scrollToOffset(endPoint, animate: true)
}
}
case .cancelled:
self.touchInfo = nil
default:
break
}
}
open func scrollToOffset(_ offset: Double, animate: Bool) {
var offsetInRange = offset
if offset < 0 {
offsetInRange = 0
} else if offset > self.contentLength {
offsetInRange = self.contentLength
}
let anim = CABasicAnimation(keyPath: "offset")
anim.toValue = offsetInRange
anim.duration = CircularScrollView.kInertiaAnimationDuration
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
self.layer.add(anim, forKey: CircularScrollView.kAnimationKey)
}
open func cancelAnimation() {
self.layer.removeAnimation(forKey: CircularScrollView.kAnimationKey)
}
// MARK: UIView methods
override open func layoutSubviews() {
super.layoutSubviews()
let localCenter = self.convert(self.center, from: self.superview)
for subview in self.contentView.subviews {
if let view = subview as? PolarCoordinatedView {
let x = localCenter.x + CGFloat(view.radius * cos(view.angle))
let y = localCenter.y + CGFloat(view.radius * sin(view.angle))
view.center = CGPoint(x: x, y: y)
}
}
}
override open func addSubview(_ view: UIView) {
super.addSubview(view)
self.layer.updateSublayerMask()
}
}
| mit | 2da9e6003b0e13531b51ddf24181c010 | 34.209677 | 142 | 0.603451 | 4.377674 | false | false | false | false |
sonnygauran/trailer | PocketTrailer/MasterViewController.swift | 1 | 26509 |
import UIKit
import CoreData
final class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, UITextFieldDelegate, UITabBarControllerDelegate, UITabBarDelegate {
private var detailViewController: DetailViewController!
private var _fetchedResultsController: NSFetchedResultsController?
// Filtering
private var searchField: UITextField!
private var searchTimer: PopTimer!
// Refreshing
private var refreshOnRelease: Bool = false
private let pullRequestsItem = UITabBarItem()
private let issuesItem = UITabBarItem()
private var tabBar: UITabBar?
@IBAction func editSelected(sender: UIBarButtonItem ) {
let a = UIAlertController(title: "Action", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
a.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { action in
a.dismissViewControllerAnimated(true, completion: nil)
}))
a.addAction(UIAlertAction(title: "Mark all as read", style: UIAlertActionStyle.Destructive, handler: { [weak self] action in
self!.markAllAsRead()
}))
a.addAction(UIAlertAction(title: "Remove merged", style:UIAlertActionStyle.Default, handler: { [weak self] action in
self!.removeAllMerged()
}))
a.addAction(UIAlertAction(title: "Remove closed", style:UIAlertActionStyle.Default, handler: { [weak self] action in
self!.removeAllClosed()
}))
a.addAction(UIAlertAction(title: "Refresh Now", style:UIAlertActionStyle.Default, handler: { action in
app.startRefresh()
}))
presentViewController(a, animated: true, completion: nil)
}
private func tryRefresh() {
refreshOnRelease = false
if api.noNetworkConnection() {
showMessage("No Network", "There is no network connectivity, please try again later")
} else {
if !app.startRefresh() {
updateStatus()
}
}
}
func removeAllMerged()
{
dispatch_async(dispatch_get_main_queue(), { [weak self] in
if Settings.dontAskBeforeWipingMerged {
self!.removeAllMergedConfirmed()
} else {
let a = UIAlertController(title: "Sure?", message: "Remove all \(self!.viewMode.namePlural()) in the Merged section?", preferredStyle: UIAlertControllerStyle.Alert)
a.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
a.addAction(UIAlertAction(title: "Remove", style: UIAlertActionStyle.Destructive, handler: { [weak self] action in
self!.removeAllMergedConfirmed()
}))
self!.presentViewController(a, animated: true, completion: nil)
}
})
}
func removeAllClosed() {
dispatch_async(dispatch_get_main_queue(), { [weak self] in
if Settings.dontAskBeforeWipingClosed {
self!.removeAllClosedConfirmed()
} else {
let a = UIAlertController(title: "Sure?", message: "Remove all \(self!.viewMode.namePlural()) in the Closed section?", preferredStyle: UIAlertControllerStyle.Alert)
a.addAction(UIAlertAction(title: "Cancel", style:UIAlertActionStyle.Cancel, handler: nil))
a.addAction(UIAlertAction(title: "Remove", style:UIAlertActionStyle.Destructive, handler: { [weak self] action in
self!.removeAllClosedConfirmed()
}))
self!.presentViewController(a, animated: true, completion: nil)
}
})
}
func removeAllClosedConfirmed() {
if viewMode == MasterViewMode.PullRequests {
for p in PullRequest.allClosedRequestsInMoc(mainObjectContext) {
mainObjectContext.deleteObject(p)
}
} else {
for p in Issue.allClosedIssuesInMoc(mainObjectContext) {
mainObjectContext.deleteObject(p)
}
}
DataManager.saveDB()
}
func removeAllMergedConfirmed() {
if viewMode == MasterViewMode.PullRequests {
for p in PullRequest.allMergedRequestsInMoc(mainObjectContext) {
mainObjectContext.deleteObject(p)
}
DataManager.saveDB()
}
}
func markAllAsRead() {
if viewMode == MasterViewMode.PullRequests {
for p in fetchedResultsController.fetchedObjects as! [PullRequest] {
p.catchUpWithComments()
}
} else {
for p in fetchedResultsController.fetchedObjects as! [Issue] {
p.catchUpWithComments()
}
}
DataManager.saveDB()
}
func refreshControlChanged() {
refreshOnRelease = !app.isRefreshing
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if refreshOnRelease && !decelerate {
tryRefresh()
}
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if refreshOnRelease {
tryRefresh()
}
}
override func viewDidLoad() {
super.viewDidLoad()
searchTimer = PopTimer(timeInterval: 0.5) { [weak self] in
self!.reloadDataWithAnimation(true)
}
refreshControl?.addTarget(self, action: Selector("refreshControlChanged"), forControlEvents: UIControlEvents.ValueChanged)
searchField = UITextField(frame: CGRectMake(10, 10, 300, 31))
searchField.autoresizingMask = UIViewAutoresizing.FlexibleWidth
searchField.translatesAutoresizingMaskIntoConstraints = true
searchField.placeholder = "Filter..."
searchField.returnKeyType = UIReturnKeyType.Done
searchField.font = UIFont.systemFontOfSize(17)
searchField.borderStyle = UITextBorderStyle.RoundedRect
searchField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
searchField.clearButtonMode = UITextFieldViewMode.Always
searchField.autocapitalizationType = UITextAutocapitalizationType.None
searchField.autocorrectionType = UITextAutocorrectionType.No
searchField.delegate = self
let searchHolder = UIView(frame: CGRectMake(0, 0, 320, 41))
searchHolder.addSubview(searchField)
tableView.tableHeaderView = searchHolder
tableView.contentOffset = CGPointMake(0, searchHolder.frame.size.height)
tableView.rowHeight = UITableViewAutomaticDimension
if let detailNav = splitViewController?.viewControllers.last as? UINavigationController {
detailViewController = detailNav.topViewController as? DetailViewController
}
let n = NSNotificationCenter.defaultCenter()
n.addObserver(self, selector: Selector("updateStatus"), name:REFRESH_STARTED_NOTIFICATION, object: nil)
n.addObserver(self, selector: Selector("updateStatus"), name:REFRESH_ENDED_NOTIFICATION, object: nil)
pullRequestsItem.title = "Pull Requests"
pullRequestsItem.image = UIImage(named: "prsTab")
issuesItem.title = "Issues"
issuesItem.image = UIImage(named: "issuesTab")
}
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
viewMode = indexOfObject(tabBar.items!, value: item)==0 ? MasterViewMode.PullRequests : MasterViewMode.Issues
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.tableHeaderView?.frame = CGRectMake(0, 0, tableView.bounds.size.width, 41)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateStatus()
updateTabBarVisibility(animated)
}
func reloadDataWithAnimation(animated: Bool) {
heightCache.removeAll()
if !Repo.interestedInIssues() && Repo.interestedInPrs() && viewMode == MasterViewMode.Issues {
showTabBar(false, animated: animated)
viewMode = MasterViewMode.PullRequests
return
}
if !Repo.interestedInPrs() && Repo.interestedInIssues() && viewMode == MasterViewMode.PullRequests {
showTabBar(false, animated: animated)
viewMode = MasterViewMode.Issues
return
}
if animated {
let currentIndexes = NSIndexSet(indexesInRange: NSMakeRange(0, fetchedResultsController.sections?.count ?? 0))
_fetchedResultsController = nil
updateStatus()
let dataIndexes = NSIndexSet(indexesInRange: NSMakeRange(0, fetchedResultsController.sections?.count ?? 0))
let removedIndexes = currentIndexes.indexesPassingTest { (idx, _) -> Bool in
return !dataIndexes.containsIndex(idx)
}
let addedIndexes = dataIndexes.indexesPassingTest { (idx, _) -> Bool in
return !currentIndexes.containsIndex(idx)
}
let untouchedIndexes = dataIndexes.indexesPassingTest { (idx, _) -> Bool in
return !(removedIndexes.containsIndex(idx) || addedIndexes.containsIndex(idx))
}
tableView.beginUpdates()
if removedIndexes.count > 0 {
tableView.deleteSections(removedIndexes, withRowAnimation:UITableViewRowAnimation.Automatic)
}
if untouchedIndexes.count > 0 {
tableView.reloadSections(untouchedIndexes, withRowAnimation:UITableViewRowAnimation.Automatic)
}
if addedIndexes.count > 0 {
tableView.insertSections(addedIndexes, withRowAnimation:UITableViewRowAnimation.Automatic)
}
tableView.endUpdates()
} else {
tableView.reloadData()
}
updateTabBarVisibility(animated)
}
func updateTabBarVisibility(animated: Bool) {
showTabBar(Repo.interestedInPrs() && Repo.interestedInIssues(), animated: animated)
}
private func showTabBar(show: Bool, animated: Bool) {
if show {
tableView.contentInset = UIEdgeInsetsMake(tableView.contentInset.top, 0, 49, 0)
tableView.scrollIndicatorInsets = UIEdgeInsetsMake(tableView.scrollIndicatorInsets.top, 0, 49, 0)
if tabBar == nil {
if let s = navigationController?.view {
let t = UITabBar(frame: CGRectMake(0, s.bounds.size.height-49, s.bounds.size.width, 49))
t.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin.union(UIViewAutoresizing.FlexibleBottomMargin).union(UIViewAutoresizing.FlexibleWidth)
t.items = [pullRequestsItem, issuesItem]
t.selectedItem = viewMode==MasterViewMode.PullRequests ? pullRequestsItem : issuesItem
t.delegate = self
t.itemPositioning = UITabBarItemPositioning.Fill
s.addSubview(t)
tabBar = t
if animated {
t.transform = CGAffineTransformMakeTranslation(0, 49)
UIView.animateWithDuration(0.2,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
t.transform = CGAffineTransformIdentity
}, completion: nil);
}
}
}
} else {
if !(Repo.interestedInPrs() && Repo.interestedInIssues()) {
tableView.contentInset = UIEdgeInsetsMake(tableView.contentInset.top, 0, 0, 0)
tableView.scrollIndicatorInsets = UIEdgeInsetsMake(tableView.scrollIndicatorInsets.top, 0, 0, 0)
}
if let t = tabBar {
if animated {
UIView.animateWithDuration(0.2,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
t.transform = CGAffineTransformMakeTranslation(0, 49)
}, completion: { [weak self] finished in
t.removeFromSuperview()
self!.tabBar = nil
})
} else {
t.removeFromSuperview()
tabBar = nil
}
}
}
}
func localNotification(userInfo: [NSObject : AnyObject]) {
var urlToOpen = userInfo[NOTIFICATION_URL_KEY] as? String
var relatedItem: ListableItem?
if let commentId = DataManager.idForUriPath(userInfo[COMMENT_ID_KEY] as? String), c = existingObjectWithID(commentId) as? PRComment {
relatedItem = c.pullRequest ?? c.issue
if urlToOpen == nil {
urlToOpen = c.webUrl
}
} else if let pullRequestId = DataManager.idForUriPath(userInfo[PULL_REQUEST_ID_KEY] as? String) {
relatedItem = existingObjectWithID(pullRequestId) as? ListableItem
if relatedItem == nil {
showMessage("PR not found", "Could not locale the PR related to this notification")
} else if urlToOpen == nil {
urlToOpen = relatedItem!.webUrl
}
} else if let issueId = DataManager.idForUriPath(userInfo[ISSUE_ID_KEY] as? String) {
relatedItem = existingObjectWithID(issueId) as? ListableItem
if relatedItem == nil {
showMessage("Issue not found", "Could not locale the issue related to this notification")
} else if urlToOpen == nil {
urlToOpen = relatedItem!.webUrl
}
}
if urlToOpen != nil && !(searchField.text ?? "").isEmpty {
searchField.text = nil
searchField.resignFirstResponder()
reloadDataWithAnimation(false)
}
if let p = relatedItem as? PullRequest {
viewMode = MasterViewMode.PullRequests
detailViewController.catchupWithDataItemWhenLoaded = p.objectID
if let ip = fetchedResultsController.indexPathForObject(p) {
tableView.selectRowAtIndexPath(ip, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
}
} else if let i = relatedItem as? Issue {
viewMode = MasterViewMode.Issues
detailViewController.catchupWithDataItemWhenLoaded = i.objectID
if let ip = fetchedResultsController.indexPathForObject(i) {
tableView.selectRowAtIndexPath(ip, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
}
}
if let u = urlToOpen {
detailViewController.detailItem = NSURL(string: u)
if !detailViewController.isVisible {
showTabBar(false, animated: true)
showDetailViewController(detailViewController.navigationController!, sender: self)
}
}
}
func openPrWithId(prId: String) {
viewMode = MasterViewMode.PullRequests
if let
pullRequestId = DataManager.idForUriPath(prId),
pr = existingObjectWithID(pullRequestId) as? PullRequest,
ip = fetchedResultsController.indexPathForObject(pr)
{
pr.catchUpWithComments()
tableView.selectRowAtIndexPath(ip, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
tableView(tableView, didSelectRowAtIndexPath: ip)
}
}
func openIssueWithId(iId: String) {
viewMode = MasterViewMode.Issues
if let
issueId = DataManager.idForUriPath(iId),
issue = existingObjectWithID(issueId) as? Issue,
ip = fetchedResultsController.indexPathForObject(issue)
{
issue.catchUpWithComments()
tableView.selectRowAtIndexPath(ip, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
tableView(tableView, didSelectRowAtIndexPath: ip)
}
}
func openCommentWithId(cId: String) {
if let
itemId = DataManager.idForUriPath(cId),
comment = existingObjectWithID(itemId) as? PRComment
{
if let url = comment.webUrl {
var ip: NSIndexPath?
if let pr = comment.pullRequest {
viewMode = MasterViewMode.PullRequests
ip = fetchedResultsController.indexPathForObject(pr)
detailViewController.catchupWithDataItemWhenLoaded = nil
pr.catchUpWithComments()
} else if let issue = comment.issue {
viewMode = MasterViewMode.Issues
ip = fetchedResultsController.indexPathForObject(issue)
detailViewController.catchupWithDataItemWhenLoaded = nil
issue.catchUpWithComments()
}
if let i = ip {
tableView.selectRowAtIndexPath(i, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
detailViewController.detailItem = NSURL(string: url)
if !detailViewController.isVisible {
showTabBar(false, animated: true)
showDetailViewController(detailViewController.navigationController!, sender: self)
}
}
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
return cell
}
private var sizer: PRCell?
private var heightCache = [NSIndexPath : CGFloat]()
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if sizer == nil {
sizer = tableView.dequeueReusableCellWithIdentifier("Cell") as? PRCell
sizer?.forDisplay = false
} else if let h = heightCache[indexPath] {
//DLog("using cached height for %d - %d", indexPath.section, indexPath.row)
return h
}
configureCell(sizer!, atIndexPath: indexPath)
let h = sizer!.systemLayoutSizeFittingSize(CGSizeMake(tableView.bounds.width, UILayoutFittingCompressedSize.height),
withHorizontalFittingPriority: UILayoutPriorityRequired,
verticalFittingPriority: UILayoutPriorityFittingSizeLevel).height
heightCache[indexPath] = h
return h
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if viewMode == MasterViewMode.PullRequests, let
p = fetchedResultsController.objectAtIndexPath(indexPath) as? PullRequest,
u = p.urlForOpening(),
url = NSURL(string: u)
{
if openItem(p, url: url, oid: p.objectID) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} else if viewMode == MasterViewMode.Issues, let
i = fetchedResultsController.objectAtIndexPath(indexPath) as? Issue,
u = i.urlForOpening(),
url = NSURL(string: u)
{
if openItem(i, url: url, oid: i.objectID) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
private func openItem(item: ListableItem, url: NSURL, oid: NSManagedObjectID) -> Bool {
if Settings.openItemsDirectlyInSafari && !detailViewController.isVisible {
item.catchUpWithComments()
UIApplication.sharedApplication().openURL(url)
return true
} else {
detailViewController.detailItem = url
detailViewController.catchupWithDataItemWhenLoaded = oid
if !detailViewController.isVisible {
showTabBar(false, animated: true)
showDetailViewController(detailViewController.navigationController!, sender: self)
}
return false
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return fetchedResultsController.sections?[section].name ?? "Unknown Section"
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if let sectionName = fetchedResultsController.sections?[indexPath.section].name {
return sectionName == PullRequestSection.Merged.prMenuName() || sectionName == PullRequestSection.Closed.prMenuName()
} else {
return false
}
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let pr = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
mainObjectContext.deleteObject(pr)
DataManager.saveDB()
}
}
private var fetchedResultsController: NSFetchedResultsController {
if let c = _fetchedResultsController {
return c
}
var fetchRequest: NSFetchRequest
if viewMode == MasterViewMode.PullRequests {
fetchRequest = ListableItem.requestForItemsOfType("PullRequest", withFilter: searchField.text, sectionIndex: -1)
} else {
fetchRequest = ListableItem.requestForItemsOfType("Issue", withFilter: searchField.text, sectionIndex: -1)
}
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: mainObjectContext, sectionNameKeyPath: "sectionName", cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
try! aFetchedResultsController.performFetch()
return aFetchedResultsController
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
heightCache.removeAll()
switch(type) {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Automatic)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Automatic)
case .Update:
tableView.reloadSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Automatic)
default:
break
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
heightCache.removeAll()
switch(type) {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath ?? indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation:UITableViewRowAnimation.Automatic)
case .Update:
if let cell = tableView.cellForRowAtIndexPath(newIndexPath ?? indexPath!) {
configureCell(cell, atIndexPath: newIndexPath ?? indexPath!)
}
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation:UITableViewRowAnimation.Automatic)
if let n = newIndexPath {
tableView.insertRowsAtIndexPaths([n], withRowAnimation:UITableViewRowAnimation.Automatic)
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
updateStatus()
}
private func configureCell(cell: UITableViewCell, atIndexPath: NSIndexPath) {
let c = cell as! PRCell
//c._statuses.preferredMaxLayoutWidth = tableView.bounds.size.width - 20
//c._title.preferredMaxLayoutWidth = tableView.bounds.size.width - 20
//c._description.preferredMaxLayoutWidth = tableView.bounds.size.width - 80
let o = fetchedResultsController.objectAtIndexPath(atIndexPath)
if viewMode == MasterViewMode.PullRequests {
c.setPullRequest(o as! PullRequest)
} else {
c.setIssue(o as! Issue)
}
}
func updateStatus() {
let prUnreadCount = PullRequest.badgeCountInMoc(mainObjectContext)
pullRequestsItem.badgeValue = prUnreadCount > 0 ? "\(prUnreadCount)" : nil
let issuesUnreadCount = Issue.badgeCountInMoc(mainObjectContext)
issuesItem.badgeValue = issuesUnreadCount > 0 ? "\(issuesUnreadCount)" : nil
if app.isRefreshing {
title = "Refreshing..."
tableView.tableFooterView = EmptyView(message: DataManager.reasonForEmptyWithFilter(searchField.text), parentWidth: view.bounds.size.width)
if !(refreshControl?.refreshing ?? false) {
dispatch_async(dispatch_get_main_queue(), { [weak self] in
self!.refreshControl!.beginRefreshing()
})
}
} else {
let count = fetchedResultsController.fetchedObjects?.count ?? 0
if viewMode == MasterViewMode.PullRequests {
title = pullRequestsTitle(true)
tableView.tableFooterView = (count == 0) ? EmptyView(message: DataManager.reasonForEmptyWithFilter(searchField.text), parentWidth: view.bounds.size.width) : nil
} else {
title = issuesTitle()
tableView.tableFooterView = (count == 0) ? EmptyView(message: DataManager.reasonForEmptyIssuesWithFilter(searchField.text), parentWidth: view.bounds.size.width) : nil
}
dispatch_async(dispatch_get_main_queue(), { [weak self] in
self!.refreshControl!.endRefreshing()
})
}
refreshControl?.attributedTitle = NSAttributedString(string: api.lastUpdateDescription(), attributes: nil)
app.updateBadge()
if splitViewController?.displayMode != UISplitViewControllerDisplayMode.AllVisible {
detailViewController.navigationItem.leftBarButtonItem?.title = title
}
tabBar?.selectedItem = (viewMode==MasterViewMode.PullRequests) ? pullRequestsItem : issuesItem
}
private func unreadCommentCount(count: Int) -> String {
return count == 0 ? "" : count == 1 ? " (1 new comment)" : " (\(count) new comments)"
}
private func pullRequestsTitle(long: Bool) -> String {
let f = ListableItem.requestForItemsOfType("PullRequest", withFilter: nil, sectionIndex: -1)
let count = mainObjectContext.countForFetchRequest(f, error: nil)
let unreadCount = pullRequestsItem.badgeValue?.toInt() ?? 0
let pr = long ? "Pull Request" : "PR"
if count == 0 {
return "No \(pr)s"
} else if count == 1 {
return "1 " + (unreadCount > 0 ? "PR\(unreadCommentCount(unreadCount))" : pr)
} else {
return "\(count) " + (unreadCount > 0 ? "PRs\(unreadCommentCount(unreadCount))" : pr + "s")
}
}
private func issuesTitle() -> String {
let f = ListableItem.requestForItemsOfType("Issue", withFilter: nil, sectionIndex: -1)
let count = mainObjectContext.countForFetchRequest(f, error: nil)
let unreadCount = issuesItem.badgeValue?.toInt() ?? 0
if count == 0 {
return "No Issues"
} else if count == 1 {
return "1 Issue\(unreadCommentCount(unreadCount))"
} else {
return "\(count) Issues\(unreadCommentCount(unreadCount))"
}
}
///////////////////////////// filtering
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
if searchField.isFirstResponder() {
searchField.resignFirstResponder()
}
}
func textFieldShouldClear(textField: UITextField) -> Bool {
searchTimer!.push()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string == "\n" {
textField.resignFirstResponder()
} else {
searchTimer!.push()
}
return true
}
////////////////// mode
func showPullRequestsSelected(sender: AnyObject) {
viewMode = MasterViewMode.PullRequests
}
func showIssuesSelected(sender: AnyObject) {
viewMode = MasterViewMode.Issues
}
private var _viewMode: MasterViewMode = .PullRequests
var viewMode: MasterViewMode {
set {
if newValue != _viewMode {
_viewMode = newValue
_fetchedResultsController = nil
heightCache.removeAll()
tableView.reloadData()
tableView.scrollRectToVisible(CGRectMake(0, tableView.tableHeaderView?.frame.size.height ?? tableView.contentInset.top, 1, 1), animated: false)
updateStatus()
}
}
get {
return _viewMode
}
}
////////////////// opening prefs
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var allServersHaveTokens = true
for a in ApiServer.allApiServersInMoc(mainObjectContext) {
if !a.goodToGo {
allServersHaveTokens = false
break
}
}
if let destination = segue.destinationViewController as? UITabBarController {
if allServersHaveTokens {
destination.selectedIndex = min(Settings.lastPreferencesTabSelected, (destination.viewControllers?.count ?? 1)-1)
destination.delegate = self
}
}
}
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
Settings.lastPreferencesTabSelected = indexOfObject(tabBarController.viewControllers!, value: viewController) ?? 0
}
}
| mit | 47164d560a2123b5cc7c6f2237fd331e | 34.678331 | 208 | 0.748915 | 4.31813 | false | false | false | false |
maurovc/MyMarvel | MyMarvel/StringUtils.swift | 1 | 865 | //
// StringUtils.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 25/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import Foundation
//MARK: Extension from String that adds the needed functionalities.
extension String {
func urlWithParameters(parameters: [String : String]?) -> String? {
guard let parameters = parameters else {
return nil
}
var first = true
var url = self
for parameter in parameters.keys {
if let value = parameters[parameter] {
url += (first ? "?" : "&") + "\(parameter)=\(value)"
first = false
}
}
return url
}
func httpsVersion() -> String? {
return stringByReplacingOccurrencesOfString("http", withString: "https")
}
} | mit | 1830adc94ba0a0666c08041e7c63d75e | 23.714286 | 80 | 0.560185 | 4.8 | false | false | false | false |
AndrewBarba/AsyncSwift | Async/Future.swift | 1 | 2459 | //
// Future.swift
// Async
//
// Created by Andrew Barba on 6/9/14.
// Copyright (c) 2014 Andrew Barba. All rights reserved.
//
import Foundation
enum FutureState {
case Pending, Operating, Complete
}
class Future<SuccessType, ErrorType> {
var state = FutureState.Pending
// results
// this is fucking dumb, workaround until swift fixes their shit
var __result: SuccessType?[] = []
var _result: SuccessType? {
get {
return __result.count > 0 ? __result[0] : nil
}
set(val) {
if __result.count > 0 {
__result[0] = val
} else {
__result += val
}
}
}
// errors
// this is fucking dumb, workaround until swift fixes their shit
var __error: ErrorType?[] = []
var _error: ErrorType? {
get {
return __error.count > 0 ? __error[0] : nil
}
set(val) {
if __error.count > 0 {
__error[0] = val
} else {
__error += val
}
}
}
// callbacks
var _onSuccess: (SuccessType -> ())[] = []
var _onError: (ErrorType -> ())[] = []
init() {
// override
}
func success(onSuccess: SuccessType -> ()) -> Future<SuccessType, ErrorType> {
if state == .Complete {
if let res = _result {
onSuccess(res)
}
} else {
_onSuccess += onSuccess
}
return self
}
func error(onError: ErrorType -> ()) -> Future<SuccessType, ErrorType> {
if state == .Complete {
if let err = _error {
onError(err)
}
} else {
_onError += onError
}
return self
}
func finish(result: SuccessType?, error: ErrorType?) {
_result = result
_error = error
_notify()
state = .Complete
_clean()
}
func operate() {
state = .Operating
}
func _notify() {
if let err = _error {
for block in _onError {
block(err)
}
} else if let res = _result {
for block in _onSuccess {
block(res)
}
}
}
func _clean() {
_onSuccess = []
_onError = []
_result = nil
_error = nil
}
}
| mit | 3d936c595ed139ce1fbcaf069cebc7cc | 20.955357 | 82 | 0.442863 | 4.383244 | false | false | false | false |
ccwuzhou/WWZSwift | Source/Views/WWZInputView.swift | 1 | 4635 |
//
// WWZInputView.swift
// wwz_swift
//
// Created by wwz on 17/3/3.
// Copyright © 2017年 tijio. All rights reserved.
//
import UIKit
fileprivate let INPUT_LINE_COLOR = UIColor.colorFromRGBA(204, 204, 204, 1)
fileprivate let INPUT_BUTTON_TAG = 99
fileprivate let INPUT_BUTTON_HEIGHT : CGFloat = 45.0
open class WWZInputView: WWZShowView {
// MARK: -私有属性
fileprivate var block : ((String, Int)->())?
fileprivate lazy var inputTextField : UITextField = {
let textFieldX : CGFloat = 20.0
let textField = UITextField(frame: CGRect(x: textFieldX, y: 0, width: self.width-textFieldX*2, height: 40), placeholder: nil, font: UIFont.systemFont(ofSize: 14))
textField.delegate = self
return textField
}()
public init(title: String, text: String?, placeHolder: String?, buttonTitles: [String], clickButtonAtIndex block: @escaping (_ inputText: String,_ index: Int)->()) {
let inputViewW : CGFloat = WWZ_IsPad ? 425 : WWZ_SCREEN_WIDTH * 250.0/320.0
let inputViewH : CGFloat = WWZ_IsPad ? 183 : 150
super.init(frame: CGRect(x: (WWZ_SCREEN_WIDTH-inputViewW)*0.5, y: WWZ_SCREEN_HEIGHT*0.25, width: inputViewW, height: inputViewH))
guard buttonTitles.count != 2 else {
return
}
self.backgroundColor = UIColor.white
self.block = block
self.layer.wwz_setCorner(radius: 15)
let spaceY : CGFloat = WWZ_IsPad ? 20 : 15
// title label
let titleLabel = UILabel(text: title, font: UIFont.boldSystemFont(ofSize: 20), tColor: UIColor.black, alignment: .center, numberOfLines: 1)
titleLabel.y = spaceY
titleLabel.x = (self.width-titleLabel.width)*0.5
self.addSubview(titleLabel)
// textField
self.inputTextField.y = titleLabel.bottom + spaceY
self.inputTextField.placeholder = placeHolder
self.inputTextField.text = text
self.addSubview(self.inputTextField)
// buttons
self.p_addBottomButtons(buttonTitles: buttonTitles)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WWZInputView : UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension WWZInputView {
// MARK: -添加按钮
fileprivate func p_addBottomButtons(buttonTitles: [String]) {
for buttonTitle in buttonTitles {
let index = buttonTitles.index(of: buttonTitle)!
let rect = CGRect(x: 0+CGFloat(index)*self.width/CGFloat(buttonTitles.count), y: self.height-INPUT_BUTTON_HEIGHT, width: self.width/CGFloat(buttonTitles.count), height: INPUT_BUTTON_HEIGHT)
self.addSubview(self.p_bottomButton(frame: rect, title: buttonTitle, tag: index))
if index == 1 {
let lineView = UIView(frame: CGRect(x: self.width*0.5-0.25, y: self.height-INPUT_BUTTON_HEIGHT, width: 0.5, height: INPUT_BUTTON_HEIGHT), backgroundColor: INPUT_LINE_COLOR)
self.addSubview(lineView)
}
}
}
fileprivate func p_bottomButton(frame: CGRect, title: String, tag: Int) -> UIButton {
let btn = UIButton(frame: frame, nTitle: title, titleFont: UIFont.systemFont(ofSize: 16), nColor: UIColor.black)
btn.setBackgroundImage(UIImage.wwz_image(color: INPUT_LINE_COLOR, size: frame.size), for: .highlighted)
btn.tag = INPUT_BUTTON_TAG + tag
btn.addTarget(self, action: #selector(self.clickButtonAtIndex), for: .touchUpInside)
let lineView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 0.5), backgroundColor: INPUT_LINE_COLOR)
btn.addSubview(lineView)
return btn
}
@objc private func clickButtonAtIndex(sender: UIButton) {
self.block?(self.inputTextField.text ?? "", sender.tag - INPUT_BUTTON_TAG)
self.wwz_dismiss(completion: nil)
}
public override func wwz_show(completion: ((Bool) -> ())?) {
self.inputTextField.becomeFirstResponder()
super.wwz_show(completion: completion)
}
public override func wwz_dismiss(completion: ((Bool) -> ())?) {
self.inputTextField.resignFirstResponder()
super.wwz_dismiss(completion: completion)
}
}
| mit | 1362a022ef6f7236acfaf8c30006eb6f | 34.236641 | 201 | 0.621534 | 4.278035 | false | false | false | false |
FlaneurApp/FlaneurOpen | Sources/Classes/Form Tools/FlaneurFormElementCollectionViewCell.swift | 1 | 1587 | //
// FlaneurFormElementCollectionViewCell.swift
// FlaneurOpen
//
// Created by Mickaël Floc'hlay on 28/09/2017.
//
import UIKit
public protocol FlaneurFormElementCollectionViewCellDelegate: AnyObject {
func nextElementShouldBecomeFirstResponder(cell: FlaneurFormElementCollectionViewCell)
func scrollToVisibleSection(cell: FlaneurFormElementCollectionViewCell)
func presentViewController(viewController: UIViewController)
func cacheValue(forLabel: String) -> String?
}
public class FlaneurFormElementCollectionViewCell: UICollectionViewCell {
let label = UILabel()
public weak var delegate: FlaneurFormElementCollectionViewCellDelegate? = nil
override init(frame: CGRect) {
super.init(frame: frame)
label.font = FlaneurOpenThemeManager.shared.theme.formLabelsFont
label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
_ = LayoutBorderManager(item: label,
toItem: self,
top: 12.0,
left: 16.0,
right: 16.0)
_ = createBottomBorder()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureWith(formElement: FlaneurFormElement) {
label.text = formElement.label
}
}
extension UITextField {
func flaneurFormStyle() {
self.font = FlaneurOpenThemeManager.shared.theme.formTextFieldFont
self.borderStyle = .none
}
}
| mit | 558e2854a8875e7515bf63b499377a3f | 30.098039 | 90 | 0.677175 | 5.116129 | false | false | false | false |
nkirby/Humber | Humber/_src/View Controller/Overview/OverviewViewController.swift | 1 | 10127 | // =======================================================
// Humber
// Nathaniel Kirby
// =======================================================
import UIKit
import Async
import SafariServices
import HMCore
import HMGithub
private let reuseIdentifier = "Cell"
// =======================================================
class OverviewViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, NavigationBarUpdating, UIViewControllerPreviewingDelegate {
private var overviewItems = [GithubOverviewItemModel]()
private var viewControllers = [OverviewItemSingleStatViewController]()
// =======================================================
// MARK: - Init, etc...
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.navigationController?.tabBarItem.imageInsets = UIEdgeInsets(top: 4.0, left: 0.0, bottom: -4.0, right: 0.0)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// =======================================================
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupCollectionView()
self.setupNavigationBarStyling()
self.setupNavigationItemTitle()
self.setupBarButtonItems()
self.fetch()
if let notifName = ServiceController.component(GithubOverviewSyncProviding.self)?.didChangeOverviewNotification {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OverviewViewController.fetch), name: notifName, object: nil)
}
if self.traitCollection.forceTouchCapability == .Available {
self.registerForPreviewingWithDelegate(self, sourceView: self.view)
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OverviewViewController.didChangeTheme), name: Theme.themeChangedNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.sync()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
Async.main {
self.collectionView?.reloadData()
}
}
// =======================================================
// MARK: - Setup
private func setupCollectionView() {
self.collectionView?.contentInset = UIEdgeInsets(top: 20.0, left: 0.0, bottom: 20.0, right: 0.0)
self.collectionView?.registerClass(OverviewDividerCollectionCell.self, forCellWithReuseIdentifier: "OverviewDividerCollectionCell")
self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView?.registerClass(OverviewStatItemCollectionCell.self, forCellWithReuseIdentifier: "OverviewStatItemCollectionCell")
self.collectionView?.backgroundColor = Theme.color(type: .ViewBackgroundColor)
self.collectionView?.alwaysBounceVertical = true
// self.collectionView?.alwaysBounceHorizontal = true
}
private func setupNavigationItemTitle() {
self.navigationItem.title = "Overview"
}
private func setupBarButtonItems() {
let barButtonItem = UIBarButtonItem(title: "Edit", style: .Done, target: self, action: #selector(OverviewViewController.didTapEdit))
self.navigationItem.rightBarButtonItem = barButtonItem
}
@objc private func didChangeTheme() {
self.collectionView?.backgroundColor = Theme.color(type: .ViewBackgroundColor)
self.setupNavigationBarStyling()
}
// =======================================================
// MARK: - Data Lifecycle
@objc private func fetch() {
Async.main {
if let items = ServiceController.component(GithubOverviewDataProviding.self)?.sortedOverviewItems() {
self.overviewItems = items
var currentVCs = [OverviewItemSingleStatViewController]()
for item in items {
if item.type != "divider" {
if let vc = self.viewController(model: item) {
if !currentVCs.contains(vc) {
currentVCs.append(vc)
}
} else {
let vc = OverviewItemSingleStatViewController()
vc.itemModel = item
currentVCs.append(vc)
}
}
}
self.viewControllers = currentVCs
self.collectionView?.reloadData()
}
}
}
private func sync() {
self.viewControllers.forEach { $0.sync() }
}
// =======================================================
// MARK: - View Controllers
private func viewController(model model: GithubOverviewItemModel) -> OverviewItemSingleStatViewController? {
return self.viewControllers.filter { $0.itemModel?.itemID == model.itemID }.first
}
// =======================================================
// MARK: - Actions
@objc private func didTapEdit() {
Router.route(path: GithubRoutes.editOverview, source: .UserInitiated)
}
// =======================================================
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.overviewItems.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let feedItem = self.overviewItems.get(indexPath.row) else {
return CGSize(width: 1, height: 1)
}
switch feedItem.type {
case "divider":
return CGSize(width: collectionView.frame.size.width, height: 32.0)
case "stats":
return CGSize(width: collectionView.frame.size.width / 2.0, height: collectionView.frame.size.width / 2.0)
default:
break
}
return CGSize(width: collectionView.frame.size.width, height: 140.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return CGFloat.min
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return CGFloat.min
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let feedItem = self.overviewItems.get(indexPath.row) else {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
return cell
}
switch feedItem.type {
case "divider":
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("OverviewDividerCollectionCell", forIndexPath: indexPath) as! OverviewDividerCollectionCell
cell.render(model: feedItem)
return cell
case "stats":
if let vc = self.viewController(model: feedItem) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("OverviewStatItemCollectionCell", forIndexPath: indexPath) as! OverviewStatItemCollectionCell
cell.render(viewController: vc)
return cell
}
default:
break
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let feedItem = self.overviewItems.get(indexPath.row) else {
return
}
switch feedItem.type {
case "stats":
if let url = NSURL(string: "https://github.com/\(feedItem.repoOwner)/\(feedItem.repoName)/\(feedItem.action)") {
let sfvc = SFSafariViewController(URL: url)
sfvc.modalPresentationStyle = .FormSheet
self.navigationController?.presentViewController(sfvc, animated: true, completion: nil)
}
default:
break
}
}
// =======================================================
// MARK: - Force Touch
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = self.collectionView?.indexPathForItemAtPoint(location),
let feedItem = self.overviewItems.get(indexPath.row) else {
return nil
}
if let url = NSURL(string: "https://github.com/\(feedItem.repoOwner)/\(feedItem.repoName)/\(feedItem.action)") {
let sfvc = SFSafariViewController(URL: url)
sfvc.modalPresentationStyle = .FormSheet
return sfvc
}
return nil
}
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
self.navigationController?.presentViewController(viewControllerToCommit, animated: true, completion: nil)
}
}
| mit | 1fe8c8ff1fb2b73e38eb6dc7f69c3aba | 37.95 | 178 | 0.603733 | 6.122733 | false | false | false | false |
zl00/CocoaMQTT | Source/CocoaMQTT.swift | 1 | 30780 | //
// CocoaMQTT.swift
// CocoaMQTT
//
// Created by Feng Lee<[email protected]> on 14/8/3.
// Copyright (c) 2015 emqtt.io. All rights reserved.
//
import Foundation
import CocoaAsyncSocket
import SwiftyTimer
/**
* QOS
*/
@objc public enum CocoaMQTTQOS: UInt8 {
case qos0 = 0
case qos1
case qos2
}
/**
* Connection State
*/
@objc public enum CocoaMQTTConnState: UInt8 {
case initial = 0
case connecting
case connected
case disconnected
}
/**
* Conn Ack
*/
@objc public enum CocoaMQTTConnAck: UInt8 {
case accept = 0
case unacceptableProtocolVersion
case identifierRejected
case serverUnavailable
case badUsernameOrPassword
case notAuthorized
case reserved
}
/**
* asyncsocket read tag
*/
fileprivate enum CocoaMQTTReadTag: Int {
case header = 0
case length
case payload
}
/**
* MQTT log delegate
*/
@objc public protocol CocoaMqttLogProtocol: NSObjectProtocol {
var minLevel: CocoaMQTTLoggerLevel { get }
func log(level: CocoaMQTTLoggerLevel, message: String)
}
/**
* MQTT Delegate
*/
@objc public protocol CocoaMQTTDelegate: CocoaMqttLogProtocol {
func mqtt(_ mqtt: CocoaMQTT, didConnect host: String, port: Int)
func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck)
func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16)
func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16)
func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 )
func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topic: String)
func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String)
func mqttDidPing(_ mqtt: CocoaMQTT)
func mqttDidReceivePong(_ mqtt: CocoaMQTT)
func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?)
var minLevel: CocoaMQTTLoggerLevel { get }
func log(level: CocoaMQTTLoggerLevel, message: String)
@objc optional func mqtt(_ mqtt: CocoaMQTT, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void)
@objc optional func mqtt(_ mqtt: CocoaMQTT, didPublishComplete id: UInt16)
}
/**
* Blueprint of the MQTT client
*/
internal protocol CocoaMQTTClient {
var host: String { get set }
var port: UInt16 { get set }
var clientID: String { get }
var username: String? { get set }
var password: String? { get set }
var cleanSession: Bool { get set }
var keepAlive: UInt16 { get set }
var willMessage: CocoaMQTTWill? { get set }
var presence: UInt8 { get set }
func connect() -> Bool
func disconnect()
func ping()
func subscribe(_ topic: String, qos: CocoaMQTTQOS) -> UInt16
func unsubscribe(_ topic: String) -> UInt16
func publish(_ topic: String, withString string: String, qos: CocoaMQTTQOS, retained: Bool, dup: Bool) -> UInt16
func publish(_ message: CocoaMQTTMessage) -> UInt16
}
/**
* MQTT Reader Delegate
*/
internal protocol CocoaMQTTReaderDelegate {
func didReceiveConnAck(_ reader: CocoaMQTTReader, connack: UInt8)
func didReceivePublish(_ reader: CocoaMQTTReader, message: CocoaMQTTMessage, id: UInt16)
func didReceivePubAck(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubRec(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubRel(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePubComp(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceiveSubAck(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceiveUnsubAck(_ reader: CocoaMQTTReader, msgid: UInt16)
func didReceivePong(_ reader: CocoaMQTTReader)
}
/**
* Heart Beats Protocol
*/
internal protocol PingPongProtocol: NSObjectProtocol {
func ping()
func pongDidTimeOut()
}
extension Int {
var MB: Int {
return self * 1024 * 1024
}
}
/**
* Main CocoaMQTT Class
*
* Notice: GCDAsyncSocket need delegate to extend NSObject
*/
public class CocoaMQTT: NSObject, CocoaMQTTClient, CocoaMQTTFrameBufferProtocol {
public var host = "localhost"
public var port: UInt16 = 1883
public var clientID: String
public var username: String?
public var password: String?
public var secureMQTT = false
public var cleanSession = true
public var willMessage: CocoaMQTTWill?
public var presence: UInt8 = 1
public weak var delegate: CocoaMQTTDelegate? {
didSet { CocoaMQTTLogger.shared.delegate = delegate }
}
public var backgroundOnSocket = false
public fileprivate(set) var connState = CocoaMQTTConnState.initial
public var dispatchQueue = DispatchQueue.main
// flow control
var buffer = CocoaMQTTFrameBuffer()
// heart beat
public var keepAlive: UInt16 = 60 {
didSet { pingpong = PingPong(keepAlive: Double(keepAlive / 2 + 1).seconds, delegate: self) }
}
fileprivate var pingpong: PingPong?
// auto reconnect
public var retrySetting: (retry: Bool, maxCount: UInt, step: TimeInterval, fusingDepth: UInt, fusingDuration: TimeInterval) = (true, 10, 1.2, 60, 60) {
didSet {
retry = Retry(retry: retrySetting.retry, maxRetryCount: retrySetting.maxCount, step: retrySetting.step, fusingDepth: retrySetting.fusingDepth, fusingDuration: retrySetting.fusingDuration)
}
}
public var retrying: Bool { return retry.retrying }
fileprivate var retry: Retry
fileprivate var disconnectExpectedly = false
// ssl
public var enableSSL = false
public var sslSettings: [String: NSObject]?
public var allowUntrustCACertificate = false
// subscribed topics. (dictionary structure -> [msgid: [topicString: QoS]])
var subscriptions: [UInt16: [String: CocoaMQTTQOS]] = [:]
var subscriptionsWaitingAck: [UInt16: [String: CocoaMQTTQOS]] = [:]
var unsubscriptionsWaitingAck: [UInt16: [String: CocoaMQTTQOS]] = [:]
// global message id
var gmid: UInt16 = 1
var socket = GCDAsyncSocket()
fileprivate var reader: CocoaMQTTReader?
// MARK: init
public init(clientID: String, host: String = "localhost", port: UInt16 = 1883) {
self.clientID = clientID
self.host = host
self.port = port
retry = Retry(retry: retrySetting.retry, maxRetryCount: retrySetting.maxCount, step: retrySetting.step, fusingDepth: retrySetting.fusingDepth, fusingDuration: retrySetting.fusingDuration)
super.init()
buffer.delegate = self
printNotice("init")
}
deinit {
printNotice("deinit")
pingpong?.reset()
retry.reset()
socket.delegate = nil
socket.disconnect()
}
internal func buffer(_ buffer: CocoaMQTTFrameBuffer, sendPublishFrame frame: CocoaMQTTFramePublish) {
send(frame, tag: Int(frame.msgid!))
}
fileprivate func send(_ frame: CocoaMQTTFrame, tag: Int = 0) {
let data = frame.data()
socket.write(Data(bytes: data, count: data.count), withTimeout: -1, tag: tag)
}
fileprivate func sendConnectFrame() {
let frame = CocoaMQTTFrameConnect(client: self)
send(frame)
reader!.start()
delegate?.mqtt(self, didConnect: host, port: Int(port))
}
fileprivate func nextMessageID() -> UInt16 {
if gmid == UInt16.max {
gmid = 0
}
gmid += 1
return gmid
}
fileprivate func puback(_ type: CocoaMQTTFrameType, msgid: UInt16) {
var descr: String?
switch type {
case .puback:
descr = "PUBACK"
case .pubrec:
descr = "PUBREC"
case .pubrel:
descr = "PUBREL"
case .pubcomp:
descr = "PUBCOMP"
default: break
}
if descr != nil {
printDebug("Send \(descr!), msgid: \(msgid)")
}
send(CocoaMQTTFramePubAck(type: type, msgid: msgid))
}
@discardableResult
public func connect() -> Bool {
printNotice("connect")
retry.reset()
retry.resetFusing()
pingpong?.reset()
return internal_connect()
}
@discardableResult
public func internal_connect() -> Bool {
printNotice("internal_connect")
socket.delegate = nil
socket = GCDAsyncSocket()
socket.setDelegate(self, delegateQueue: dispatchQueue)
reader = CocoaMQTTReader(socket: socket, delegate: self)
do {
try socket.connect(toHost: self.host, onPort: self.port)
connState = .connecting
return true
} catch let error as NSError {
printError("socket connect error: \(error.description)")
return false
}
}
/// Only can be called from outside. If you want to disconnect from inside framwork, call internal_disconnect()
/// disconnect expectedly
public func disconnect() {
printNotice("disconnect")
disconnectExpectedly = true
internal_disconnect()
}
/// disconnect unexpectedly
public func internal_disconnect() {
printNotice("internal_disconnect")
send(CocoaMQTTFrame(type: CocoaMQTTFrameType.disconnect), tag: -0xE0)
socket.disconnect()
}
public func ping() {
printDebug("Ping")
send(CocoaMQTTFrame(type: CocoaMQTTFrameType.pingreq, payload: [self.presence]), tag: -0xC0)
self.delegate?.mqttDidPing(self)
}
@discardableResult
public func publish(_ topic: String, withString string: String, qos: CocoaMQTTQOS = .qos1, retained: Bool = false, dup: Bool = false) -> UInt16 {
let message = CocoaMQTTMessage(topic: topic, string: string, qos: qos, retained: retained, dup: dup)
return publish(message)
}
@discardableResult
public func publish(_ message: CocoaMQTTMessage) -> UInt16 {
let msgid: UInt16 = nextMessageID()
let frame = CocoaMQTTFramePublish(msgid: msgid, topic: message.topic, payload: message.payload)
frame.qos = message.qos.rawValue
frame.retained = message.retained
frame.dup = message.dup
// send(frame, tag: Int(msgid))
_ = buffer.add(frame)
if message.qos != CocoaMQTTQOS.qos0 {
}
delegate?.mqtt(self, didPublishMessage: message, id: msgid)
return msgid
}
@discardableResult
public func subscribe(_ topic: String, qos: CocoaMQTTQOS = .qos1) -> UInt16 {
let msgid = nextMessageID()
let frame = CocoaMQTTFrameSubscribe(msgid: msgid, topic: topic, reqos: qos.rawValue)
send(frame, tag: Int(msgid))
subscriptionsWaitingAck[msgid] = [topic:qos]
return msgid
}
@discardableResult
public func unsubscribe(_ topic: String) -> UInt16 {
let msgid = nextMessageID()
let frame = CocoaMQTTFrameUnsubscribe(msgid: msgid, topic: topic)
unsubscriptionsWaitingAck[msgid] = [topic:CocoaMQTTQOS.qos0]
send(frame, tag: Int(msgid))
return msgid
}
}
// MARK: - GCDAsyncSocketDelegate
extension CocoaMQTT: GCDAsyncSocketDelegate {
public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
printNotice("AsyncSock connected to \(host) : \(port)")
#if TARGET_OS_IPHONE
if backgroundOnSocket {
sock.performBlock { sock.enableBackgroundingOnSocket() }
}
#endif
if enableSSL {
if sslSettings == nil {
if allowUntrustCACertificate {
sock.startTLS([GCDAsyncSocketManuallyEvaluateTrust: true as NSObject]) }
else {
sock.startTLS(nil)
}
} else {
sslSettings![GCDAsyncSocketManuallyEvaluateTrust as String] = NSNumber(value: true)
sock.startTLS(sslSettings!)
}
} else {
sendConnectFrame()
}
}
public func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Swift.Void) {
printNotice("AsyncSock didReceiveTrust")
delegate?.mqtt!(self, didReceive: trust, completionHandler: completionHandler)
}
public func socketDidSecure(_ sock: GCDAsyncSocket) {
printNotice("AsyncSock socketDidSecure")
sendConnectFrame()
}
public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
printDebug("AsyncSock Socket write message with tag: \(tag)")
}
public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
let etag = CocoaMQTTReadTag(rawValue: tag)!
var bytes = [UInt8]([0])
switch etag {
case CocoaMQTTReadTag.header:
data.copyBytes(to: &bytes, count: 1)
reader!.headerReady(bytes[0])
case CocoaMQTTReadTag.length:
data.copyBytes(to: &bytes, count: 1)
reader!.lengthReady(bytes[0])
case CocoaMQTTReadTag.payload:
reader!.payloadReady(data)
}
}
public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
printNotice("AsyncSock didDisconnect. Error: \(String(describing: err))")
DispatchQueue.main.async { [weak self] in
guard let `self` = self else { return }
guard self.disconnectExpectedly == false else { self.retry.reset(); return }
self.retry.start(success: {
self.handleDisconnect(with: err)
self.internal_connect()
}, failure: { (error) in
self.handleDisconnect(with: error)
})
}
}
private func handleDisconnect(with error: Error?) {
pingpong?.reset()
connState = .disconnected
delegate?.mqttDidDisconnect(self, withError: error)
}
}
// MARK: - CocoaMQTTReaderDelegate
extension CocoaMQTT: CocoaMQTTReaderDelegate {
internal func didReceiveConnAck(_ reader: CocoaMQTTReader, connack: UInt8) {
printNotice("Reader CONNACK Received: \(connack)")
let ack: CocoaMQTTConnAck
switch connack {
case 0:
ack = .accept
connState = .connected
case 1...5:
ack = CocoaMQTTConnAck(rawValue: connack)!
internal_disconnect()
case _ where connack > 5:
ack = .reserved
internal_disconnect()
default:
internal_disconnect()
return
}
delegate?.mqtt(self, didConnectAck: ack)
if ack == .accept {
DispatchQueue.main.async { [weak self] in
self?.retry.reset()
self?.pingpong?.start()
}
disconnectExpectedly = false
} else {
pingpong?.reset()
}
}
internal func didReceivePublish(_ reader: CocoaMQTTReader, message: CocoaMQTTMessage, id: UInt16) {
printDebug("Reader PUBLISH Received from \(message.topic)")
delegate?.mqtt(self, didReceiveMessage: message, id: id)
switch message.qos {
case .qos1: puback(CocoaMQTTFrameType.puback, msgid: id)
case .qos2: puback(CocoaMQTTFrameType.pubrec, msgid: id)
case .qos0: return
}
}
internal func didReceivePubAck(_ reader: CocoaMQTTReader, msgid: UInt16) {
printDebug("Reader PUBACK Received: \(msgid)")
buffer.sendSuccess(withMsgid: msgid)
delegate?.mqtt(self, didPublishAck: msgid)
}
internal func didReceivePubRec(_ reader: CocoaMQTTReader, msgid: UInt16) {
printDebug("Reader PUBREC Received: \(msgid)")
puback(CocoaMQTTFrameType.pubrel, msgid: msgid)
}
internal func didReceivePubRel(_ reader: CocoaMQTTReader, msgid: UInt16) {
printDebug("Reader PUBREL Received: \(msgid)")
puback(CocoaMQTTFrameType.pubcomp, msgid: msgid)
}
internal func didReceivePubComp(_ reader: CocoaMQTTReader, msgid: UInt16) {
printDebug("Reader PUBCOMP Received: \(msgid)")
buffer.sendSuccess(withMsgid: msgid)
delegate?.mqtt?(self, didPublishComplete: msgid)
}
internal func didReceiveSubAck(_ reader: CocoaMQTTReader, msgid: UInt16) {
if let topicDict = subscriptionsWaitingAck.removeValue(forKey: msgid) {
let topic = topicDict.first!.key
// remove subscription with same topic
for (key, value) in subscriptions {
if value.first!.key == topic {
subscriptions.removeValue(forKey: key)
}
}
subscriptions[msgid] = topicDict
printDebug("SUBACK Received: \(topic)")
delegate?.mqtt(self, didSubscribeTopic: topic)
} else {
printWarning("UNEXPECT SUBACK Received: \(msgid)")
}
}
internal func didReceiveUnsubAck(_ reader: CocoaMQTTReader, msgid: UInt16) {
if let topicDict = unsubscriptionsWaitingAck.removeValue(forKey: msgid) {
let topic = topicDict.first!.key
for (key, value) in subscriptions {
if value.first!.key == topic {
subscriptions.removeValue(forKey: key)
}
}
printDebug("UNSUBACK Received: \(topic)")
delegate?.mqtt(self, didUnsubscribeTopic: topic)
} else {
printWarning("UNEXPECT UNSUBACK Received: \(msgid)")
}
}
internal func didReceivePong(_ reader: CocoaMQTTReader) {
printDebug("PONG Received")
pingpong?.pongTime = Date()
delegate?.mqttDidReceivePong(self)
}
}
// MARK: - PingPongProtocol
extension CocoaMQTT: PingPongProtocol {
func pongDidTimeOut() {
printError("Pong timeout!")
internal_disconnect()
}
}
// MAR: - CocoaMQTTReader
internal class CocoaMQTTReader {
private var socket: GCDAsyncSocket
private var header: UInt8 = 0
private var length: UInt = 0
private var data: [UInt8] = []
private var multiply = 1
private var delegate: CocoaMQTTReaderDelegate
private var timeout = 30000
init(socket: GCDAsyncSocket, delegate: CocoaMQTTReaderDelegate) {
self.socket = socket
self.delegate = delegate
}
func start() {
readHeader()
}
func headerReady(_ header: UInt8) {
printDebug("reader header ready: \(header) ")
self.header = header
readLength()
}
func lengthReady(_ byte: UInt8) {
length += (UInt)((Int)(byte & 127) * multiply)
// done
if byte & 0x80 == 0 {
if length == 0 {
frameReady()
} else {
readPayload()
}
// more
} else {
multiply *= 128
readLength()
}
}
func payloadReady(_ data: Data) {
self.data = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &(self.data), count: data.count)
frameReady()
}
private func readHeader() {
reset()
socket.readData(toLength: 1, withTimeout: -1, tag: CocoaMQTTReadTag.header.rawValue)
}
private func readLength() {
socket.readData(toLength: 1, withTimeout: TimeInterval(timeout), tag: CocoaMQTTReadTag.length.rawValue)
}
private func readPayload() {
socket.readData(toLength: length, withTimeout: TimeInterval(timeout), tag: CocoaMQTTReadTag.payload.rawValue)
}
private func frameReady() {
// handle frame
let frameType = CocoaMQTTFrameType(rawValue: UInt8(header & 0xF0))!
switch frameType {
case .connack:
delegate.didReceiveConnAck(self, connack: data[1])
case .publish:
let (msgid, message) = unpackPublish()
if message != nil {
delegate.didReceivePublish(self, message: message!, id: msgid)
}
case .puback:
delegate.didReceivePubAck(self, msgid: msgid(data))
case .pubrec:
delegate.didReceivePubRec(self, msgid: msgid(data))
case .pubrel:
delegate.didReceivePubRel(self, msgid: msgid(data))
case .pubcomp:
delegate.didReceivePubComp(self, msgid: msgid(data))
case .suback:
delegate.didReceiveSubAck(self, msgid: msgid(data))
case .unsuback:
delegate.didReceiveUnsubAck(self, msgid: msgid(data))
case .pingresp:
delegate.didReceivePong(self)
default:
break
}
readHeader()
}
private func unpackPublish() -> (UInt16, CocoaMQTTMessage?) {
let frame = CocoaMQTTFramePublish(header: header, data: data)
frame.unpack()
// if unpack fail
if frame.msgid == nil {
return (0, nil)
}
let msgid = frame.msgid!
let qos = CocoaMQTTQOS(rawValue: frame.qos)!
let message = CocoaMQTTMessage(topic: frame.topic!, payload: frame.payload, qos: qos, retained: frame.retained, dup: frame.dup)
return (msgid, message)
}
private func msgid(_ bytes: [UInt8]) -> UInt16 {
if bytes.count < 2 { return 0 }
return UInt16(bytes[0]) << 8 + UInt16(bytes[1])
}
private func reset() {
length = 0
multiply = 1
header = 0
data = []
}
}
private extension CocoaMQTT {
// MARK: -- RetryQueue
class RetryQueue {
let depth: UInt
let duration: TimeInterval
private var _queue = [Date]()
init(depth: UInt, duration: TimeInterval) {
self.depth = depth
self.duration = duration
printNotice("RetryQueue init. Depth: \(depth), duration: \(duration)")
}
func append(timestamp: Date) throws {
printDebug("RetryQueue append timestamp: \(timestamp), now queue count: \(_queue.count), queue: \(_queue)")
// remove expired record
_queue = _queue.filter { $0.addingTimeInterval(duration) >= timestamp }
guard UInt(_queue.count) < depth else {
throw NSError(domain: "CocoaMQTT-RetryFusing", code: -1, userInfo: ["depth": depth, "duration": duration, "count": _queue.count])
}
_queue.append(timestamp)
}
func reset() {
printNotice("RetryQueue reset.")
_queue = []
}
}
// MARK: -- Retry
class Retry {
let retry: Bool
let maxRetryCount: UInt
let step: TimeInterval
let fusing: RetryQueue
var retriedCount: UInt = 0
private var timer: Timer? = nil
private(set) var retrying: Bool = false
// MARK: --- life cycle
init(retry needRetry: Bool, maxRetryCount maxCount: UInt, step s: TimeInterval, fusingDepth: UInt, fusingDuration: TimeInterval) {
retry = needRetry
maxRetryCount = maxCount
step = s
retrying = false
fusing = RetryQueue(depth: fusingDepth, duration: fusingDuration)
printNotice("Object.Retry init. retry:\(retry), maxRetryCount:\(maxRetryCount), step:\(step), retrying:\(retrying), fusingDepth: \(fusingDepth), fusingDuration: \(fusingDuration)")
}
deinit {
timer?.invalidate()
timer = nil
printNotice("Object.Retry deinit.")
}
// MARK: --- public methods
func start(success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
guard retrying == false else { return }
printNotice("Object.Retry start")
doRetry(success: success, failure: failure)
}
func reset() {
printNotice("Object.Retry reset!")
timer?.invalidate()
timer = nil
retriedCount = 0
retrying = false
}
func resetFusing() {
fusing.reset()
}
// MARK: --- private
private func doRetry(success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
timer?.invalidate()
timer = nil
// inner loop
guard retry && retriedCount < maxRetryCount else {
retrying = false
printError("Object.Retry interrupt retrying!")
failure(NSError(domain: "CocoaMQTT-MaxRetryCount", code: -2, userInfo: ["retry": retry, "retriedCount": retriedCount, "maxRetryCount": maxRetryCount]))
return
}
let delay = calcDelay(retried: retriedCount, step: step)
// fusing
do {
try fusing.append(timestamp: Date() + delay)
} catch {
retrying = false
printError("Fusing start, error: \(error)")
failure(error)
return
}
retrying = true
timer = Timer.after(delay) { [weak self] in
success()
self?.retriedCount += 1
printNotice("Object.Retry retriedCount:\(String(describing: self?.retriedCount))")
self?.doRetry(success: success, failure: failure)
}
}
private func calcDelay(retried: UInt, step: TimeInterval) -> TimeInterval {
let randTime: TimeInterval = Double(arc4random_uniform(UInt32(step * 1000))) / 1000.0
let delay = Double(retried) * step + randTime
printDebug("Object.Retry calcDealy:\(delay), retried:\(retried)")
return delay
}
}
// MARK: -- PingPong
class PingPong {
var pongTime: Date? {
didSet {
printDebug("Object.PingPong pongTime:\(String(describing: pongTime))")
if checkPongExpired(pingTime: pingTime, pongTime: self.pongTime, now: Date(), timeOut: timeInterval) == true {
self.delegate?.pongDidTimeOut()
}
}
}
// MARK: --- private
private var pingTime: Date?
private var timer: Timer?
private let timeInterval: TimeInterval
private weak var delegate: PingPongProtocol?
// MARK: --- life cycle
init(keepAlive: TimeInterval, delegate d: PingPongProtocol?) {
timeInterval = keepAlive
delegate = d
printNotice("Object.PingPong init. KeepAlive:\(timeInterval)")
}
deinit {
printNotice("Object.PingPong deinit")
delegate = nil
reset()
}
// MARK: --- API
func start() {
printNotice("Object.PingPong start")
// refresh self's presence status immediately
delegate?.ping()
pingTime = Date()
printDebug("Object.PingPong pingTime:\(String(describing: self.pingTime))")
timer?.invalidate()
timer = nil
self.timer = Timer.every(timeInterval) { [weak self] (timer: Timer) in
guard let timeinterval = self?.timeInterval else {
printWarning("Object.PingPong timeInterval is nil. \(String(describing: self))")
return
}
let now = Date()
if self?.checkPongExpired(pingTime: self?.pingTime, pongTime: self?.pongTime, now: now, timeOut: timeinterval) == true {
printError("Object.PingPong Pong TIMEOUT! Ping: \(String(describing: self?.pingTime)), Pong: \(String(describing: self?.pongTime)), now: \(now), timeOut: \(timeinterval)")
self?.reset()
self?.delegate?.pongDidTimeOut()
} else {
self?.delegate?.ping()
self?.pingTime = Date()
printDebug("Object.PingPong pingTime:\(String(describing: self?.pingTime))")
}
}
}
func reset() {
printNotice("Object.PingPong reset")
timer?.invalidate()
timer = nil
pingTime = nil
pongTime = nil
}
// MARK: --- private
private func checkPongExpired(pingTime: Date?, pongTime: Date?, now: Date, timeOut: TimeInterval) -> Bool {
if let pingT = pingTime,
let pongExpireT = pingTime?.addingTimeInterval(timeOut),
now > pongExpireT {
if let pongT = pongTime, pongT >= pingT, pongT <= pongExpireT {
return false
} else {
printError("Object.PingPong checkPongExpired. Ping:\(pingT), PongExpired:\(pongExpireT), Now:\(now), Pong:\(String(describing: pongTime))")
return true
}
} else {
return false
}
}
}
}
// MARK: - Logger
@objc public enum CocoaMQTTLoggerLevel: Int {
case debug = 0, info, notice, warning, error
}
extension CocoaMQTTLoggerLevel: CustomStringConvertible {
public var description: String {
switch self {
case .debug: return "Debug"
case .info: return "Info"
case .notice: return "Notice"
case .warning: return "Warning"
case .error: return "Error"
}
}
}
public class CocoaMQTTLogger: NSObject {
static let shared = CocoaMQTTLogger()
weak var delegate: CocoaMqttLogProtocol?
public func log(level: CocoaMQTTLoggerLevel, message: String) {
if let limitLevel = delegate?.minLevel.rawValue,
level.rawValue >= limitLevel {
delegate?.log(level: level, message: "CocoaMQTT " + message)
}
}
}
func printDebug(_ message: String) {
CocoaMQTTLogger.shared.log(level: .debug, message: message)
}
func printInfo(_ message: String) {
CocoaMQTTLogger.shared.log(level: .info, message: message)
}
func printNotice(_ message: String) {
CocoaMQTTLogger.shared.log(level: .notice, message: message)
}
func printWarning(_ message: String) {
CocoaMQTTLogger.shared.log(level: .warning, message: message)
}
func printError(_ message: String) {
CocoaMQTTLogger.shared.log(level: .error, message: message)
}
| mit | 119c420f71c6acaa2f78ac7e62298e77 | 31.365931 | 199 | 0.591423 | 4.559325 | false | false | false | false |
mwoytowich/protobuf-swift | src/ProtocolBuffers/runtime-pb-swift/UnknownFieldSet.swift | 2 | 4471 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public func == (lhs: UnknownFieldSet, rhs: UnknownFieldSet) -> Bool
{
return lhs.fields == rhs.fields
}
public class UnknownFieldSet:Hashable,Equatable
{
public var fields:Dictionary<Int32,Field>
convenience public init()
{
self.init(fields: Dictionary())
}
public init(fields:Dictionary<Int32,Field>)
{
self.fields = fields
}
public var hashValue:Int
{
get {
var hashCode:Int = 0
for value in fields.values
{
hashCode = (hashCode &* 31) &+ value.hashValue
}
return hashCode
}
}
public func hasField(number:Int32) -> Bool
{
if let unwrappedValue = fields[number] {
return true
}
return false
}
public func getField(number:Int32) -> Field
{
if let field = fields[number]
{
return field
}
return Field()
}
public func writeToCodedOutputStream(output:CodedOutputStream)
{
var sortedKeys = Array(fields.keys)
sortedKeys.sort { $0 < $1 }
for number in sortedKeys
{
let value:Field = fields[number]!
value.writeTo(number, output: output)
}
}
public func writeToOutputStream(output:NSOutputStream)
{
let codedOutput:CodedOutputStream = CodedOutputStream(output: output)
writeToCodedOutputStream(codedOutput)
codedOutput.flush()
}
public func writeDescriptionTo(inout output:String, indent:String)
{
var sortedKeys = Array(fields.keys)
sortedKeys.sort { $0 < $1 }
for number in sortedKeys
{
let value:Field = fields[number]!
value.writeDescriptionFor(number, outputString: &output, indent: indent)
}
}
public class func builder() -> UnknownFieldSetBuilder {
return UnknownFieldSetBuilder()
}
public class func parseFromCodedInputStream(input:CodedInputStream) -> UnknownFieldSet {
return UnknownFieldSet.builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromData(data:NSData) -> UnknownFieldSet {
return UnknownFieldSet.builder().mergeFromData(data).build()
}
public class func parseFromInputStream(input:NSInputStream) -> UnknownFieldSet
{
return UnknownFieldSet.builder().mergeFromInputStream(input).build()
}
public class func builderWithUnknownFields(copyFrom:UnknownFieldSet) -> UnknownFieldSetBuilder
{
return UnknownFieldSet.builder().mergeUnknownFields(copyFrom)
}
public func serializedSize()->Int32
{
var result:Int32 = 0
for number in fields.keys
{
let field:Field = fields[number]!
result += field.getSerializedSize(number)
}
return result
}
public func writeAsMessageSetTo(output:CodedOutputStream)
{
for number in fields.keys
{
let field:Field = fields[number]!
field.writeAsMessageSetExtensionTo(number, output:output)
}
}
public func serializedSizeAsMessageSet() -> Int32
{
var result:Int32 = 0
for number in fields.keys
{
let field:Field = fields[number]!
result += field.getSerializedSizeAsMessageSetExtension(number)
}
return result
}
public func data() -> NSData
{
var size = serializedSize()
let data = NSMutableData(length: Int(size))!
var stream:CodedOutputStream = CodedOutputStream(data: data)
writeToCodedOutputStream(stream)
return stream.buffer.buffer
}
}
| apache-2.0 | 5bdbbb20adf0501d04fa00c35439084c | 26.94375 | 98 | 0.623127 | 4.951274 | false | false | false | false |
liuCodeBoy/Ant | Ant/Ant/Tools/NetWorkTool.swift | 1 | 12712 | //
// NetWorkTool.swift
// E
//
// Created by LiuXinQiang on 17/3/25.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import AFNetworking
import SVProgressHUD
// MARK:- 定义枚举类型
enum RequestType : String {
case GET = "GET"
case POST = "POST"
}
enum LunTanType : String {
case house = "house"
case seek = "seek"
case job = "job"
case car = "car"
case secondHand = "market"
case cityWide = "friends"
}
class NetWorkTool: AFHTTPSessionManager {
var canConnect : Bool = true
//let 是线程安全的,创建单例
static let shareInstance : NetWorkTool = {
let tools = NetWorkTool()
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
tools.responseSerializer.acceptableContentTypes?.insert("application/json")
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
tools.responseSerializer.acceptableContentTypes?.insert("text/json")
return tools
}()
}
// MARK:- 封装请求方法
extension NetWorkTool {
func request(_ method: RequestType, urlString : String, parameters:[String :AnyObject]?, finished:@escaping (_ result : AnyObject?, _ error : Error?)->()){
if(canConnect == true){
//定义成功的回调闭包
let successCallBack = { (task: URLSessionDataTask?, result: Any?) -> Void in
finished(result as AnyObject, nil )
}
//定义失败的回调闭包
let failureCallBack = { (task: URLSessionDataTask?, error: Error?) -> Void in
finished(nil, error )
}
//发送网络请求
if method == RequestType.GET {
self.get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
} else {
self.post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
} else {
}
}
}
// MARK:- 用户登录请求
extension NetWorkTool {
//用户登录
func UserLogin( _ account:String, password:String , type : String , finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/login/login"
//2.获取请求参数
let parameters = ["account" : account , "password": password , "type" : type]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
//用户注册
func UserRegister( _ account:String, password:String , finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/login/register"
//2.获取请求参数
let parameters = ["account" : account , "password": password]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
}
// MARK:- 新闻
extension NetWorkTool {
//轮播图
func rotationList( finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/news/rotationList"
//2.获取请求参数
let parameters = ["cate_id" : 2]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
//天气接口
func weather( _ city : String , finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/news/weather"
//2.获取请求参数
let parameters = ["city" : city]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
//新闻分类接口
func newsCate( _ type : String , finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/news/newsCate"
//2.获取请求参数
let parameters = ["type" : type]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
//获取新闻列表
func newsList( _ cate_id : String , p : String ,finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/news/newsList"
//2.获取请求参数
let parameters = ["cate_id" : cate_id , "p" : p ]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
//新闻详情
func newsDet( _ id : String ,finished:@escaping (_ result : [String : AnyObject]? ,_ error:Error?) ->()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/news/newsDet"
//2.获取请求参数
let parameters = ["id" : 169 ]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
}
// MARK:- 论坛
extension NetWorkTool {
// MARK:- 论坛发布信息
func publishInfo(_ token: String,
cate_1: LunTanType.RawValue,
cate_2 : String,
rootpath : String,
savepath : LunTanType.RawValue,
image : [UIImage],
dict : NSDictionary?,
finished: @escaping (_ result: [String: AnyObject]?, _ error: Error?) -> ()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/user/publish"
self.requestSerializer.setValue(token, forHTTPHeaderField: "token")
//2.获取请求参数
var parameters = ["cate_1": cate_1, "cate_2" : cate_2 , "rootpath" : rootpath , "savepath" : savepath ] as [String : Any]
for (key, value) in dict!{
parameters.updateValue(value, forKey: key as! String)
}
//3.发送请求参数
post(urlString, parameters: parameters, constructingBodyWith: { [weak self](formData) in
//确定选择类型
if image.count > 0 {
var cateName = ""
cateName = image.count > 1 ? "image[]" : "image"
for pic in image {
if let imageData = UIImageJPEGRepresentation(pic, 0.5){
let imageName = self?.getNowTime()
formData.appendPart(withFileData: imageData, name: cateName, fileName: imageName! , mimeType: "image/png")
}
}
}
}, progress: { (Progress) in
}, success: { (URLSessionDataTask, success) in //获取字典数据
guard let resultDict = success as? [String : AnyObject] else {
return
}
finished(resultDict , nil)
//将数组数据回调给外界控制器
print(resultDict)
}) { (URLSessionDataTask, error) in
print(error)
finished(nil , error)
}
}
func getNowTime() -> (String){
let date = NSDate.init(timeIntervalSinceNow: 0)
let a = date.timeIntervalSince1970
let timesString = "\(a).png"
return timesString
}
// MARK:- 论坛信息列表查询均
func infoList(VCType cate_1: LunTanType, cate_2 : String, cate_3 : String, cate_4 : String,p: Int, finished: @escaping (_ result: [String: AnyObject]?, _ error: Error?) -> ()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/forum/forumList"
//2.获取请求参数
let parameters = ["cate_1" : cate_1.rawValue, "cate_2" : cate_2, "cate_3": cate_3,"cate_4" : cate_4, "p": p] as [String : AnyObject]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
// MARK:- 论坛详情信息
func infoDetial(VCType cate_1: LunTanType, id: Int, finished: @escaping (_ result: [String: AnyObject]?, _ error: Error?) -> ()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/forum/forumInfo"
//2.获取请求参数
let parameters = ["cate_1" : cate_1.rawValue, "id": id] as [String : AnyObject]
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
}
//MARK: - 个人发布界面
extension NetWorkTool {
func userRelated( token: String, uid: Int, cate:String , p : Int , finished: @escaping (_ result: [String: AnyObject]?, _ error: Error?) -> ()) {
//1.获取请求的URLString
let urlString = "http://106.15.199.8/jraz/api/user/userRelated"
self.requestSerializer.setValue(token, forHTTPHeaderField: "token")
//2.获取请求参数
var parameters = ["cate": cate , "p" : p] as [String : AnyObject]
if uid < 0 {
parameters.updateValue(uid as AnyObject, forKey: "uid")
}
//3.发送请求参数
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
//获取字典数据
guard let resultDict = result as? [String : AnyObject] else {
finished(nil, error)
return
}
//将数组数据回调给外界控制器
finished(resultDict, error)
}
}
}
| apache-2.0 | 5876df2f8a2cc889c384a0e0d3a22965 | 34.70948 | 182 | 0.546031 | 4.137845 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Geometry/Format coordinates/FormatCoordinatesViewController.swift | 1 | 3098 | // Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class FormatCoordinatesViewController: UIViewController, AGSGeoViewTouchDelegate {
@IBOutlet private var mapView: AGSMapView!
private weak var tableViewController: FormatCoordinatesTableViewController?
private var graphicsOverlay = AGSGraphicsOverlay()
var point = AGSPoint(x: 0, y: 0, spatialReference: .webMercator()) {
didSet {
// display a graphic at the point
displayGraphicAtPoint(point)
// populate the coordinate strings for the new point
tableViewController?.point = point
}
}
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = [
"FormatCoordinatesViewController",
"FormatCoordinatesTableViewController"
]
// initializer map with basemap
let map = AGSMap(basemapStyle: .arcGISImageryStandard)
// assign map to map view
mapView.map = map
// add graphics overlay to the map view
mapView.graphicsOverlays.add(graphicsOverlay)
// touch delegate for map view
mapView.touchDelegate = self
// add initial graphic
displayGraphicAtPoint(point)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let tableViewController = segue.destination as? FormatCoordinatesTableViewController {
self.tableViewController = tableViewController
tableViewController.point = point
tableViewController.changeHandler = { [weak self] point in
self?.point = point
}
}
}
private func displayGraphicAtPoint(_ point: AGSPoint) {
// remove previous graphic from graphics overlay
graphicsOverlay.graphics.removeAllObjects()
// add graphic at tapped location
let symbol = AGSSimpleMarkerSymbol(style: .cross, color: .yellow, size: 20)
let graphic = AGSGraphic(geometry: point, symbol: symbol, attributes: nil)
graphicsOverlay.graphics.add(graphic)
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// update the point with the tapped location
point = mapPoint
}
}
| apache-2.0 | c074706c16c53896fc20c77383912b0e | 35.447059 | 103 | 0.663331 | 5.350604 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Tools/NetworkTools.swift | 1 | 3275 | //
// NetworkTools.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/15.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import AFNetworking
import SVProgressHUD
enum AFNSESSION_TYPE : NSInteger{
case GET = 0
case POST = 1
}
class NetworkTools: AFHTTPSessionManager {
//定义单例对象
static let shareNetWorkTools : NetworkTools = {
let urlStr = "https://api.weibo.com/"
let baseURL = NSURL(string: urlStr)
let tools = NetworkTools(baseURL: baseURL)
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tools
}()
func requiredJsonValueToDictionary( requestType : AFNSESSION_TYPE , urlStr : String , parameters : [String : AnyObject]? , finishedBlock : (result : [String : AnyObject]? , error : NSError?) -> ()){
//判断请求方式
if requestType == AFNSESSION_TYPE.GET{
GET(urlStr, parameters: parameters, success: { (_, result) -> Void in
//获取到正确的信息
if let dataArray = result as? [String : AnyObject]{
finishedBlock(result: dataArray, error: nil)
return
}
finishedBlock(result: nil, error: dataError)
}) { (_, error) -> Void in
finishedBlock(result: nil, error: error)
}
}else if requestType == AFNSESSION_TYPE.POST{
POST(urlStr, parameters: parameters, success: { (_, result) -> Void in
if let dict = result as? [String : AnyObject]{
finishedBlock(result: dict, error: nil)
return
}
finishedBlock(result: nil, error: dataError)
}) { (_, error) -> Void in
finishedBlock(result: nil, error: error)
}
}else{
return
}
}
//定义上传的方法,拼接请求头信息
func uploadPicture(imageData : NSData , urlStr : String , parameters : [String : AnyObject]? , finishedBlock : (result : [String : AnyObject]? , error : NSError?) -> ()){
POST(urlStr, parameters: parameters, constructingBodyWithBlock: { (multipartFormData) -> Void in
//在这里构建请求头信息
multipartFormData.appendPartWithFileData(imageData, name: "pic", fileName: "myPic", mimeType: "image/jpeg")
}, success: { (_, result) -> Void in
finishedBlock(result: result as? [String : AnyObject], error: nil)
}) { (_, error) -> Void in
finishedBlock(result: nil, error: error)
}
}
}
| mit | cea1d900c443e2c654c3402114163b60 | 23.976378 | 202 | 0.461854 | 5.614159 | false | false | false | false |
banxi1988/BXAppKit | BXModel/SimpleTableViewController.swift | 1 | 1017 | //
// SimpleGenericTableViewController.swift
// Pods
//
// Created by Haizhen Lee on 15/11/20.
//
//
import UIKit
/// 极简 tableViewController
/// 数据设置可通过 公开的 adapter 对象,直接对 adapter 进行设置
open class SimpleTableViewController<V:UITableViewCell>: UITableViewController where V:BXBindable{
typealias ItemType = V.ModelType
public private(set) var adapter:SimpleTableViewAdapter<V> = SimpleTableViewAdapter()
public typealias DidSelectedItemBlock = ( (V.ModelType,IndexPath) -> Void )
open var didSelectedItemBlock: DidSelectedItemBlock?{
didSet{
adapter.didSelectedItem = didSelectedItemBlock
}
}
open override func loadView() {
super.loadView()
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = 88
tableView.rowHeight = UITableViewAutomaticDimension
}
open override func viewDidLoad() {
super.viewDidLoad()
adapter.bind(to: tableView)
adapter.didSelectedItem = didSelectedItemBlock
}
}
| mit | 0b3bdf576bd3a172bdf7c994c45112e9 | 24 | 98 | 0.739487 | 4.513889 | false | false | false | false |
timestocome/SoundFFT | Sounds/SoundViewController.swift | 1 | 7188 | //
// SoundViewController.swift
// Sensors
//
// Created by Linda Cobb on 9/22/14.
// Copyright (c) 2014 TimesToCome Mobile. All rights reserved.
//
import Foundation
import UIKit
import CoreMedia
import AudioToolbox
import AudioUnit
import AVFoundation
import Accelerate
// incoming data - pressure
// calculate: frequency
class SoundViewController: UIViewController, AVCaptureAudioDataOutputSampleBufferDelegate
{
// output to user
@IBOutlet var dataLabel: UILabel!
@IBOutlet var frequencyLabel: UILabel!
@IBOutlet var graphView: GraphView!
@IBOutlet var barGraphView: BarGraphView!
// capture sound
var captureSession: AVCaptureSession!
var captureDevice: AVCaptureDevice!
var captureDeviceInput: AVCaptureDeviceInput!
var audioDataOutput: AVCaptureAudioDataOutput!
var captureAudioDataOutput: AVCaptureAudioDataOutput!
var data = [Float](count: 64, repeatedValue: 0.0)
// trip wire so we can call stop session on main thread
var stopUpdates = false
// fft
let windowSize = 64
let windowSizeOverTwo = 32
let hz = 1024 // sample rate 44,100 hz
// get frequencies from data
var frequency:Float = 0.0
var max:Float = 0.0
var imagp = [Float](count: 64, repeatedValue: 0.0)
var zerosR = [Float](count: 64, repeatedValue: 0.0)
var zerosI = [Float](count: 64, repeatedValue: 0.0)
var log2n:vDSP_Length!
var setup : COpaquePointer!
// update fft arrays and call after after x loop counts
let maxArrayPosition = 64 - 1
let loopCount = 32 // number of data points between fft calls
var graphLoopCount = 0
var dataCount = 0
required init( coder aDecoder: NSCoder ){ super.init(coder: aDecoder) }
convenience override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!){ self.init(nibName: nil, bundle: nil) }
override func viewDidLoad() {
graphView.setupGraphView()
barGraphView.setupGraphView()
// set up memory for FFT
log2n = vDSP_Length(log2(Double(windowSize)))
setup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2))
}
func setupCaptureSession(){
// setup session
captureSession = AVCaptureSession()
var error: NSError?
// inputs
captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
captureDeviceInput = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: &error) as! AVCaptureDeviceInput
if captureSession.canAddInput(captureDeviceInput) {
captureSession.addInput(captureDeviceInput)
}
// outputs
captureAudioDataOutput = AVCaptureAudioDataOutput()
captureSession.addOutput(captureAudioDataOutput)
let queue = dispatch_queue_create("com.timestocomemobile.queue", DISPATCH_QUEUE_SERIAL)
captureAudioDataOutput.setSampleBufferDelegate(self, queue: queue)
captureSession.startRunning()
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
var totalBytes = 0 as UInt64
let blockBufferRef = CMSampleBufferGetDataBuffer(sampleBuffer)
let lengthOfBlock = CMBlockBufferGetDataLength(blockBufferRef)
let data = NSMutableData(length: Int(lengthOfBlock))
CMBlockBufferCopyDataBytes(blockBufferRef, 0, lengthOfBlock, data!.mutableBytes)
var samples = UnsafeMutablePointer<UInt8>(data!.mutableBytes)
var value:UInt8 = samples.memory
NSOperationQueue.mainQueue().addOperationWithBlock({
// compute fft, update graph, give user data
if self.stopUpdates == false {
self.graphView.addX(value)
self.dataLabel.text = NSString (format:"Data: %d", value) as String
self.updateFFT(Float(value))
}
});
}
func updateFFT( x: Float){
// first fill up array
if dataCount < windowSize {
data[dataCount] = x
dataCount++
// then pop oldest off top push newest onto end
}else{
data.removeAtIndex(0)
data.insert(x, atIndex: maxArrayPosition)
}
// call fft?
if graphLoopCount > loopCount {
graphLoopCount = 0;
FFT()
}else{ graphLoopCount++; }
}
func FFT() {
// parse data input into complex vector
// var cplxData = DSPSplitComplex( realp: &zerosR, imagp: &zerosI )
// var xAsComplex = UnsafePointer<DSPComplex>( data.withUnsafeBufferPointer { $0.baseAddress } )
// vDSP_ctoz( xAsComplex, 2, &cplxData, 1, vDSP_Length(windowSizeOverTwo) )
var cplxData = DSPSplitComplex(realp: &data, imagp: &zerosI)
//perform fft
vDSP_fft_zrip( setup, &cplxData, 1, log2n, FFTDirection(kFFTDirection_Forward) )
//calculate power
var powerVector = [Float](count: 64, repeatedValue: 0.0)
vDSP_zvmags(&cplxData, 1, &powerVector, 1, vDSP_Length(windowSizeOverTwo))
// find peak power and bin
var power = 0.0 as Float
var bin = 0 as vDSP_Length
vDSP_maxvi(&powerVector, 1, &power, &bin, vDSP_Length(windowSizeOverTwo))
// convert power to frequency
frequency = Float(hz) * Float(bin) / Float(windowSize);
// push the data to the user
frequencyLabel.text = NSString(format:"Frequency: %.2lf", self.frequency) as String
// scale and send to bar graph
// bar graph view has height of 200 pixels
// var scale:Float = 200.0/power // viewHeight/maxValue
// var scaledPowerVector = [Float](count: 128, repeatedValue: 0.0)
// vDSP_vsmul(&powerVector, 1, &scale, &scaledPowerVector, 1, 128)
barGraphView.addX(frequency)
// println("***************************************************************************")
// for i in 0..<128 { println("scaled value \(scaledPowerVector[i])" ) }
var minF = 0
var maxF:Float = Float(hz) * 64.0
println("min \(minF) max \(maxF)")
}
@IBAction func stop(){
stopUpdates = true
if captureSession != nil {
captureSession.stopRunning()
captureSession = nil
}
}
@IBAction func start(){
stopUpdates = false
setupCaptureSession()
}
override func viewDidDisappear(animated: Bool){
super.viewDidDisappear(animated)
stop()
vDSP_destroy_fftsetupD(setup)
}
} | mit | 7710f5bc57b142a87550dcab1b50ab01 | 25.724907 | 159 | 0.593489 | 4.933425 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift | 13 | 3337 | //
// Throttle.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ThrottleSink<O: ObserverType, Scheduler: SchedulerType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias ParentType = Throttle<Element, Scheduler>
let parent: ParentType
let lock = NSRecursiveLock()
// state
var id = 0 as UInt64
var value: Element? = nil
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = parent.source.subscribeSafe(self)
return CompositeDisposable(subscription, cancellable)
}
func on(event: Event<Element>) {
switch event {
case .Next:
break
case .Error, .Completed:
cancellable.dispose()
}
let latestId = self.lock.calculateLocked { () -> UInt64 in
let observer = self.observer
let oldValue = self.value
self.id = self.id &+ 1
switch event {
case .Next(let element):
self.value = element
case .Error:
self.value = nil
observer?.on(event)
self.dispose()
case .Completed:
self.value = nil
if let value = oldValue {
observer?.on(.Next(value))
}
observer?.on(.Completed)
self.dispose()
}
return id
}
switch event {
case .Next(_):
let d = SingleAssignmentDisposable()
self.cancellable.disposable = d
let scheduler = self.parent.scheduler
let dueTime = self.parent.dueTime
let disposeTimer = scheduler.scheduleRelative(latestId, dueTime: dueTime) { (id) in
self.propagate()
return NopDisposable.instance
}
d.disposable = disposeTimer
default: break
}
}
func propagate() {
let originalValue: Element? = self.lock.calculateLocked {
let originalValue = self.value
self.value = nil
return originalValue
}
if let value = originalValue {
observer?.on(.Next(value))
}
}
}
class Throttle<Element, Scheduler: SchedulerType> : Producer<Element> {
let source: Observable<Element>
let dueTime: Scheduler.TimeInterval
let scheduler: Scheduler
init(source: Observable<Element>, dueTime: Scheduler.TimeInterval, scheduler: Scheduler) {
self.source = source
self.dueTime = dueTime
self.scheduler = scheduler
}
override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | mit | d5f6c77f6eca5c0662923e9da68e5403 | 26.586777 | 139 | 0.538807 | 5.157651 | false | false | false | false |
Keanyuan/SwiftContact | CoreDataStu/CoreDataStu/ViewController.swift | 1 | 2469 | //
// ViewController.swift
// CoreDataStu
//
// Created by KeanQ on 2018/2/23.
// Copyright © 2018年 anji-allways. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// 模型数组
var modelArr = Array<Any>()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var addBtn: UIButton!
@IBOutlet weak var selectBtn: UIButton!
@IBOutlet weak var deleteBtn: UIButton!
@IBAction func addBtnClick(_ sender: UIButton) {
//添加对象
var dic = [String:String]()
dic["key"] = "self.searchView?.inputLabel.text"
if SearchHistoryForOrder.insertObject(dic) {
addBtn.setTitle("添加成功", for: .normal)
}else{
addBtn.setTitle("添加失败", for: .normal)
}
self.getHistorySearch()
}
@IBAction func selectBtnClick(_ sender: UIButton) {
// self.getHistorySearch()
let searchVC = storyboardViewController(withIdentifier: "DFViewController") as! DFViewController
self.navigationController?.pushViewController(searchVC, animated: true)
}
@IBAction func deleteBtnClick(_ sender: UIButton) {
SearchHistoryForOrder.deleteObject(completeCallBack: {[weak self](result : Bool) in
if result {
self?.modelArr = SearchHistoryForOrder.fetchObjects(fetchLimit: 20,fetchOffset: 0)!
self?.deleteBtn.setTitle("删除成功", for: .normal)
// weakself?.searchState = SearchState.searchNoInfo
}else{
self?.deleteBtn.setTitle("删除失败", for: .normal)
}
self?.getHistorySearch()
})
}
func getHistorySearch(){
self.modelArr = SearchHistoryForOrder.fetchObjects(fetchLimit: 20,fetchOffset: 0)!
selectBtn.setTitle("查询(\(self.modelArr.count))", for: .normal)
}
func storyboardViewController(withIdentifier identifier: String) -> UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC = storyboard.instantiateViewController(withIdentifier: identifier)
return VC
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 9493d94d9de029b74568c1790e2ea19e | 31.133333 | 104 | 0.626556 | 4.599237 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Views/Cells/Chat/Info/ChannelInfoDetailCell.swift | 2 | 855 | //
// ChannelInfoDetailCell.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
struct ChannelInfoDetailCellData: ChannelInfoCellDataProtocol {
let cellType = ChannelInfoDetailCell.self
var title: String?
var detail: String?
}
class ChannelInfoDetailCell: UITableViewCell, ChannelInfoCellProtocol {
static let identifier = "kChannelInfoCellDetail"
static let defaultHeight: Float = 44
var data: ChannelInfoDetailCellData? {
didSet {
labelTitle.text = data?.title
labelDetail.text = data?.detail
}
}
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDetail: UILabel! {
didSet {
labelDetail.textColor = UIColor.RCLightGray()
}
}
}
| mit | ee080eb4c808effadd65bd9b12ed8fab | 24.117647 | 71 | 0.676815 | 4.566845 | false | false | false | false |
jingyaokuku/JYweibo05 | JYSinaWeibo/JYSinaWeibo/Classse/Module/Home/View/JYStatusTopView.swift | 1 | 3784 | //
// JYStatusTopView.swift
// JYSinaWeibo
//
// Created by apple on 15/11/3.
// Copyright © 2015年 Jingyao. All rights reserved.
//
import UIKit
import SDWebImage
class JYStatusTopView: UIView {
//MARK: 微博模型
var status: JYStatus?{
didSet{
//设置视图内容
//用户头像
if let iconUrl = status?.user?.profile_image_url {
iconView.sd_setImageWithURL(NSURL(string: iconUrl))
}
//名称
nameLabel.text = status?.user?.name
//时间
timeLabel.text = status?.created_at
//来源
sourceLabel.text = "来自**微博"
//认证类型
// 判断类型设置不同的图片
// 没有认证:-1 认证用户:0 企业认证:2,3,5 达人:220
verifiedView.image = status?.user?.verifiedTypeImage
//会员等级
memberView.image = status?.user?.mbrankImage
}
}
/// 构造函数
override init (frame: CGRect){
super.init(frame:frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///MARK: -准备UI
private func prepareUI () {
//添加子控件
addSubview(topSeparatorView)
addSubview(iconView)
addSubview(nameLabel)
addSubview(timeLabel)
addSubview(sourceLabel)
addSubview(verifiedView)
addSubview(memberView)
//添加约束
topSeparatorView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10))
//头像视图
iconView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topSeparatorView, size: CGSize(width: 35, height: 35),offset: CGPoint(x: StatusCellMargin, y: StatusCellMargin))
//名称
nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil , offset: CGPoint(x: StatusCellMargin, y: 0))
//时间
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil , offset: CGPoint(x: StatusCellMargin, y: 0))
//来源
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: timeLabel, size: nil , offset: CGPoint(x: StatusCellMargin, y: 0))
//会员等级
memberView.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: nameLabel, size: CGSize(width: 14, height: 14), offset: CGPoint(x: StatusCellMargin, y: 0))
///认证图标
verifiedView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: CGSize(width: 17, height: 17),offset: CGPoint(x: 8.5, y: 8.5))
}
///MARK - 懒加载
///顶部分割视图
private lazy var topSeparatorView: UIView = {
let view = UIView()
//背景
view.backgroundColor = UIColor(white: 0.9, alpha: 1)
return view
}()
//用户头像
private lazy var iconView = UIImageView()
//用户名称
private lazy var nameLabel: UILabel = UILabel(fonsize: 14, textColor: UIColor.darkGrayColor())
// 时间
private lazy var timeLabel: UILabel = UILabel(fonsize: 9, textColor: UIColor.orangeColor())
//来源
private lazy var sourceLabel:UILabel = UILabel(fonsize: 9, textColor: UIColor.lightGrayColor())
//认证图标
private lazy var verifiedView = UIImageView()
//会员等级
private lazy var memberView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
}
| apache-2.0 | 83b0322fc23e0a84d4c21db688d1d8b9 | 30.882883 | 188 | 0.600452 | 4.305353 | false | false | false | false |
FoodMob/FoodMob-iOS | FoodMob/ViewControllers/FriendTableViewController.swift | 1 | 4317 | //
// FriendTableViewController.swift
// FoodMob
//
// Created by Jonathan Jemson on 4/16/16.
// Copyright © 2016 FoodMob. All rights reserved.
//
import UIKit
protocol FriendTableViewControllerDelegate: class {
func didFinishSelectingFriends(friends: Set<User>)
}
class FriendTableViewController: UITableViewController {
var selectedFriends = Set<User>()
weak var delegate: FriendTableViewControllerDelegate? {
didSet {
if delegate != nil {
self.tableView.allowsSelection = true
} else {
self.tableView.allowsSelection = false
}
}
}
private var friends = [User]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(FriendTableViewController.addFriend))
self.refreshControl = UIRefreshControl()
self.refreshControl!.addTarget(self, action: #selector(FriendTableViewController.reloadDataFromServer), forControlEvents: .ValueChanged)
self.reloadDataFromServer()
}
func addFriend() {
let popup = UIAlertController(title: "Add Friend", message: nil, preferredStyle: .Alert)
popup.addTextFieldWithConfigurationHandler { (emailField) in
emailField.keyboardType = UIKeyboardType.EmailAddress
emailField.autocorrectionType = .No
emailField.autocapitalizationType = .None
emailField.placeholder = "Email address"
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (_) in }
let addAction = UIAlertAction(title: "Add", style: .Default) { [weak self] (_) in
if let emailAddress = popup.textFields?.first?.text {
currentDataProvider.addFriendWithEmail(emailAddress, forUser: Session.sharedSession.currentUser!, completion: { [weak self] (success, reason) in
if success {
self?.reloadDataFromServer()
} else {
self?.alert("Could not add friend", message: reason)
}
})
}
}
popup.addAction(cancelAction)
popup.addAction(addAction)
self.presentViewController(popup, animated: true) {}
}
func reloadDataFromServer() {
currentDataProvider.fetchFriendsListing(forUser: Session.sharedSession.currentUser!) { [weak self] (users) in
self?.friends = users
self?.tableView.reloadData()
self?.refreshControl?.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
override func viewWillDisappear(animated: Bool) {
delegate?.didFinishSelectingFriends(selectedFriends)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath)
guard let friendCell = cell as? FriendTableViewCell else { return cell }
friendCell.configureCellForUser(friends[indexPath.row])
if selectedFriends.contains(friends[indexPath.row]) {
friendCell.accessoryType = .Checkmark
}
return friendCell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if delegate != nil {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
selectedFriends.remove(friends[indexPath.row])
} else {
cell.accessoryType = .Checkmark
selectedFriends.insert(friends[indexPath.row])
}
}
}
}
}
| mit | ec2390bf9deba0ea4af9f6480dd7db47 | 36.859649 | 161 | 0.641798 | 5.533333 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/ConversationProtocol.swift | 1 | 3610 | // Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
/// from UI project, to randomize users display in avatar icon
protocol StableRandomParticipantsProvider {
var stableRandomParticipants: [UserType] { get }
}
protocol ConversationStatusProvider {
var status: ConversationStatus { get }
}
protocol ConnectedUserProvider {
var connectedUserType: UserType? { get }
}
// MARK: - ZMConversation extension from sync engine
protocol TypingStatusProvider {
var typingUsers: [UserType] { get }
func setIsTyping(_ isTyping: Bool)
}
protocol VoiceChannelProvider {
var voiceChannel: VoiceChannel? { get }
}
protocol CanManageAccessProvider {
var canManageAccess: Bool { get }
}
// MARK: - Input Bar View controller
protocol InputBarConversation {
var typingUsers: [UserType] { get }
var hasDraftMessage: Bool { get }
var draftMessage: DraftMessage? { get }
var activeMessageDestructionTimeoutValue: MessageDestructionTimeoutValue? { get }
var hasSyncedMessageDestructionTimeout: Bool { get }
var isSelfDeletingMessageSendingDisabled: Bool { get }
var isSelfDeletingMessageTimeoutForced: Bool { get }
var isReadOnly: Bool { get }
var participants: [UserType] { get }
}
typealias InputBarConversationType = InputBarConversation & TypingStatusProvider & ConversationLike
extension ZMConversation: InputBarConversation {
var isSelfDeletingMessageSendingDisabled: Bool {
guard let context = managedObjectContext else { return false }
let feature = FeatureService(context: context).fetchSelfDeletingMesssages()
return feature.status == .disabled
}
var isSelfDeletingMessageTimeoutForced: Bool {
guard let context = managedObjectContext else { return false }
let feature = FeatureService(context: context).fetchSelfDeletingMesssages()
return feature.config.enforcedTimeoutSeconds > 0
}
var participants: [UserType] {
Array(localParticipants) as [UserType]
}
}
// MARK: - GroupDetailsConversation View controllers and child VCs
protocol GroupDetailsConversation {
var userDefinedName: String? { get set }
var sortedServiceUsers: [UserType] { get }
var allowGuests: Bool { get }
var hasReadReceiptsEnabled: Bool { get }
var freeParticipantSlots: Int { get }
var teamRemoteIdentifier: UUID? { get }
var syncedMessageDestructionTimeout: TimeInterval { get }
}
typealias GroupDetailsConversationType = GroupDetailsConversation & Conversation
extension ZMConversation: ConversationStatusProvider {}
extension ZMConversation: TypingStatusProvider {}
extension ZMConversation: VoiceChannelProvider {}
extension ZMConversation: CanManageAccessProvider {}
extension ZMConversation: GroupDetailsConversation {
var syncedMessageDestructionTimeout: TimeInterval {
return messageDestructionTimeoutValue(for: .groupConversation).rawValue
}
}
| gpl-3.0 | bb774098d56d73869fed533813fb7429 | 29.854701 | 99 | 0.751247 | 4.737533 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Synchronization/Strategies/CallingRequestStrategy.swift | 1 | 20898 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireRequestStrategy
import WireDataModel
@objcMembers
public final class CallingRequestStrategy: AbstractRequestStrategy, ZMSingleRequestTranscoder, ZMContextChangeTracker, ZMContextChangeTrackerSource, ZMEventConsumer {
// MARK: - Private Properties
private let zmLog = ZMSLog(tag: "calling")
private let messageSync: ProteusMessageSync<GenericMessageEntity>
private let flowManager: FlowManagerType
private let decoder = JSONDecoder()
private let callEventStatus: CallEventStatus
private var callConfigRequestSync: ZMSingleRequestSync! = nil
private var callConfigCompletion: CallConfigRequestCompletion?
private var clientDiscoverySync: ZMSingleRequestSync! = nil
private var clientDiscoveryRequest: ClientDiscoveryRequest?
private let ephemeralURLSession = URLSession(configuration: .ephemeral)
// MARK: - Internal Properties
var callCenter: WireCallCenterV3?
// MARK: - Init
public init(managedObjectContext: NSManagedObjectContext,
applicationStatus: ApplicationStatus,
clientRegistrationDelegate: ClientRegistrationDelegate,
flowManager: FlowManagerType,
callEventStatus: CallEventStatus) {
self.messageSync = ProteusMessageSync(context: managedObjectContext, applicationStatus: applicationStatus)
self.flowManager = flowManager
self.callEventStatus = callEventStatus
super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus)
configuration = [.allowsRequestsWhileInBackground,
.allowsRequestsWhileOnline,
.allowsRequestsWhileWaitingForWebsocket]
callConfigRequestSync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: managedObjectContext)
clientDiscoverySync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: managedObjectContext)
let selfUser = ZMUser.selfUser(in: managedObjectContext)
if let clientId = selfUser.selfClient()?.remoteIdentifier {
zmLog.debug("Creating callCenter from init")
callCenter = WireCallCenterV3Factory.callCenter(withUserId: selfUser.avsIdentifier,
clientId: clientId,
uiMOC: managedObjectContext.zm_userInterface,
flowManager: flowManager,
analytics: managedObjectContext.analytics,
transport: self)
}
}
// MARK: - Methods
public override func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? {
let request = callConfigRequestSync.nextRequest(for: apiVersion) ??
clientDiscoverySync.nextRequest(for: apiVersion) ??
messageSync.nextRequest(for: apiVersion)
return request
}
public func dropPendingCallMessages(for conversation: ZMConversation) {
messageSync.expireMessages(withDependency: conversation)
}
// MARK: - Single Request Transcoder
public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? {
switch sync {
case callConfigRequestSync:
zmLog.debug("Scheduling request to '/calls/config/v2'")
return ZMTransportRequest(path: "/calls/config/v2",
method: .methodGET,
binaryData: nil,
type: "application/json",
contentDisposition: nil,
shouldCompress: true,
apiVersion: apiVersion.rawValue)
case clientDiscoverySync:
guard
let request = clientDiscoveryRequest,
let selfClient = ZMUser.selfUser(in: managedObjectContext).selfClient()
else {
return nil
}
zmLog.debug("Scheduling request to discover clients")
let factory = ClientMessageRequestFactory()
return factory.upstreamRequestForFetchingClients(
conversationId: request.conversationId,
domain: request.domain,
selfClient: selfClient,
apiVersion: apiVersion
)
default:
return nil
}
}
public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) {
switch sync {
case callConfigRequestSync:
zmLog.debug("Received call config response for \(self): \(response)")
if response.httpStatus == 200 {
var payloadAsString: String?
if let payload = response.payload, let data = try? JSONSerialization.data(withJSONObject: payload, options: []) {
payloadAsString = String(data: data, encoding: .utf8)
}
zmLog.debug("Callback: \(String(describing: self.callConfigCompletion))")
self.callConfigCompletion?(payloadAsString, response.httpStatus)
self.callConfigCompletion = nil
}
case clientDiscoverySync:
zmLog.debug("Received client discovery response for \(self): \(response)")
defer {
clientDiscoveryRequest = nil
}
guard response.httpStatus == 412 else {
zmLog.warn("Expected 412 response: missing clients")
return
}
guard let jsonData = response.rawData else { return }
let apiVersion = APIVersion(rawValue: response.apiVersion)!
decoder.userInfo = [ClientDiscoveryResponsePayload.apiVersionKey: apiVersion]
do {
let payload = try decoder.decode(ClientDiscoveryResponsePayload.self, from: jsonData)
clientDiscoveryRequest?.completion(payload.clients)
} catch {
zmLog.error("Could not parse client discovery response: \(error.localizedDescription)")
}
default:
break
}
}
// MARK: - Context Change Tracker
public var contextChangeTrackers: [ZMContextChangeTracker] {
return [self] + messageSync.contextChangeTrackers
}
public func fetchRequestForTrackedObjects() -> NSFetchRequest<NSFetchRequestResult>? {
return nil
}
public func addTrackedObjects(_ objects: Set<NSManagedObject>) {
// nop
}
public func objectsDidChange(_ objects: Set<NSManagedObject>) {
guard callCenter == nil else { return }
for object in objects {
if let userClient = object as? UserClient, userClient.isSelfClient(), let clientId = userClient.remoteIdentifier, let userId = userClient.user?.avsIdentifier {
zmLog.debug("Creating callCenter")
let uiContext = managedObjectContext.zm_userInterface!
let analytics = managedObjectContext.analytics
uiContext.performGroupedBlock {
self.callCenter = WireCallCenterV3Factory.callCenter(withUserId: userId,
clientId: clientId,
uiMOC: uiContext.zm_userInterface,
flowManager: self.flowManager,
analytics: analytics,
transport: self)
}
break
}
}
}
// MARK: - Event Consumer
public func processEvents(_ events: [ZMUpdateEvent], liveEvents: Bool, prefetchResult: ZMFetchRequestBatchResult?) {
events.forEach(processEvent)
}
public func processEventsWhileInBackground(_ events: [ZMUpdateEvent]) {
events.forEach(processEvent)
}
private func processEvent(_ event: ZMUpdateEvent) {
let serverTimeDelta = managedObjectContext.serverTimeDelta
guard event.type == .conversationOtrMessageAdd else { return }
if let genericMessage = GenericMessage(from: event), genericMessage.hasCalling {
guard
let payload = genericMessage.calling.content.data(using: .utf8, allowLossyConversion: false),
let senderUUID = event.senderUUID,
let conversationUUID = event.conversationUUID,
let clientId = event.senderClientID,
let eventTimestamp = event.timestamp
else {
zmLog.error("ignoring calling message: \(genericMessage.debugDescription)")
return
}
self.zmLog.debug("received calling message, timestamp \(eventTimestamp), serverTimeDelta \(serverTimeDelta)")
let isRemoteMute = CallEventContent(from: payload, with: decoder)?.isRemoteMute ?? false
guard !isRemoteMute else {
callCenter?.muted = true
zmLog.debug("muted remotely from calling message")
return
}
processCallEvent(
conversationUUID: conversationUUID,
senderUUID: senderUUID,
clientId: clientId,
conversationDomain: event.conversationDomain,
senderDomain: event.senderDomain,
payload: payload,
currentTimestamp: serverTimeDelta,
eventTimestamp: eventTimestamp
)
}
}
func processCallEvent(conversationUUID: UUID,
senderUUID: UUID,
clientId: String,
conversationDomain: String?,
senderDomain: String?,
payload: Data,
currentTimestamp: TimeInterval,
eventTimestamp: Date) {
let conversationId = AVSIdentifier(
identifier: conversationUUID,
domain: conversationDomain
)
let userId = AVSIdentifier(
identifier: senderUUID,
domain: senderDomain
)
let callEvent = CallEvent(
data: payload,
currentTimestamp: Date().addingTimeInterval(currentTimestamp),
serverTimestamp: eventTimestamp,
conversationId: conversationId,
userId: userId,
clientId: clientId
)
callEventStatus.scheduledCallEventForProcessing()
callCenter?.processCallEvent(callEvent, completionHandler: { [weak self] in
self?.zmLog.debug("processed calling message")
self?.callEventStatus.finishedProcessingCallEvent()
})
}
}
// MARK: - Wire Call Center Transport
extension CallingRequestStrategy: WireCallCenterTransport {
public func send(data: Data, conversationId: AVSIdentifier, targets: [AVSClient]?, completionHandler: @escaping ((Int) -> Void)) {
guard let dataString = String(data: data, encoding: .utf8) else {
zmLog.error("Not sending calling messsage since it's not UTF-8")
completionHandler(500)
return
}
managedObjectContext.performGroupedBlock {
guard let conversation = ZMConversation.fetch(with: conversationId.identifier,
domain: conversationId.domain,
in: self.managedObjectContext)
else {
self.zmLog.error("Not sending calling messsage since conversation doesn't exist")
completionHandler(500)
return
}
self.zmLog.debug("schedule calling message")
let genericMessage = GenericMessage(content: Calling(content: dataString))
let recipients = targets.map { self.recipients(for: $0, in: self.managedObjectContext) } ?? .conversationParticipants
let message = GenericMessageEntity(conversation: conversation,
message: genericMessage,
targetRecipients: recipients,
completionHandler: nil)
self.messageSync.sync(message) { (result, response) in
if case .success = result {
completionHandler(response.httpStatus)
}
}
}
}
public func sendSFT(data: Data, url: URL, completionHandler: @escaping ((Result<Data>) -> Void)) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = data
ephemeralURLSession.task(with: request) { data, response, error in
if let error = error {
completionHandler(.failure(SFTResponseError.transport(error: error)))
return
}
guard
let response = response as? HTTPURLResponse,
let data = data
else {
completionHandler(.failure(SFTResponseError.missingData))
return
}
guard (200...299).contains(response.statusCode) else {
completionHandler(.failure(SFTResponseError.server(status: response.statusCode)))
return
}
completionHandler(.success(data))
}.resume()
}
public func requestCallConfig(completionHandler: @escaping CallConfigRequestCompletion) {
self.zmLog.debug("requestCallConfig() called, moc = \(managedObjectContext)")
managedObjectContext.performGroupedBlock { [unowned self] in
self.zmLog.debug("requestCallConfig() on the moc queue")
self.callConfigCompletion = completionHandler
self.callConfigRequestSync.readyForNextRequestIfNotBusy()
RequestAvailableNotification.notifyNewRequestsAvailable(nil)
}
}
public func requestClientsList(conversationId: AVSIdentifier, completionHandler: @escaping ([AVSClient]) -> Void) {
self.zmLog.debug("requestClientList() called, moc = \(managedObjectContext)")
managedObjectContext.performGroupedBlock { [unowned self] in
self.clientDiscoveryRequest = ClientDiscoveryRequest(
conversationId: conversationId.identifier,
domain: conversationId.domain,
completion: completionHandler
)
self.clientDiscoverySync.readyForNextRequestIfNotBusy()
RequestAvailableNotification.notifyNewRequestsAvailable(nil)
}
}
enum SFTResponseError: LocalizedError {
case server(status: Int)
case transport(error: Error)
case missingData
var errorDescription: String? {
switch self {
case let .server(status: status):
return "Server http status code: \(status)"
case let .transport(error: error):
return "Transport error: \(error.localizedDescription)"
case .missingData:
return "Response body missing data"
}
}
}
private func recipients(for targets: [AVSClient], in managedObjectContext: NSManagedObjectContext) -> GenericMessageEntity.Recipients {
let clientsByUser = targets
.compactMap { UserClient.fetchExistingUserClient(with: $0.clientId, in: managedObjectContext) }
.partition(by: \.user)
.mapValues { Set($0) }
return .clients(clientsByUser)
}
}
// MARK: - Client Discovery Request
extension CallingRequestStrategy {
struct ClientDiscoveryRequest {
let conversationId: UUID
let domain: String?
let completion: ([AVSClient]) -> Void
}
struct ClientDiscoveryResponsePayload: Decodable {
static let apiVersionKey = CodingUserInfoKey(rawValue: "clientDiscoveryDecodingOptions")!
let clients: [AVSClient]
/// This can decode the two types of responses listed below given that v0 uses legacy endpoints and v1 uses federation endpoints
///
/// When querying the legacy endpoint, this will be the response
/// {
/// "missing": {
/// "000600d0-000b-9c1a-000d-a4130002c221": [
/// "60f85e4b15ad3786",
/// "6e323ab31554353b"
/// ]
/// }
/// ...
/// }
///
/// When querying the federation enabled endpoint, this will be the response
/// {
/// "missing": {
/// "domain1.example.com": {
/// "000600d0-000b-9c1a-000d-a4130002c221": [
/// "60f85e4b15ad3786",
/// "6e323ab31554353b"
/// ]
/// }
/// }
/// ...
/// }
init(from decoder: Decoder) throws {
guard let apiVersion = decoder.userInfo[Self.apiVersionKey] as? APIVersion else {
fatalError("missing api version")
}
// get the main container from the decoder
let container = try decoder.container(keyedBy: CodingKeys.self)
// get the nested container keyed by "missing"
// it will contain a list of users and their client ids, but depending on the response, it may be segmented by domains
let nestedContainer = try container.nestedContainer(keyedBy: DynamicKey.self, forKey: .missing)
// define the block used below to extract the clients from a container
let extractClientsFromContainer = { (container: KeyedDecodingContainer<DynamicKey>, domain: String?) -> [AVSClient] in
var clients = [AVSClient]()
try container.allKeys.forEach { userIdKey in
let clientIds = try container.decode([String].self, forKey: userIdKey)
let identifier = AVSIdentifier(
identifier: UUID(uuidString: userIdKey.stringValue)!,
domain: domain
)
clients += clientIds.compactMap {
AVSClient(userId: identifier, clientId: $0)
}
}
return clients
}
var allClients = [AVSClient]()
switch apiVersion {
case .v0:
// `nestedContainer` contains all the user ids with no notion of domain, we can extract clients directly
allClients = try extractClientsFromContainer(nestedContainer, nil)
case .v1, .v2:
// `nestedContainer` has further nested containers each dynamically keyed by a domain name.
// we need to loop over each container to extract the clients.
try nestedContainer.allKeys.forEach { domainKey in
let usersContainer = try nestedContainer.nestedContainer(keyedBy: DynamicKey.self, forKey: domainKey)
allClients += try extractClientsFromContainer(usersContainer, domainKey.stringValue)
}
}
clients = allClients
}
enum CodingKeys: String, CodingKey {
case missing
}
}
private struct DynamicKey: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
}
| gpl-3.0 | ce8c266f6668d2463e9d82b832efb268 | 38.208255 | 171 | 0.589482 | 5.800167 | false | false | false | false |
dcilia/csv-export-swift | Sources/CSVExport.swift | 1 | 2990 | //
// CSVExport.swift
// CSVExportSwift
//
// Created by dcilia on 1/17/16.
// Copyright © 2016 David Cilia. All rights reserved.
//
import Foundation
public protocol CSVExporting {
/**
Getting a formatted CSV string
- returns: An instance of String with comma separated values.
Must end in a newline \n !!
*/
func exportAsCommaSeparatedString() -> String
/**
The template to which to map values to:
make sure to end with a newline "\n"
- Note:
"Make,Model,Max_Speed,Year\n"
*/
static func templateString() -> String
}
public class CSVExporter<T: CSVExporting> {
public var filePath : String = ""
public var rawData : Data?
private var _dataArray : [T]
private var _csvString : String
public init(source input: [T], template: String) {
_dataArray = input
_csvString = template
}
/**
Creates a file at the specified path
- parameter path: the path that you would like to create
*/
private func _createFile(_ path: String) -> Void {
let fileManager = FileManager.default
if fileManager.createFile(atPath: path, contents: nil, attributes: nil) {
self.filePath = path
}
}
/**
Encodes the data array into a CSV NSData object.
- returns: an instance of NSData (may be empty)
*/
private func _encode() -> Data {
//CSV is a delimited data format that has fields/columns separated by the comma character and records/rows terminated by newlines.
/*
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
*/
_dataArray.forEach {
self._csvString += $0.exportAsCommaSeparatedString()
}
//Use NSFileHandle to write the data to disk
guard let data = _csvString.data(using: String.Encoding.utf8) else {
return Data()
}
return data
}
/**
Writes data to file
- parameter data: an instance of NSData you want to write
- parameter path: the path where to write to
*/
private func _writeDataToFile(_ data: Data, path: String) -> Void {
self.rawData = data
if let handle = FileHandle(forWritingAtPath: self.filePath) {
handle.truncateFile(atOffset: handle.seekToEndOfFile())
handle.write(data)
}
}
public func export(_ finishHandler: () -> Void) -> Void {
_createFile(self.filePath)
_writeDataToFile(_encode(), path: filePath)
finishHandler()
}
}
| mit | 1687e9bf2c2b270db79c5d93ad7eec54 | 24.767241 | 138 | 0.572767 | 4.515106 | false | false | false | false |
NobodyNada/SwiftStack | Sources/SwiftStack/RequestsSuggestedEdits.swift | 1 | 5615 | //
// RequestsSuggestedEdits.swift
// SwiftStack
//
// Created by FelixSFD on 22.12.16.
//
//
import Foundation
/**
This extension contains all requests in the SUGGESTED EDITS section of the StackExchange API Documentation.
- authors: NobodyNada, FelixSFD
*/
public extension APIClient {
// - MARK: /suggested-edits
/**
Fetches all `SuggestedEdit`s synchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- returns: The list of sites as `APIResponse<SuggestedEdit>`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdits(
parameters: [String:String] = [:],
backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<SuggestedEdit> {
return try performAPIRequest(
"suggested-edits",
parameters: parameters,
backoffBehavior: backoffBehavior
)
}
/**
Fetches all `SuggestedEdit`s asynchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- parameter completionHandler: Passes either an `APIResponse<SuggestedEdit>?` or an `Error?`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdits(
parameters: [String: String] = [:],
backoffBehavior: BackoffBehavior = .wait,
completionHandler: @escaping (APIResponse<SuggestedEdit>?, Error?) -> ()) {
queue.async {
do {
let response: APIResponse<SuggestedEdit> = try self.fetchSuggestedEdits(
parameters: parameters,
backoffBehavior: backoffBehavior
)
completionHandler(response, nil)
} catch {
completionHandler(nil, error)
}
}
}
// - MARK: /suggested-edits/{ids}
/**
Fetches `SuggestedEdit`s synchronously.
- parameter ids: The IDs to fetch.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- returns: The list of sites as `APIResponse<SuggestedEdit>`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdits(
_ ids: [Int],
parameters: [String:String] = [:],
backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<SuggestedEdit> {
guard !ids.isEmpty else {
fatalError("ids is empty")
}
return try performAPIRequest(
"suggested-edits/\(ids.map {String($0)}.joined(separator: ";"))",
parameters: parameters,
backoffBehavior: backoffBehavior
)
}
/**
Fetches `SuggestedEdit`s asynchronously.
- parameter ids: The IDs to fetch.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- parameter completionHandler: Passes either an `APIResponse<SuggestedEdit>?` or an `Error?`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdits(
_ ids: [Int],
parameters: [String: String] = [:],
backoffBehavior: BackoffBehavior = .wait,
completionHandler: @escaping (APIResponse<SuggestedEdit>?, Error?) -> ()) {
queue.async {
do {
let response: APIResponse<SuggestedEdit> = try self.fetchSuggestedEdits(
ids,
parameters: parameters,
backoffBehavior: backoffBehavior
)
completionHandler(response, nil)
} catch {
completionHandler(nil, error)
}
}
}
/**
Fetches a `SuggestedEdit` synchronously.
- parameter id: The ID to fetch.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an APIRequest has a backoff
- returns: The list of sites as `APIResponse<SuggestedEdit>`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdit(
_ id: Int,
parameters: [String:String] = [:],
backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<SuggestedEdit> {
return try fetchSuggestedEdits([id], parameters: parameters, backoffBehavior: backoffBehavior)
}
/**
Fetches a `SuggestedEdit` asynchronously.
- parameter id: The ID to fetch.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an APIRequest has a backoff
- parameter completionHandler: Passes either an `APIResponse<SuggestedEdit>?` or an `Error?`
- authors: NobodyNada, FelixSFD
*/
func fetchSuggestedEdit(
_ id: Int,
parameters: [String: String] = [:],
backoffBehavior: BackoffBehavior = .wait,
completionHandler: @escaping (APIResponse<SuggestedEdit>?, Error?) -> ()) {
fetchSuggestedEdits([id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler)
}
}
| mit | 04c58ebabacaafaf3280fda96d4595c7 | 29.516304 | 129 | 0.596972 | 5.462062 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Site Creation/Site Name/SiteNameViewController.swift | 1 | 3788 |
import UIKit
/// Site Name screen for the Site Creation flow
class SiteNameViewController: UIViewController {
private let siteNameViewFactory: () -> UIView
private let onSkip: () -> Void
init(siteNameViewFactory: @escaping () -> UIView, onSkip: @escaping () -> Void) {
self.siteNameViewFactory = siteNameViewFactory
self.onSkip = onSkip
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = siteNameViewFactory()
setTitleForTraitCollection()
configureNavigationBar()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setTitleForTraitCollection()
}
override func viewDidLoad() {
super.viewDidLoad()
SiteCreationAnalyticsHelper.trackSiteNameViewed()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
view.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent {
// Called when popping from a nav controller, e.g. hitting "Back"
SiteCreationAnalyticsHelper.trackSiteNameCanceled()
}
}
}
// MARK: Navigation Bar
private extension SiteNameViewController {
func configureNavigationBar() {
removeNavigationBarBorder()
// Title
navigationItem.backButtonTitle = TextContent.backButtonTitle
// Add skip button
navigationItem.rightBarButtonItem = UIBarButtonItem(title: TextContent.skipButtonTitle,
style: .done,
target: self,
action: #selector(skipButtonTapped))
}
@objc
private func skipButtonTapped() {
onSkip()
}
/// Removes the separator line at the bottom of the navigation bar
func removeNavigationBarBorder() {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.backgroundColor = .basicBackground
navBarAppearance.shadowColor = .clear
navBarAppearance.shadowImage = UIImage()
navigationItem.standardAppearance = navBarAppearance
navigationItem.scrollEdgeAppearance = navBarAppearance
navigationItem.compactAppearance = navBarAppearance
setNeedsStatusBarAppearanceUpdate()
}
}
// MARK: Title
private extension SiteNameViewController {
// hides or shows the title depending on the vertical size class ands accessibility category
func setTitleForTraitCollection() {
title = (traitCollection.verticalSizeClass == .compact ||
traitCollection.preferredContentSizeCategory.isAccessibilityCategory) ?
TextContent.titleForVerticalCompactSizeClass :
""
}
}
// MARK: Constants
private extension SiteNameViewController {
enum TextContent {
static let titleForVerticalCompactSizeClass = NSLocalizedString("Give your website a name",
comment: "Title for Site Name screen in iPhone landscape.")
static let skipButtonTitle = NSLocalizedString("Skip",
comment: "Title for the Skip button in the Site Name Screen.")
static let backButtonTitle = NSLocalizedString("Name",
comment: "Shortened version of the main title to be used in back navigation.")
}
}
| gpl-2.0 | 480b0d9b726fcc7ffc6c22b29fdf9f9e | 34.401869 | 133 | 0.635164 | 6.189542 | false | false | false | false |
Ezfen/iOS.Apprentice.1-4 | Checklists/Checklists/DataModel.swift | 1 | 2847 | //
// DataModel.swift
// Checklists
//
// Created by ezfen on 16/8/11.
// Copyright © 2016年 Ezfen Inc. All rights reserved.
//
import Foundation
class DataModel {
var lists = [Checklist]()
var indexOfSelectedChecklist: Int {
get {
return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex")
}
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
init() {
loadChecklists()
registerDefaults()
handleFirstTime()
}
func documentDirection() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return paths[0]
}
func dataFilePath() -> String {
return "\(documentDirection())/Checklists.plist"
}
func saveChecklists() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(lists, forKey: "Checklists")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
func loadChecklists() {
let path = dataFilePath()
if NSFileManager.defaultManager().fileExistsAtPath(path) {
if let data = NSData(contentsOfFile: path) {
let unArchiver = NSKeyedUnarchiver(forReadingWithData: data)
lists = unArchiver.decodeObjectForKey("Checklists") as! [Checklist]
unArchiver.finishDecoding()
sortChecklists()
}
}
}
func registerDefaults() {
let dictionary = ["ChecklistIndex": -1,
"FirstTime": true,
"ChecklistItemID": 0]
NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
}
func handleFirstTime() {
let userDefaults = NSUserDefaults.standardUserDefaults()
let firstTime = userDefaults.boolForKey("FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.setBool(false, forKey: "FirstTime")
userDefaults.synchronize()
}
}
func sortChecklists() {
lists.sortInPlace({checklist1, checklist2 in
return checklist1.name.localizedCompare(checklist2.name) == .OrderedAscending})
}
class func nextChecklistItemID() -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults()
let itemID = userDefaults.integerForKey("ChecklistItemID")
userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID")
userDefaults.synchronize()
return itemID
}
} | mit | 3bb68472d3eca86f090c7ebdd13e41ea | 32.470588 | 98 | 0.62166 | 5.554688 | false | false | false | false |
natecook1000/swift | test/SILGen/expressions.swift | 1 | 25473 |
// RUN: %empty-directory(%t)
// RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-emit-silgen -parse-stdlib -module-name expressions -enable-sil-ownership %s -I%t -disable-access-control | %FileCheck %s
import Swift
import FooBar
struct SillyString : _ExpressibleByBuiltinStringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {}
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
}
init(stringLiteral value: SillyString) { }
}
struct SillyUTF16String : _ExpressibleByBuiltinUTF16StringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { }
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) { }
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
}
init(stringLiteral value: SillyUTF16String) { }
}
struct SillyConstUTF16String : _ExpressibleByBuiltinConstUTF16StringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { }
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init( _builtinConstStringLiteral start: Builtin.RawPointer) { }
init( _builtinConstUTF16StringLiteral start: Builtin.RawPointer) { }
init(stringLiteral value: SillyUTF16String) { }
}
func literals() {
var a = 1
var b = 1.25
var d = "foö"
var e:SillyString = "foo"
var f:SillyConstUTF16String = "foobar"
var non_ascii:SillyConstUTF16String = "foobarö"
}
// CHECK-LABEL: sil hidden @$S11expressions8literalsyyF
// CHECK: integer_literal $Builtin.Int2048, 1
// CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}}
// CHECK: string_literal utf16 "foö"
// CHECK: string_literal utf8 "foo"
// CHECK: [[CONST_STRING_LIT:%.*]] = const_string_literal utf8 "foobar"
// CHECK: [[METATYPE:%.*]] = metatype $@thin SillyConstUTF16String.Type
// CHECK: [[FUN:%.*]] = function_ref @$S11expressions21SillyConstUTF16StringV08_builtincE7LiteralACBp_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
// CHECK: apply [[FUN]]([[CONST_STRING_LIT]], [[METATYPE]]) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
// CHECK: [[CONST_UTF16STRING_LIT:%.*]] = const_string_literal utf16 "foobarö"
// CHECK: [[FUN:%.*]] = function_ref @$S11expressions21SillyConstUTF16StringV08_builtincdE7LiteralACBp_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
// CHECK: apply [[FUN]]([[CONST_UTF16STRING_LIT]], {{.*}}) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
func bar(_ x: Int) {}
func bar(_ x: Int, _ y: Int) {}
func call_one() {
bar(42);
}
// CHECK-LABEL: sil hidden @$S11expressions8call_oneyyF
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: [[BAR:%[0-9]+]] = function_ref @$S11expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int) -> ()
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]])
func call_two() {
bar(42, 219)
}
// CHECK-LABEL: sil hidden @$S11expressions8call_twoyyF
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219
// CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}})
// CHECK: [[BAR:%[0-9]+]] = function_ref @$S11expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int, Int) -> ()
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]])
func tuples() {
bar((4, 5).1)
var T1 : (a: Int16, b: Int) = (b : 42, a : 777)
}
// CHECK-LABEL: sil hidden @$S11expressions6tuplesyyF
class C {
var chi:Int
init() {
chi = 219
}
init(x:Int) {
chi = x
}
}
// CHECK-LABEL: sil hidden @$S11expressions7classesyyF
func classes() {
// CHECK: function_ref @$S11expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
var a = C()
// CHECK: function_ref @$S11expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick C.Type) -> @owned C
var b = C(x: 0)
}
struct S {
var x:Int
init() {
x = 219
}
init(x: Int) {
self.x = x
}
}
// CHECK-LABEL: sil hidden @$S11expressions7structsyyF
func structs() {
// CHECK: function_ref @$S11expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S
var a = S()
// CHECK: function_ref @$S11expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin S.Type) -> S
var b = S(x: 0)
}
func inoutcallee(_ x: inout Int) {}
func address_of_expr() {
var x: Int = 4
inoutcallee(&x)
}
func identity<T>(_ x: T) -> T {}
struct SomeStruct {
mutating
func a() {}
}
// CHECK-LABEL: sil hidden @$S11expressions5callsyyF
// CHECK: [[METHOD:%[0-9]+]] = function_ref @$S11expressions10SomeStructV1a{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout SomeStruct) -> ()
// CHECK: apply [[METHOD]]({{.*}})
func calls() {
var a : SomeStruct
a.a()
}
// CHECK-LABEL: sil hidden @$S11expressions11module_path{{[_0-9a-zA-Z]*}}F
func module_path() -> Int {
return FooBar.x
// CHECK: [[x_GET:%[0-9]+]] = function_ref @$S6FooBar1xSivau
// CHECK-NEXT: apply [[x_GET]]()
}
func default_args(_ x: Int, y: Int = 219, z: Int = 20721) {}
// CHECK-LABEL: sil hidden @$S11expressions19call_default_args_1{{[_0-9a-zA-Z]*}}F
func call_default_args_1(_ x: Int) {
default_args(x)
// CHECK: [[YFUNC:%[0-9]+]] = function_ref @$S11expressions12default_args{{[_0-9a-zA-Z]*}}A0_
// CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]()
// CHECK: [[ZFUNC:%[0-9]+]] = function_ref @$S11expressions12default_args{{[_0-9a-zA-Z]*}}A1_
// CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S11expressions12default_args{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]])
}
// CHECK-LABEL: sil hidden @$S11expressions19call_default_args_2{{[_0-9a-zA-Z]*}}F
func call_default_args_2(_ x: Int, z: Int) {
default_args(x, z:z)
// CHECK: [[DEFFN:%[0-9]+]] = function_ref @$S11expressions12default_args{{[_0-9a-zA-Z]*}}A0_
// CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$S11expressions12default_args{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply [[FUNC]]({{.*}}, [[C219]], {{.*}})
}
struct Generic<T> {
var mono_member:Int
var typevar_member:T
// CHECK-LABEL: sil hidden @$S11expressions7GenericV13type_variable{{[_0-9a-zA-Z]*}}F
mutating
func type_variable() -> T.Type {
return T.self
// CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type
// CHECK: return [[METATYPE]]
}
// CHECK-LABEL: sil hidden @$S11expressions7GenericV19copy_typevar_member{{[_0-9a-zA-Z]*}}F
mutating
func copy_typevar_member(_ x: Generic<T>) {
typevar_member = x.typevar_member
}
// CHECK-LABEL: sil hidden @$S11expressions7GenericV12class_method{{[_0-9a-zA-Z]*}}FZ
static func class_method() {}
}
// CHECK-LABEL: sil hidden @$S11expressions18generic_member_ref{{[_0-9a-zA-Z]*}}F
func generic_member_ref<T>(_ x: Generic<T>) -> Int {
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Generic<T>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @$S11expressions24bound_generic_member_ref{{[_0-9a-zA-Z]*}}F
func bound_generic_member_ref(_ x: Generic<UnicodeScalar>) -> Int {
var x = x
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $Generic<Unicode.Scalar>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @$S11expressions6coerce{{[_0-9a-zA-Z]*}}F
func coerce(_ x: Int32) -> Int64 {
return 0
}
class B {
}
class D : B {
}
// CHECK-LABEL: sil hidden @$S11expressions8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ x: B) -> D {
return x as! D
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D
}
// CHECK-LABEL: sil hidden @$S11expressions6upcast{{[_0-9a-zA-Z]*}}F
func upcast(_ x: D) -> B {
return x
// CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B
}
// CHECK-LABEL: sil hidden @$S11expressions14generic_upcast{{[_0-9a-zA-Z]*}}F
func generic_upcast<T : B>(_ x: T) -> B {
return x
// CHECK: upcast %{{.*}} to $B
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S11expressions16generic_downcast{{[_0-9a-zA-Z]*}}F
func generic_downcast<T : B>(_ x: T, y: B) -> T {
return y as! T
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T
// CHECK: return
}
// TODO: generic_downcast
// CHECK-LABEL: sil hidden @$S11expressions15metatype_upcast{{[_0-9a-zA-Z]*}}F
func metatype_upcast() -> B.Type {
return D.self
// CHECK: metatype $@thick D
// CHECK-NEXT: upcast
}
// CHECK-LABEL: sil hidden @$S11expressions19interpolated_string{{[_0-9a-zA-Z]*}}F
func interpolated_string(_ x: Int, y: String) -> String {
return "The \(x) Million Dollar \(y)"
}
protocol Runcible {
associatedtype U
var free:Int { get }
var associated:U { get }
func free_method() -> Int
mutating func associated_method() -> U.Type
static func static_method()
}
protocol Mincible {
var free:Int { get }
func free_method() -> Int
static func static_method()
}
protocol Bendable { }
protocol Wibbleable { }
// CHECK-LABEL: sil hidden @$S11expressions20archetype_member_ref{{[_0-9a-zA-Z]*}}F
func archetype_member_ref<T : Runcible>(_ x: T) {
var x = x
x.free_method()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X:%.*]]
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[READ]] to [initialization] [[TEMP]]
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: witness_method $T, #Runcible.free_method!1
// CHECK-NEXT: apply
// CHECK-NEXT: destroy_addr [[TEMP]]
var u = x.associated_method()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown]
// CHECK-NEXT: witness_method $T, #Runcible.associated_method!1
// CHECK-NEXT: apply
T.static_method()
// CHECK: metatype $@thick T.Type
// CHECK-NEXT: witness_method $T, #Runcible.static_method!1
// CHECK-NEXT: apply
}
// CHECK-LABEL: sil hidden @$S11expressions22existential_member_ref{{[_0-9a-zA-Z]*}}F
func existential_member_ref(_ x: Mincible) {
x.free_method()
// CHECK: open_existential_addr
// CHECK-NEXT: witness_method
// CHECK-NEXT: apply
}
/*TODO archetype and existential properties and subscripts
func archetype_property_ref<T : Runcible>(_ x: T) -> (Int, T.U) {
x.free = x.free_method()
x.associated = x.associated_method()
return (x.free, x.associated)
}
func existential_property_ref<T : Runcible>(_ x: T) -> Int {
x.free = x.free_method()
return x.free
}
also archetype/existential subscripts
*/
struct Spoon : Runcible, Mincible {
typealias U = Float
var free: Int { return 4 }
var associated: Float { return 12 }
func free_method() -> Int {}
func associated_method() -> Float.Type {}
static func static_method() {}
}
struct Hat<T> : Runcible {
typealias U = [T]
var free: Int { return 1 }
var associated: U { get {} }
func free_method() -> Int {}
// CHECK-LABEL: sil hidden @$S11expressions3HatV17associated_method{{[_0-9a-zA-Z]*}}F
mutating
func associated_method() -> U.Type {
return U.self
// CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type
// CHECK: return [[META]]
}
static func static_method() {}
}
// CHECK-LABEL: sil hidden @$S11expressions7erasure{{[_0-9a-zA-Z]*}}F
func erasure(_ x: Spoon) -> Mincible {
return x
// CHECK: init_existential_addr
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S11expressions19declref_to_metatypeAA5SpoonVmyF
func declref_to_metatype() -> Spoon.Type {
return Spoon.self
// CHECK: metatype $@thin Spoon.Type
}
// CHECK-LABEL: sil hidden @$S11expressions27declref_to_generic_metatype{{[_0-9a-zA-Z]*}}F
func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type {
// FIXME parsing of T<U> in expression context
typealias GenericChar = Generic<UnicodeScalar>
return GenericChar.self
// CHECK: metatype $@thin Generic<Unicode.Scalar>.Type
}
func int(_ x: Int) {}
func float(_ x: Float) {}
func tuple() -> (Int, Float) { return (1, 1.0) }
// CHECK-LABEL: sil hidden @$S11expressions13tuple_element{{[_0-9a-zA-Z]*}}F
func tuple_element(_ x: (Int, Float)) {
var x = x
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Float) }
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
int(x.0)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: apply
float(x.1)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: apply
int(tuple().0)
// CHECK: ([[ZERO:%.*]], {{%.*}}) = destructure_tuple
// CHECK: apply {{.*}}([[ZERO]])
float(tuple().1)
// CHECK: ({{%.*}}, [[ONE:%.*]]) = destructure_tuple
// CHECK: apply {{.*}}([[ONE]])
}
// CHECK-LABEL: sil hidden @$S11expressions10containers{{[_0-9a-zA-Z]*}}F
func containers() -> ([Int], Dictionary<String, Int>) {
return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3])
}
// CHECK-LABEL: sil hidden @$S11expressions7if_expr{{[_0-9a-zA-Z]*}}F
func if_expr(_ a: Bool, b: Bool, x: Int, y: Int, z: Int) -> Int {
var a = a
var b = b
var x = x
var y = y
var z = z
// CHECK: bb0({{.*}}):
// CHECK: [[AB:%[0-9]+]] = alloc_box ${ var Bool }
// CHECK: [[PBA:%.*]] = project_box [[AB]]
// CHECK: [[BB:%[0-9]+]] = alloc_box ${ var Bool }
// CHECK: [[PBB:%.*]] = project_box [[BB]]
// CHECK: [[XB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBX:%.*]] = project_box [[XB]]
// CHECK: [[YB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBY:%.*]] = project_box [[YB]]
// CHECK: [[ZB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBZ:%.*]] = project_box [[ZB]]
return a
? x
: b
? y
: z
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBA]]
// CHECK: [[A:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]])
// CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]]
// CHECK: [[IF_A]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]]
// CHECK: [[XVAL:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int)
// CHECK: [[ELSE_A]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBB]]
// CHECK: [[B:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]])
// CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]]
// CHECK: [[IF_B]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBY]]
// CHECK: [[YVAL:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int)
// CHECK: [[ELSE_B]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBZ]]
// CHECK: [[ZVAL:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int)
// CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : @trivial $Int):
// CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int)
// CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : @trivial $Int):
// CHECK: return [[A_RES]]
}
// Test that magic identifiers expand properly. We test #column here because
// it isn't affected as this testcase slides up and down the file over time.
func magic_identifier_expansion(_ a: Int = #column) {
// CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion
// This should expand to the column number of the first _.
var tmp = #column
// CHECK: integer_literal $Builtin.Int2048, 13
// This should expand to the column number of the (, not to the column number
// of #column in the default argument list of this function.
// rdar://14315674
magic_identifier_expansion()
// CHECK: integer_literal $Builtin.Int2048, 29
}
func print_string() {
// CHECK-LABEL: print_string
var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}"
// CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}"
}
// Test that we can silgen superclass calls that go farther than the immediate
// superclass.
class Super1 {
func funge() {}
}
class Super2 : Super1 {}
class Super3 : Super2 {
override func funge() {
super.funge()
}
}
// <rdar://problem/16880240> SILGen crash assigning to _
func testDiscardLValue() {
var a = 42
_ = a
}
func dynamicTypePlusZero(_ a: Super1) -> Super1.Type {
return type(of: a)
}
// CHECK-LABEL: dynamicTypePlusZero
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Super1):
// CHECK-NOT: copy_value
// CHECK: value_metatype $@thick Super1.Type, [[ARG]] : $Super1
struct NonTrivialStruct {
var c : Super1
var x: NonTrivialStruct? {
get { return nil }
set {}
}
}
func dontEmitIgnoredLoadExpr(_ a: NonTrivialStruct) -> NonTrivialStruct.Type {
return type(of: a)
}
// CHECK-LABEL: dontEmitIgnoredLoadExpr
// CHECK: bb0(%0 : @guaranteed $NonTrivialStruct):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[RESULT:%.*]] = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: return [[RESULT]] : $@thin NonTrivialStruct.Type
// Test that we evaluate the force unwrap to get its side effects (a potential trap),
// but don't actually need to perform the load of its value.
func dontLoadIgnoredLValueForceUnwrap(_ a: inout NonTrivialStruct?) -> NonTrivialStruct.Type {
return type(of: a!)
}
// CHECK-LABEL: dontLoadIgnoredLValueForceUnwrap
// CHECK: bb0(%0 : @trivial $*Optional<NonTrivialStruct>):
// CHECK-NEXT: debug_value_addr %0
// CHECK-NEXT: [[READ:%[0-9]+]] = begin_access [read] [unknown] %0
// CHECK-NEXT: switch_enum_addr [[READ]] : $*Optional<NonTrivialStruct>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: unreachable
// CHECK: bb2:
// CHECK-NEXT: unchecked_take_enum_data_addr [[READ]] : $*Optional<NonTrivialStruct>, #Optional.some!enumelt.1
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: [[METATYPE:%[0-9]+]] = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: return [[METATYPE]]
func dontLoadIgnoredLValueDoubleForceUnwrap(_ a: inout NonTrivialStruct??) -> NonTrivialStruct.Type {
return type(of: a!!)
}
// CHECK-LABEL: dontLoadIgnoredLValueDoubleForceUnwrap
// CHECK: bb0(%0 : @trivial $*Optional<Optional<NonTrivialStruct>>):
// CHECK-NEXT: debug_value_addr %0
// CHECK-NEXT: [[READ:%[0-9]+]] = begin_access [read] [unknown] %0
// CHECK-NEXT: switch_enum_addr [[READ]] : $*Optional<Optional<NonTrivialStruct>>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: unreachable
// CHECK: bb2:
// CHECK-NEXT: [[UNWRAPPED:%[0-9]+]] = unchecked_take_enum_data_addr [[READ]] : $*Optional<Optional<NonTrivialStruct>>, #Optional.some!enumelt.1
// CHECK-NEXT: switch_enum_addr [[UNWRAPPED]] : $*Optional<NonTrivialStruct>, case #Optional.some!enumelt.1: bb4, case #Optional.none!enumelt: bb3
// CHECK: bb3:
// CHECK: unreachable
// CHECK: bb4:
// CHECK-NEXT: unchecked_take_enum_data_addr [[UNWRAPPED]] : $*Optional<NonTrivialStruct>, #Optional.some!enumelt.1
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: [[METATYPE:%[0-9]+]] = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: return [[METATYPE]]
func loadIgnoredLValueForceUnwrap(_ a: inout NonTrivialStruct) -> NonTrivialStruct.Type {
return type(of: a.x!)
}
// CHECK-LABEL: loadIgnoredLValueForceUnwrap
// CHECK: bb0(%0 : @trivial $*NonTrivialStruct):
// CHECK-NEXT: debug_value_addr %0
// CHECK-NEXT: [[READ:%[0-9]+]] = begin_access [read] [unknown] %0
// CHECK-NEXT: [[BORROW:%[0-9]+]] = load_borrow [[READ]]
// CHECK-NEXT: // function_ref NonTrivialStruct.x.getter
// CHECK-NEXT: [[GETTER:%[0-9]+]] = function_ref @$S{{[_0-9a-zA-Z]*}}vg : $@convention(method) (@guaranteed NonTrivialStruct) -> @owned Optional<NonTrivialStruct>
// CHECK-NEXT: [[X:%[0-9]+]] = apply [[GETTER]]([[BORROW]])
// CHECK-NEXT: end_borrow [[BORROW]] from [[READ]]
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: switch_enum [[X]] : $Optional<NonTrivialStruct>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: unreachable
// CHECK: bb2([[UNWRAPPED_X:%[0-9]+]] : @owned $NonTrivialStruct):
// CHECK-NEXT: destroy_value [[UNWRAPPED_X]]
// CHECK-NEXT: [[METATYPE:%[0-9]+]] = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: return [[METATYPE]]
func loadIgnoredLValueThroughForceUnwrap(_ a: inout NonTrivialStruct?) -> NonTrivialStruct.Type {
return type(of: a!.x!)
}
// CHECK-LABEL: loadIgnoredLValueThroughForceUnwrap
// CHECK: bb0(%0 : @trivial $*Optional<NonTrivialStruct>):
// CHECK-NEXT: debug_value_addr %0
// CHECK-NEXT: [[READ:%[0-9]+]] = begin_access [read] [unknown] %0
// CHECK-NEXT: switch_enum_addr [[READ]] : $*Optional<NonTrivialStruct>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: unreachable
// CHECK: bb2:
// CHECK-NEXT: [[UNWRAPPED:%[0-9]+]] = unchecked_take_enum_data_addr [[READ]] : $*Optional<NonTrivialStruct>, #Optional.some!enumelt.1
// CHECK-NEXT: [[BORROW:%[0-9]+]] = load_borrow [[UNWRAPPED]]
// CHECK-NEXT: // function_ref NonTrivialStruct.x.getter
// CHECK-NEXT: [[GETTER:%[0-9]+]] = function_ref @$S{{[_0-9a-zA-Z]*}}vg : $@convention(method) (@guaranteed NonTrivialStruct) -> @owned Optional<NonTrivialStruct>
// CHECK-NEXT: [[X:%[0-9]+]] = apply [[GETTER]]([[BORROW]])
// CHECK-NEXT: end_borrow [[BORROW]] from [[UNWRAPPED]]
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: switch_enum [[X]] : $Optional<NonTrivialStruct>, case #Optional.some!enumelt.1: bb4, case #Optional.none!enumelt: bb3
// CHECK: bb3:
// CHECK: unreachable
// CHECK: bb4([[UNWRAPPED_X:%[0-9]+]] : @owned $NonTrivialStruct):
// CHECK-NEXT: destroy_value [[UNWRAPPED_X]]
// CHECK-NEXT: [[METATYPE:%[0-9]+]] = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: return [[METATYPE]]
func evaluateIgnoredKeyPathExpr(_ s: inout NonTrivialStruct, _ kp: WritableKeyPath<NonTrivialStruct, Int>) -> Int.Type {
return type(of: s[keyPath: kp])
}
// CHECK-LABEL: evaluateIgnoredKeyPathExpr
// CHECK: bb0(%0 : @trivial $*NonTrivialStruct, %1 : @guaranteed $WritableKeyPath<NonTrivialStruct, Int>):
// CHECK-NEXT: debug_value_addr %0
// CHECK-NEXT: debug_value %1
// CHECK-NEXT: [[S_READ:%[0-9]+]] = begin_access [read] [unknown] %0
// CHECK-NEXT: [[S_TEMP:%[0-9]+]] = alloc_stack $NonTrivialStruct
// CHECK-NEXT: copy_addr [[S_READ]] to [initialization] [[S_TEMP]]
// CHECK-NEXT: [[KP_TEMP:%[0-9]+]] = copy_value %1
// CHECK-NEXT: [[KP:%[0-9]+]] = upcast [[KP_TEMP]]
// CHECK-NEXT: [[RESULT:%[0-9]+]] = alloc_stack $Int
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[PROJECT_FN:%[0-9]+]] = function_ref @$Ss23_projectKeyPathReadOnly{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[KP_BORROW:%.*]] = begin_borrow [[KP]]
// CHECK-NEXT: apply [[PROJECT_FN]]<NonTrivialStruct, Int>([[RESULT]], [[S_TEMP]], [[KP_BORROW]])
// CHECK-NEXT: end_access [[S_READ]]
// CHECK-NEXT: end_borrow [[KP_BORROW]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_value [[KP]]
// CHECK-NEXT: destroy_addr [[S_TEMP]]
// CHECK-NEXT: dealloc_stack [[S_TEMP]]
// CHECK-NEXT: [[METATYPE:%[0-9]+]] = metatype $@thin Int.Type
// CHECK-NOT: destroy_value %1
// CHECK-NEXT: return [[METATYPE]]
// <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding
// CHECK-LABEL: sil hidden @$S11expressions21implodeRecursiveTupleyySi_Sit_SitSgF
// CHECK: bb0(%0 : @trivial $Optional<((Int, Int), Int)>):
func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) {
// CHECK: bb2([[WHOLE:%.*]] : @trivial $((Int, Int), Int)):
// CHECK-NEXT: ([[X:%[0-9]+]], [[Y:%[0-9]+]]) = destructure_tuple [[WHOLE]]
// CHECK-NEXT: ([[X0:%[0-9]+]], [[X1:%[0-9]+]]) = destructure_tuple [[X]]
// CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[X0]] : $Int, [[X1]] : $Int)
// CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x"
// CHECK-NEXT: debug_value [[Y]] : $Int, let, name "y"
let (x, y) = expr!
}
func test20087517() {
class Color {
static func greenColor() -> Color { return Color() }
}
let x: (Color?, Int) = (.greenColor(), 1)
}
func test20596042() {
enum E {
case thing1
case thing2
}
func f() -> (E?, Int)? {
return (.thing1, 1)
}
}
func test21886435() {
() = ()
}
| apache-2.0 | b2119a9ed548d03ce1a3d7bef46ba649 | 33.64898 | 210 | 0.634979 | 3.172667 | false | false | false | false |
Yoseob/Trevi | Lime/Lime/Lime.swift | 1 | 3893 | //
// Trevi.swift
// Trevi
//
// Created by LeeYoseob on 2015. 12. 7..
// Copyright © 2015년 LeeYoseob. All rights reserved.
//
import Foundation
import Trevi
/*
For Trevi users, allow routing and to apply middlewares without difficulty.
*/
public class Lime : Routable {
public var setting: [String: AnyObject]!
public var router: Router{
let r = self._router
if let r = r {
return r
}
return Router()
}
public override init () {
super.init()
lazyRouter()
}
private func lazyRouter(){
guard _router == nil else {
return
}
_router = Router()
_router.use(md: Query())
}
public func use(middleware: Middleware) {
_router.use(md: middleware)
}
#if os(Linux)
public func set(name: String, _ val: String){
if setting == nil {
setting = [String: AnyObject]()
}
setting[name] = StringWrapper(string: val)
}
#endif
public func set(name: String, _ val: AnyObject){
if setting == nil {
setting = [String: AnyObject]()
}
setting[name] = val
}
public func handle(req: IncomingMessage, res: ServerResponse, next: NextCallback?){
var done: NextCallback? = next
if next == nil{
func finalHandler() {
res.statusCode = 404
let msg = "Not Found 404"
res.write(msg)
res.end()
}
done = finalHandler
req.app = self
}
return self._router.handle(req,res: res,next: done!)
}
}
// Needed to activate lime in the Trevi Fountain.
extension Lime: ApplicationProtocol {
public func createApplication() -> Any {
return self.handle
}
}
// For Lime extension ServerResponse
extension ServerResponse {
// Lime recommend using that send rather than using write
public func send(data: String, encoding: String! = nil, type: String! = ""){
write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
public func send(data: NSData, encoding: String! = nil, type: String! = ""){
write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
public func send(data: [String : String], encoding: String! = nil, type: String! = ""){
write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
private func endReuqstAndClean(){
end()
if req.files != nil {
for file in self.req.files.values{
FSBase.unlink(path: file.path)
}
}
}
public func render(path: String, args: [String:String]? = nil) {
if let app = req.app as? Lime, let render = app.setting["view engine"] as? Render {
var entirePath = path
#if os(Linux)
if let abpath = app.setting["views"] as? StringWrapper {
entirePath = "\(abpath.string)/\(entirePath)"
}
#else
if let bundlePath = NSBundle.mainBundle().pathForResource(NSURL(fileURLWithPath: path).lastPathComponent!, ofType: nil) {
entirePath = bundlePath
}
#endif
if args != nil {
render.render(entirePath, args: args!) { data in
self.write(data)
}
} else {
render.render(entirePath) { data in
self.write(data)
}
}
}
end()
}
public func redirect(url: String){
self.writeHead(302, headers: [Location:url])
self.end()
}
}
//extention incomingMessage for lime
extension IncomingMessage {
}
| apache-2.0 | 04f142aad59f50d15b6a5b3aafed6b32 | 23.77707 | 133 | 0.527763 | 4.375703 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/Map Detail/Presenter Tests/Test Doubles/FakeMapDetailInteractor.swift | 1 | 1603 | import EurofurenceApplication
import EurofurenceModel
import Foundation
import XCTEurofurenceModel
class FakeMapDetailViewModelFactory: MapDetailViewModelFactory {
private let expectedMapIdentifier: MapIdentifier
init(expectedMapIdentifier: MapIdentifier = .random) {
self.expectedMapIdentifier = expectedMapIdentifier
}
let viewModel = FakeMapDetailViewModel()
func makeViewModelForMap(identifier: MapIdentifier, completionHandler: @escaping (MapDetailViewModel) -> Void) {
guard identifier == expectedMapIdentifier else { return }
completionHandler(viewModel)
}
}
class FakeMapDetailViewModel: MapDetailViewModel {
var mapImagePNGData: Data = .random
var mapName: String = .random
private(set) var positionToldToShowMapContentsFor: (x: Float, y: Float)?
fileprivate var contentsVisitor: MapContentVisitor?
func showContentsAtPosition(x: Float, y: Float, describingTo visitor: MapContentVisitor) {
positionToldToShowMapContentsFor = (x: x, y: y)
contentsVisitor = visitor
}
}
extension FakeMapDetailViewModel {
func resolvePositionalContent(with position: MapCoordinate) {
contentsVisitor?.visit(position)
}
func resolvePositionalContent(with content: MapInformationContextualContent) {
contentsVisitor?.visit(content)
}
func resolvePositionalContent(with dealer: DealerIdentifier) {
contentsVisitor?.visit(dealer)
}
func resolvePositionalContent(with mapContents: MapContentOptionsViewModel) {
contentsVisitor?.visit(mapContents)
}
}
| mit | c7309e86269860e96df89af6a8891b0b | 28.685185 | 116 | 0.749844 | 4.947531 | false | false | false | false |
Witcast/witcast-ios | Pods/Material/Sources/iOS/FABMenu.swift | 1 | 16316 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(FABMenuDirection)
public enum FABMenuDirection: Int {
case up
case down
case left
case right
}
open class FABMenuItem: View {
/// A reference to the titleLabel.
open let titleLabel = UILabel()
/// A reference to the fabButton.
open let fabButton = FABButton()
open override func prepare() {
super.prepare()
backgroundColor = nil
prepareFABButton()
prepareTitleLabel()
}
/// A reference to the titleLabel text.
open var title: String? {
get {
return titleLabel.text
}
set(value) {
titleLabel.text = value
layoutSubviews()
}
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let t = title, 0 < t.utf16.count else {
titleLabel.removeFromSuperview()
return
}
if nil == titleLabel.superview {
addSubview(titleLabel)
}
}
}
extension FABMenuItem {
/// Shows the titleLabel.
open func showTitleLabel() {
let interimSpace = InterimSpacePresetToValue(preset: .interimSpace6)
titleLabel.sizeToFit()
titleLabel.width += 1.5 * interimSpace
titleLabel.height += interimSpace / 2
titleLabel.y = (height - titleLabel.height) / 2
titleLabel.x = -titleLabel.width - interimSpace
titleLabel.alpha = 0
titleLabel.isHidden = false
UIView.animate(withDuration: 0.25, animations: { [weak self] in
guard let s = self else {
return
}
s.titleLabel.alpha = 1
})
}
/// Hides the titleLabel.
open func hideTitleLabel() {
titleLabel.isHidden = true
}
}
extension FABMenuItem {
/// Prepares the fabButton.
fileprivate func prepareFABButton() {
layout(fabButton).edges()
}
/// Prepares the titleLabel.
fileprivate func prepareTitleLabel() {
titleLabel.font = RobotoFont.regular(with: 14)
titleLabel.textAlignment = .center
titleLabel.backgroundColor = .white
titleLabel.depthPreset = fabButton.depthPreset
titleLabel.cornerRadiusPreset = .cornerRadius1
}
}
@objc(FABMenuDelegate)
public protocol FABMenuDelegate {
/**
A delegation method that is execited when the fabMenu will open.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuWillOpen(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu did open.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuDidOpen(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu will close.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuWillClose(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu did close.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuDidClose(fabMenu: FABMenu)
/**
A delegation method that is executed when the user taps while
the menu is opened.
- Parameter fabMenu: A FABMenu.
- Parameter tappedAt point: A CGPoint.
- Parameter isOutside: A boolean indicating whether the tap
was outside the menu button area.
*/
@objc
optional func fabMenu(fabMenu: FABMenu, tappedAt point: CGPoint, isOutside: Bool)
}
@objc(FABMenu)
open class FABMenu: View {
/// A reference to the SpringAnimation object.
internal let spring = SpringAnimation()
open var fabMenuDirection: FABMenuDirection {
get {
switch spring.springDirection {
case .up:
return .up
case .down:
return .down
case .left:
return .left
case .right:
return .right
}
}
set(value) {
switch value {
case .up:
spring.springDirection = .up
case .down:
spring.springDirection = .down
case .left:
spring.springDirection = .left
case .right:
spring.springDirection = .right
}
layoutSubviews()
}
}
/// A reference to the base FABButton.
open var fabButton: FABButton? {
didSet {
oldValue?.removeFromSuperview()
guard let v = fabButton else {
return
}
addSubview(v)
v.addTarget(self, action: #selector(handleFABButton(button:)), for: .touchUpInside)
}
}
/// An internal handler for the FABButton.
internal var handleFABButtonCallback: ((UIButton) -> Void)?
/// An internal handler for the open function.
internal var handleOpenCallback: (() -> Void)?
/// An internal handler for the close function.
internal var handleCloseCallback: (() -> Void)?
/// An internal handler for the completion function.
internal var handleCompletionCallback: ((UIView) -> Void)?
/// Size of FABMenuItems.
open var fabMenuItemSize: CGSize {
get {
return spring.itemSize
}
set(value) {
spring.itemSize = value
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset: InterimSpacePreset {
get {
return spring.interimSpacePreset
}
set(value) {
spring.interimSpacePreset = value
}
}
/// The space between views.
open var interimSpace: InterimSpace {
get {
return spring.interimSpace
}
set(value) {
spring.interimSpace = value
}
}
/// A boolean indicating if the menu is open or not.
open var isOpened: Bool {
get {
return spring.isOpened
}
set(value) {
spring.isOpened = value
}
}
/// A boolean indicating if the menu is enabled.
open var isEnabled: Bool {
get {
return spring.isEnabled
}
set(value) {
spring.isEnabled = value
}
}
/// An optional delegation handler.
open weak var delegate: FABMenuDelegate?
/// A reference to the FABMenuItems
open var fabMenuItems: [FABMenuItem] {
get {
return spring.views as! [FABMenuItem]
}
set(value) {
for v in spring.views {
v.removeFromSuperview()
}
for v in value {
addSubview(v)
}
spring.views = value
}
}
open override func layoutSubviews() {
super.layoutSubviews()
fabButton?.frame.size = bounds.size
spring.baseSize = bounds.size
}
open override func prepare() {
super.prepare()
backgroundColor = nil
interimSpacePreset = .interimSpace6
}
}
extension FABMenu {
/**
Open the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
open func open(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
open(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
/**
Open the Menu component with animation options.
- Parameter isTriggeredByUserInteraction: A boolean indicating whether the
state was changed by a user interaction, true if yes, false otherwise.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
internal func open(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
handleOpenCallback?()
if isTriggeredByUserInteraction {
delegate?.fabMenuWillOpen?(fabMenu: self)
}
spring.expand(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in
guard let s = self else {
return
}
(view as? FABMenuItem)?.showTitleLabel()
if isTriggeredByUserInteraction && view == s.fabMenuItems.last {
s.delegate?.fabMenuDidOpen?(fabMenu: s)
}
completion?(view)
s.handleCompletionCallback?(view)
}
}
/**
Close the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
open func close(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
close(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
/**
Close the Menu component with animation options.
- Parameter isTriggeredByUserInteraction: A boolean indicating whether the
state was changed by a user interaction, true if yes, false otherwise.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
internal func close(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
handleCloseCallback?()
if isTriggeredByUserInteraction {
delegate?.fabMenuWillClose?(fabMenu: self)
}
spring.contract(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in
guard let s = self else {
return
}
(view as? FABMenuItem)?.hideTitleLabel()
if isTriggeredByUserInteraction && view == s.fabMenuItems.last {
s.delegate?.fabMenuDidClose?(fabMenu: s)
}
completion?(view)
s.handleCompletionCallback?(view)
}
}
}
extension FABMenu {
/**
Handles the hit test for the Menu and views outside of the Menu bounds.
- Parameter _ point: A CGPoint.
- Parameter with event: An optional UIEvent.
- Returns: An optional UIView.
*/
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard isOpened, isEnabled else {
return super.hitTest(point, with: event)
}
for v in subviews {
let p = v.convert(point, from: self)
if v.bounds.contains(p) {
delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: false)
return v.hitTest(p, with: event)
}
}
delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: true)
close(isTriggeredByUserInteraction: true)
return super.hitTest(point, with: event)
}
}
extension FABMenu {
/**
Handler to toggle the FABMenu opened or closed.
- Parameter button: A UIButton.
*/
@objc
fileprivate func handleFABButton(button: UIButton) {
guard nil == handleFABButtonCallback else {
handleFABButtonCallback?(button)
return
}
guard isOpened else {
open(isTriggeredByUserInteraction: true)
return
}
close(isTriggeredByUserInteraction: true)
}
}
| apache-2.0 | 45b3225cee9d3d428048940c0aff22f4 | 34.702407 | 308 | 0.630547 | 5.097157 | false | false | false | false |
031240302/DouYuZB | DYZB/DYZB/Tools/Common.swift | 1 | 334 | //
// Common.swift
// DYZB
//
// Created by kk on 2017/10/11.
// Copyright © 2017年 kk. All rights reserved.
//
import UIKit
let kStatusBarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
let kTabbarY = UITabBar.appearance().bounds.origin.y
| mit | d2be06360593626b19cb4278d8431f1f | 22.642857 | 52 | 0.728097 | 3.447917 | false | false | false | false |
myTargetSDK/mytarget-ios | myTargetDemoSwift/myTargetDemo/Controllers/MainViewController.swift | 1 | 8016 | //
// MainViewController.swift
// myTargetDemo
//
// Created by Alexander Vorobyev on 17.08.2022.
// Copyright © 2022 Mail.ru Group. All rights reserved.
//
import UIKit
import MyTargetSDK
final class MainViewController: UIViewController {
private enum CellType {
case advertisment(Advertisment)
case custom(CustomAdvertisment)
var title: String {
switch self {
case .advertisment(let advertisment):
return advertisment.title
case .custom(let advertisment):
return advertisment.title
}
}
var description: String {
switch self {
case .advertisment(let advertisment):
return advertisment.description
case .custom(let advertisment):
return advertisment.description
}
}
}
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.separatorColor = .separatorColor()
tableView.backgroundColor = .backgroundColor()
tableView.tableFooterView = UIView()
tableView.register(MenuTableViewCell.self, forCellReuseIdentifier: MenuTableViewCell.reuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
private lazy var provider: CustomAdvertismentProvider = .init()
private var content: [CellType] = []
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .backgroundColor()
view.addSubview(tableView)
let titleView = TitleView(frame: CGRect(x: 0, y: 0, width: 150, height: 32))
titleView.version.text = "SDK version: " + MTRGVersion.currentVersion()
titleView.title.text = "myTarget Demo"
navigationItem.titleView = titleView
navigationItem.rightBarButtonItem = .init(barButtonSystemItem: .add, target: self, action: #selector(addBarButtonTap(_:)))
let bannersDescription = UIDevice.current.userInterfaceIdiom == .pad ? "320x50, 300x250 and 728x90 banners" : "320x50 and 300x250 banners"
content = [
.advertisment(.init(title: "Banners", description: bannersDescription, type: .banner)),
.advertisment(.init(title: "Interstitial Ads", description: "Fullscreen banners", type: .interstitial)),
.advertisment(.init(title: "Rewarded video", description: "Fullscreen rewarded video", type: .rewarded)),
.advertisment(.init(title: "Native Ads", description: "Advertisement inside app's content", type: .native)),
.advertisment(.init(title: "Native Banners", description: "Compact advertisement inside app's content", type: .nativeBanner)),
.advertisment(.init(title: "In-stream video", description: "Advertisement inside video stream", type: .instream))
]
content.append(contentsOf: provider.receive().map { .custom($0) })
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.indexPathForSelectedRow.map { tableView.deselectRow(at: $0, animated: true) }
}
// MARK: - Actions
@objc func addBarButtonTap(_ sender: UIBarButtonItem) {
let viewController = AddingAdViewController()
viewController.delegate = self
navigationController?.pushViewController(viewController, animated: true)
}
}
// MARK: - UITableViewDelegate
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController: UIViewController
switch content[indexPath.row] {
case .advertisment(let advertisment):
switch advertisment.type {
case .banner:
viewController = BannerSettingsViewController()
case .instream:
viewController = InstreamViewController()
case .interstitial:
viewController = InterstitialViewController()
case .native:
viewController = NativeSettingsViewController()
case .nativeBanner:
viewController = NativeBannerViewController()
case .rewarded:
viewController = RewardedViewController()
}
case .custom(let customAdvertisment):
switch customAdvertisment.type {
case .banner:
viewController = BannerSettingsViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
case .instream:
viewController = InstreamViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
case .interstitial:
viewController = InterstitialViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
case .native:
viewController = NativeViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
case .nativeBanner:
viewController = NativeBannerViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
case .rewarded:
viewController = RewardedViewController(slotId: customAdvertisment.slotId,
query: customAdvertisment.query)
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// MARK: - UITableViewDataSource
extension MainViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return content.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MenuTableViewCell.reuseIdentifier, for: indexPath) as! MenuTableViewCell
cell.configure(title: content[indexPath.row].title, description: content[indexPath.row].description)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
switch content[indexPath.row] {
case .advertisment:
return false
case .custom:
return true
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete,
case .custom(let customAd) = content[indexPath.row]
else {
return
}
tableView.beginUpdates()
provider.remove(customAd)
content.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
}
// MARK: - AddingAdViewControllerDelegate
extension MainViewController: AddingAdViewControllerDelegate {
func addingAdViewControllerDidAddCustomAdvertisment(_ customAdvertisment: CustomAdvertisment) {
tableView.beginUpdates()
provider.add(customAdvertisment)
content.append(.custom(customAdvertisment))
tableView.insertRows(at: [.init(row: content.count - 1, section: 0)], with: .automatic)
tableView.endUpdates()
navigationController?.popToViewController(self, animated: true)
}
}
| lgpl-3.0 | 2b19e3f2843af967faeff087da41afc9 | 38.482759 | 146 | 0.62121 | 5.539046 | false | false | false | false |
kosicki123/WWDC | WWDC/Session.swift | 6 | 2972 | //
// Video.swift
// WWDC
//
// Created by Guilherme Rambo on 18/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Foundation
let SessionProgressDidChangeNotification = "SessionProgressDidChangeNotification"
let SessionFavoriteStatusDidChangeNotification = "SessionFavoriteStatusDidChangeNotification"
struct Session {
var date: String?
var description: String
var focus: [String]
var id: Int
var slides: String?
var title: String
var track: String
var url: String
var year: Int
var hd_url: String?
var progress: Double {
get {
return DataStore.SharedStore.fetchSessionProgress(self)
}
set {
DataStore.SharedStore.putSessionProgress(self, progress: newValue)
NSNotificationCenter.defaultCenter().postNotificationName(SessionProgressDidChangeNotification, object: self.progressKey)
}
}
var currentPosition: Double {
get {
return DataStore.SharedStore.fetchSessionCurrentPosition(self)
}
set {
DataStore.SharedStore.putSessionCurrentPosition(self, position: newValue)
}
}
var favorite: Bool {
get {
return DataStore.SharedStore.fetchSessionIsFavorite(self)
}
set {
DataStore.SharedStore.putSessionIsFavorite(self, favorite: newValue)
NSNotificationCenter.defaultCenter().postNotificationName(SessionFavoriteStatusDidChangeNotification, object: self.uniqueKey)
}
}
var shareURL: String {
get {
return "wwdc://\(year)/\(id)"
}
}
var uniqueKey: String {
get {
return "\(year)-\(id)"
}
}
var progressKey: String {
get {
return "\(uniqueKey)-progress"
}
}
var currentPositionKey: String {
get {
return "\(uniqueKey)-currentPosition"
}
}
init(date: String?, description: String, focus: [String], id: Int, slides: String?, title: String, track: String, url: String, year: Int, hd_url: String?)
{
self.date = date
self.description = description
self.focus = focus
self.id = id
self.slides = slides
self.title = title
self.track = track
self.url = url
self.year = year
self.hd_url = hd_url
}
func setProgressWithoutSendingNotification(progress: Double) {
DataStore.SharedStore.putSessionProgress(self, progress: progress)
}
func setFavoriteWithoutSendingNotification(favorite: Bool) {
DataStore.SharedStore.putSessionIsFavorite(self, favorite: favorite)
}
func shareURL(time: Double) -> String {
return "\(shareURL)?t=\(time)"
}
}
extension Session: Equatable {}
func ==(lhs: Session, rhs: Session) -> Bool {
return lhs.uniqueKey == rhs.uniqueKey
} | bsd-2-clause | 1b1164a70a86cd2ad42f9602fba126d9 | 26.027273 | 158 | 0.617093 | 4.770465 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/data types/XGLevelUpMove.swift | 1 | 1086 | //
// LevelUpMove.swift
// Mausoleum Stats Tool
//
// Created by StarsMmd on 26/12/2014.
// Copyright (c) 2014 StarsMmd. All rights reserved.
//
import Foundation
let kNumberOfLevelUpMoves = 0x13
let kSizeOfLevelUpData = 0x4
let kLevelUpMoveLevelOffset = 0x0 // 1 byte
let kLevelUpMoveIndexOffset = 0x2 // 2 bytes
class XGLevelUpMove: NSObject, Codable {
var level = 0x0
var move = XGMoves.index(0)
init(level: Int, move: Int) {
super.init()
self.level = level
self.move = .index(move)
}
func isSet() -> Bool {
return self.level > 0
}
func toInts() -> (Int, Int) {
return (level, move.index)
}
}
extension XGLevelUpMove: XGDocumentable {
static var className: String {
return "Level Up Move"
}
var documentableName: String {
return move.name.unformattedString
}
static var DocumentableKeys: [String] {
return ["level", "move"]
}
func documentableValue(for key: String) -> String {
switch key {
case "level":
return level.string
case "move":
return move.name.unformattedString
default:
return ""
}
}
}
| gpl-2.0 | 8581d399bb66c90bfa7c5d31d8b56559 | 16.238095 | 53 | 0.672192 | 3.042017 | false | false | false | false |
Authman2/Pix | Pix/ActivityCell.swift | 1 | 1302 | //
// FollowRequestCellTableViewCell.swift
// Pix
//
// Created by Adeola Uthman on 1/8/17.
// Copyright © 2017 Adeola Uthman. All rights reserved.
//
import UIKit
import SnapKit
import Firebase
class ActivityCell: UICollectionViewCell {
/********************************
*
* VARIABLES
*
********************************/
let titleLabel: UILabel = {
let a = UILabel();
a.translatesAutoresizingMaskIntoConstraints = false;
a.numberOfLines = 0;
a.textColor = .black;
a.textAlignment = .left;
return a;
}();
/********************************
*
* METHODS
*
********************************/
override init(frame: CGRect) {
super.init(frame: frame);
backgroundColor = .white;
addSubview(titleLabel);
titleLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(snp.left).offset(10);
maker.top.equalTo(snp.top);
maker.right.equalTo(snp.right);
maker.bottom.equalTo(snp.bottom);
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | f3cf8acd543b5b587326c97e9bb4db69 | 21.050847 | 68 | 0.491161 | 5.062257 | false | false | false | false |
MichaelBuckley/MAIKit | Examples/Circles/Circles/Common/ViewController.swift | 1 | 879 | //
// ViewController.swift
// Circles
//
// Created by Buckley on 6/14/15.
// Copyright © 2015 Buckleyisms. All rights reserved.
//
import MAIKit
class ViewController: MAIViewController {
weak var circlesView : CirclesView? = nil
@IBOutlet weak var clearButton : MAIButtonProtocol? = nil
override func viewDidLoad()
{
super.viewDidLoad()
self.clearButton?.isEnabled = false
NotificationCenter.default().addObserver(
self,
selector: #selector(ViewController.circleDrawn(_:)),
name: "circleDrawn",
object: nil
)
}
@IBAction func clear(_ sender: AnyObject)
{
self.circlesView?.clear()
self.clearButton?.isEnabled = false
}
@objc func circleDrawn(_ notification: NSNotification?)
{
self.clearButton?.isEnabled = true
}
}
| mit | 3463cc8b77b7b2b04fd8b0d30f3826dd | 20.414634 | 64 | 0.618451 | 4.41206 | false | false | false | false |
md0u80c9/ResearchKit | samples/ORKSample/ORKSample/AppDelegate.swift | 2 | 4386 | /*
Copyright (c) 2015, Apple Inc. 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(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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
import ResearchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let healthStore = HKHealthStore()
var window: UIWindow?
var containerViewController: ResearchContainerViewController? {
return window?.rootViewController as? ResearchContainerViewController
}
private func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let standardDefaults = UserDefaults.standard
if standardDefaults.object(forKey: "ORKSampleFirstRun") == nil {
ORKPasscodeViewController.removePasscodeFromKeychain()
standardDefaults.setValue("ORKSampleFirstRun", forKey: "ORKSampleFirstRun")
}
// Appearance customization
let pageControlAppearance = UIPageControl.appearance()
pageControlAppearance.pageIndicatorTintColor = UIColor.lightGray
pageControlAppearance.currentPageIndicatorTintColor = UIColor.black
// Dependency injection.
containerViewController?.injectHealthStore(healthStore)
return true
}
private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
lockApp()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
if ORKPasscodeViewController.isPasscodeStoredInKeychain() {
// Hide content so it doesn't appear in the app switcher.
containerViewController?.contentHidden = true
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
lockApp()
}
func lockApp() {
/*
Only lock the app if there is a stored passcode and a passcode
controller isn't already being shown.
*/
guard ORKPasscodeViewController.isPasscodeStoredInKeychain() && !(containerViewController?.presentedViewController is ORKPasscodeViewController) else { return }
window?.makeKeyAndVisible()
let passcodeViewController = ORKPasscodeViewController.passcodeAuthenticationViewController(withText: "Welcome back to ResearchKit Sample App", delegate: self)
containerViewController?.present(passcodeViewController, animated: false, completion: nil)
}
}
extension AppDelegate: ORKPasscodeDelegate {
func passcodeViewControllerDidFinish(withSuccess viewController: UIViewController) {
containerViewController?.contentHidden = false
viewController.dismiss(animated: true, completion: nil)
}
func passcodeViewControllerDidFailAuthentication(_ viewController: UIViewController) {
}
}
| bsd-3-clause | 2e1b08fd93b6809d54b5cb57e7f72efc | 42.425743 | 168 | 0.747606 | 5.863636 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/MessagesUtils/EKButtonView.swift | 2 | 2546 | //
// EKButtonView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 12/8/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class EKButtonView: UIView {
// MARK: - Properties
private let button = UIButton()
private let titleLabel = UILabel()
private let content: EKProperty.ButtonContent
// MARK: - Setup
init(content: EKProperty.ButtonContent) {
self.content = content
super.init(frame: .zero)
setupTitleLabel()
setupButton()
setupAcceessibility()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupAcceessibility() {
isAccessibilityElement = true
accessibilityIdentifier = content.accessibilityIdentifier
accessibilityLabel = content.label.text
accessibilityTraits = [.button]
}
private func setupButton() {
addSubview(button)
button.fillSuperview()
button.addTarget(self, action: #selector(buttonTouchUp), for: [.touchUpInside, .touchUpOutside, .touchCancel])
button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
button.addTarget(self, action: #selector(buttonTouchUpInside), for: .touchUpInside)
}
private func setupTitleLabel() {
titleLabel.numberOfLines = content.label.style.numberOfLines
titleLabel.font = content.label.style.font
titleLabel.textColor = content.label.style.color
titleLabel.text = content.label.text
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byWordWrapping
backgroundColor = content.backgroundColor
addSubview(titleLabel)
titleLabel.layoutToSuperview(axis: .horizontally, offset: content.contentEdgeInset)
titleLabel.layoutToSuperview(axis: .vertically, offset: content.contentEdgeInset)
}
private func setBackground(by content: EKProperty.ButtonContent, isHighlighted: Bool) {
if isHighlighted {
backgroundColor = content.highlightedBackgroundColor
} else {
backgroundColor = content.backgroundColor
}
}
// MARK: - Selectors
@objc func buttonTouchUpInside() {
content.action?()
}
@objc func buttonTouchDown() {
setBackground(by: content, isHighlighted: true)
}
@objc func buttonTouchUp() {
setBackground(by: content, isHighlighted: false)
}
}
| apache-2.0 | 13b046a5302b61af1cbeff23799d7679 | 29.662651 | 118 | 0.657367 | 5.151822 | false | false | false | false |
1457792186/JWSwift | SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGPresentAnimationController.swift | 1 | 1832 | //
// LGPresentAnimationController.swift
// LGWeChatKit
//
// Created by jamy on 11/2/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
class LGPresentAnimationController: NSObject , UIViewControllerAnimatedTransitioning{
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.2
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromCtrl = (transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! UINavigationController).topViewController as! UICollectionViewController
let toCtrl = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
let containertView = transitionContext.containerView
let finalFrame = transitionContext.finalFrame(for: toCtrl!)
let layoutAttribute = fromCtrl.collectionView?.layoutAttributesForItem(at: (fromCtrl.selectedIndexPath)! as IndexPath)
let selectRect = fromCtrl.collectionView?.convert((layoutAttribute?.frame)!, to: fromCtrl.collectionView?.superview)
toView?.frame = selectRect!
containertView.addSubview(toView!)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.5, initialSpringVelocity: 0.0, options: .curveLinear, animations: { () -> Void in
fromView?.alpha = 0.5
toView?.frame = finalFrame
}) { (finish) -> Void in
transitionContext.completeTransition(true)
fromView?.alpha = 1
}
}
}
| apache-2.0 | 099e81fa55e7819a72f26185690deeea | 47.184211 | 202 | 0.729656 | 5.599388 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS | Mr-Ride-iOS/Mr-Ride-iOS/LoginViewController.swift | 1 | 5760 | //
// LoginViewController.swift
// Mr-Ride-iOS
//
// Created by Derek on 6/8/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var btnLogin: UIButton!
@IBOutlet weak var textFieldHeight: UITextField!
@IBOutlet weak var textFieldWeight: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textFieldHeight.delegate = self
textFieldWeight.delegate = self
textFieldHeight.keyboardType = UIKeyboardType.NumberPad
textFieldWeight.keyboardType = UIKeyboardType.NumberPad
setupBackground()
setupBtn()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupBackground() {
let height = UIScreen.mainScreen().bounds.height
- UIApplication.sharedApplication().statusBarFrame.height
let upperBackground = CALayer()
upperBackground.frame = CGRectMake(0, 0, view.frame.width, height / 2)
upperBackground.backgroundColor = UIColor.mrLightblueColor().CGColor
view.layer.insertSublayer(upperBackground, atIndex: 0)
UIGraphicsBeginImageContext(view.frame.size)
UIImage(named: "image-history-background")!.drawInRect(CGRectMake(0, height / 2, view.frame.width, height / 2))
let bgImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
view.backgroundColor = UIColor(patternImage: bgImg!)
let color1 = UIColor.mrLightblueColor()
let color2 = UIColor.mrPineGreen50Color()
let gradient = CAGradientLayer()
gradient.frame = CGRectMake(0, height / 2, view.frame.width, height / 2)
gradient.colors = [color1.CGColor, color2.CGColor]
view.layer.insertSublayer(gradient, atIndex: 0)
}
func setupBtn() {
btnLogin.addTarget(self, action: #selector(btnTaped), forControlEvents: UIControlEvents.TouchUpInside)
}
// func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// let text = (textField.text as? NSString)!.stringByReplacingCharactersInRange(range, withString: string)
//
// guard let doubleVal = Double(text) else {
// btnLogin.enabled = false
// }
//
//
// return true
// }
func btnTaped() {
let loginManager: FBSDKLoginManager = FBSDKLoginManager()
if FBSDKAccessToken.currentAccessToken() != nil {
loginManager.logOut()
} else {
loginManager.logInWithReadPermissions(["public_profile", "email"], fromViewController: self) { (result, error) -> Void in
guard error == nil else {
//error handling
loginManager.logOut()
print("login error " + String(error))
return
}
guard result != nil else {
//error handling
loginManager.logOut()
print("result nil " + String(result))
return
}
print(result.grantedPermissions)
guard result.grantedPermissions.contains("email") else {
return
}
self.getFBUserData()
}
}
}
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, link"]).startWithCompletionHandler({ (connection, result, error) -> Void in
guard error == nil else {
return
}
guard result != nil else {
print("result nil " + String(result))
return
}
if let fbResult = result as? NSDictionary {
// print(fbResult)
self.JSONParseToNSUserDefault(fbResult)
}
})
print("login successed ")
let starting = storyboard?.instantiateViewControllerWithIdentifier("StartingPageController") as! SWRevealViewController
self.presentViewController(starting, animated: true, completion: nil)
}
}
func JSONParseToNSUserDefault(fbResult: NSDictionary) {
let userDefault = NSUserDefaults.standardUserDefaults()
if let name = fbResult["name"] as? String {
userDefault.setObject(name, forKey: "name")
}
if let email = fbResult["email"] as? String {
userDefault.setObject(email, forKey: "email")
}
if let link = fbResult["link"] as? String {
userDefault.setURL(NSURL(string: link), forKey: "link")
}
if let picStruct = fbResult["picture"] as? NSDictionary
,let picData = picStruct["data"] as? NSDictionary
,let picURL = picData["url"] as? String {
userDefault.setURL(NSURL(string: picURL), forKey: "picture")
}
userDefault.synchronize()
// print(userDefault.stringForKey("name"))
// print(userDefault.stringForKey("email"))
// print(userDefault.URLForKey("link"))
// print(userDefault.URLForKey("picture"))
}
}
| mit | a58941b92adc608f31c9238dbb7af32f | 34.549383 | 207 | 0.576489 | 5.397376 | false | false | false | false |
GyrosWorkshop/WukongiOS | UI/AppDelegate.swift | 1 | 1099 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundTask = UIBackgroundTaskIdentifier.invalid
private func beginBackgroundTask() {
guard backgroundTask == .invalid else { return }
backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: endBackgroundTask)
}
private func endBackgroundTask() {
guard backgroundTask != .invalid else { return }
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
window = UIWindow()
window?.rootViewController = AppController()
window?.makeKeyAndVisible()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
beginBackgroundTask()
}
func applicationWillEnterForeground(_ application: UIApplication) {
endBackgroundTask()
}
}
| mit | c82202efa8af3ce6745c0e470cd8330c | 30.4 | 151 | 0.714286 | 6.426901 | false | false | false | false |
Dwarfartisan/sparsec | sparsec/sparsec/combinator.swift | 1 | 6501 | //
// combinator.swift
// sparsec
//
// Created by Mars Liu on 15/3/16.
// Copyright (c) 2015年 Dwarf Artisan. All rights reserved.
//
import Foundation
// 即 Haskell Parsec 的 try 算子,如果发生错误,将 state 复位
func attempt<T, S:State>(parsec: (S) throws->T) -> (S) throws -> T {
return {(var state: S) throws -> T in
let tran = state.begin()
do {
let result = try parsec(state)
state.commit(tran)
return result
} catch let err {
state.rollback(tran)
throw err
}
}
}
// 如果第一个算子成功,返回其结果,否则要检查其是否复位,如果复位,就尝试第二个算子并返回其结果
func either<T, S:State where S.I:Equatable>(x: Parsec<T, S>.Parser, _ y: Parsec<T, S>.Parser) -> Parsec<T, S>.Parser {
return {( state: S) throws -> T in
let p = state.pos
do {
let re = try x(state)
return re
} catch let err {
if state.pos == p {
return try y(state)
}else{
throw err
}
}
}
}
// either 的中置运算符形式
infix operator <|> { associativity left }
func <|><T, S:State where S.I:Equatable>(left: Parsec<T, S>.Parser,
right: Parsec<T, S>.Parser) -> Parsec<T, S>.Parser {
return either(left, right)
}
// 如果给定算子发生错误,给出指定的错误信息
func otherwise<T, S:State >(x:Parsec<T, S>.Parser, _ message:String)->Parsec<T, S>.Parser {
return {( state: S) throws -> T in
do {
let re = try x(state)
return re
} catch {
throw ParsecError.Parse(pos: state.pos, message: message)
}
}
}
// otherwise 的中置运算符形式
infix operator <?> { associativity left }
func <?><T, S:State>(x: Parsec<T, S>.Parser, message: String) -> Parsec<T, S>.Parser {
return otherwise(x, message)
}
// 如果给定算子发生错误,给出指定的值
func option<T, S:State where S.I:Equatable>(value:T, _ parsec:Parsec<T, S>.Parser) -> Parsec<T, S>.Parser {
return {( state: S) throws -> T in
let p = state.pos
do {
let re = try parsec(state)
return re
} catch let err {
if state.pos == p {
return value
}else{
throw err
}
}
}
}
// 给出在指定起止算子之间的给定算子的计算结果
func between<B, E, T, S:State>(open:Parsec<B, S>.Parser, _ close:Parsec<E, S>.Parser,
_ p:Parsec<T, S>.Parser)->Parsec<T, S>.Parser{
return {( state: S) throws -> T in
// return try (open >> p =>> close)(state)
try open(state)
let re = try p(state)
try close(state)
return re
}
}
// 匹配给定算子0到多次
func many<T, S:State >(p:Parsec<T, S>.Parser) -> Parsec<[T], S>.Parser {
return {( state: S) throws -> [T] in
var re = [T]()
let psc = attempt(p)
do {
while true {
if let item = try? psc(state) {
re.append(item)
} else {
break
}
}
}
return re
}
}
// 匹配给定算子一到多次
func many1<T, S:State>(p: Parsec<T, S>.Parser)->Parsec<[T], S>.Parser {
return {( state: S) throws -> [T] in
let start = try p(state)
var re:[T] = [start]
let psc = attempt(p)
do {
while true {
if let item = try? psc(state) {
re.append(item)
} else {
break
}
}
}
return re
}
}
// 匹配给定算子0到多次,并以指定的算子结尾,饥饿模式
func manyTill<T, EndType, S:State>(p:Parsec<T, S>.Parser,
end:Parsec<EndType, S>.Parser)->Parsec<[T], S>.Parser{
return {(state: S) throws -> [T] in
var re:[T] = []
let ep = attempt(end)
while true{
do {
try ep(state)
return re;
} catch {
try re.append(p(state))
}
}
}
}
// 匹配给定算子0到1次,失败返回 nil
func zeroOrOnce<T, S:State>(p:Parsec<T, S>.Parser)->Parsec<T?, S>.Parser{
return{( state: S) throws -> T? in
do{
let re = try p(state)
return re
} catch {
return nil
}
}
}
// 以指定算子分隔的 many 匹配
func sepBy<T, SepType, S:State>(p: Parsec<T, S>.Parser,
sep:Parsec<SepType, S>.Parser)->Parsec<[T], S>.Parser {
return {( state: S) throws -> [T] in
var re = [T]()
do {
let head = try p(state)
re.append(head)
let step = sep >> p
while true {
if let item = try? step(state) {
re.append(item)
} else {
break
}
}
}
return re
}
}
// 以指定算子分隔的 many1 匹配
func sepBy1<T, SepType, S:State>(p: Parsec<T, S>.Parser,
sep:Parsec<SepType, S>.Parser)->Parsec<[T], S>.Parser {
return {(state: S) throws ->[T] in
let first = try p(state)
var re:[T] = [first]
let parser = attempt(sep)>>attempt(p)
do {
while true {
if let item = try? parser(state) {
re.append(item)
} else {
break
}
}
}
return re
}
}
// 跳过给定算子0到多次
func skip<T, S:State >(p:Parsec<T, S>.Parser) -> Parsec<T?, S>.Parser {
return {( state: S) throws -> T? in
let psc = attempt(p)
do {
while true {
let re = try? psc(state)
if re == nil {
break
}
}
}
return nil
}
}
// 跳过给定算子 1 到多次
func skip1<T, S:State>(p: Parsec<T, S>.Parser)->Parsec<T?, S>.Parser {
return {( state: S) throws -> T? in
try p(state)
let psc = attempt(p)
do {
while true {
let re = try? psc(state)
if re == nil {
break
}
}
}
return nil
}
}
| mit | 3470fe8639c9d2f9cf676ea7303bf2fb | 24.489451 | 118 | 0.455885 | 3.424603 | false | false | false | false |
noahemmet/FingerPaint | FingerPaint/Stroke.swift | 1 | 1122 | //
// Paint.swift
// FingerPaint
//
// Created by Noah Emmet on 4/28/16.
// Copyright © 2016 Sticks. All rights reserved.
//
import Foundation
public class Stroke {
public let path: UIBezierPath
public var color: UIColor?
public init(points: [CGPoint], closed: Bool = false) {
self.path = UIBezierPath(catmullRomPoints: points, closed: closed, alpha: 0.5)
}
public init(touches: [Touch], closed: Bool = false) {
let points = touches.map { $0.location }
self.path = UIBezierPath(catmullRomPoints: points, closed: closed, alpha: 0.5)
}
public init?(touchPath: TouchPath) {
return nil
}
}
extension Stroke {
public func createLayer(scale scale: CGFloat = 1) -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
var affineTransform = CGAffineTransformMakeScale(scale, scale)
let transformedPath = CGPathCreateCopyByTransformingPath(path.CGPath, &affineTransform)
shapeLayer.path = transformedPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = color?.CGColor ?? UIColor.blackColor().CGColor
shapeLayer.lineWidth = 8 * scale
return shapeLayer
}
} | apache-2.0 | 9b2ca46349f3100ad3b739b242774532 | 25.093023 | 89 | 0.727029 | 3.663399 | false | false | false | false |
idappthat/UTANow-iOS | UTANow/EventListViewController.swift | 1 | 23817 | //
// EventListViewController.swift
// UTANow
//
// Created by Cameron Moreau on 11/7/15.
// Copyright © 2015 Mobi. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import Parse
import ParseFacebookUtilsV4
import Firebase
class EventListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
@IBAction func openMenu(sender: AnyObject) {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("MenuOverlayViewController") as!MenuOverlayViewController
vc.delegate = self
vc.modalPresentationStyle = .OverCurrentContext
vc.modalTransitionStyle = .CrossDissolve
self.presentViewController(vc, animated: true, completion: nil)
}
var refreshControl:UIRefreshControl!
let kSearchPaddingX: CGFloat = 15
let kSearchPaddingY: CGFloat = 20
let kSearchBarHeight: CGFloat = 44
let kNumFilterButtons: CGFloat = 4
let kFilterButtonHeight: CGFloat = 55
var events = [Event]()
@IBAction func tempPublishLogin(sender: UIBarButtonItem) {
let permissions = ["manage_pages"]
PFFacebookUtils.logInInBackgroundWithPublishPermissions(permissions, block: {
(user, error) -> Void in
if user != nil {
print("It worked")
}
})
}
@IBOutlet weak var tableView: UITableView!
var searchBar: UIView!
var searchButton: UIButton!
var searchField: UITextField!
var filterMenu: UIView!
var noResultsLabel: UILabel!
var searchBarCreated = false
var searchBarExpanded = false
var filterMenuExpanded = false
//MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//change nav bar title font
//TODO: pretty-up the navbar title
//navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Woah", size: 35)!]
let nav = self.navigationController!.navigationBar
nav.barTintColor = UIColor.primaryColor()
nav.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
nav.translucent = false
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl)
//Query for parse events
refresh(nil)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if searchBarCreated == false {
createSearchBar()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Pull to refresh
func refresh(sender: AnyObject?) {
let ref = Firebase(url:"https://uta-now.firebaseio.com/events")
ref.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let snap = snapshot.childSnapshotForPath(child.key)
let event = Event(snapshot: snap)
self.events.append(event)
self.tableView.reloadData()
}
})
}
//MARK: - Search bar
func createSearchBar() {
let container = UIView(frame: CGRectMake(kSearchPaddingX, kSearchPaddingY, UIScreen.mainScreen().bounds.size.width-kSearchPaddingX*2, kSearchBarHeight))
searchBar = UIView(frame: CGRectMake(0, 0, container.frame.size.width, kSearchBarHeight))
searchBar.clipsToBounds = true
searchBar.layer.cornerRadius = 4
searchBar.backgroundColor = UIColor.whiteColor()
searchBar.layer.borderColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0).CGColor
searchBar.layer.borderWidth = 0.5
container.addSubview(searchBar)
searchButton = UIButton(type: .System)
searchButton.frame = CGRectMake(0, 0, kSearchBarHeight, kSearchBarHeight)
searchButton.backgroundColor = UIColor.whiteColor()
searchButton.layer.cornerRadius = searchButton.frame.size.width/2
searchButton.layer.borderColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0).CGColor
//TODO: add search bar icon
searchButton.setImage(UIImage(named: ""), forState: .Normal)
searchButton.addTarget(self, action: Selector("searchButtonTapped:"), forControlEvents: .TouchUpInside)
searchBar.addSubview(searchButton)
let filterBtn = UIButton(type: .System)
filterBtn.frame = CGRectMake(searchBar.frame.size.width-70, 0, 70, kSearchBarHeight)
filterBtn.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
filterBtn.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
filterBtn.setTitle("Filter", forState: .Normal)
filterBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
filterBtn.addTarget(self, action: Selector("filterButtonTapped:"), forControlEvents: .TouchUpInside)
searchBar.addSubview(filterBtn)
searchField = UITextField()
searchField.borderStyle = .None
searchField.frame = CGRectMake(searchButton.frame.size.width, 0, searchBar.frame.size.width-searchButton.frame.size.width-filterBtn.frame.size.width, kSearchBarHeight)
searchField.returnKeyType = .Done
searchField.backgroundColor = UIColor.whiteColor()
searchField.font = UIFont(name: "AvenirNext-Regular", size: 13)
searchField.clearButtonMode = .WhileEditing
searchField.placeholder = "Search for an event!"
searchField.delegate = self
searchField.addTarget(self, action:"searchTextChanged:", forControlEvents:.EditingChanged)
searchBar.addSubview(searchField)
filterMenu = UIView(frame: CGRectMake(0, 0, searchBar.frame.size.width, 0))
filterMenu.backgroundColor = UIColor.whiteColor()
filterMenu.clipsToBounds = true
filterMenu.layer.cornerRadius = 4
filterMenu.layer.borderColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0).CGColor
filterMenu.layer.borderWidth = 0.5
container.insertSubview(filterMenu, belowSubview: searchBar)
let dateBtn = UIButton(type: .System)
dateBtn.frame = CGRectMake(14, kSearchBarHeight+14, (filterMenu.frame.size.width-14*5)/kNumFilterButtons, kFilterButtonHeight) //14 because odd number padding doesn't divide equally
dateBtn.layer.cornerRadius = 4
dateBtn.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
dateBtn.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
dateBtn.setTitle("Date", forState: .Normal)
dateBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
//TODO: dateBtnTapped implementation
//dateBtn.addTarget(self, action: <#T##Selector#>, forControlEvents: .TouchUpInside)
filterMenu.addSubview(dateBtn)
let sportsBtn = UIButton(type: .System)
sportsBtn.frame = CGRectMake(14+dateBtn.frame.size.width+14, dateBtn.frame.origin.y, dateBtn.frame.size.width, kFilterButtonHeight)
sportsBtn.layer.cornerRadius = 4
sportsBtn.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
sportsBtn.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
sportsBtn.setTitle("Sports", forState: .Normal)
sportsBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
//TODO: sportsBtnTapped implementation
//sportsBtn.addTarget(self, action: <#T##Selector#>, forControlEvents: .TouchUpInside)
filterMenu.addSubview(sportsBtn)
let distanceBtn = UIButton(type: .System)
distanceBtn.frame = CGRectMake(14+dateBtn.frame.size.width+14+sportsBtn.frame.size.width+14, dateBtn.frame.origin.y, dateBtn.frame.size.width, kFilterButtonHeight)
distanceBtn.layer.cornerRadius = 4
distanceBtn.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
distanceBtn.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
distanceBtn.setTitle("Distance", forState: .Normal)
distanceBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
//TODO: distanceBtnTapped implementation
//distanceBtn.addTarget(self, action: <#T##Selector#>, forControlEvents: .TouchUpInside)
filterMenu.addSubview(distanceBtn)
let foodBtn = UIButton(type: .System)
foodBtn.frame = CGRectMake(14+dateBtn.frame.size.width+14+sportsBtn.frame.size.width+14+distanceBtn.frame.size.width+14, dateBtn.frame.origin.y, dateBtn.frame.size.width, kFilterButtonHeight)
foodBtn.layer.cornerRadius = 4
foodBtn.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
foodBtn.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 12)
foodBtn.setTitle("Food", forState: .Normal)
foodBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
//TODO: foodBtnTapped implementation
//foodBtn.addTarget(self, action: <#T##Selector#>, forControlEvents: .TouchUpInside)
filterMenu.addSubview(foodBtn)
self.view.addSubview(container)
searchBar.frame = CGRectMake(searchBar.frame.origin.x, searchBar.frame.origin.y, searchButton.frame.size.width, searchBar.frame.size.height) //hide initially
searchBar.superview?.frame = CGRectMake(kSearchPaddingX, kSearchPaddingY, searchBar.frame.size.width, searchBar.frame.size.height)
searchBarCreated = true
//set up no results label
noResultsLabel = UILabel(frame: CGRectMake(kSearchPaddingX, 0, UIScreen.mainScreen().bounds.size.width-kSearchPaddingX*2, 150))
noResultsLabel.center = CGPointMake(self.view.center.x, self.view.center.y - (navigationController?.navigationBar.frame.size.height)! - UIApplication.sharedApplication().statusBarFrame.size.height - 150/2)
noResultsLabel.numberOfLines = 0
noResultsLabel.hidden = true
noResultsLabel.backgroundColor = UIColor.clearColor()
noResultsLabel.lineBreakMode = .ByWordWrapping
noResultsLabel.textAlignment = .Center
noResultsLabel.textColor = UIColor.lightGrayColor()
noResultsLabel.text = "No results"
noResultsLabel.font = UIFont(name: "AvenirNext-Medium", size: 18)
self.view.addSubview(noResultsLabel)
}
func searchButtonTapped(sender: UIButton) {
if let searchText = self.searchField?.text {
if self.filterEventsForSearchText(searchText).count != 0 {
expandSearchBar()
}
}
}
func filterButtonTapped(sender: UIButton) {
expandFilterMenu(false)
}
@IBAction func expandSearchBar() {
searchBarExpanded = !searchBarExpanded
if filterMenuExpanded {
expandFilterMenu(true)
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
if self.searchBarExpanded {
self.searchBar.layer.borderWidth = 0.5
self.searchButton.layer.borderWidth = 0
self.searchButton.layer.cornerRadius = 0
self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x, self.searchBar.frame.origin.y, UIScreen.mainScreen().bounds.size.width-self.kSearchPaddingX*2, self.searchBar.frame.size.height)
self.searchBar.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.searchBar.frame.size.width, self.searchBar.frame.size.height)
} else {
self.searchBar.layer.borderWidth = 0
self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x, self.searchBar.frame.origin.y, self.searchButton.frame.size.width, self.searchBar.frame.size.height)
self.searchBar.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.searchBar.frame.size.width, self.searchBar.frame.size.height)
self.searchField.resignFirstResponder()
}
}) { (finished: Bool) -> Void in
if self.searchBarExpanded {
self.searchBar.backgroundColor = UIColor.whiteColor()
self.searchButton.layer.borderWidth = 0
} else {
self.searchBar.backgroundColor = UIColor.clearColor()
self.searchButton.layer.borderWidth = 0.5
self.searchButton.layer.cornerRadius = 4
}
}
}
}
@IBAction func expandFilterMenu(collapseSearchBarToo: Bool) {
filterMenuExpanded = !filterMenuExpanded
let animationDuration = 0.3
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
if self.filterMenuExpanded {
self.searchBar.layer.borderWidth = 0
self.filterMenu.frame = CGRectMake(self.filterMenu.frame.origin.x, self.filterMenu.frame.origin.y, self.filterMenu.frame.size.width, self.searchBar.frame.size.height+83)
self.filterMenu.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.filterMenu.frame.size.width, self.filterMenu.frame.size.height)
} else {
self.filterMenu.frame = CGRectMake(self.filterMenu.frame.origin.x, self.filterMenu.frame.origin.y, self.filterMenu.frame.size.width, 0)
self.filterMenu.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.filterMenu.frame.size.width, self.searchBar.frame.size.height)
}
}) { (finished: Bool) -> Void in
if !self.filterMenuExpanded {
self.searchBar.layer.borderWidth = 0.5
}
}
if collapseSearchBarToo {
if let searchText = self.searchField?.text {
if filterEventsForSearchText(searchText).count != 0 {
UIView.animateWithDuration(animationDuration, delay: animationDuration, options: .AllowAnimatedContent, animations: { () -> Void in
self.searchBar.layer.borderWidth = 0
self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x, self.searchBar.frame.origin.y, self.searchButton.frame.size.width, self.searchBar.frame.size.height)
self.searchBar.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.searchBar.frame.size.width, self.searchBar.frame.size.height)
self.searchField.resignFirstResponder()
}) { (finished: Bool) -> Void in
self.searchBar.backgroundColor = UIColor.clearColor()
self.searchButton.layer.borderWidth = 0.5
self.searchButton.layer.cornerRadius = 4
}
}
}
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if let searchText = searchField?.text {
if filterEventsForSearchText(searchText).count != 0 {
//collapse search bar when scrolling
let animationDuration = 0.2
var delay = 0.0
if filterMenuExpanded {
delay = animationDuration
}
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.filterMenu.frame = CGRectMake(self.filterMenu.frame.origin.x, self.filterMenu.frame.origin.y, self.filterMenu.frame.size.width, 0)
self.filterMenu.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.filterMenu.frame.size.width, self.searchBar.frame.size.height)
}, completion: { (finished: Bool) -> Void in
self.searchBar.layer.borderWidth = 0.5
self.filterMenuExpanded = false
})
UIView.animateWithDuration(animationDuration, delay: delay, options: .AllowAnimatedContent, animations: { () -> Void in
self.searchBar.layer.borderWidth = 0
self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x, self.searchBar.frame.origin.y, self.searchButton.frame.size.width, self.searchBar.frame.size.height)
self.searchBar.superview?.frame = CGRectMake(self.kSearchPaddingX, self.kSearchPaddingY, self.searchBar.frame.size.width, self.searchBar.frame.size.height)
self.searchField.resignFirstResponder()
}) { (finished: Bool) -> Void in
self.searchBar.backgroundColor = UIColor.clearColor()
self.searchButton.layer.borderWidth = 0.5
self.searchButton.layer.cornerRadius = 4
self.searchBarExpanded = false
}
}
}
}
//MARK: - Text field
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let searchText = searchField?.text {
if filterEventsForSearchText(searchText).count != 0 {
textField.resignFirstResponder()
}
}
return true
}
func searchTextChanged(sender: UITextField) {
tableView.reloadData()
if filterEventsForSearchText(sender.text!).count == 0 {
//no results
noResultsLabel.hidden = false
} else {
noResultsLabel.hidden = true
}
}
func filterEventsForSearchText(searchText: String) -> [Event] {
if searchText.characters.count > 0 {
return events.filter({(event: Event) -> Bool in
return event.title?.lowercaseString.rangeOfString(searchText.lowercaseString) != nil
})
} else {
return events
}
}
//MARK: - Table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let searchText = searchField?.text {
return filterEventsForSearchText(searchText).count
} else {
return events.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! EventListTableViewCell
//Give search results
var filteredEvents: [Event] = events
if let searchText = searchField?.text {
filteredEvents = filterEventsForSearchText(searchText)
}
//Give event object to the cell
cell.setData(filteredEvents[indexPath.row])
cell.btnOpenMap.tag = indexPath.row;
cell.btnOpenMap.addTarget(self, action: "openMapView:", forControlEvents: .TouchUpInside)
cell.btnQuickAdd.tag = indexPath.row;
cell.btnQuickAdd.addTarget(self, action: "quickAdd:", forControlEvents: .TouchUpInside)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 185
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showEventSegue" {
let tvc = segue.destinationViewController as! EventViewController
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) //gets rid of text after chevron
if tableView.indexPathForSelectedRow?.row != nil {
tvc.event = events[tableView.indexPathForSelectedRow!.row]
}
}
else if segue.identifier == "mapSegue" {
let mapVC = (segue.destinationViewController as! UINavigationController).topViewController as! MapViewController
let selectedEvent = events[sender!.tag]
//mapVC.markerPoint = selectedEvent.getLocationGPS()
mapVC.markerTitle = selectedEvent.title
}
}
// MARK: - EventCell Clickable Items
func openMapView(sender: UIButton) {
self.performSegueWithIdentifier("mapSegue", sender: sender)
}
func quickAdd(sender: UIButton) {
}
}
extension EventListViewController : MenuOverlayDelegate {
func closePressed() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func organizationsPressed() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func createEventPressed() {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("createEventSegue", sender: nil)
}
func settingsPressed() {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("settingsSegue", sender: nil)
}
}
| mit | 1cee493f96c714b0de6c82b0d4166fda | 44.624521 | 213 | 0.63936 | 4.919645 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/Styles/Bubble/BubbleRoomTimelineStyle.swift | 1 | 2307 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class BubbleRoomTimelineStyle: RoomTimelineStyle {
// MARK: - Properties
// MARK: Private
private var theme: Theme
// MARK: Public
let identifier: RoomTimelineStyleIdentifier
let cellLayoutUpdater: RoomCellLayoutUpdating?
let cellProvider: RoomTimelineCellProvider
let cellDecorator: RoomTimelineCellDecorator
// MARK: - Setup
init(theme: Theme) {
self.theme = theme
self.identifier = .bubble
self.cellLayoutUpdater = BubbleRoomCellLayoutUpdater(theme: theme)
self.cellProvider = BubbleRoomTimelineCellProvider()
self.cellDecorator = BubbleRoomTimelineCellDecorator()
}
// MARK: - Public
func canAddEvent(_ event: MXEvent, and roomState: MXRoomState, to cellData: MXKRoomBubbleCellData) -> Bool {
return false
}
func applySelectedStyleIfNeeded(toCell cell: MXKRoomBubbleTableViewCell, cellData: RoomBubbleCellData) {
// Check whether the selected event belongs to this bubble
let selectedComponentIndex = cellData.selectedComponentIndex
if selectedComponentIndex != NSNotFound {
cell.selectComponent(UInt(selectedComponentIndex),
showEditButton: false,
showTimestamp: false)
self.cellDecorator.addTimestampLabel(toCell: cell, cellData: cellData)
} else {
cell.blurred = true
}
}
// MARK: Themable
func update(theme: Theme) {
self.theme = theme
self.cellLayoutUpdater?.update(theme: theme)
}
}
| apache-2.0 | d8dc6f4ff03617d19f74998c75e1c4be | 29.355263 | 112 | 0.650629 | 4.908511 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/RadarChartDataSet.swift | 8 | 1629 | //
// RadarChartDataSet.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
public class RadarChartDataSet: LineRadarChartDataSet, IRadarChartDataSet
{
private func initialize()
{
self.valueFont = NSUIFont.systemFontOfSize(13.0)
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// flag indicating whether highlight circle should be drawn or not
/// **default**: false
public var drawHighlightCircleEnabled: Bool = false
/// - returns: true if highlight circle should be drawn, false if not
public var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled }
public var highlightCircleFillColor: NSUIColor? = NSUIColor.whiteColor()
/// The stroke color for highlight circle.
/// If `nil`, the color of the dataset is taken.
public var highlightCircleStrokeColor: NSUIColor?
public var highlightCircleStrokeAlpha: CGFloat = 0.3
public var highlightCircleInnerRadius: CGFloat = 3.0
public var highlightCircleOuterRadius: CGFloat = 4.0
public var highlightCircleStrokeWidth: CGFloat = 2.0
} | apache-2.0 | 812affbec3fd667290fe7b66a12ba064 | 25.721311 | 87 | 0.674647 | 4.848214 | false | false | false | false |
troystribling/BlueCap | Examples/BlueCap/BlueCap/Peripheral/PeripheralManagerBeaconViewController.swift | 1 | 8166 | //
// PeripheralManagerBeaconViewController.swift
// BlueCap
//
// Created by Troy Stribling on 9/28/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class PeripheralManagerBeaconViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var advertiseSwitch: UISwitch!
@IBOutlet var advertiseLabel: UILabel!
@IBOutlet var nameTextField: UITextField!
@IBOutlet var uuidTextField: UITextField!
@IBOutlet var majorTextField: UITextField!
@IBOutlet var minorTextField: UITextField!
@IBOutlet var generaUUIDBuuton: UIButton!
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField.text = PeripheralStore.getBeaconName()
self.uuidTextField.text = PeripheralStore.getBeaconUUID()?.uuidString
let beaconMinorMajor = PeripheralStore.getBeaconMinorMajor()
if beaconMinorMajor.count == 2 {
self.minorTextField.text = "\(beaconMinorMajor[0])"
self.majorTextField.text = "\(beaconMinorMajor[1])"
}
let stateChangeFuture = Singletons.peripheralManager.whenStateChanges()
stateChangeFuture.onSuccess { [weak self] state in
self.forEach { strongSelf in
strongSelf.setUIState()
switch state {
case .poweredOn:
break
case .poweredOff:
strongSelf.present(UIAlertController.alert(message: "PeripheralManager powered off."), animated: true)
case .unauthorized:
strongSelf.present(UIAlertController.alert(message: "Bluetooth not authorized."), animated: true)
case .unknown:
break
case .unsupported:
strongSelf.present(UIAlertController.alert(message: "Bluetooth not supported."), animated: true)
case .resetting:
let message = "PeripheralManager state \"\(Singletons.peripheralManager.state)\". The connection with the system bluetooth service was momentarily lost."
strongSelf.present(UIAlertController.alert(message: message) { _ in
Singletons.peripheralManager.reset()
}, animated: true)
}
}
}
stateChangeFuture.onFailure { [weak self] error in
self?.present(UIAlertController.alert(error: error) { _ in
Singletons.peripheralManager.reset()
}, animated: true, completion: nil)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setUIState()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@IBAction func generateUUID(_ sender: AnyObject) {
self.uuidTextField.text = UUID().uuidString
}
// UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let enteredUUID = self.uuidTextField.text, !enteredUUID.isEmpty {
if let uuid = UUID(uuidString:enteredUUID) {
PeripheralStore.setBeaconUUID(uuid)
} else {
self.present(UIAlertController.alertOnErrorWithMessage("UUID '\(enteredUUID)' is invalid."), animated:true, completion:nil)
return false
}
}
if let enteredName = self.nameTextField.text, !enteredName.isEmpty {
PeripheralStore.setBeaconName(enteredName)
}
if let enteredMinor = self.minorTextField.text, let enteredMajor = self.majorTextField.text, !enteredMinor.isEmpty, !enteredMajor.isEmpty {
if let minor = UInt16(enteredMinor), let major = UInt16(enteredMajor), minor <= 65535, major <= 65535 {
PeripheralStore.setBeaconMinorMajor([minor, major])
} else {
present(UIAlertController.alertOnErrorWithMessage("major or minor not convertable to a number."), animated:true, completion:nil)
return false
}
}
setUIState()
return true
}
@IBAction func toggleAdvertise(_ sender:AnyObject) {
guard Singletons.peripheralManager.poweredOn else {
present(UIAlertController.alertOnErrorWithMessage("Bluetooth powered off"), animated:true, completion:nil)
return
}
if Singletons.peripheralManager.isAdvertising {
let stopAdvertisingFuture = Singletons.peripheralManager.stopAdvertising()
stopAdvertisingFuture.onSuccess { [weak self] _ in
self?.setUIState()
}
stopAdvertisingFuture.onFailure { [weak self] (error) -> Void in
self?.present(UIAlertController.alert(error: error) { _ in
Singletons.peripheralManager.reset()
}, animated: true, completion: nil)
}
return
}
let beaconMinorMajor = PeripheralStore.getBeaconMinorMajor()
if let uuid = PeripheralStore.getBeaconUUID(), let name = PeripheralStore.getBeaconName(), beaconMinorMajor.count == 2 {
let beaconRegion = BeaconRegion(proximityUUID: uuid, identifier: name, major: beaconMinorMajor[1], minor: beaconMinorMajor[0])
let startAdvertiseFuture = Singletons.peripheralManager.startAdvertising(beaconRegion)
startAdvertiseFuture.onSuccess { [weak self] _ in
self?.setUIState()
self?.present(UIAlertController.alert(message: "Started advertising."), animated: true, completion: nil)
}
startAdvertiseFuture.onFailure { [weak self] error in
self.forEach { strongSelf in
let stopAdvertisingFuture = Singletons.peripheralManager.stopAdvertising()
stopAdvertisingFuture.onSuccess { _ in
strongSelf.setUIState()
}
stopAdvertisingFuture.onFailure { _ in
strongSelf.setUIState()
}
self?.present(UIAlertController.alert(error: error) { _ in
Singletons.peripheralManager.reset()
}, animated: true, completion: nil)
}
}
} else {
present(UIAlertController.alert(message: "iBeacon config is invalid."), animated: true, completion: nil)
}
}
func setUIState() {
if Singletons.peripheralManager.isAdvertising {
navigationItem.setHidesBackButton(true, animated:true)
advertiseSwitch.isOn = true
nameTextField.isEnabled = false
uuidTextField.isEnabled = false
majorTextField.isEnabled = false
minorTextField.isEnabled = false
generaUUIDBuuton.isEnabled = false
advertiseLabel.textColor = UIColor.black
} else {
navigationItem.setHidesBackButton(false, animated:true)
advertiseSwitch.isOn = false
nameTextField.isEnabled = true
uuidTextField.isEnabled = true
majorTextField.isEnabled = true
minorTextField.isEnabled = true
generaUUIDBuuton.isEnabled = true
if canAdvertise() {
advertiseSwitch.isEnabled = true
advertiseLabel.textColor = UIColor.black
} else {
advertiseSwitch.isEnabled = false
advertiseLabel.textColor = UIColor.lightGray
}
}
if !Singletons.peripheralManager.poweredOn {
advertiseSwitch.isEnabled = false
advertiseLabel.textColor = UIColor.lightGray
}
}
func canAdvertise() -> Bool {
return PeripheralStore.getBeaconUUID() != nil && PeripheralStore.getBeaconName() != nil && PeripheralStore.getBeaconMinorMajor().count == 2
}
}
| mit | e12042412101c4a56af66fc4e1201aa2 | 42.903226 | 173 | 0.617438 | 5.647303 | false | false | false | false |
xedin/swift | test/Parse/matching_patterns.swift | 5 | 11549 | // RUN: %target-typecheck-verify-swift -swift-version 4 -I %S/Inputs -enable-source-import
import imported_enums
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool {
return true
}
var x:Int
func square(_ x: Int) -> Int { return x*x }
struct A<B> {
struct C<D> { }
}
switch x {
// Expressions as patterns.
case 0:
()
case 1 + 2:
()
case square(9):
()
// 'var' and 'let' patterns.
case var a:
a = 1
case let a: // expected-warning {{case is already handled by previous patterns; consider removing it}}
a = 1 // expected-error {{cannot assign}}
case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
a += 1
case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
print(a, terminator: "")
case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
b += 1
// 'Any' pattern.
case _: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
// patterns are resolved in expression-only positions are errors.
case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
()
}
switch (x,x) {
case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
fallthrough
case _: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
var e : Any = 0
switch e { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
// 'is' pattern.
case is Int,
is A<Int>,
is A<Int>.C<Int>,
is (Int, Int),
is (a: Int, b: Int):
()
}
// Enum patterns.
enum Foo { case A, B, C }
func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true }
enum Voluntary<T> : Equatable {
case Naught
case Mere(T)
case Twain(T, T)
func enumMethod(_ other: Voluntary<T>, foo: Foo) {
switch self {
case other:
()
case .Naught,
.Naught(), // expected-error {{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-19=}}
.Naught(_), // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-20=}}
.Naught(_, _): // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-23=}}
()
case .Mere,
.Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
.Mere(_),
.Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
()
case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
.Twain(_),
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
()
}
switch foo {
case .Naught: // expected-error{{type 'Foo' has no member 'Naught'}}
()
case .A, .B, .C:
()
}
}
}
var n : Voluntary<Int> = .Naught
if case let .Naught(value) = n {} // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{20-27=}}
if case let .Naught(value1, value2, value3) = n {} // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{20-44=}}
switch n {
case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}}
()
case Voluntary<Int>.Naught,
Voluntary<Int>.Naught(), // expected-error {{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{27-29=}}
Voluntary<Int>.Naught(_, _), // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{27-33=}}
Voluntary.Naught,
.Naught:
()
case Voluntary<Int>.Mere,
Voluntary<Int>.Mere(_),
Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}}
Voluntary.Mere,
Voluntary.Mere(_),
.Mere,
.Mere(_):
()
case .Twain,
.Twain(_),
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}}
()
}
var notAnEnum = 0
switch notAnEnum {
case .Foo: // expected-error{{type 'Int' has no member 'Foo'}}
()
}
struct ContainsEnum {
enum Possible<T> {
case Naught
case Mere(T)
case Twain(T, T)
}
func member(_ n: Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
ContainsEnum.Possible.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
Possible<Int>.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
Possible.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Naught: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
}
}
func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
.Naught: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
}
var m : ImportedEnum = .Simple
switch m {
case imported_enums.ImportedEnum.Simple,
ImportedEnum.Simple, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Simple: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
case imported_enums.ImportedEnum.Compound,
imported_enums.ImportedEnum.Compound(_), // expected-warning {{case is already handled by previous patterns; consider removing it}}
ImportedEnum.Compound, // expected-warning {{case is already handled by previous patterns; consider removing it}}
ImportedEnum.Compound(_), // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Compound, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Compound(_): // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
// Check that single-element tuple payloads work sensibly in patterns.
enum LabeledScalarPayload {
case Payload(name: Int)
}
var lsp: LabeledScalarPayload = .Payload(name: 0)
func acceptInt(_: Int) {}
func acceptString(_: String) {}
switch lsp {
case .Payload(0):
()
case .Payload(name: 0):
()
case let .Payload(x):
acceptInt(x)
acceptString("\(x)")
case let .Payload(name: x): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case let .Payload((name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let x): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload((let x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
}
// Property patterns.
struct S {
static var stat: Int = 0
var x, y : Int
var comp : Int {
return x + y
}
func nonProperty() {}
}
// Tuple patterns.
var t = (1, 2, 3)
prefix operator +++
infix operator +++
prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x }
func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) {
return (x.0+y.0, x.1+y.1, x.2+y.2)
}
switch t {
case (_, var a, 3):
a += 1
case var (_, b, 3):
b += 1
case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}}
c += 1
case (1, 2, 3):
()
// patterns in expression-only positions are errors.
case +++(_, var d, 3):
// expected-error@-1{{'_' can only appear in a pattern or on the left side of an assignment}}
// expected-error@-2{{'var' binding pattern cannot appear in an expression}}
()
case (_, var e, 3) +++ (1, 2, 3):
// expected-error@-1{{'_' can only appear in a pattern}}
// expected-error@-2{{'var' binding pattern cannot appear in an expression}}
()
case (let (_, _, _)) + 1:
// expected-error@-1 2 {{'var' binding pattern cannot appear in an expression}}
// expected-error@-2 {{expression pattern of type 'Int' cannot match values of type '(Int, Int, Int)'}}
()
}
// FIXME: We don't currently allow subpatterns for "isa" patterns that
// require interesting conditional downcasts.
class Base { }
class Derived : Base { }
switch [Derived(), Derived(), Base()] {
case let ds as [Derived]: // expected-error{{collection downcast in cast pattern is not implemented; use an explicit downcast to '[Derived]' instead}}
()
case is [Derived]: // expected-error{{collection downcast in cast pattern is not implemented; use an explicit downcast to '[Derived]' instead}}
()
default:
()
}
// Optional patterns.
let op1 : Int?
let op2 : Int??
switch op1 {
case nil: break
case 1?: break
case _?: break
}
switch op2 {
case nil: break
case _?: break
case (1?)?: break
case (_?)?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail"
let (responseObject: Int?) = op1
// expected-error @-1 {{expected ',' separator}} {{25-25=,}}
// expected-error @-2 {{expected pattern}}
// expected-error @-3 {{expression type 'Int?' is ambiguous without more context}}
| apache-2.0 | ca3d6cc3f9ea1fe107746260fee073e8 | 33.168639 | 322 | 0.645597 | 3.885935 | false | false | false | false |
xcodeswift/xcproj | Sources/XcodeProj/Objects/Targets/PBXLegacyTarget.swift | 1 | 4925 | import Foundation
/// This is the element for a build target that according to Xcode is an "External Build System". You can use this target to run a script.
public final class PBXLegacyTarget: PBXTarget {
/// Path to the build tool that is invoked (required)
public var buildToolPath: String?
/// Build arguments to be passed to the build tool.
public var buildArgumentsString: String?
/// Whether or not to pass Xcode build settings as environment variables down to the tool when invoked
public var passBuildSettingsInEnvironment: Bool
/// The directory where the build tool will be invoked during a build
public var buildWorkingDirectory: String?
/// Initializes the legacy target with its attributes.
///
/// - Parameters:
/// - name: name.
/// - buildToolPath: build tool path.
/// - buildArgumentsString: build arguments.
/// - passBuildSettingsInEnvironment: pass build settings in environment.
/// - buildWorkingDirectory: build working directory.
/// - buildConfigurationList: build configuration list.
/// - buildPhases: build phases.
/// - buildRules: build rules.
/// - dependencies: dependencies.
/// - productName: product name.
/// - product: product file reference.
/// - productType: product type.
public init(name: String,
buildToolPath: String? = nil,
buildArgumentsString: String? = nil,
passBuildSettingsInEnvironment: Bool = false,
buildWorkingDirectory: String? = nil,
buildConfigurationList: XCConfigurationList? = nil,
buildPhases: [PBXBuildPhase] = [],
buildRules: [PBXBuildRule] = [],
dependencies: [PBXTargetDependency] = [],
productName: String? = nil,
product: PBXFileReference? = nil,
productType: PBXProductType? = nil) {
self.buildToolPath = buildToolPath
self.buildArgumentsString = buildArgumentsString
self.passBuildSettingsInEnvironment = passBuildSettingsInEnvironment
self.buildWorkingDirectory = buildWorkingDirectory
super.init(name: name,
buildConfigurationList: buildConfigurationList,
buildPhases: buildPhases,
buildRules: buildRules,
dependencies: dependencies,
productName: productName,
product: product,
productType: productType)
}
// MARK: - Decodable
fileprivate enum CodingKeys: String, CodingKey {
case buildToolPath
case buildArgumentsString
case passBuildSettingsInEnvironment
case buildWorkingDirectory
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
buildToolPath = try container.decodeIfPresent(.buildToolPath)
buildArgumentsString = try container.decodeIfPresent(.buildArgumentsString)
passBuildSettingsInEnvironment = try container.decodeIntBool(.passBuildSettingsInEnvironment)
buildWorkingDirectory = try container.decodeIfPresent(.buildWorkingDirectory)
try super.init(from: decoder)
}
override func plistValues(proj: PBXProj, isa _: String, reference: String) throws -> (key: CommentedString, value: PlistValue) {
let (key, value) = try super.plistValues(proj: proj, isa: PBXLegacyTarget.isa, reference: reference)
var dict: [CommentedString: PlistValue]!
switch value {
case let .dictionary(dictValue):
dict = dictValue
if let buildToolPath = buildToolPath {
dict["buildToolPath"] = PlistValue.string(CommentedString(buildToolPath))
}
if let buildArgumentsString = buildArgumentsString {
dict["buildArgumentsString"] =
PlistValue.string(CommentedString(buildArgumentsString))
}
dict["passBuildSettingsInEnvironment"] =
PlistValue.string(CommentedString(passBuildSettingsInEnvironment.int.description))
if let buildWorkingDirectory = buildWorkingDirectory {
dict["buildWorkingDirectory"] =
PlistValue.string(CommentedString(buildWorkingDirectory))
}
default:
throw XcodeprojWritingError.invalidType(class: String(describing: type(of: self)), expected: "Dictionary")
}
return (key: key, value: .dictionary(dict))
}
}
// MARK: - PBXNativeTarget Extension (PlistSerializable)
extension PBXLegacyTarget: PlistSerializable {
func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) {
return try plistValues(proj: proj, isa: PBXLegacyTarget.isa, reference: reference)
}
}
| mit | 764681cda711ce57253b42b4c57674d4 | 44.601852 | 138 | 0.656041 | 5.307112 | false | true | false | false |
h-n-y/BigNerdRanch-SwiftProgramming | chapter-15/bronze-challenge/Zombie.swift | 1 | 650 | import Foundation
class Zombie: Monster {
var walksWithLimp = true
final override func terrorizeTown() {
let decrementAmount = 10
// only terrorize town if population is greater than zero
if town?.population > 0 {
town?.population < decrementAmount ? ( town?.population = 0 ) :
( town?.changePopulation(-decrementAmount) )
}
super.terrorizeTown()
}
func changeName(name: String, walksWithLimp: Bool) {
self.name = name
self.walksWithLimp = walksWithLimp
}
}
| mit | 83105d7fec206ac23df74e894607d5b2 | 25 | 96 | 0.533846 | 4.850746 | false | false | false | false |
nerdishbynature/TanukiKit | TanukiKit/User.swift | 1 | 3972 | import Foundation
import RequestKit
// MARK: model
@objc open class User: NSObject {
open let id: Int
open var username: String?
open var state: String?
open var avatarURL: URL?
open var webURL: URL?
open var createdAt: Date?
open var isAdmin: Bool?
open var bio: String?
open var name: String?
open var location: String?
open var skype: String?
open var linkedin: String?
open var twitter: String?
open var websiteURL: URL?
open var lastSignInAt: Date?
open var confirmedAt: Date?
open var email: String?
open var themeId: Int?
open var colorSchemeId: Int?
open var projectsLimit: Int?
open var currentSignInAt: Date?
open var canCreateGroup: Bool?
open var canCreateProject: Bool?
open var twoFactorEnabled: Bool?
open var external: Bool?
public init(_ json: [String: Any]) {
if let id = json["id"] as? Int {
name = json["name"] as? String
username = json["username"] as? String
self.id = id
state = json["state"] as? String
if let urlString = json["avatar_url"] as? String, let url = URL(string: urlString) {
avatarURL = url
}
if let urlString = json["web_url"] as? String, let url = URL(string: urlString) {
webURL = url
}
createdAt = Time.rfc3339Date(json["created_at"] as? String)
isAdmin = json["is_admin"] as? Bool
bio = json["bio"] as? String
location = json["location"] as? String
skype = json["skype"] as? String
linkedin = json["linkedin"] as? String
twitter = json["twitter"] as? String
if let urlString = json["website_url"] as? String, let url = URL(string: urlString) {
websiteURL = url
}
lastSignInAt = Time.rfc3339Date(json["last_sign_in_at"] as? String)
confirmedAt = Time.rfc3339Date(json["confirmed_at"] as? String)
email = json["email"] as? String
themeId = json["theme_id"] as? Int
colorSchemeId = json["color_scheme_id"] as? Int
projectsLimit = json["projects_limit"] as? Int
currentSignInAt = Time.rfc3339Date(json["current_sign_in_at"] as? String)
canCreateGroup = json["can_create_group"] as? Bool
canCreateProject = json["can_create_project"] as? Bool
twoFactorEnabled = json["two_factor_enabled"] as? Bool
external = json["external"] as? Bool
} else {
id = -1
}
}
}
// MARK: request
public extension TanukiKit {
/**
Fetches the currently logged in user
- parameter completion: Callback for the outcome of the fetch.
*/
public func me(_ session: RequestKitURLSession = URLSession.shared, completion: @escaping (_ response: Response<User>) -> Void) -> URLSessionDataTaskProtocol? {
let router = UserRouter.readAuthenticatedUser(self.configuration)
return router.loadJSON(session, expectedResultType: [String: Any].self) { json, error in
if let error = error {
completion(Response.failure(error))
} else {
if let json = json {
let parsedUser = User(json)
completion(Response.success(parsedUser))
}
}
}
}
}
// MARK: Router
enum UserRouter: Router {
case readAuthenticatedUser(Configuration)
var configuration: Configuration {
switch self {
case .readAuthenticatedUser(let config): return config
}
}
var method: HTTPMethod {
return .GET
}
var encoding: HTTPEncoding {
return .url
}
var path: String {
switch self {
case .readAuthenticatedUser:
return "user"
}
}
var params: [String: Any] {
return [:]
}
}
| mit | 7df44fd47c1dc4ca833ff01053d38ca6 | 31.292683 | 164 | 0.578298 | 4.374449 | false | false | false | false |
xiaomudegithub/iosstar | iOSStar/Model/ShareDataModel/ShareDataModel.swift | 3 | 1597 | //
// ShareDataModel.swift
// iOSStar
//
// Created by sum on 2017/4/24.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class ShareDataModel: NSObject {
private static var model: ShareDataModel = ShareDataModel()
class func share() -> ShareDataModel{
return model
}
var wechatUserInfo = [String:String]()
dynamic var isweichaLogin : Bool = false
var phone : String = ""
var codeToeken : String = ""
dynamic var selectMonth : String = ""
var isReturnBackClick : Bool = false
var orderInfo : OrderInformation?
var isShowInWindows : Bool = false
var registerModel: RegisterRequestModel = RegisterRequestModel()
var wxregisterModel: WXRegisterRequestModel = WXRegisterRequestModel()
var controlSwitch: Bool = true
var buttonExtOnceSwitch = true
var voiceSwitch = false
var selectStarCode = ""
var baseTabbarC: BaseTabBarController?
var netInfo: NetModel = NetModel()
var qiniuHeader = "http://out9d2vy4.bkt.clouddn.com/"
}
class OrderInformation: NSObject {
var orderAllPrice : String = ""
var orderAccount : String = ""
var orderPrice : String = ""
var orderStatus : String = ""
var orderInfomation : String = ""
var ordertitlename : String = "订单详情"
}
class Share: NSObject {
var titlestr : String = ""
var Image : UIImage!
var name : String = ""
var descr : String = ""
var star_code : String = ""
var work : String = ""
var webpageUrl : String = ""
var PromotionUrl : String = ""
}
| gpl-3.0 | 3a85acefee16620f739b5b339eb1f1aa | 27.321429 | 74 | 0.648802 | 4.119481 | false | false | false | false |
phimage/Prephirences | Sources/NSUbiquitousKeyValueStore+Prephirences.swift | 1 | 3481 | //
// NSUbiquitousKeyValueStore+Prephirences.swift
// Prephirences
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
/** Prephirences Extends NSUbiquitousKeyValueStore
*/
#if !os(watchOS)
extension NSUbiquitousKeyValueStore: MutablePreferencesType {
public func dictionary() -> PreferencesDictionary {
return self.dictionaryRepresentation
}
public func stringArray(forKey key: PreferenceKey) -> [String]? {
return array(forKey: key) as? [String]
}
// MARK: number
public func integer(forKey key: PreferenceKey) -> Int {
return Int(longLong(forKey: key))
}
public func float(forKey key: PreferenceKey) -> Float {
return Float(double(forKey: key))
}
@nonobjc public func set(_ value: Int, forKey key: PreferenceKey) {
set(Int64(value), forKey: key)
}
@nonobjc public func set(_ value: Float, forKey key: PreferenceKey) {
set(Double(value), forKey: key)
}
}
// MARK: url
extension NSUbiquitousKeyValueStore {
public func url(forKey key: PreferenceKey) -> URL? {
if let bookData = self.data(forKey: key) {
var isStale: ObjCBool = false
#if os(OSX)
let options = NSURL.BookmarkResolutionOptions.withSecurityScope
#elseif os(iOS) || os(watchOS) || os(tvOS)
let options = URL.BookmarkResolutionOptions.withoutUI
#endif
do {
let url = try (NSURL(resolvingBookmarkData: bookData, options: options, relativeTo: nil, bookmarkDataIsStale: &isStale) as URL)
set(url, forKey: key)
return url
} catch { }
}
return nil
}
public func set(_ url: URL?, forKey key: PreferenceKey) {
if let urlToSet = url {
#if os(OSX)
let options = URL.BookmarkCreationOptions.withSecurityScope.union(.securityScopeAllowOnlyReadAccess)
#elseif os(iOS) || os(watchOS) || os(tvOS)
let options = URL.BookmarkCreationOptions()
#endif
let data: Data?
do {
data = try urlToSet.bookmarkData(options: options, includingResourceValuesForKeys: nil, relativeTo: nil)
} catch _ {
data = nil
}
set(data, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
#endif
| mit | b6e3a3fd3750026d481ff510b966b0d8 | 32.471154 | 143 | 0.659293 | 4.742507 | false | false | false | false |
cs4278-2015/tinderFood | tinderForFood/MatchPhotoCell.swift | 1 | 1592 | //
// GalleryTableViewCell.swift
// tinderForFood
//
// Created by Edward Yun on 11/21/15.
// Copyright © 2015 Edward Yun. All rights reserved.
//
import UIKit
class GalleryTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
//TODO - Change to UICollectionView
func loadImages(rowHeight rowHeight: CGFloat, rowWidth: CGFloat, leftImage: String, centerImage: String, rightImage: String) {
let leftLoadedImage = UIImage(named: leftImage)
let centerLoadedImage = UIImage(named: centerImage)
let rightLoadedImage = UIImage(named: rightImage)
let leftImageView = UIImageView(image: leftLoadedImage)
let centerImageView = UIImageView(image: centerLoadedImage)
let rightImageView = UIImageView(image: rightLoadedImage)
let spacing = (rowWidth - (rowHeight * 3))/2
leftImageView.frame = CGRect(x: 0, y: 0, width: rowHeight, height: rowHeight)
centerImageView.frame = CGRect(x: rowHeight + spacing, y: 0, width: rowHeight, height: rowHeight)
rightImageView.frame = CGRect(x: (rowHeight + spacing)*2, y: 0, width: rowHeight, height: rowHeight)
self.addSubview(leftImageView)
self.addSubview(centerImageView)
self.addSubview(rightImageView)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 0e0047706e81fa9fcf1dc039986ad494 | 29.596154 | 130 | 0.650534 | 4.777778 | false | false | false | false |
prolificinteractive/Kumi-iOS | Kumi/Core/Shadow/ShadowStyle+JSON.swift | 1 | 1039 | //
// ShadowStyle+JSON.swift
// Pods
//
// Created by Prolific Interactive on 6/4/17.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
import Foundation
extension ShadowStyle {
public init?(json: JSON) {
var shadowOpacity: Float = 1.0
var shadowRadius: CGFloat = 0
var shadowOffset: CGSize = CGSize.zero
var shadowColor: CGColor? = nil
if let shadowOpacityValue = json["shadowOpacity"].double {
shadowOpacity = Float(shadowOpacityValue)
}
if let shadowRadiusValue = json["shadowRadius"].cgFloat {
shadowRadius = shadowRadiusValue
}
if let shadowOffsetValue = CGSize(json: json["shadowOffset"]) {
shadowOffset = shadowOffsetValue
}
shadowColor = UIColor(json: json["shadowColor"])?.cgColor
self.init(shadowOpacity: shadowOpacity,
shadowRadius: shadowRadius,
shadowOffset: shadowOffset,
shadowColor: shadowColor)
}
}
| mit | 751325efd49df9915661582c60dbae26 | 26.315789 | 71 | 0.619461 | 5.138614 | false | false | false | false |
GENG-GitHub/weibo-gd | GDWeibo/Class/Module/Main/Controller/GDBasicViewController.swift | 1 | 2577 | //
// GDBasicViewController.swift
// GDWeibo
//
// Created by geng on 15/10/27.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDBasicViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
//根据用户是否登录上网
let userLogin = GDUserAccount.userLogin()
var visitorView: GDVisitorView?
override func loadView()
{
userLogin ? super.loadView() : setupVisitorView()
}
//创建访客视图
func setupVisitorView() {
visitorView = GDVisitorView()
view = visitorView
//设置背景颜色
view.backgroundColor = UIColor(white: 237/255, alpha: 1.0)
if self is GDHomeViewController{
//旋转轮盘
visitorView?.startRotationAnimation()
}
else if self is GDMessageViewController{
//信息界面
visitorView?.setupVisiter("登录后,别人评论你的微博l,发给你的消息,都会在这里收到通知", imageName: "visitordiscover_image_message")
}
else if self is GDDiscoverViewController {
//发现界面
visitorView?.setupVisiter("登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过", imageName: "visitordiscover_image_message")
}
else if self is GDProfileViewController
{
//我界面
visitorView?.setupVisiter("登录后,你的微博、相册、个人资料会显示在这里,展示给别人", imageName: "visitordiscover_image_profile")
}
//设置代理
visitorView?.visitorDelegate = self
// 添加导航栏按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillRegister")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillLogin")
}
}
extension GDBasicViewController: GDVisitorViewDelegate {
func visitorViewWillRegister()
{
print(__FUNCTION__)
}
func visitorViewWillLogin()
{
let oauthVC = GDOauthViewController()
presentViewController(UINavigationController(rootViewController: oauthVC), animated: true, completion: nil)
}
}
| apache-2.0 | 53d383cdffd1e79c83ec4c6b81161c21 | 21.772277 | 155 | 0.603043 | 5.088496 | false | false | false | false |
asp2insp/yowl | yowl/YelpClient.swift | 1 | 3310 | //
// YelpClient.swift
// yowl
//
// Created by Josiah Gaskin on 5/14/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
import UIKit
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "jefUNHNlaU0Ku7EndY7opg"
let yelpConsumerSecret = "FOzSN3-R1Y7KjTfjWIScdimnIoI"
let yelpToken = "CbCSzMQqH6pc8wD7_o4UU01EQnMq987z"
let yelpTokenSecret = "JvbR6jTcelDly1FN5TEX1RQrvxU"
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
var debounceTimer : NSTimer?
class var sharedInstance : YelpClient {
struct Static {
static var token : dispatch_once_t = 0
static var instance : YelpClient? = nil
}
dispatch_once(&Static.token) {
Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
}
return Static.instance!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
var baseUrl = NSURL(string: "http://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
var token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithCurrentTerms() {
if let timer = debounceTimer {
timer.invalidate()
}
debounceTimer = NSTimer(timeInterval: 0.2, target: self, selector: Selector("dispatchRequest:"), userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode")
}
func dispatchRequest(sender: AnyObject) {
if let timer = debounceTimer {
timer.invalidate()
}
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// For SF: "term": term, "ll": "37.785771,-122.406165"
var parameters : [String:AnyObject] = [:]
var categories = Reactor.instance.evaluateToSwift(CATEGORIES) as! String
if !categories.isEmpty {
parameters["category_filter"] = categories
}
var offset = Reactor.instance.evaluateToSwift(OFFSET) as! Int
parameters["offset"] = offset
for (key, val) in Reactor.instance.evaluateToSwift(QUERY) as! [String:Any?] {
parameters[key] = val as? AnyObject
}
// println(parameters)
self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
Reactor.instance.dispatch("setResults", payload: response)
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
NSLog("Operation error \(error)")
})
}
} | mit | b3e2250e1aac8b21149b0fc316c44e18 | 36.202247 | 161 | 0.649849 | 4.254499 | false | false | false | false |
azukinohiroki/positionmaker2 | positionmaker2/CoreDataHelper.swift | 1 | 4050 | //
// CoreDataHelper.swift
// positionmaker2
//
// Created by Hiroki Taoka on 2015/06/11.
// Copyright (c) 2015年 azukinohiroki. All rights reserved.
//
import Foundation
import CoreData
class CoreDataHelper {
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.azk.hr.positionmaker2" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "positionmaker2", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("positionmaker2.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(String(describing: error)), \(error!.userInfo)")
// abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(String(describing: error)), \(error!.userInfo)")
// abort()
}
}
}
}
}
| mit | ef59019ee2acf516804f73beb3e36072 | 46.069767 | 286 | 0.720356 | 5.196406 | false | false | false | false |
DianQK/TransitionTreasury | TransitionAnimation/SlideTransitionAnimation.swift | 1 | 4417 | //
// SlideTransitionAnimation.swift
// TransitionTreasury
//
// Created by DianQK on 16/1/21.
// Copyright © 2016年 TransitionTreasury. All rights reserved.
//
import TransitionTreasury
open class SlideTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning, TabBarTransitionInteractiveable {
open var transitionStatus: TransitionStatus
open var transitionContext: UIViewControllerContextTransitioning?
open var completion: (() -> Void)?
open var gestureRecognizer: UIGestureRecognizer? {
didSet {
gestureRecognizer?.addTarget(self, action: #selector(SlideTransitionAnimation.interactiveTransition(_:)))
}
}
open var percentTransition: UIPercentDrivenInteractiveTransition = UIPercentDrivenInteractiveTransition()
open var interactivePrecent: CGFloat = 0.3
open var interacting: Bool = false
fileprivate var tabBarTransitionDirection: TabBarTransitionDirection = .right
public init(status: TransitionStatus = .tabBar) {
transitionStatus = status
super.init()
}
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let containView = transitionContext.containerView
guard let tabBarController = fromVC?.tabBarController else { fatalError("No TabBarController.") }
guard let fromVCIndex = tabBarController.viewControllers?.firstIndex(of: fromVC!)
, let toVCIndex = tabBarController.viewControllers?.firstIndex(of: toVC!) else {
fatalError("VC not in TabBarController.")
}
let fromVCStartOriginX: CGFloat = 0
var fromVCEndOriginX: CGFloat = -UIScreen.main.bounds.width
var toVCStartOriginX: CGFloat = UIScreen.main.bounds.width
let toVCEndOriginX: CGFloat = 0
tabBarTransitionDirection = TabBarTransitionDirection.TransitionDirection(fromVCIndex, toVCIndex: toVCIndex)
if tabBarTransitionDirection == .left {
swap(&fromVCEndOriginX, &toVCStartOriginX)
}
containView.addSubview(fromVC!.view)
containView.addSubview(toVC!.view)
fromVC?.view.frame.origin.x = fromVCStartOriginX
toVC?.view.frame.origin.x = toVCStartOriginX
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: {
fromVC?.view.frame.origin.x = fromVCEndOriginX
toVC?.view.frame.origin.x = toVCEndOriginX
}) { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
if !transitionContext.transitionWasCancelled && finished {
self.completion?()
self.completion = nil
}
}
}
@objc open func interactiveTransition(_ sender: UIPanGestureRecognizer) {
guard let view = sender.view else { return }
let offsetX = tabBarTransitionDirection == .left ? sender.translation(in: view).x : -sender.translation(in: view).x
var percent = offsetX / view.bounds.size.width
percent = min(1.0, max(0, percent))
switch sender.state {
case .began :
percentTransition.startInteractiveTransition(transitionContext!)
interacting = true
case .changed :
interacting = true
percentTransition.update(percent)
default :
interacting = false
if percent > interactivePrecent {
percentTransition.completionSpeed = 1.0 - percentTransition.percentComplete
percentTransition.finish()
gestureRecognizer?.removeTarget(self, action: #selector(SlideTransitionAnimation.interactiveTransition(_:)))
} else {
percentTransition.cancel()
}
}
}
}
| mit | ea68c9cd97c3af412fefb34a0cd4e60e | 38.410714 | 132 | 0.663344 | 6.113573 | false | false | false | false |
s-aska/Justaway-for-iOS | Justaway/TwitterList.swift | 1 | 2199 | //
// TwitterList.swift
// Justaway
//
// Created by Shinichiro Aska on 7/3/15.
// Copyright (c) 2015 Shinichiro Aska. All rights reserved.
//
import Foundation
import SwiftyJSON
struct TwitterList {
let id: String
let name: String
let description: String
let subscriberCount: Int
let memberCount: Int
let mode: String
let following: Bool
let user: TwitterUser
let createdAt: TwitterDate
init(_ json: JSON) {
self.id = json["id_str"].string ?? ""
self.name = json["name"].string ?? ""
self.description = json["description"].string ?? ""
self.subscriberCount = json["subscriber_count"].int ?? 0
self.memberCount = json["member_count"].int ?? 0
self.following = json["member_count"].boolValue
self.mode = json["mode"].string ?? ""
self.createdAt = TwitterDate(json["created_at"].string ?? "")
self.user = TwitterUser(json["user"])
}
init(_ dictionary: [String: AnyObject]) {
self.id = dictionary["id"] as? String ?? ""
self.name = dictionary["name"] as? String ?? ""
self.description = dictionary["description"] as? String ?? ""
self.subscriberCount = dictionary["subscriberCount"] as? Int ?? 0
self.memberCount = dictionary["memberCount"] as? Int ?? 0
self.mode = dictionary["mode"] as? String ?? ""
self.following = dictionary["following"] as? Bool ?? false
self.user = TwitterUser(dictionary["id"] as? [String: AnyObject] ?? [:])
self.createdAt = TwitterDate(Date(timeIntervalSince1970: (dictionary["createdAt"] as? NSNumber ?? 0).doubleValue))
}
var dictionaryValue: [String: AnyObject] {
return [
"id": id as AnyObject,
"name": name as AnyObject,
"description": description as AnyObject,
"subscriberCount": subscriberCount as AnyObject,
"memberCount": memberCount as AnyObject,
"mode": mode as AnyObject,
"following": following as AnyObject,
"user": user.dictionaryValue as AnyObject,
"createdAt": Int(createdAt.date.timeIntervalSince1970) as AnyObject
]
}
}
| mit | 0f96c43b17962daa4b56d1cb89b28748 | 35.65 | 122 | 0.612096 | 4.398 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/BuildCancellationInformation.swift | 1 | 493 | public struct BuildCancellationInformation {
public let user: UserSummary
public let timestamp: String
init?(dictionary: [String: AnyObject]) {
guard let timestamp = dictionary["timestamp"] as? String,
let userDictionary = dictionary["user"] as? [String: AnyObject],
let user = UserSummary(dictionary: userDictionary) else {
return nil
}
self.user = user
self.timestamp = timestamp
}
} | mit | 240700c7d562e1eb61d620fa6e961aac | 28.058824 | 76 | 0.604462 | 5.301075 | false | false | false | false |
reversegremlin/SwiftTools | SwiftUtils/main.swift | 1 | 1720 | //
// main.swift
// SwiftUtils
//
// Created by Nadia Morris on 10/27/14.
// Copyright (c) 2014 Nadia Morris. All rights reserved.
//
import Foundation
println("Hello, World!")
var q = Queue<String>()
q.enqueue("Coffee")
q.enqueue("Tea")
q.enqueue("Milk")
let test = q.dequeue()!
//println(test)
//println(q.peek()!)
var s = Stack<String>()
s.push("Niblet")
s.push("Sarah")
s.push("Sally")
//for index in 1...10 {
// if let foo = s.pop() {
// println(foo)
// }
//}
var rArray: [Int] = []
var i = 1
for nums in 1...10 {
// let ran = Int(arc4random() % 1000)
rArray.append(i++)
}
func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let count = countElements(list)
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&list[i], &list[j])
}
return list
}
var nArray = shuffle(rArray)
var text = String(contentsOfFile:"/Users/hexjunky/Downloads/QuickSort.txt", encoding: NSUTF8StringEncoding, error: nil)!
var stringArray = text.componentsSeparatedByString("\n")
var intArray = [Int]()
for intStr in stringArray {
let item: String = intStr.stringByReplacingOccurrencesOfString("\r", withString: "", options: nil, range: nil)
if let intVal = item.toInt() {
intArray.append(intVal)
}
}
var anotherIntArray = intArray
//quickSortLastElement(&intArray)
quickSortFirstElement(&intArray)
//
//quickSortLastElement(&anotherIntArray)
//quickSortMedianOfThree(&intArray)
for thing in intArray {
println(thing)
}
//quickSort(&intArray)
//mergeSort(&nArray)
//for thing in intArray {
// println(thing)
//}
//insertionSort(&randStrings)
//
//
//for thing in randStrings {
// println(thing)
//}
| apache-2.0 | 87a3d157f8969fe02424b416df0d0187 | 17.695652 | 120 | 0.659884 | 3.121597 | false | false | false | false |
russbishop/swift | test/SourceKit/CodeComplete/complete_test.swift | 1 | 1491 | // RUN: not %complete-test 2>&1 | FileCheck -check-prefix=MISSING-ALL %s
// MISSING-ALL: usage: complete-test -tok=A file
// MISSING-ALL: missing <source-file>
// RUN: not %complete-test %s 2>&1 | FileCheck -check-prefix=MISSING-TOK %s
// MISSING-TOK: missing -tok=
// RUN: not %complete-test -tok=NOPE %s 2>&1 | FileCheck -check-prefix=MISSING-TOK-IN %s
// MISSING-TOK-IN: cannot find code completion token in source file
// RUN: %complete-test -tok=INT_DOT %s | FileCheck -check-prefix=INT_DOT %s -strict-whitespace
// RUN: %complete-test -tok=ALL %s | FileCheck -check-prefix=ALL %s
// RUN: %complete-test -tok=DIFF -raw %s > %t.complete-test
// RUN: %sourcekitd-test -req=complete.open -pos=49:5 %s -- %s > %t.sourcekitd-test
// RUN: diff %t.complete-test %t.sourcekitd-test
struct MyInt {
func advancedFeatures(x: Int) {}
func advancedFeatures(x: Int, y: Int) {}
var bigPower: Int = 0
func descriptiveIntention(x: Int) {}
}
func foo() {
let x = MyInt()
x.#^INT_DOT^#
// INT_DOT: {{^}}advancedFeatures(x:
// INT_DOT: {{^}}bigPower{{$}}
// INT_DOT: {{^}}descriptiveIntention(x: Int){{$}}
}
func bar() {
#^ALL^#
// ALL: bar()
// ALL: foo()
}
// A simple struct that will have a reliable sort order for diff'ing so that we
// can check that the -raw output from complete-test looks like
// sourcekitd-test.
struct ForDiff {
let w: Int
let x: String
func y() {}
func z() throws {}
}
func diff(x: ForDiff) {
x.#^DIFF^#
}
// XFAIL: broken_std_regex
| apache-2.0 | 8fc3dccce388a9ce5ba9da5f22d8bfe3 | 27.673077 | 94 | 0.65057 | 2.987976 | false | true | false | false |
honghaoz/RRNCollapsableSectionTableViewSwift | Example-Swift/Example-Swift/MenuSectionHeader.swift | 1 | 2056 | //
// MenuSectionHeader.swift
// Example-Swift
//
// Created by Robert Nash on 22/09/2015.
// Copyright © 2015 Robert Nash. All rights reserved.
//
import UIKit
class MenuSectionHeaderView: UITableViewHeaderFooterView, RRNCollapsableSectionHeaderProtocol {
@IBOutlet weak var sectionTitleLabel: UILabel!
@IBOutlet weak var arrowImageView: UIImageView!
var interactionDelegate: RRNCollapsableSectionHeaderReactiveProtocol!
func radians(degrees: Double) -> Double {
return M_PI * degrees / 180.0
}
private var isRotating = false
func open(animated: Bool) {
if animated && !isRotating {
isRotating = true
UIView.animateWithDuration(0.2, delay: 0.0, options: [.AllowUserInteraction, .CurveLinear], animations: { () -> Void in
self.arrowImageView.transform = CGAffineTransformIdentity
}, completion: { (let finished) -> Void in
self.isRotating = false
})
} else {
layer.removeAllAnimations()
arrowImageView.transform = CGAffineTransformIdentity
isRotating = false
}
}
func close(animated: Bool) {
if animated && !isRotating {
isRotating = true
UIView.animateWithDuration(0.2, delay: 0.0, options: [.AllowUserInteraction, .CurveLinear], animations: { () -> Void in
self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(self.radians(180.0)))
}, completion: { (let finished) -> Void in
self.isRotating = false
})
} else {
layer.removeAllAnimations()
arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(radians(180.0)))
isRotating = false
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
interactionDelegate?.userTapped(self)
}
}
| mit | 530fc712512ad684728e98d0939b4188 | 31.619048 | 131 | 0.59708 | 5.337662 | false | false | false | false |
GeekerHua/GHSwiftTest | GHPlayground.playground/Pages/08.数组.xcplaygroundpage/Contents.swift | 1 | 1481 | //: [Previous](@previous)
import UIKit
let array = ["张三","李四"]
let array2 = ["张三",18,UIView()]
let array3 = [Int](count: 3, repeatedValue: 32)
for name in array {
print(name)
}
// 日常开发中,类型一致的数组多
for name in array2{
print(name)
}
// 可变 var 和不可变 let
var list = ["zhang", "lisi"]
list.append("wang")
//list.removeFirst()
//list.removeLast()
list.removeAtIndex(1)
print(list.capacity)
list.removeAll(keepCapacity: true)
//list.removeAll()
print(list.capacity)
list
// 数组容量的变化
var arrayM = [String]()
arrayM.capacity
for i in 0..<16 {
arrayM.append("hello\(i)")
print("索引\(i) 数组容量\(arrayM.capacity)")
}
// 定义数组并且实例化
//var arrayM2 = [Int]()
// 定义数组指定容量
var arrayM2 : [Int]
arrayM2 = [Int]()
print(arrayM2.capacity)
arrayM2 = []
arrayM2.append(33)
print(arrayM2.capacity)
// 指定数组容量,count: 指定容量: ,repeatValue: 填充内容
var arrayM3 = [Int](count: 32, repeatedValue: 0)
print(arrayM3.capacity)
// 数组的拼接
var arr1 = [1,2,3,4,5]
var arr2 = [6,7,8,9,10]
var arr3 = ["13","33"]
arr2 + arr1
arr1 += arr2
//arr1 += arr3 // 数组类型不同无法拼接
//: [Next](@next)
let a1 = ["23", "33"]
let a2 = ["23", "33"]
a1 == a2
let t = [("111",1), ("222",2)]
//let p = t.filter { (tuples) -> Bool in
// if let _ = tuples.0 as! String {
// return true
// } else {
// reuturn false
// }
//}
| mit | 2923c0a1b7bc56ebbfc282309594f294 | 14.746988 | 48 | 0.607498 | 2.489524 | false | false | false | false |
rainedAllNight/RNScrollPageView | RNScrollPageView-Example/RNScrollPageView/RNScrollPageView/RNScrollPageView.swift | 1 | 22759 | //
// RNScrollPageView.swift
// RNScrollPageView
//
// Created by 罗伟 on 2017/5/31.
// Copyright © 2017年 罗伟. All rights reserved.
//
import UIKit
public enum PageItemState {
case normal
case selected
}
@objc protocol RNScrollPageViewDelegate: NSObjectProtocol {
@objc optional func scrollPageView(_ scrollPageView: RNScrollPageView, didShow viewController: UIViewController, at index: Int)
}
class RNScrollPageView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
// viewController array
open var viewControllers = [UIViewController]() {
didSet {
self.configScrollPage()
}
}
// title array
open var titles = [String]() {
didSet {
self.configScrollPage()
}
}
@IBInspectable open var selectedIndex: Int = 0 // selected index, default is 0
@IBInspectable open var pageItemWidth: CGFloat = 0 // pageItem's width, is dont set, default is adjust according to the number of titles
@IBInspectable open var pageItemHeight: CGFloat = 40.0 // pageItem's height, default is 40.0
@IBInspectable open var isHideSubLine: Bool = false // is hide the slidable subLine, default is false
@IBInspectable open var subLineHeight: CGFloat = 2.0 // subLineView's height, default is 2.0
@IBInspectable open var subLineWidth: CGFloat = 0 // if dont set, default is item width
@IBInspectable open var itemTitleMargin: CGFloat = 20.0 // the margin between with the adjoining item, default is 20.0
@IBInspectable open var subLineViewColor: UIColor = UIColor.red // subLineView's color, default is red
@IBInspectable open var titleColorNormal: UIColor = UIColor.black // item's titleColor for normal, default is black
@IBInspectable open var titleColorSelected: UIColor = UIColor.red // item's titleColor for selected, default is red
@IBInspectable open var isZoomTitle: Bool = true // item's title zoom animation, default is true; if true, the titleFontSelected is does not work
@IBInspectable open var maxItemScale: CGFloat = 1.2 // item's title max zoom scale, default is 1.2
@IBInspectable open var splitLineViewHeight: CGFloat = 0.5 // bottom splitLine's height, default is 0.5
@IBInspectable open var splitLineViewColor: UIColor = UIColor.white // the bottom splitLineView's background color, default is white
@IBInspectable open var isHideSplit: Bool = true // is hide bottom splitLineView, default is true
@IBInspectable open var titleFontSizeNormal: CGFloat = 14 {
didSet {
self.titleFontNormal = UIFont.systemFont(ofSize: titleFontSizeNormal)
}
} // titleFontSize for normal, default is system 14
@IBInspectable open var titleFontSizeSelected: CGFloat = 16 {
didSet {
self.titleFontSelected = UIFont.systemFont(ofSize: titleFontSizeSelected)
}
} // item's titleFontSize for selected, default is system 16
open var titleFontNormal: UIFont = UIFont.systemFont(ofSize: 14) // item's titleFont for normal, default is system 14
open var titleFontSelected: UIFont = UIFont.systemFont(ofSize: 16) // item's titleFont for selected, default is system 16
weak open var delegate: RNScrollPageViewDelegate?
open var splitLineView: UIView = UIView()
open var subLineView = UIView()
open var currentSelectedIndex = 0
private var expectedItemWidths = [CGFloat]()
private var collectionView: UICollectionView?
private var scrollView: UIScrollView?
private var isPageItemActionScroll = false
private var lastSelectedCell: PageItemCell?
// MARK: - open method
open func config(with viewControllers: [UIViewController], titles: [String]) {
self.viewControllers = viewControllers
self.titles = titles
}
open func setTitleFont(_ font: UIFont, for state: PageItemState) {
switch state {
case .selected:
self.titleFontSelected = font
case .normal:
self.titleFontNormal = font
}
}
open func setTitleColor(_ color: UIColor, for state: PageItemState) {
switch state {
case .selected:
self.titleColorSelected = color
case .normal:
self.titleColorNormal = color
}
}
open func titleFont(for state: PageItemState) -> UIFont {
switch state {
case .selected:
return self.titleFontSelected
case .normal:
return self.titleFontNormal
}
}
open func titleColor(for state: PageItemState) -> UIColor {
switch state {
case .selected:
return self.titleColorSelected
case .normal:
return self.titleColorNormal
}
}
// MARK: - private method
private func configScrollPage() {
guard self.titles.count > 0 else {
return
}
guard self.viewControllers.count > 0 else {
return
}
guard self.titles.count == self.viewControllers.count else {
print("vc和标题数据源大小不匹配, 请检查")
return
}
// fix cellForItem not call bug
self.parentViewController?.automaticallyAdjustsScrollViewInsets = false
self.layoutIfNeeded()
if self.collectionView == nil {
self.addPageItemsCollectionView()
if !isHideSplit {
self.addSplitLineView()
}
}
if self.scrollView == nil {
self.addContentScrollView()
}
self.expectedItemWidths = self.getPageItemWidths()
// when the total itemWidth is less than pageViewWidth, itemWidth = pageViewWidth/itemCount
if self.pageItemWidth == 0 {
var maxWidth: CGFloat = 0
let widths = self.expectedItemWidths.reduce(0) { (result, width) -> CGFloat in
maxWidth = max(width, maxWidth)
return result + width
}
let compareWidth = self.bounds.width/CGFloat(self.titles.count)
if widths <= self.bounds.width, compareWidth >= maxWidth {
self.pageItemWidth = compareWidth
}
}
// set subLineView
var subLineWidth: CGFloat = 0
if self.subLineWidth == 0 {
subLineWidth = self.expectedItemWidths[self.selectedIndex]
} else {
subLineWidth = self.subLineWidth
}
if subLineWidth > pageItemWidth, pageItemWidth > 0 {
subLineWidth = pageItemWidth
}
var centerX: CGFloat = 0
if self.pageItemWidth != 0 {
centerX = pageItemWidth * CGFloat(self.selectedIndex) + pageItemWidth/2
} else {
for (index, width) in self.expectedItemWidths.enumerated() {
if index < self.selectedIndex {
centerX += width
} else if index == self.selectedIndex {
centerX += width/2
}
}
}
self.subLineView.center = CGPoint(x: centerX, y: pageItemHeight - subLineHeight + 1.0 + splitLineViewHeight) // 1.0 is collectionView's contentSize edgeInset
self.subLineView.bounds = CGRect(x: 0, y: 0, width: subLineWidth, height: subLineHeight + 1.0 + splitLineViewHeight)
self.subLineView.isHidden = self.isHideSubLine
self.subLineView.backgroundColor = subLineViewColor
self.collectionView?.addSubview(self.subLineView)
self.currentSelectedIndex = self.selectedIndex
self.collectionView?.reloadData()
// handle default selectedIndex
if self.selectedIndex <= self.viewControllers.count, self.selectedIndex <= self.titles.count, self.selectedIndex >= 0 {
self.collectionView?.scrollToItem(at: IndexPath(item: self.selectedIndex, section: 0), at: .centeredHorizontally, animated: false)
self.scrollView?.scrollRectToVisible(CGRect(x: self.scrollView!.bounds.width * CGFloat(self.selectedIndex), y: 0, width: self.scrollView!.bounds.width, height: self.scrollView!.bounds.width), animated: false)
}
// show default viewController
self.showSelectedViewController(self.selectedIndex)
}
private func addPageItemsCollectionView() {
// set collectionView
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.pageItemHeight)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(PageItemCell.self, forCellWithReuseIdentifier: PageItemCell.description())
collectionView.backgroundColor = UIColor.white
self.addSubview(collectionView)
self.collectionView = collectionView
}
private func addSplitLineView() {
self.splitLineView.frame = CGRect(x: 0, y: self.pageItemHeight, width: self.bounds.width, height: splitLineViewHeight)
self.splitLineView.backgroundColor = self.splitLineViewColor
self.addSubview(splitLineView)
}
private func addContentScrollView() {
let width = self.bounds.width
var height = self.bounds.height - self.pageItemHeight
if let _ = self.parentViewController?.navigationController {
height = height - 64 // hard code
}
var y = self.pageItemHeight
if !isHideSplit {
height = height - splitLineViewHeight
y = y + splitLineViewHeight
}
let scrollView = UIScrollView(frame: CGRect(x: 0, y: y, width: width, height: height))
scrollView.delegate = self
scrollView.contentSize = CGSize(width: (width * CGFloat(self.viewControllers.count)), height: height)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
self.addSubview(scrollView)
self.scrollView = scrollView
}
private func updateSubLineViewPosition(_ scrollView: UIScrollView) {
let offSetX = scrollView.contentOffset.x
guard 0 <= offSetX, offSetX <= scrollView.contentSize.width - scrollView.bounds.width else {
return
}
let beforeIndex = floorf(Float(offSetX/self.bounds.width))
let afterIndex = ceilf(Float(offSetX/self.bounds.width))
guard let beforeCell = self.collectionView?.cellForItem(at: IndexPath(item: Int(beforeIndex), section: 0)) else {
return
}
guard let afterCell = self.collectionView?.cellForItem(at: IndexPath(item: Int(afterIndex), section: 0)) else {
return
}
let centerDistance = afterCell.center.x - beforeCell.center.x
let scrollScale = offSetX.truncatingRemainder(dividingBy: scrollView.bounds.width)/scrollView.bounds.width
let centerX = scrollScale * centerDistance + beforeCell.center.x
if self.subLineWidth == 0 {
let width = centerX >= self.subLineView.center.x ? afterCell.bounds.width : beforeCell.bounds.width
UIView.animate(withDuration: 0.2, animations: {
self.subLineView.bounds = CGRect(x: 0, y: 0, width: width, height: self.subLineHeight)
})
}
self.subLineView.center.x = centerX
}
private func getPageItemWidths() -> [CGFloat] {
let widths = self.titles.map { (title) -> CGFloat in
let maxFont = max(self.titleFontNormal.pointSize, self.titleFontSelected.pointSize)
let font = self.titleFontNormal.pointSize == maxFont ? self.titleFontNormal : self.titleFontSelected
let rect = title.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: self.pageItemHeight), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return rect.width + self.itemTitleMargin
}
return widths
}
private func showSelectedViewController(_ selectedIndex: Int) {
// add currentSelected viewController
guard let parentViewController = self.parentViewController else {
return
}
let width = self.scrollView!.bounds.width
let height = self.scrollView!.bounds.height
let selectedViewController = self.viewControllers[selectedIndex]
if !parentViewController.childViewControllers.contains(selectedViewController) {
self.parentViewController?.addChildViewController(selectedViewController)
selectedViewController.view.frame = CGRect(x: width * CGFloat(selectedIndex), y: 0, width: width, height: height)
self.scrollView?.addSubview(selectedViewController.view)
self.parentViewController?.didMove(toParentViewController: selectedViewController)
}
self.delegate?.scrollPageView?(self, didShow: selectedViewController, at: selectedIndex)
}
private func updatePageItemState(_ index: Int, scrollView: UIScrollView) {
// update pageItem titleLabel`
//边界item不处理
if scrollView.contentOffset.x > scrollView.contentSize.width - scrollView.bounds.width || scrollView.contentOffset.x < 0 {
return
}
var progress = scrollView.contentOffset.x.truncatingRemainder(dividingBy: scrollView.bounds.width)/scrollView.bounds.width
if progress == 0 {
progress = 1
}
//get next index
var nextIndex = index
if scrollView.contentOffset.x > scrollView.bounds.width * CGFloat(index) {
nextIndex += 1
} else if scrollView.contentOffset.x < scrollView.bounds.width * CGFloat(index) {
nextIndex -= 1
}
//update titleColor
let currentCell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? PageItemCell
currentCell?.titleLabel?.textColor = self.titleColorSelected.transFormColorTo(self.titleColorNormal, progress: progress)
let nextCell = self.collectionView?.cellForItem(at: IndexPath(item: nextIndex, section: 0)) as? PageItemCell
nextCell?.titleLabel?.textColor = self.titleColorNormal.transFormColorTo(self.titleColorSelected, progress: progress)
//update size or font
if isZoomTitle {
let currentItemScale = maxItemScale - (maxItemScale - 1) * progress
let nextItemScale = 1 + (maxItemScale - 1) * progress
currentCell?.transform = CGAffineTransform(scaleX: currentItemScale, y: currentItemScale)
nextCell?.transform = CGAffineTransform(scaleX: nextItemScale, y: nextItemScale)
} else {
nextCell?.titleLabel?.font = self.titleFont(for: .selected)
currentCell?.titleLabel?.font = self.titleFont(for: .normal)
}
}
private func updatePageItemState(_ formIndex: Int, toIndex: Int) {
//update titleColor
let currentCell = self.collectionView?.cellForItem(at: IndexPath(item: formIndex, section: 0)) as? PageItemCell
currentCell?.titleLabel?.textColor = self.titleColorNormal
let nextCell = self.collectionView?.cellForItem(at: IndexPath(item: toIndex, section: 0)) as? PageItemCell
nextCell?.titleLabel?.textColor = self.titleColorSelected
//update size or font
if isZoomTitle {
currentCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
nextCell?.transform = CGAffineTransform(scaleX: maxItemScale, y: maxItemScale)
} else {
currentCell?.titleLabel?.font = self.titleFont(for: .normal)
nextCell?.titleLabel?.font = self.titleFont(for: .selected)
}
// fix a bug
if currentCell == nil {
self.lastSelectedCell?.titleLabel?.textColor = self.titleColorNormal
if isZoomTitle {
self.lastSelectedCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
} else {
self.lastSelectedCell?.titleLabel?.font = self.titleFont(for: .normal)
}
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.viewControllers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PageItemCell.description(), for: indexPath) as! PageItemCell
cell.titleLabel?.text = self.titles[indexPath.item]
if indexPath.item == self.currentSelectedIndex {
self.lastSelectedCell = cell
cell.titleLabel?.textColor = self.titleColor(for: .selected)
if self.isZoomTitle {
cell.transform = CGAffineTransform(scaleX: maxItemScale, y: maxItemScale)
cell.titleLabel?.font = self.titleFont(for: .normal)
} else {
cell.titleLabel?.font = self.titleFont(for: .selected)
}
} else {
cell.titleLabel?.textColor = self.titleColor(for: .normal)
cell.titleLabel?.font = self.titleFont(for: .normal)
cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if self.pageItemWidth == 0 {
return CGSize(width: self.expectedItemWidths[indexPath.item], height: pageItemHeight)
} else {
return CGSize(width: self.pageItemWidth, height: pageItemHeight)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 0, 0, 0)
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let width = self.scrollView?.bounds.width ?? 0
let height = self.scrollView?.bounds.height ?? 0
self.isPageItemActionScroll = true
let isAnimated = fabsf(Float(self.currentSelectedIndex - indexPath.item)) <= 2
self.updatePageItemState(self.currentSelectedIndex, toIndex: indexPath.item)
self.scrollView?.scrollRectToVisible(CGRect(x: width * CGFloat(indexPath.item), y: 0, width: width, height: height), animated: isAnimated)
self.showSelectedViewController(indexPath.item)
self.collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
self.lastSelectedCell = collectionView.cellForItem(at: indexPath) as? PageItemCell
}
// MARK: - UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.isPageItemActionScroll = false
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView.isMember(of: UIScrollView.self) {
self.collectionView?.scrollToItem(at: IndexPath(item: self.currentSelectedIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isMember(of: UIScrollView.self) {
let offSetX = scrollView.contentOffset.x
self.currentSelectedIndex = Int(offSetX/self.bounds.width)
self.updateSubLineViewPosition(scrollView)
if !self.isPageItemActionScroll {
self.updatePageItemState(self.currentSelectedIndex, scrollView: scrollView)
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.isMember(of: UIScrollView.self) {
self.showSelectedViewController(self.currentSelectedIndex)
}
}
}
class PageItemCell: UICollectionViewCell {
var titleLabel: UILabel?
var state: PageItemState = .normal
override init(frame: CGRect) {
super.init(frame: frame)
let label = UILabel.init(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
label.textAlignment = .center
self.addSubview(label)
self.titleLabel = label
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension RNScrollPageView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
extension UIColor {
var redValue: CGFloat {return CIColor(color: self).red}
var greenValue: CGFloat {return CIColor(color: self).green}
var blueValue: CGFloat {return CIColor(color: self).blue}
var alphaValue: CGFloat {return CIColor(color: self).alpha}
func transFormColorTo(_ color: UIColor, progress: CGFloat) -> UIColor? {
var progress = progress
progress = progress >= 1 ? 1 : progress
progress = progress <= 0 ? 0 : progress
let newR = self.redValue * (1 - progress) + color.redValue * progress
let newG = self.greenValue * (1 - progress) + color.greenValue * progress
let newB = self.blueValue * (1 - progress) + color.blueValue * progress
let alpha = self.alphaValue * (1 - progress) + color.alphaValue * progress
let newColor = UIColor.init(colorLiteralRed: Float(newR), green: Float(newG), blue: Float(newB), alpha: Float(alpha))
return newColor
}
}
| mit | e81aadbac8735df13329de30bdf35c92 | 41.930057 | 220 | 0.648305 | 5.025448 | false | false | false | false |
RCacheaux/BitbucketKit | Carthage/Checkouts/Swinject/Tests/AssemblerSpec.swift | 1 | 12219 | //
// AssemblerSpec.swift
// Swinject
//
// Created by mike.owens on 12/9/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Swinject
class AssemblerSpec: QuickSpec {
override func spec() {
describe("Assembler basic init") {
it("can assembly a single container") {
let assembler = try! Assembler(assemblies: [
AnimalAssembly()
])
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
}
it("can assembly a container with nil parent") {
let assembler = Assembler(parentAssembler: nil)
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
}
it("can assembly a container with nil parent and assemblies") {
let assembler = try! Assembler(assemblies: [
AnimalAssembly()
], parentAssembler : nil)
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
}
it("can assembly a multiple container") {
let assembler = try! Assembler(assemblies: [
AnimalAssembly(),
FoodAssembly()
])
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
it("can assembly a multiple container with inter dependencies") {
let assembler = try! Assembler(assemblies: [
AnimalAssembly(),
FoodAssembly(),
PersonAssembly()
])
let petOwner = assembler.resolver.resolve(PetOwner.self)
expect(petOwner).toNot(beNil())
let cat = petOwner!.pet
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = petOwner!.favoriteFood
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
it("can assembly a multiple container with inter dependencies in any order") {
let assembler = try! Assembler(assemblies: [
PersonAssembly(),
AnimalAssembly(),
FoodAssembly(),
])
let petOwner = assembler.resolver.resolve(PetOwner.self)
expect(petOwner).toNot(beNil())
let cat = petOwner!.pet
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let sushi = petOwner!.favoriteFood
expect(sushi).toNot(beNil())
expect(sushi is Sushi) == true
}
}
describe("Assembler lazy build") {
it("can assembly a single container") {
let assembler = try! Assembler(assemblies: [])
var cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
assembler.applyAssembly(AnimalAssembly())
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
}
it("can assembly a single load aware container") {
let assembler = try! Assembler(assemblies: [])
var cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
let loadAwareAssembly = LoadAwareAssembly() { resolver in
let cat = resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
expect(loadAwareAssembly.loaded) == false
assembler.applyAssembly(loadAwareAssembly)
expect(loadAwareAssembly.loaded) == true
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
it("can assembly a multiple containers 1 by 1") {
let assembler = try! Assembler(assemblies: [])
var cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
var sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
assembler.applyAssembly(AnimalAssembly())
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
assembler.applyAssembly(FoodAssembly())
sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).toNot(beNil())
}
it("can assembly a multiple containers at once") {
let assembler = try! Assembler(assemblies: [])
var cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
var sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
assembler.applyAssemblies([
AnimalAssembly(),
FoodAssembly()
])
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).toNot(beNil())
}
}
describe("Assembler load aware") {
it("can assembly a single container") {
let loadAwareAssembly = LoadAwareAssembly() { resolver in
let cat = resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
expect(loadAwareAssembly.loaded) == false
let assembler = try! Assembler(assemblies: [
loadAwareAssembly
])
expect(loadAwareAssembly.loaded) == true
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
}
it("can assembly a multiple container") {
let loadAwareAssembly = LoadAwareAssembly() { resolver in
let cat = resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
let sushi = resolver.resolve(FoodType.self)
expect(sushi).toNot(beNil())
}
expect(loadAwareAssembly.loaded) == false
let assembler = try! Assembler(assemblies: [
loadAwareAssembly,
FoodAssembly()
])
expect(loadAwareAssembly.loaded) == true
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Bojangles"
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).toNot(beNil())
}
}
describe("Assembler with properties") {
it("can assembly with properties") {
let assembler = try! Assembler(assemblies: [
PropertyAsssembly()
], propertyLoaders: [
PlistPropertyLoader(bundle: NSBundle(forClass: self.dynamicType.self), name: "first")
])
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "first"
}
it("can't assembly with missing properties") {
expect {
try Assembler(assemblies: [
PropertyAsssembly()
], propertyLoaders: [
PlistPropertyLoader(bundle: NSBundle(forClass: self.dynamicType.self), name: "noexist")
])
}.to(throwError(errorType: PropertyLoaderError.self))
}
}
describe("Empty Assembler") {
it("can create an empty assembler and build it") {
let assembler = Assembler()
var cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
assembler.applyAssembly(AnimalAssembly())
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "Whiskers"
let loader = PlistPropertyLoader(bundle: NSBundle(forClass: self.dynamicType.self), name: "first")
try! assembler.applyPropertyLoader(loader)
assembler.applyAssembly(PropertyAsssembly())
cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
expect(cat!.name) == "first"
}
}
describe("Child Assembler") {
it("can be empty") {
let assembler = try! Assembler(assemblies: [
AnimalAssembly()
])
let childAssembler = Assembler(parentAssembler: assembler)
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).toNot(beNil())
let sushi = assembler.resolver.resolve(FoodType.self)
expect(sushi).to(beNil())
let childCat = childAssembler.resolver.resolve(AnimalType.self)
expect(childCat).toNot(beNil())
let childSushi = childAssembler.resolver.resolve(FoodType.self)
expect(childSushi).to(beNil())
}
it("can't give entities to parent") {
let assembler = Assembler()
let childAssembler = try! Assembler(assemblies: [
AnimalAssembly()
], parentAssembler: assembler)
let cat = assembler.resolver.resolve(AnimalType.self)
expect(cat).to(beNil())
let childCat = childAssembler.resolver.resolve(AnimalType.self)
expect(childCat).toNot(beNil())
}
}
}
}
| apache-2.0 | dcfc9692f0b7ba9cc741d81ce6e8bf6b | 38.928105 | 114 | 0.478311 | 5.604587 | false | false | false | false |
joostholslag/BNRiOS | iOSProgramming6ed/24 - Accessibility/Solutions/Photorama/Photorama/PhotoStore.swift | 1 | 5553 | //
// Copyright © 2015 Big Nerd Ranch
//
import UIKit
import CoreData
enum ImageResult {
case Success(UIImage)
case Failure(ErrorType)
}
enum PhotoError: ErrorType {
case ImageCreationError
}
class PhotoStore {
let coreDataStack = CoreDataStack(modelName: "Photorama")
let imageStore = ImageStore()
let session: NSURLSession = {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: config)
}()
func processPhotosRequest(data data: NSData?, error: NSError?) -> PhotosResult {
guard let jsonData = data else {
return .Failure(error!)
}
return FlickrAPI.photosFromJSONData(jsonData,
inContext: self.coreDataStack.privateQueueContext)
}
func processImageRequest(data data: NSData?, error: NSError?) -> ImageResult {
guard let
imageData = data,
image = UIImage(data: imageData) else {
// Couldn't create an image
if data == nil {
return .Failure(error!)
}
else {
return .Failure(PhotoError.ImageCreationError)
}
}
return .Success(image)
}
func fetchImageForPhoto(photo: Photo, completion: (ImageResult) -> Void) {
let photoKey = photo.photoKey
if let image = imageStore.imageForKey(photoKey) {
completion(.Success(image))
return
}
let photoURL = photo.remoteURL
let request = NSURLRequest(URL: photoURL)
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let result = self.processImageRequest(data: data, error: error)
if case let .Success(image) = result {
photo.image = image
self.imageStore.setImage(image, forKey: photoKey)
}
completion(result)
}
task.resume()
}
func fetchMainQueuePhotos(predicate predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil) throws -> [Photo] {
let fetchRequest = NSFetchRequest(entityName: "Photo")
fetchRequest.sortDescriptors = sortDescriptors
let mainQueueContext = self.coreDataStack.mainQueueContext
var mainQueuePhotos: [Photo]?
var fetchRequestError: ErrorType?
mainQueueContext.performBlockAndWait({
do {
mainQueuePhotos = try mainQueueContext.executeFetchRequest(fetchRequest) as? [Photo]
}
catch let error {
fetchRequestError = error
}
})
guard let photos = mainQueuePhotos else {
throw fetchRequestError!
}
return photos
}
func fetchInterestingPhotos(completion completion: (PhotosResult) -> Void) {
let url = FlickrAPI.interestingPhotosURL()
let request = NSURLRequest(URL: url)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
var result = self.processPhotosRequest(data: data, error: error)
if case let .Success(photos) = result {
let privateQueueContext = self.coreDataStack.privateQueueContext
privateQueueContext.performBlockAndWait({
try! privateQueueContext.obtainPermanentIDsForObjects(photos)
})
let objectIDs = photos.map{ $0.objectID }
let predicate = NSPredicate(format: "self IN %@", objectIDs)
let sortByDateTaken = NSSortDescriptor(key: "dateTaken", ascending: true)
do {
try self.coreDataStack.saveChanges()
let mainQueuePhotos = try self.fetchMainQueuePhotos(predicate: predicate,
sortDescriptors: [sortByDateTaken])
result = .Success(mainQueuePhotos)
}
catch let error {
result = .Failure(error)
}
}
completion(result)
})
task.resume()
}
func fetchMainQueueTags(predicate predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil) throws -> [NSManagedObject] {
let fetchRequest = NSFetchRequest(entityName: "Tag")
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
let mainQueueContext = self.coreDataStack.mainQueueContext
var mainQueueTags: [NSManagedObject]?
var fetchRequestError: ErrorType?
mainQueueContext.performBlockAndWait({
do {
mainQueueTags = try mainQueueContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
}
catch let error {
fetchRequestError = error
}
})
guard let tags = mainQueueTags else {
throw fetchRequestError!
}
return tags
}
}
| gpl-3.0 | 17317feb21809c1aaaf875e596e16ce5 | 32.648485 | 112 | 0.544128 | 5.931624 | false | false | false | false |
firebase/firebase-ios-sdk | Example/FirestoreSample/FirestoreSample/Views/FavouriteFruitsView.swift | 2 | 2052 | // Copyright 2021 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
//
// 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 SwiftUI
import FirebaseFirestoreSwift
private struct Fruit: Codable, Identifiable, Equatable {
@DocumentID var id: String?
var name: String
var isFavourite: Bool
}
struct FavouriteFruitsView: View {
@FirestoreQuery(
collectionPath: "fruits",
predicates: [
.where("isFavourite", isEqualTo: true),
]
) fileprivate var fruitResults: Result<[Fruit], Error>
@State var showOnlyFavourites = true
var body: some View {
if case let .success(fruits) = fruitResults {
List(fruits) { fruit in
Text(fruit.name)
}
.animation(.default, value: fruits)
.navigationTitle("Fruits")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: toggleFilter) {
Image(systemName: showOnlyFavourites
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle")
}
}
}
} else if case let .failure(error) = fruitResults {
// Handle error
Text("Couldn't map data: \(error.localizedDescription)")
}
}
func toggleFilter() {
showOnlyFavourites.toggle()
if showOnlyFavourites {
$fruitResults.predicates = [
.whereField("isFavourite", isEqualTo: true),
]
} else {
$fruitResults.predicates = []
}
}
}
struct FavouriteFruitsView_Previews: PreviewProvider {
static var previews: some View {
FavouriteFruitsView()
}
}
| apache-2.0 | 00c8d7002620652b988c634cdc39ac8a | 27.5 | 75 | 0.667641 | 4.230928 | false | false | false | false |
dictav/SwiftLint | Source/SwiftLintFrameworkTests/TestHelpers.swift | 1 | 1927 | //
// TestHelpers.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SwiftLintFramework
import SourceKittenFramework
import XCTest
let allRuleIdentifiers = Configuration.rulesFromYAML().map {
$0.dynamicType.description.identifier
}
func violations(string: String, config: Configuration = Configuration()) -> [StyleViolation] {
return Linter(file: File(contents: string), configuration: config).styleViolations
}
private func violations(string: String, _ description: RuleDescription) -> [StyleViolation] {
let disabledRules = allRuleIdentifiers.filter { $0 != description.identifier }
return violations(string, config: Configuration(disabledRules: disabledRules)!)
}
extension XCTestCase {
func verifyRule(ruleDescription: RuleDescription, commentDoesntViolate: Bool = true) {
XCTAssertEqual(
ruleDescription.nonTriggeringExamples.flatMap({violations($0, ruleDescription)}),
[]
)
XCTAssertEqual(
ruleDescription.triggeringExamples.flatMap({
violations($0, ruleDescription).map({$0.ruleDescription})
}),
Array(count: ruleDescription.triggeringExamples.count, repeatedValue: ruleDescription)
)
let commentedViolations = ruleDescription.triggeringExamples.flatMap {
violations("/*\n " + $0 + "\n */", ruleDescription)
}.map({$0.ruleDescription})
XCTAssertEqual(
commentedViolations,
Array(count: commentDoesntViolate ? 0 : ruleDescription.triggeringExamples.count,
repeatedValue: ruleDescription)
)
let command = "// swiftlint:disable \(ruleDescription.identifier)\n"
XCTAssertEqual(
ruleDescription.triggeringExamples.flatMap({violations(command + $0, ruleDescription)}),
[]
)
}
}
| mit | b56a3e9bf9a0ffb488504ca115ba3617 | 34.685185 | 100 | 0.676181 | 5.005195 | false | true | false | false |
hq7781/MoneyBook | MoneyBook/Controller/Main/MainNavigationController.swift | 1 | 2105 | //
// MainNavigationController.swift
// MoneyBook
//
// Created by HONGQUAN on 7/25/17.
// Copyright © 2017 Roan.Hong. All rights reserved.
//
import UIKit
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.interactivePopGestureRecognizer!.delegate = nil
}
lazy var backButton: UIButton = {
let backButton = UIButton(type: UIButtonType.custom)
backButton.titleLabel?.font = UIFont.systemFont(ofSize: 17)
backButton.setTitleColor(UIColor.black, for: .normal)
backButton.setTitleColor(UIColor.gray, for: .highlighted)
backButton.setImage(UIImage(named:"back_1"), for: .normal)
backButton.setImage(UIImage(named:"back_2"), for: .highlighted)
backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -25, 0, 0)
backButton.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
let btnWeight: CGFloat = appWidth > 375.0 ? 50 : 44
backButton.frame = CGRect.CGRectMake(0, 0, btnWeight, 40)
backButton.addTarget(self, action: #selector(onClickBackButton), for: .touchUpInside)
return backButton
}()
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.childViewControllers.count > 0 {
let vc = self.childViewControllers[0]
if self.childViewControllers.count == 1 {
backButton.setTitle(vc.tabBarItem.title, for: UIControlState.normal)
} else {
backButton.setTitle("BACK", for: UIControlState.normal)
}
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView:backButton)
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
func onClickBackButton() {
self.popViewController(animated: true)
}
}
| mit | 865d687b2682dd7da1133ff9507d739d | 35.912281 | 100 | 0.657795 | 5.094431 | false | false | false | false |
volodg/iAsync.cache | Sources/Details/InternalCacheDB.swift | 1 | 2614 | //
// InternalCacheDB.swift
// iAsync_cache
//
// Created by Vladimir Gorbenko on 13.08.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
import iAsync_restkit
import iAsync_utils
import func iAsync_reactiveKit.asyncStreamWithJob
import enum ReactiveKit.Result
private var autoremoveSchedulersByCacheName: [String:iAsync_utils.Timer] = [:]
private let internalCacheDBLockObject = NSObject()
//TODO should be private?
final internal class InternalCacheDB : KeyValueDB, CacheDB {
let cacheDBInfo: CacheDBInfo
init(cacheDBInfo: CacheDBInfo) {
self.cacheDBInfo = cacheDBInfo
super.init(cacheFileName: cacheDBInfo.fileName)
}
private func removeOldData() {
let removeRarelyAccessDataDelay = cacheDBInfo.autoRemoveByLastAccessDate
if removeRarelyAccessDataDelay > 0.0 {
let fromDate = Date().addingTimeInterval(-removeRarelyAccessDataDelay)
removeRecordsToAccessDate(fromDate)
}
let bytes = Int64(cacheDBInfo.autoRemoveByMaxSizeInMB) * 1024 * 1024
if bytes > 0 {
removeRecordsWhileTotalSizeMoreThenBytes(bytes)
}
}
func runAutoRemoveDataSchedulerIfNeeds() {
synced(internalCacheDBLockObject, { () -> () in
let dbPropertyName = self.cacheDBInfo.dbPropertyName
if autoremoveSchedulersByCacheName[dbPropertyName] != nil {
return
}
let timer = Timer()
autoremoveSchedulersByCacheName[dbPropertyName] = timer
let block = { (cancel: (() -> ())) in
let loadDataBlock = { (progress: (AnyObject) -> Void) -> Result<Void, ErrorWithContext> in
self.removeOldData()
return .success(())
}
let queueName = "com.embedded_sources.dbcache.thread_to_remove_old_data"
_ = asyncStreamWithJob(queueName, job: loadDataBlock).logError().run()
}
block({})
let _ = timer.add(actionBlock: block, delay:.seconds(3600))
})
}
//todo rename?
func migrateDB(_ dbInfo: DBInfo) {
let currentDbInfo = dbInfo.currentDbVersionsByName
let currVersionNum = currentDbInfo?[cacheDBInfo.dbPropertyName] as? NSNumber
guard let currVersionNum_ = currVersionNum else { return }
let lastVersion = cacheDBInfo.version
let currentVersion = currVersionNum_.intValue
if lastVersion > currentVersion {
removeAllRecordsWith(callback: nil)
}
}
}
| mit | 354c0a210274b6658061171b49dae34c | 26.21875 | 106 | 0.641026 | 4.459044 | false | false | false | false |
bluejava/GeoTools4iOS | GeoTools4iOS/GameViewController.swift | 1 | 10048 | //
// GameViewController.swift
// GeoTools4iOS
//
// Created by Glenn Crownover on 5/4/15.
// Copyright (c) 2015 bluejava. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* First, some boilerplate SceneKit setup - lights, camera, (action comes later) */
// create a new scene
var scene = SCNScene()
var rootNode = scene.rootNode
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
rootNode.addChildNode(ambientLightNode)
/*
Here are the actual custom geometry test functions
*/
textureTileExample(scene.rootNode) // A parallelogram with stretched texture
textureTileExampleNonPar(scene.rootNode) // A non-parallel quadrilateral shape with tiled texture
textureTileExample3d(scene.rootNode) // A 3d custom shape with tiled texture
/* Now, some more boilerplate… */
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.whiteColor()
}
// Always keep in mind the orientation of the verticies when looking at the face from the "front"
// With single-sided faces, we only see from the front side - so this is important.
// v1 --------------v0
// | __/ |
// | face __/ |
// | 1 __/ |
// | __/ face |
// | __/ 2 |
// v2 ------------- v3
// Two triangular faces are created from the 4 vertices - think of drawing the letter C when considering the order
// to enter your vertices - top right, then top left, then bottom left, then bottom right - But of course, this is
// relative only to your field of view - not the global coordinate system - "bottom" for your shape may be "up" in
// the world view!
// This function creates a quadrilateral shape with non-parallel sides. Note how the
// texture originates at v2 and tiles to the right, up and to the left seamlessly.
func textureTileExample(pnode: SCNNode)
{
// First, we create the 4 vertices for our custom geometry - note, they share a plane, but are otherwise irregular
var v0 = SCNVector3(x: 6, y: 6, z: 0)
var v1 = SCNVector3(x: 0, y: 6, z: 0)
var v2 = SCNVector3(x: 0, y: 0, z: 0)
var v3 = SCNVector3(x: 6, y: 0, z: 0)
// Now we create the GeometryBuilder - which allows us to add quads to make up a custom shape
var geobuild = GeometryBuilder(uvMode: GeometryBuilder.UVModeType.StretchToFitXY)
geobuild.addQuad(Quad(v0: v0,v1: v1,v2: v2,v3: v3)) // only the one quad for us today, thanks!
var geo = geobuild.getGeometry() // And here we get an SCNGeometry instance from our new shape
// Lets setup the diffuse, normal and specular maps - located in a subdirectory
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
// Now we simply create the node, position it, and add to our parent!
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: 5, y: 2, z: 0)
pnode.addChildNode(node)
}
func textureTileExampleFlipped(pnode: SCNNode)
{
// First, we create the 4 vertices for our custom geometry - note, they share a plane, but are otherwise irregular
var v0 = SCNVector3(x: 6, y: 0, z: 0)
var v1 = SCNVector3(x: 0, y: 0, z: 0)
var v2 = SCNVector3(x: 0, y: 6, z: 0)
var v3 = SCNVector3(x: 6, y: 6, z: 0)
// Now we create the GeometryBuilder - which allows us to add quads to make up a custom shape
var geobuild = GeometryBuilder(uvMode: GeometryBuilder.UVModeType.StretchToFitXY)
geobuild.addQuad(Quad(v0: v0,v1: v1,v2: v2,v3: v3)) // only the one quad for us today, thanks!
var geo = geobuild.getGeometry() // And here we get an SCNGeometry instance from our new shape
// Lets setup the diffuse, normal and specular maps - located in a subdirectory
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
// Now we simply create the node, position it, and add to our parent!
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: 5, y: 2, z: 0)
pnode.addChildNode(node)
}
// This function creates a quadrilateral shape with parallel sides to demonstrate
// a stretchedToFit texture mapping. Of course, since it is non-square, the texture is
// skewed.
func textureTileExampleNonPar(pnode: SCNNode)
{
var v0 = SCNVector3(x: 6, y: 6.0, z: 6)
var v1 = SCNVector3(x: 1, y: 4, z: 1)
var v2 = SCNVector3(x: 2, y: 0, z: 2)
var v3 = SCNVector3(x: 5, y: -2, z: 5)
var geobuild = GeometryBuilder(uvMode: GeometryBuilder.UVModeType.StretchToFitXY)
geobuild.addQuad(Quad(v0: v0,v1: v1,v2: v2,v3: v3)) // simple
var geo = geobuild.getGeometry()
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: 5, y: -6, z: 0)
pnode.addChildNode(node)
}
func testQ3D(pnode: SCNNode)
{
var node = buildQuad3D([
SCNVector3(x: 4,y: 4,z: -4),
SCNVector3(x: 0,y: 4,z: -4),
SCNVector3(x: 0,y: 4,z: 0),
SCNVector3(x: 4,y: 4,z: 0),
SCNVector3(x: 4,y: 1,z: 0),
SCNVector3(x: 0,y: 1,z: 0),
SCNVector3(x: 0,y: 1,z: -4),
SCNVector3(x: 4,y: 1,z: -4),
])
// node.geometry?.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "3d textures/brickTexture") ]
node.geometry?.firstMaterial?.diffuse.contents = UIColor.purpleColor()
node.position = SCNVector3(x: 4, y: 4.0, z: -4)
pnode.addChildNode(node)
// var xx = SCNNode(geometry: SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0.1))
// xx.geometry?.firstMaterial!.diffuse.contents = UIColor.redColor()
// xx.position.y = 8
// pnode.addChildNode(xx)
}
func buildQuad3D(v: [SCNVector3]) -> SCNNode
{
var geobuild = GeometryBuilder(uvMode: .SizeToWorldUnitsXY)
geobuild.addQuad(Quad(v0: v[3],v1: v[2],v2: v[5],v3: v[4])) // front
geobuild.addQuad(Quad(v0: v[2],v1: v[1],v2: v[6],v3: v[5])) // left
geobuild.addQuad(Quad(v0: v[0],v1: v[3],v2: v[4],v3: v[7])) // right
geobuild.addQuad(Quad(v0: v[1],v1: v[0],v2: v[7],v3: v[6])) // back
geobuild.addQuad(Quad(v0: v[0],v1: v[1],v2: v[2],v3: v[3])) // top
geobuild.addQuad(Quad(v0: v[4],v1: v[5],v2: v[6],v3: v[7])) // bottom
var geo = geobuild.getGeometry()
return SCNNode(geometry: geo)
}
// And finally, here is a full 3d object with six sides. We only create the 8 vertices of the shape once,
// but they are replicated for each quad and then for each face as they have their own normals, texture coordinates, etc.
// But it sure makes our job easy at this point - just enter your vertices, build your quads and generate the shape!
func textureTileExample3d(pnode: SCNNode)
{
var f0 = SCNVector3(x: 6, y: 6.0, z: 2)
var f1 = SCNVector3(x: 1, y: 4, z: 2)
var f2 = SCNVector3(x: 2, y: 0, z: 2)
var f3 = SCNVector3(x: 5, y: -2, z: 2)
var b0 = SCNVector3(x: 6, y: 6.0, z: 0)
var b1 = SCNVector3(x: 1, y: 4, z: 0)
var b2 = SCNVector3(x: 2, y: 0, z: 0)
var b3 = SCNVector3(x: 5, y: -2, z: 0)
// Note: This uvMode will consider 1 by 1 coordinate units to coorespond with one full texture.
// This works great for drawing large irregularly shaped objects made with tile-able textures.
// The textures tile across each face without stretching or skewing regardless of size.
var geobuild = GeometryBuilder(uvMode: .SizeToWorldUnitsXY)
geobuild.addQuad(Quad(v0: f0,v1: f1,v2: f2,v3: f3)) // front
geobuild.addQuad(Quad(v0: b1,v1: b0,v2: b3,v3: b2)) // back
geobuild.addQuad(Quad(v0: b0,v1: b1,v2: f1,v3: f0)) // top
geobuild.addQuad(Quad(v0: f1,v1: b1,v2: b2,v3: f2)) // left
geobuild.addQuad(Quad(v0: b0,v1: f0,v2: f3,v3: b3)) // right
geobuild.addQuad(Quad(v0: f3,v1: f2,v2: b2,v3: b3)) // bottom
var geo = geobuild.getGeometry()
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: -5, y: 2, z: 0)
pnode.addChildNode(node)
}
override func shouldAutorotate() -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| mit | a025490e66e4b79f32193e81b9835586 | 37.343511 | 170 | 0.66315 | 3.172087 | false | false | false | false |
18775134221/SwiftBase | SwiftTest/SwiftTest/Classes/Main/View/BaseTabBar.swift | 2 | 1983 | //
// BaseTabBar.swift
// SwiftTest
//
// Created by MAC on 2016/12/10.
// Copyright © 2016年 MAC. All rights reserved.
//
import UIKit
enum plusLocation {
case plusDefault
case plusUp
}
class BaseTabBar: UITabBar {
var type: plusLocation? = .plusDefault
override func layoutSubviews() {
super.layoutSubviews()
let count: Int = (items?.count)! + 1
let btnW: CGFloat = UIScreen.main.bounds.size.width / CGFloat(count)
let btnH: CGFloat = bounds.height;
var i: Int = 0
subviews.forEach({ (button) in
if button.isKind(of: NSClassFromString("UITabBarButton")!) {
if 2 == i {
i += 1
}
button.frame = CGRect(x: btnW * CGFloat(i), y: 0, width: btnW, height: btnH)
i += 1
}
if type == .plusDefault {
pBtn.center = CGPoint(x: frame.size.width * 0.5, y: frame.size.height * 0.5)
}else{
pBtn.center = CGPoint(x: frame.size.width * 0.5, y: 0)
}
})
}
fileprivate lazy var pBtn: UIButton = {[weak self] in
let btn: UIButton = UIButton(type:.custom)
btn.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)
btn.backgroundColor = UIColor.red
btn.sizeToFit()
self?.addSubview(btn)
return btn
}()
// 重写hitTest方法,去监听发布按钮的点击,目的是为了让凸出的部分点击也有反应
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if !self.isHidden {
let nPoint: CGPoint = convert(point, to: pBtn)
if pBtn.point(inside: nPoint, with: event) {
return pBtn
}else{
return super.hitTest(point, with: event)
}
}else{
return super.hitTest(point, with: event)
}
}
}
| apache-2.0 | df777942c777ef36e951d6cd74589328 | 26.73913 | 92 | 0.523511 | 3.962733 | false | true | false | false |
e-how/kingTrader | kingTrader/Pods/CryptoSwift/CryptoSwift/AES.swift | 9 | 17306 | //
// AES.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 21/11/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
final public class AES {
enum Error: ErrorType {
case BlockSizeExceeded
}
public enum AESVariant:Int {
case aes128 = 1, aes192, aes256
var Nk:Int { // Nk words
return [4,6,8][self.rawValue - 1]
}
var Nb:Int { // Nb words
return 4
}
var Nr:Int { // Nr
return Nk + 6
}
}
public let blockMode:CipherBlockMode
public static let blockSize:Int = 16 // 128 /8
public var variant:AESVariant {
switch (self.key.count * 8) {
case 128:
return .aes128
case 192:
return .aes192
case 256:
return .aes256
default:
preconditionFailure("Unknown AES variant for given key.")
}
}
private let key:[UInt8]
private let iv:[UInt8]?
public lazy var expandedKey:[UInt8] = { AES.expandKey(self.key, variant: self.variant) }()
static private let sBox:[UInt8] = [
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
static private let invSBox:[UInt8] = [
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54,
0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8,
0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab,
0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d,
0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60,
0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b,
0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
0x21, 0x0c, 0x7d]
// Parameters for Linear Congruence Generators
static private let Rcon:[UInt8] = [
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d]
public init?(key:[UInt8], iv:[UInt8], blockMode:CipherBlockMode = .CBC) {
self.key = key
self.iv = iv
self.blockMode = blockMode
if (blockMode.needIV && iv.count != AES.blockSize) {
assert(false, "Block size and Initialization Vector must be the same length!")
return nil
}
}
convenience public init?(key:[UInt8], blockMode:CipherBlockMode = .CBC) {
// default IV is all 0x00...
let defaultIV = [UInt8](count: AES.blockSize, repeatedValue: 0)
self.init(key: key, iv: defaultIV, blockMode: blockMode)
}
convenience public init?(key:String, iv:String, blockMode:CipherBlockMode = .CBC) {
if let kkey = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() {
self.init(key: kkey, iv: iiv, blockMode: blockMode)
}
else {
return nil
}
}
/**
Encrypt message. If padding is necessary, then PKCS7 padding is added and needs to be removed after decryption.
- parameter message: Plaintext data
- returns: Encrypted data
*/
public func encrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
var finalBytes = bytes;
if let padding = padding {
finalBytes = padding.add(bytes, blockSize: AES.blockSize)
} else if bytes.count % AES.blockSize != 0 {
throw Error.BlockSizeExceeded
}
let blocks = finalBytes.chunks(AES.blockSize) // 0.34
return try blockMode.encryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
}
private func encryptBlock(block:[UInt8]) -> [UInt8]? {
var out:[UInt8] = [UInt8]()
autoreleasepool { () -> () in
var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
for (i, row) in state.enumerate() {
for (j, _) in row.enumerate() {
state[j][i] = block[i * row.count + j]
}
}
state = addRoundKey(state,expandedKey, 0)
for roundCount in 1..<variant.Nr {
subBytes(&state)
state = shiftRows(state)
state = mixColumns(state)
state = addRoundKey(state, expandedKey, roundCount)
}
subBytes(&state)
state = shiftRows(state)
state = addRoundKey(state, expandedKey, variant.Nr)
out = [UInt8](count: state.count * state.first!.count, repeatedValue: 0)
for i in 0..<state.count {
for j in 0..<state[i].count {
out[(i * 4) + j] = state[j][i]
}
}
}
return out
}
public func decrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
if bytes.count % AES.blockSize != 0 {
throw Error.BlockSizeExceeded
}
let blocks = bytes.chunks(AES.blockSize)
let out:[UInt8]
switch (blockMode) {
case .CFB, .CTR:
// CFB, CTR uses encryptBlock to decrypt
out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
default:
out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: decryptBlock)
}
if let padding = padding {
return padding.remove(out, blockSize: nil)
}
return out
}
private func decryptBlock(block:[UInt8]) -> [UInt8]? {
var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
for (i, row) in state.enumerate() {
for (j, _) in row.enumerate() {
state[j][i] = block[i * row.count + j]
}
}
state = addRoundKey(state,expandedKey, variant.Nr)
for roundCount in (1..<variant.Nr).reverse() {
state = invShiftRows(state)
state = invSubBytes(state)
state = addRoundKey(state, expandedKey, roundCount)
state = invMixColumns(state)
}
state = invShiftRows(state)
state = invSubBytes(state)
state = addRoundKey(state, expandedKey, 0)
var out:[UInt8] = [UInt8]()
for i in 0..<state.count {
for j in 0..<state[0].count {
out.append(state[j][i])
}
}
return out
}
static private func expandKey(key:[UInt8], variant:AESVariant) -> [UInt8] {
/*
* Function used in the Key Expansion routine that takes a four-byte
* input word and applies an S-box to each of the four bytes to
* produce an output word.
*/
func subWord(word:[UInt8]) -> [UInt8] {
var result = word
for i in 0..<4 {
result[i] = self.sBox[Int(word[i])]
}
return result
}
var w = [UInt8](count: variant.Nb * (variant.Nr + 1) * 4, repeatedValue: 0)
for i in 0..<variant.Nk {
for wordIdx in 0..<4 {
w[(4*i)+wordIdx] = key[(4*i)+wordIdx]
}
}
var tmp:[UInt8]
for (var i = variant.Nk; i < variant.Nb * (variant.Nr + 1); i++) {
tmp = [UInt8](count: 4, repeatedValue: 0)
for wordIdx in 0..<4 {
tmp[wordIdx] = w[4*(i-1)+wordIdx]
}
if ((i % variant.Nk) == 0) {
let rotWord = rotateLeft(UInt32.withBytes(tmp), n: 8).bytes(sizeof(UInt32)) // RotWord
tmp = subWord(rotWord)
tmp[0] = tmp[0] ^ Rcon[i/variant.Nk]
} else if (variant.Nk > 6 && (i % variant.Nk) == 4) {
tmp = subWord(tmp)
}
// xor array of bytes
for wordIdx in 0..<4 {
w[4*i+wordIdx] = w[4*(i-variant.Nk)+wordIdx]^tmp[wordIdx];
}
}
return w;
}
}
extension AES {
// byte substitution with table (S-box)
public func subBytes(inout state:[[UInt8]]) {
for (i,row) in state.enumerate() {
for (j,value) in row.enumerate() {
state[i][j] = AES.sBox[Int(value)]
}
}
}
public func invSubBytes(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for (i,row) in state.enumerate() {
for (j,value) in row.enumerate() {
result[i][j] = AES.invSBox[Int(value)]
}
}
return result
}
// Applies a cyclic shift to the last 3 rows of a state matrix.
public func shiftRows(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for r in 1..<4 {
for c in 0..<variant.Nb {
result[r][c] = state[r][(c + r) % variant.Nb]
}
}
return result
}
public func invShiftRows(state:[[UInt8]]) -> [[UInt8]] {
var result = state
for r in 1..<4 {
for c in 0..<variant.Nb {
result[r][(c + r) % variant.Nb] = state[r][c]
}
}
return result
}
// Multiplies two polynomials
public func multiplyPolys(a:UInt8, _ b:UInt8) -> UInt8 {
var a = a, b = b
var p:UInt8 = 0, hbs:UInt8 = 0
for _ in 0..<8 {
if (b & 1 == 1) {
p ^= a
}
hbs = a & 0x80
a <<= 1
if (hbs > 0) {
a ^= 0x1B
}
b >>= 1
}
return p
}
public func matrixMultiplyPolys(matrix:[[UInt8]], _ array:[UInt8]) -> [UInt8] {
var returnArray:[UInt8] = [UInt8](count: array.count, repeatedValue: 0)
for (i, row) in matrix.enumerate() {
for (j, boxVal) in row.enumerate() {
returnArray[i] = multiplyPolys(boxVal, array[j]) ^ returnArray[i]
}
}
return returnArray
}
public func addRoundKey(state:[[UInt8]], _ expandedKeyW:[UInt8], _ round:Int) -> [[UInt8]] {
var newState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
let idxRow = 4*variant.Nb*round
for c in 0..<variant.Nb {
let idxCol = variant.Nb*c
newState[0][c] = state[0][c] ^ expandedKeyW[idxRow+idxCol+0]
newState[1][c] = state[1][c] ^ expandedKeyW[idxRow+idxCol+1]
newState[2][c] = state[2][c] ^ expandedKeyW[idxRow+idxCol+2]
newState[3][c] = state[3][c] ^ expandedKeyW[idxRow+idxCol+3]
}
return newState
}
// mixes data (independently of one another)
public func mixColumns(state:[[UInt8]]) -> [[UInt8]] {
var state = state
let colBox:[[UInt8]] = [[2,3,1,1],[1,2,3,1],[1,1,2,3],[3,1,1,2]]
var rowMajorState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: state.first!.count, repeatedValue: 0)) //state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
var newRowMajorState = rowMajorState
for i in 0..<state.count {
for j in 0..<state[0].count {
rowMajorState[j][i] = state[i][j]
}
}
for (i, row) in rowMajorState.enumerate() {
newRowMajorState[i] = matrixMultiplyPolys(colBox, row)
}
for i in 0..<state.count {
for j in 0..<state[0].count {
state[i][j] = newRowMajorState[j][i]
}
}
return state
}
public func invMixColumns(state:[[UInt8]]) -> [[UInt8]] {
var state = state
let invColBox:[[UInt8]] = [[14,11,13,9],[9,14,11,13],[13,9,14,11],[11,13,9,14]]
var colOrderState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
for i in 0..<state.count {
for j in 0..<state[0].count {
colOrderState[j][i] = state[i][j]
}
}
var newState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } })
for (i, row) in colOrderState.enumerate() {
newState[i] = matrixMultiplyPolys(invColBox, row)
}
for i in 0..<state.count {
for j in 0..<state[0].count {
state[i][j] = newState[j][i]
}
}
return state
}
} | apache-2.0 | 76bf836baf7913adc04e79f92c2acbcb | 38.969977 | 211 | 0.533977 | 2.741762 | false | false | false | false |
davidtucker/WaterCooler-Demo | EnterpriseMessenger/KinveyExtensions.swift | 1 | 4429 | //
// KinveyExtensions.swift
// EnterpriseMessenger
//
// Created by David Tucker on 2/9/15.
// Copyright (c) 2015 Universal Mind. All rights reserved.
//
import Foundation
/*
The following methods and properties are extensions of the core KCSUser object
(which is provided in the Kinvey iOS SDK.
*/
extension KCSUser {
/*
This method is a convenience method to get the user's profile picture as a
UIImage. This leverages a cache that is defined within the app delegate. If
the image has not been saved in the cache, this will return nil. If that
happens, you can call populateProfileImage to populate the cache.
*/
func getProfileImage() -> UIImage? {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
return appDelegate.dataManager.imageCache[self.userId]
}
/*
This method populates the profile pic in the application cache for this user.
Once this has been called, the profile pic can be fetched synchronously by
using the getProfileImage method.
*/
func populateProfileImage(completion:(UIImage?) -> ()) {
let pictureId = self.getValueForAttribute(WaterCoolerConstants.Kinvey.ProfilePicIdField) as String!
if(pictureId == nil) {
completion(nil)
}
var options = [ KCSFileOnlyIfNewer : true ]
KCSFileStore.downloadFile(pictureId, options: options, completionBlock: { (result, error) -> Void in
if(error == nil) {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let file:KCSFile = result[0] as KCSFile
let image:UIImage = UIImage(contentsOfFile: file.localURL.path!)!
dispatch_async(dispatch_get_main_queue(), { () -> Void in
appDelegate.dataManager.imageCache[self.userId] = image
completion(image)
})
}
}, progressBlock: nil)
}
/*
This synchronous method allows us to check if a user has a profile picture
in their user profile or not.
*/
func hasProfileImage() -> Bool {
let pictureId = self.getValueForAttribute(WaterCoolerConstants.Kinvey.ProfilePicIdField) as String!
if pictureId != nil && !pictureId.isEmpty {
return true
}
return false
}
/*
This property handles the getting / setting of the profile picture ID for
the user. This uses Kinvey's ability to save arbitrary key-value data to
the specific user.
*/
var profilePictureId:String? {
get {
return self.getValueForAttribute(WaterCoolerConstants.Kinvey.ProfilePicIdField) as String!
}
set {
if(newValue != nil) {
setValue(newValue, forAttribute: WaterCoolerConstants.Kinvey.ProfilePicIdField)
} else {
removeValueForAttribute(WaterCoolerConstants.Kinvey.ProfilePicIdField)
}
}
}
/*
This property handles the getting / setting of the job title for the user.
This uses Kinvey's ability to save arbitrary key-value data to the specific
user.
*/
var title:String {
get {
return self.getValueForAttribute(WaterCoolerConstants.Kinvey.UserTitleField) as String!
}
set {
setValue(newValue, forAttribute: WaterCoolerConstants.Kinvey.UserTitleField)
}
}
}
/*
The following methods and properties are extensions of the core KCSMetadata object
(which is provided in the Kinvey iOS SDK.
*/
extension KCSMetadata {
/*
This convenience initializer handles the configurating of permissions metadata.
You can pass in an array of User ID's which will be allowed both read and write
access to the data. You can also add the active user without having to pass in
the ID.
*/
convenience init(userIds:[String], includeActiveUser:Bool) {
self.init()
var ids = userIds
setGloballyReadable(false)
setGloballyWritable(false)
if(includeActiveUser) {
ids.append(KCSUser.activeUser().userId)
}
for userId in ids {
readers.addObject(userId)
writers.addObject(userId)
}
}
}
| mit | dfe8b14f4b30e4a5ba01b925b3db4e68 | 34.150794 | 108 | 0.629939 | 4.762366 | false | false | false | false |
romansorochak/ParallaxHeader | Exmple/ParallaxVC.swift | 1 | 2098 | //
// ParallaxVC.swift
// ParallaxHeader
//
// Created by Roman Sorochak on 6/27/17.
// Copyright © 2017 MagicLab. All rights reserved.
//
import UIKit
import ParallaxHeader
class ParallaxVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
weak var headerImageView: UIView?
//MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupParallaxHeader()
setupNavBar()
}
//MARK: - private
private func setupParallaxHeader() {
let imageView = UIImageView()
imageView.image = UIImage(named: "profile")
imageView.contentMode = .scaleAspectFill
headerImageView = imageView
tableView.parallaxHeader.view = imageView
tableView.parallaxHeader.height = 400
tableView.parallaxHeader.minimumHeight = 0
tableView.parallaxHeader.mode = .topFill
tableView.parallaxHeader.parallaxHeaderDidScrollHandler = { parallaxHeader in
print(parallaxHeader.progress)
}
}
//MARK: - nav bar
private func setupNavBar() {
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Push me",
style: UIBarButtonItem.Style.plain,
target: self,
action: #selector(rightBarButtonAction)
)
}
@objc private func rightBarButtonAction() {
let navC = UINavigationController(rootViewController: FromCodeCollectionVC())
navC.modalPresentationStyle = .fullScreen
present(navC, animated: true, completion: nil)
}
//MARK: table view data source/delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "some row text"
return cell
}
}
| mit | 477637a9a6e2c31ea33a2baa1dd699fd | 24.888889 | 100 | 0.627563 | 5.418605 | false | false | false | false |
JohnEstropia/CoreStore | Sources/Internals.AnyFieldCoder.swift | 1 | 7055 | //
// Internals.AnyFieldCoder.swift
// CoreStore
//
// Copyright © 2020 John Rommel Estropia
//
// 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
// MARK: - Internals
extension Internals {
// MARK: - AnyFieldCoder
internal struct AnyFieldCoder {
// MARK: Internal
internal let transformerName: NSValueTransformerName
internal let transformer: Foundation.ValueTransformer
internal let encodeToStoredData: (_ fieldValue: Any?) -> Data?
internal let decodeFromStoredData: (_ data: Data?) -> Any?
internal init<Coder: FieldCoderType>(_ fieldCoder: Coder.Type) {
let transformer = CustomValueTransformer(fieldCoder: fieldCoder)
self.transformerName = transformer.id
self.transformer = transformer
self.encodeToStoredData = {
switch $0 {
case let value as Coder.FieldStoredValue:
return fieldCoder.encodeToStoredData(value)
case let valueBox as Internals.AnyFieldCoder.TransformableDefaultValueCodingBox:
return fieldCoder.encodeToStoredData(valueBox.value as! Coder.FieldStoredValue?)
default:
return fieldCoder.encodeToStoredData(nil)
}
}
self.decodeFromStoredData = { fieldCoder.decodeFromStoredData($0) }
}
internal init<V>(tag: UUID, encode: @escaping (V) -> Data?, decode: @escaping (Data?) -> V) {
let transformer = CustomValueTransformer(tag: tag)
self.transformerName = transformer.id
self.transformer = transformer
self.encodeToStoredData = { encode($0 as! V) }
self.decodeFromStoredData = { decode($0) }
}
internal func register() {
switch self.transformerName {
case .secureUnarchiveFromDataTransformerName,
.isNotNilTransformerName,
.isNilTransformerName,
.negateBooleanTransformerName:
return
case let transformerName:
Self.cachedCoders[transformerName] = self
Foundation.ValueTransformer.setValueTransformer(
self.transformer,
forName: transformerName
)
}
}
// MARK: FilePrivate
fileprivate static var cachedCoders: [NSValueTransformerName: AnyFieldCoder] = [:]
// MARK: - TransformableDefaultValueCodingBox
@objc(_CoreStore_Internals_TransformableDefaultValueCodingBox)
internal final class TransformableDefaultValueCodingBox: NSObject, NSSecureCoding {
// MARK: Internal
@objc
internal dynamic let transformerName: String
@objc
internal dynamic let data: Data
@nonobjc
internal let value: Any?
internal init?(defaultValue: Any?, fieldCoder: Internals.AnyFieldCoder?) {
guard
let fieldCoder = fieldCoder,
let defaultValue = defaultValue,
!(defaultValue is NSNull),
let data = fieldCoder.encodeToStoredData(defaultValue)
else {
return nil
}
self.transformerName = fieldCoder.transformerName.rawValue
self.value = defaultValue
self.data = data
}
// MARK: NSSecureCoding
@objc
dynamic class var supportsSecureCoding: Bool {
return true
}
// MARK: NSCoding
@objc
dynamic required init?(coder aDecoder: NSCoder) {
guard
case let transformerName as String = aDecoder.decodeObject(forKey: #keyPath(TransformableDefaultValueCodingBox.transformerName)),
let transformer = ValueTransformer(forName: .init(transformerName)),
case let data as Data = aDecoder.decodeObject(forKey: #keyPath(TransformableDefaultValueCodingBox.data)),
let value = transformer.reverseTransformedValue(data)
else {
return nil
}
self.transformerName = transformerName
self.data = data
self.value = value
}
@objc
dynamic func encode(with coder: NSCoder) {
coder.encode(self.data, forKey: #keyPath(TransformableDefaultValueCodingBox.data))
coder.encode(self.transformerName, forKey: #keyPath(TransformableDefaultValueCodingBox.transformerName))
}
}
}
// MARK: - CustomValueTransformer
fileprivate final class CustomValueTransformer: ValueTransformer {
// MARK: FilePrivate
fileprivate let id: NSValueTransformerName
fileprivate init<Coder: FieldCoderType>(fieldCoder: Coder.Type) {
self.id = .init(rawValue: "CoreStore.FieldCoders.CustomValueTransformer<\(String(reflecting: fieldCoder))>.transformerName")
}
fileprivate init(tag: UUID) {
self.id = .init(rawValue: "CoreStore.FieldCoders.CustomValueTransformer<\(tag.uuidString)>.transformerName")
}
// MARK: ValueTransformer
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
override func transformedValue(_ value: Any?) -> Any? {
return AnyFieldCoder.cachedCoders[self.id]?.encodeToStoredData(value) as Data?
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
return AnyFieldCoder.cachedCoders[self.id]?.decodeFromStoredData(value as! Data?)
}
}
}
| mit | 687ef481befd86ed80859941642263c0 | 32.117371 | 149 | 0.612277 | 5.397093 | false | false | false | false |
dotmat/StatusPageIOSampleApp | StatusPageIOStatus/StatusPageIO/StatusPageIOAPIController.swift | 1 | 3794 | //
// StatusPageIOAPIController.swift
//
//
// Created by Mathew Jenkinson on 09/03/2016.
// Copyright © 2016 Mathew Jenkinson. All rights reserved.
//
import Foundation
protocol APIControllerProtocol {
func didReceiveAPIResults(results: AnyObject)
}
class APIController {
var delegate: APIControllerProtocol?
let StatusPageIOKey: String = "" // Put the StatusPageIOKey here
func getStatusPageIOSummary() {
let baseURL = "https://\(self.StatusPageIOKey).statuspage.io/api/v2/summary.json"
self.makeHTTPGETRequest(baseURL)
}
func getStatusPageIOIncidents() {
let baseURL = "https://\(self.StatusPageIOKey).statuspage.io/api/v2/incidents.json"
self.makeHTTPGETRequest(baseURL)
}
func getStatusPageIOUnresolvedIncidents() {
let baseURL = "https://\(self.StatusPageIOKey).statuspage.io/api/v2/incidents/unresolved.json"
self.makeHTTPGETRequest(baseURL)
}
func getStatusPageIOComponents() {
let baseURL = "https://\(self.StatusPageIOKey).statuspage.io/api/v2/components.json"
self.makeHTTPGETRequest(baseURL)
}
func makeHTTPGETRequest(baseURL:String) {
let requestURL: NSURL = NSURL(string: baseURL)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(jsonData)
self.delegate?.didReceiveAPIResults(jsonData)
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
func registerforRemoteNotificationsWithNotificationServer(registrationUrl:String, datatoPost:String, loginString: String) {
let url:String = registrationUrl
let params:NSString = datatoPost
// Make credentials for Basic Auth
let loginString:NSString = String(loginString)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//request.addValue("application/html", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/html", forHTTPHeaderField: "Accept")
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
//print(params)
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(jsonData)
self.delegate?.didReceiveAPIResults(jsonData)
}catch {
print("Error with Json: \(error)")
}
}
task.resume()
}
}
| gpl-3.0 | 7c9bed93f794b134af46d143a90ca138 | 36.93 | 131 | 0.632481 | 5.050599 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Services/MercadoPagoServices+Reachability.swift | 1 | 1094 | import Foundation
// Se importa MLCardForm para reutilizar la clase de Reachability
import MLCardForm
protocol InternetConnectionProtocol: NSObjectProtocol {
func hasInternetConnection() -> Bool
}
extension MercadoPagoServices: InternetConnectionProtocol {
func hasInternetConnection() -> Bool {
return hasInternet
}
func reachabilityChanged(_ isReachable: Bool) {
hasInternet = isReachable
}
func addReachabilityObserver() {
do {
reachability = try Reachability()
} catch {
print("Unable to add reachability observer")
}
reachability?.whenReachable = { [weak self] _ in
self?.reachabilityChanged(true)
}
reachability?.whenUnreachable = { [weak self] _ in
self?.reachabilityChanged(false)
}
do {
try reachability?.startNotifier()
} catch {
print("Unable to start notifier")
}
}
func removeReachabilityObserver() {
reachability?.stopNotifier()
reachability = nil
}
}
| mit | 924e606ba383cc3dd698029b9c3536ce | 23.863636 | 65 | 0.620658 | 5.497487 | false | false | false | false |
JohnEstropia/CoreStore | Sources/NSManagedObjectContext+Transaction.swift | 1 | 8389 | //
// NSManagedObjectContext+Transaction.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - NSManagedObjectContext
extension NSManagedObjectContext {
// MARK: Internal
@nonobjc
internal weak var parentTransaction: BaseDataTransaction? {
get {
return Internals.getAssociatedObjectForKey(
&PropertyKeys.parentTransaction,
inObject: self
)
}
set {
Internals.setAssociatedWeakObject(
newValue,
forKey: &PropertyKeys.parentTransaction,
inObject: self
)
}
}
@nonobjc
internal var saveMetadata: SaveMetadata? {
get {
let value: SaveMetadata? = Internals.getAssociatedObjectForKey(
&PropertyKeys.saveMetadata,
inObject: self
)
return value
}
set {
Internals.setAssociatedRetainedObject(
newValue,
forKey: &PropertyKeys.saveMetadata,
inObject: self
)
}
}
@nonobjc
internal var isTransactionContext: Bool {
get {
let value: NSNumber? = Internals.getAssociatedObjectForKey(
&PropertyKeys.isTransactionContext,
inObject: self
)
return value?.boolValue == true
}
set {
Internals.setAssociatedCopiedObject(
NSNumber(value: newValue),
forKey: &PropertyKeys.isTransactionContext,
inObject: self
)
}
}
@nonobjc
internal var isDataStackContext: Bool {
get {
let value: NSNumber? = Internals.getAssociatedObjectForKey(
&PropertyKeys.isDataStackContext,
inObject: self
)
return value?.boolValue == true
}
set {
Internals.setAssociatedCopiedObject(
NSNumber(value: newValue),
forKey: &PropertyKeys.isDataStackContext,
inObject: self
)
}
}
@nonobjc
internal func isRunningInAllowedQueue() -> Bool {
guard let parentTransaction = self.parentTransaction else {
return false
}
return parentTransaction.isRunningInAllowedQueue()
}
@nonobjc
internal func temporaryContextInTransactionWithConcurrencyType(_ concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: concurrencyType)
context.parent = self
context.parentStack = self.parentStack
context.setupForCoreStoreWithContextName("com.corestore.temporarycontext")
context.shouldCascadeSavesToParent = (self.parentStack?.rootSavingContext == self)
context.retainsRegisteredObjects = true
return context
}
@nonobjc
internal func saveSynchronously(
waitForMerge: Bool,
sourceIdentifier: Any?
) -> (hasChanges: Bool, error: CoreStoreError?) {
var result: (hasChanges: Bool, error: CoreStoreError?) = (false, nil)
self.performAndWait {
guard self.hasChanges else {
return
}
do {
self.saveMetadata = .init(
isSavingSynchronously: waitForMerge,
sourceIdentifier: sourceIdentifier
)
try self.save()
self.saveMetadata = nil
}
catch {
let saveError = CoreStoreError(error)
Internals.log(
saveError,
"Failed to save \(Internals.typeName(NSManagedObjectContext.self))."
)
result = (true, saveError)
return
}
if let parentContext = self.parent, self.shouldCascadeSavesToParent {
let (_, error) = parentContext.saveSynchronously(
waitForMerge: waitForMerge,
sourceIdentifier: sourceIdentifier
)
result = (true, error)
}
else {
result = (true, nil)
}
}
return result
}
@nonobjc
internal func saveAsynchronously(
sourceIdentifier: Any?,
completion: @escaping (_ hasChanges: Bool, _ error: CoreStoreError?) -> Void = { (_, _) in }
) {
self.perform {
guard self.hasChanges else {
DispatchQueue.main.async {
completion(false, nil)
}
return
}
do {
self.saveMetadata = .init(
isSavingSynchronously: false,
sourceIdentifier: sourceIdentifier
)
try self.save()
self.saveMetadata = nil
}
catch {
let saveError = CoreStoreError(error)
Internals.log(
saveError,
"Failed to save \(Internals.typeName(NSManagedObjectContext.self))."
)
DispatchQueue.main.async {
completion(true, saveError)
}
return
}
if self.shouldCascadeSavesToParent, let parentContext = self.parent {
parentContext.saveAsynchronously(
sourceIdentifier: sourceIdentifier,
completion: { (_, error) in
completion(true, error)
}
)
}
else {
DispatchQueue.main.async {
completion(true, nil)
}
}
}
}
@nonobjc
internal func refreshAndMergeAllObjects() {
self.refreshAllObjects()
}
// MARK: - SaveMetadata
internal final class SaveMetadata {
// MARK: Internal
internal let isSavingSynchronously: Bool
internal let sourceIdentifier: Any?
internal init(
isSavingSynchronously: Bool,
sourceIdentifier: Any?
) {
self.isSavingSynchronously = isSavingSynchronously
self.sourceIdentifier = sourceIdentifier
}
}
// MARK: Private
private struct PropertyKeys {
static var parentTransaction: Void?
static var saveMetadata: Void?
static var isTransactionContext: Void?
static var isDataStackContext: Void?
}
}
| mit | 47ff24c7f8c71e780220e3c32ec05972 | 28.535211 | 152 | 0.523963 | 6.273747 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Common/View/TableViewController.swift | 1 | 4096 | //
// TableViewController.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class TableViewController : UIViewController {
var tableViewStyle: UITableViewStyle
var tableView: UITableView!
init(style: UITableViewStyle) {
self.tableViewStyle = style
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
self.tableViewStyle = .Plain
super.init(coder: aDecoder)
}
deinit {
tableView.delegate = nil
tableView.dataSource = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardDidShowNotification:",
name: UIKeyboardDidShowNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardWillHideNotification:",
name: UIKeyboardWillHideNotification,
object: nil
)
}
func keyboardDidShowNotification(notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
if let rectValue = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
let keyboardSize = rectValue.CGRectValue().size
var contentInset = tableView.contentInset
contentInset.bottom = keyboardSize.height
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = contentInset
}
}
func keyboardWillHideNotification(notification: NSNotification) {
var contentInset = tableView.contentInset
contentInset.bottom = 0.0
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = contentInset
}
override func loadView() {
tableView = UITableView(frame: CGRect.zero, style: tableViewStyle)
view = tableView
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
registerForKeyboardNotifications()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true)
}
}
}
extension TableViewController : UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
extension TableViewController : UITableViewDelegate {
}
| mit | 4a85dc9f89cc182523bc4f23c8ccbab7 | 33.133333 | 109 | 0.68457 | 5.728671 | false | false | false | false |
jlecomte/iOSTwitterApp | Twiddlator/AppDelegate.swift | 1 | 3241 | //
// AppDelegate.swift
// Twiddlator
//
// Created by Julien Lecomte on 9/26/14.
// Copyright (c) 2014 Julien Lecomte. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var client = TwitterClient.sharedInstance
func showLogin() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as UIViewController
window?.rootViewController = vc
}
func showHomeTimeline() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nvc = storyboard.instantiateViewControllerWithIdentifier("RootNavigationController") as UINavigationController
window?.rootViewController = nvc
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if client.isAuthorized() {
showHomeTimeline()
} else {
showLogin()
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
if url.scheme == "twiddlator" {
if url.host == "oauth" {
client.handleOAuthCallback(url.query!, success: {
() -> Void in
println("Success")
self.showHomeTimeline()
})
}
return true
}
return false
}
}
| mit | 5249bbcb8b31274167e395ee52918a71 | 41.644737 | 285 | 0.69639 | 5.616984 | false | false | false | false |
broadwaylamb/Codable | Sources/CoreGraphics+Codable.swift | 1 | 2849 | //
// CoreGraphics+Codable.swift
// Codable
//
// Created by Sergej Jaskiewicz on 31/07/2017.
//
//
import CoreGraphics
#if swift(>=3.2)
#else
extension CGPoint : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let x = try container.decode(CGFloat.self)
let y = try container.decode(CGFloat.self)
self.init(x: x, y: y)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(x)
try container.encode(y)
}
}
extension CGSize : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let width = try container.decode(CGFloat.self)
let height = try container.decode(CGFloat.self)
self.init(width: width, height: height)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(width)
try container.encode(height)
}
}
extension CGVector : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let dx = try container.decode(CGFloat.self)
let dy = try container.decode(CGFloat.self)
self.init(dx: dx, dy: dy)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(dx)
try container.encode(dy)
}
}
extension CGRect : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let origin = try container.decode(CGPoint.self)
let size = try container.decode(CGSize.self)
self.init(origin: origin, size: size)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(origin)
try container.encode(size)
}
}
extension CGAffineTransform : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let a = try container.decode(CGFloat.self)
let b = try container.decode(CGFloat.self)
let c = try container.decode(CGFloat.self)
let d = try container.decode(CGFloat.self)
let tx = try container.decode(CGFloat.self)
let ty = try container.decode(CGFloat.self)
self.init(a: a, b: b, c: c, d: d, tx: tx, ty: ty)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(a)
try container.encode(b)
try container.encode(c)
try container.encode(d)
try container.encode(tx)
try container.encode(ty)
}
}
#endif
| mit | d0bb9b48dde2b92d460088f8637f0c61 | 28.371134 | 57 | 0.642331 | 4.099281 | false | false | false | false |
ryanipete/AmericanChronicle | AmericanChronicle/Code/Modules/DatePicker/View/Subviews/DayKeyboard.swift | 1 | 3168 | import UIKit
final class DayKeyboard: UIView {
var dayTapHandler: ((String) -> Void)?
var selectedDayMonthYear: DayMonthYear? {
didSet { updateCalendar() }
}
// Holds an array of "row" stack views.
private let mainStackView: UIStackView = {
let subview = UIStackView()
subview.translatesAutoresizingMaskIntoConstraints = false
subview.axis = .vertical
subview.spacing = spacing
subview.distribution = .fillEqually
return subview
}()
private static let spacing: CGFloat = 2.0
// MARK: Init methods
func commonInit() {
backgroundColor = .white
addSubview(mainStackView)
mainStackView.fillSuperview(insets: .all(DayKeyboard.spacing))
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
// MARK: Internal methods
@objc func didTapButton(_ button: UIButton) {
if let title = button.title(for: .normal) {
dayTapHandler?(title)
}
}
// MARK: Private methods
private func updateCalendar() {
mainStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
guard let selectedDayMonthYear = selectedDayMonthYear else { return }
guard let rangeOfDaysThisMonth = selectedDayMonthYear.rangeOfDaysInMonth() else { return }
// Calculate the alignment of days by week for this month/year.
var weeks: [[Int?]] = []
for day in (1...rangeOfDaysThisMonth.length) {
let dayMonthYear = selectedDayMonthYear.copyWithDay(day)
guard let weekday = dayMonthYear.weekday() else { continue }
guard let weeknumber = dayMonthYear.weekOfMonth() else { continue }
let zeroBasedWeekNumber = weeknumber - 1
if weeks.count == zeroBasedWeekNumber {
weeks.append([Int?](repeating: nil, count: 7))
}
weeks[zeroBasedWeekNumber][(weekday - 1)] = day
}
// Add the buttons.
for week in weeks {
let weekButtons = week.map { day -> KeyboardButton in
let title: String
if let day = day {
title = "\(day)"
} else {
title = ""
}
let button = KeyboardButton(title: title)
button.addTarget(self,
action: #selector(didTapButton(_:)),
for: .touchUpInside)
button.isSelected = (day == selectedDayMonthYear.day)
return button
}
addRowWithButtons(weekButtons)
}
}
private func addRowWithButtons(_ buttons: [KeyboardButton]) {
let rowView = UIStackView(arrangedSubviews: buttons)
rowView.translatesAutoresizingMaskIntoConstraints = false
rowView.axis = .horizontal
rowView.spacing = DayKeyboard.spacing
rowView.distribution = .fillEqually
mainStackView.addArrangedSubview(rowView)
}
}
| mit | 0b525efeb5a9f2ed6a22d5df3099750e | 31.326531 | 98 | 0.586806 | 5.245033 | false | false | false | false |
SwifterLC/SinaWeibo | LCSinaWeibo/LCSinaWeibo/Classes/View/Home/StatusCell/LCStatusCellBottomView.swift | 1 | 3317 | //
// LCStatusCellBottomView.swift
// LCSinaWeibo
//
// Created by 刘成 on 2017/8/6.
// Copyright © 2017年 刘成. All rights reserved.
//
import UIKit
/// 微博 cell 底部 cell
class LCStatusCellBottomView: UIView {
@objc fileprivate func retweetBtClick(){
print("点击了转发按钮")
}
@objc fileprivate func commentBtClick(){
print("点击了评论按钮")
}
@objc fileprivate func likeBtClick(){
print("点击了点赞按钮")
}
// MARK :- 懒加载控件
/// 转发按钮
fileprivate lazy var retweetButton :UIButton = UIButton(title: "转发", fontSize: 11, imgName: "timeline_icon_retweet")
/// 评论按钮
fileprivate lazy var commentButton :UIButton = UIButton(title: "评论", fontSize: 11, imgName: "timeline_icon_comment")
/// 点赞按钮
fileprivate lazy var likeButton :UIButton = UIButton(title: "点赞", fontSize: 11, imgName: "timeline_icon_unlike")
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.9, alpha: 1)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置界面
extension LCStatusCellBottomView{
/// 设置界面
fileprivate func setupUI(){
//1> 添加子控件
addSubview(retweetButton)
addSubview(commentButton)
addSubview(likeButton)
// 添加分隔视图
let sepViewLeft = sepView()
addSubview(sepViewLeft)
let sepViewRight = sepView()
addSubview(sepViewRight)
//2> 自动布局
retweetButton.snp.makeConstraints { (make) in
make.left.top.bottom.equalToSuperview()
}
commentButton.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalTo(retweetButton.snp.right)
make.width.height.equalTo(retweetButton)
}
likeButton.snp.makeConstraints { (make) in
make.left.equalTo(commentButton.snp.right)
make.top.right.equalToSuperview()
make.width.height.equalTo(retweetButton)
}
sepViewLeft.snp.makeConstraints { (make) in
make.left.equalTo(retweetButton.snp.right)
make.centerY.equalToSuperview()
make.width.equalTo(0.5)
make.height.equalToSuperview().multipliedBy(0.4)
}
sepViewRight.snp.makeConstraints { (make) in
make.left.equalTo(commentButton.snp.right)
make.centerY.equalToSuperview()
make.width.equalTo(0.5)
make.height.equalToSuperview().multipliedBy(0.4)
}
//添加事件
retweetButton.addTarget(self, action: #selector(LCStatusCellBottomView.retweetBtClick), for: .touchUpInside)
commentButton.addTarget(self, action: #selector(LCStatusCellBottomView.commentBtClick), for: .touchUpInside)
likeButton.addTarget(self, action: #selector(LCStatusCellBottomView.likeBtClick), for: .touchUpInside)
}
/// 获取分隔视图
///
/// - Returns: 分隔视图
private func sepView()->UIView{
let view = UIView()
view.backgroundColor = UIColor(white: 0.95, alpha: 1)
return view
}
}
| mit | 215ab69b182faa4b11f0e24e92bd8b37 | 33.086957 | 120 | 0.631378 | 4.186916 | false | false | false | false |
wangshengjia/VWInstantRun | VWInstantRun/VWPluginHelpers.swift | 1 | 3320 | //
// VWPluginHelpers.swift
// VWInstantRun
//
// Created by Victor WANG on 20/12/15.
// Copyright © 2015 Victor Wang. All rights reserved.
//
import Foundation
import AppKit
struct VWPluginHelper {
static func run(output: String?) {
logOutput(output)
VWFileIO.removeItemAtPath(VWFileIO.swiftMainFilePath)
VWFileIO.removeItemAtPath(VWFileIO.objcMainFilePath)
executeBinaryFile { (output) -> () in
logOutput(output)
VWFileIO.removeItemAtPath(VWFileIO.outputBinaryFilePath)
}
}
static func logOutput(output: String?) {
guard let output = output where !output.isEmpty else {
return
}
VWXcodeHelpers.appendLogText(output)
}
static func buildWithObjc(onCompletion completionHandler:(output: String?) -> () = VWPluginHelper.run) {
guard NSFileManager.defaultManager().fileExistsAtPath(VWFileIO.objcMainFilePath) else {
return
}
runShellCommand(["/usr/bin/xcrun", "/usr/bin/clang", "-fobjc-arc", "-framework", "Foundation", VWFileIO.objcMainFilePath, "-o", VWFileIO.outputBinaryFilePath], commandTerminationHandler: completionHandler)
}
static func buildWithSwift(onCompletion completionHandler:(output: String?) -> () = VWPluginHelper.run) {
guard NSFileManager.defaultManager().fileExistsAtPath(VWFileIO.swiftMainFilePath) else {
return
}
runShellCommand(["/usr/bin/xcrun", "-sdk", "macosx", "/usr/bin/swiftc", VWFileIO.swiftMainFilePath, "-o", VWFileIO.outputBinaryFilePath], commandTerminationHandler: completionHandler)
}
static func executeBinaryFile(onCompletion completionHandler:(output: String?) -> () = VWPluginHelper.logOutput) {
guard NSFileManager.defaultManager().fileExistsAtPath(VWFileIO.outputBinaryFilePath) else {
return
}
runShellCommand([VWFileIO.outputBinaryFilePath], commandTerminationHandler: completionHandler)
}
static func runShellCommand(components: Array<String>, commandTerminationHandler: (output: String?) -> ()) {
guard !components.isEmpty else {
return
}
let outputPipe = NSPipe()
let errorPipe = NSPipe()
let task = NSTask()
task.launchPath = components.first
task.arguments = (components.count > 1) ? Array(components[1...components.count-1]) : []
task.standardOutput = outputPipe
task.standardError = errorPipe
task.launch()
task.terminationHandler = { (task: NSTask) -> () in
var output: String? = nil, error: String? = nil
if let pipe = task.standardOutput as? NSPipe {
output = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: NSUTF8StringEncoding)
}
if let pipe = task.standardError as? NSPipe {
error = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: NSUTF8StringEncoding)
}
// TODD: make it better
if (output == nil) || (output!.isEmpty) {
output = error
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
commandTerminationHandler(output: output)
})
}
}
}
| mit | 54b17bc647f8ff889ba16736590f1654 | 36.292135 | 213 | 0.642965 | 4.540356 | false | false | false | false |
haskellswift/swift-package-manager | Sources/PackageLoading/ManifestLoader.swift | 2 | 14806 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageDescription
import PackageModel
import Utility
import func POSIX.realpath
public enum ManifestParseError: Swift.Error {
/// The manifest file is empty.
case emptyManifestFile
/// The manifest had a string encoding error.
case invalidEncoding
/// The manifest contains invalid format.
case invalidManifestFormat([String]?)
}
/// Resources required for manifest loading.
///
/// These requirements are abstracted out to make it easier to add support for
/// using the package manager with alternate toolchains in the future.
public protocol ManifestResourceProvider {
/// The path of the swift compiler.
var swiftCompilerPath: AbsolutePath { get }
/// The path of the library resources.
var libraryPath: AbsolutePath { get }
}
/// Protocol for the manifest loader interface.
public protocol ManifestLoaderProtocol {
/// Load the manifest for the package at `path`.
///
/// - Parameters:
/// - path: The root path of the package.
/// - baseURL: The URL the manifest was loaded from.
/// - version: The version the manifest is from, if known.
/// - fileSystem: If given, the file system to load from (otherwise load from the local file system).
func load(packagePath path: AbsolutePath, baseURL: String, version: Version?, fileSystem: FileSystem?) throws -> Manifest
}
extension ManifestLoaderProtocol {
/// Load the manifest for the package at `path`.
///
/// - Parameters:
/// - path: The root path of the package.
/// - baseURL: The URL the manifest was loaded from.
/// - version: The version the manifest is from, if known.
public func load(packagePath path: AbsolutePath, baseURL: String, version: Version?) throws -> Manifest {
return try load(packagePath: path, baseURL: baseURL, version: version, fileSystem: nil)
}
}
/// Utility class for loading manifest files.
///
/// This class is responsible for reading the manifest data and produce a
/// properly formed `PackageModel.Manifest` object. It currently does so by
/// interpreting the manifest source using Swift -- that produces a JSON
/// serialized form of the manifest (as implemented by `PackageDescription`'s
/// `atexit()` handler) which is then deserialized and loaded.
public final class ManifestLoader: ManifestLoaderProtocol {
let resources: ManifestResourceProvider
public init(resources: ManifestResourceProvider) {
self.resources = resources
}
public func load(packagePath path: AbsolutePath, baseURL: String, version: Version?, fileSystem: FileSystem? = nil) throws -> Manifest {
// As per our versioning support, determine the appropriate manifest version to load.
for versionSpecificKey in Versioning.currentVersionSpecificKeys {
let versionSpecificPath = path.appending(component: Manifest.basename + versionSpecificKey + ".swift")
if (fileSystem ?? localFileSystem).exists(versionSpecificPath) {
return try loadFile(path: versionSpecificPath, baseURL: baseURL, version: version, fileSystem: fileSystem)
}
}
return try loadFile(path: path.appending(component: Manifest.filename), baseURL: baseURL, version: version, fileSystem: fileSystem)
}
/// Create a manifest by loading a specific manifest file from the given `path`.
///
/// - Parameters:
/// - path: The path to the manifest file (or a package root).
/// - baseURL: The URL the manifest was loaded from.
/// - version: The version the manifest is from, if known.
/// - fileSystem: If given, the file system to load from (otherwise load from the local file system).
//
// FIXME: We should stop exposing this publicly, from a public perspective
// we should only ever load complete repositories.
public func loadFile(path inputPath: AbsolutePath, baseURL: String, version: Version?, fileSystem: FileSystem? = nil) throws -> Manifest {
// If we were given a file system, load via a temporary file.
if let fileSystem = fileSystem {
let contents: ByteString
do {
contents = try fileSystem.readFileContents(inputPath)
} catch FileSystemError.noEntry {
throw PackageModel.Package.Error.noManifest(inputPath.asString)
}
let tmpFile = try TemporaryFile()
try localFileSystem.writeFileContents(tmpFile.path, bytes: contents)
return try loadFile(path: tmpFile.path, baseURL: baseURL, version: version)
}
guard baseURL.chuzzle() != nil else { fatalError() } //TODO
// Attempt to canonicalize the URL.
//
// This is important when the baseURL is a file system path, so that the
// URLs embedded into the manifest are canonical.
//
// FIXME: We really shouldn't be handling this here and in this fashion.
var baseURL = baseURL
if URL.scheme(baseURL) == nil {
if let resolved = try? realpath(baseURL) {
baseURL = resolved
}
}
// Compute the actual input file path.
let path: AbsolutePath = isDirectory(inputPath) ? inputPath.appending(component: Manifest.filename) : inputPath
// Validate that the file exists.
guard isFile(path) else { throw PackageModel.Package.Error.noManifest(path.asString) }
// Load the manifest description.
guard let jsonString = try parse(path: path) else {
print("Empty manifest file is not supported anymore. Use `swift package init` to autogenerate.")
throw ManifestParseError.emptyManifestFile
}
let json = try JSON(string: jsonString)
let package = PackageDescription.Package.fromJSON(json, baseURL: baseURL)
let products = PackageDescription.Product.fromJSON(json)
let errors = parseErrors(json)
guard errors.isEmpty else {
throw ManifestParseError.invalidManifestFormat(errors)
}
return Manifest(path: path, url: baseURL, package: package, products: products, version: version)
}
/// Parse the manifest at the given path to JSON.
private func parse(path manifestPath: AbsolutePath) throws -> String? {
// For now, we load the manifest by having Swift interpret it directly.
// Eventually, we should have two loading processes, one that loads only the
// the declarative package specification using the Swift compiler directly
// and validates it.
var cmd = [resources.swiftCompilerPath.asString]
cmd += ["--driver-mode=swift"]
cmd += verbosity.ccArgs
cmd += ["-I", resources.libraryPath.asString]
// When running from Xcode, load PackageDescription.framework
// else load the dylib version of it
#if Xcode
cmd += ["-F", resources.libraryPath.asString]
cmd += ["-framework", "PackageDescription"]
#else
cmd += ["-L", resources.libraryPath.asString, "-lPackageDescription"]
#endif
#if os(macOS)
cmd += ["-target", "x86_64-apple-macosx10.10"]
#endif
cmd += [manifestPath.asString]
// Create and open a temporary file to write json to.
let file = try TemporaryFile()
// Pass the fd in arguments.
cmd += ["-fileno", "\(file.fileHandle.fileDescriptor)"]
do {
try system(cmd)
} catch {
print("Can't parse Package.swift manifest file because it contains invalid format. Fix Package.swift file format and try again.")
throw ManifestParseError.invalidManifestFormat(nil)
}
guard let json = try localFileSystem.readFileContents(file.path).asString else {
throw ManifestParseError.invalidEncoding
}
return json.isEmpty ? nil : json
}
}
// MARK: JSON Deserialization
// We separate this out from the raw PackageDescription module, so that the code
// we need to load to interpret the `Package.swift` manifests is as minimal as
// possible.
//
// FIXME: These APIs are `internal` so they can be unit tested, but otherwise
// could be private.
extension PackageDescription.Package {
static func fromJSON(_ json: JSON, baseURL: String? = nil) -> PackageDescription.Package {
// This is a private API, currently, so we do not currently try and
// validate the input.
guard case .dictionary(let topLevelDict) = json else { fatalError("unexpected item") }
guard case .dictionary(let package)? = topLevelDict["package"] else { fatalError("missing package") }
guard case .string(let name)? = package["name"] else { fatalError("missing 'name'") }
var pkgConfig: String? = nil
if case .string(let value)? = package["pkgConfig"] {
pkgConfig = value
}
// Parse the targets.
var targets: [PackageDescription.Target] = []
if case .array(let array)? = package["targets"] {
targets = array.map(PackageDescription.Target.fromJSON)
}
var providers: [PackageDescription.SystemPackageProvider]? = nil
if case .array(let array)? = package["providers"] {
providers = array.map(PackageDescription.SystemPackageProvider.fromJSON)
}
// Parse the dependencies.
var dependencies: [PackageDescription.Package.Dependency] = []
if case .array(let array)? = package["dependencies"] {
dependencies = array.map { PackageDescription.Package.Dependency.fromJSON($0, baseURL: baseURL) }
}
// Parse the exclude folders.
var exclude: [String] = []
if case .array(let array)? = package["exclude"] {
exclude = array.map { element in
guard case .string(let excludeString) = element else { fatalError("exclude contains non string element") }
return excludeString
}
}
return PackageDescription.Package(name: name, pkgConfig: pkgConfig, providers: providers, targets: targets, dependencies: dependencies, exclude: exclude)
}
}
extension PackageDescription.Package.Dependency {
static func fromJSON(_ json: JSON, baseURL: String?) -> PackageDescription.Package.Dependency {
guard case .dictionary(let dict) = json else { fatalError("Unexpected item") }
guard case .string(let url)? = dict["url"],
case .dictionary(let versionDict)? = dict["version"],
case .string(let vv1)? = versionDict["lowerBound"],
case .string(let vv2)? = versionDict["upperBound"],
let v1 = Version(vv1), let v2 = Version(vv2)
else {
fatalError("Unexpected item")
}
func fixURL() -> String {
if let baseURL = baseURL, URL.scheme(url) == nil {
// If the URL has no scheme, we treat it as a path (either absolute or relative to the base URL).
return AbsolutePath(url, relativeTo: AbsolutePath(baseURL)).asString
} else {
return url
}
}
return PackageDescription.Package.Dependency.Package(url: fixURL(), versions: v1..<v2)
}
}
extension PackageDescription.SystemPackageProvider {
fileprivate static func fromJSON(_ json: JSON) -> PackageDescription.SystemPackageProvider {
guard case .dictionary(let dict) = json else { fatalError("unexpected item") }
guard case .string(let name)? = dict["name"] else { fatalError("missing name") }
guard case .string(let value)? = dict["value"] else { fatalError("missing value") }
switch name {
case "Brew":
return .Brew(value)
case "Apt":
return .Apt(value)
default:
fatalError("unexpected string")
}
}
}
extension PackageDescription.Target {
fileprivate static func fromJSON(_ json: JSON) -> PackageDescription.Target {
guard case .dictionary(let dict) = json else { fatalError("unexpected item") }
guard case .string(let name)? = dict["name"] else { fatalError("missing name") }
var dependencies: [PackageDescription.Target.Dependency] = []
if case .array(let array)? = dict["dependencies"] {
dependencies = array.map(PackageDescription.Target.Dependency.fromJSON)
}
return PackageDescription.Target(name: name, dependencies: dependencies)
}
}
extension PackageDescription.Target.Dependency {
fileprivate static func fromJSON(_ item: JSON) -> PackageDescription.Target.Dependency {
guard case .string(let name) = item else { fatalError("unexpected item") }
return .Target(name: name)
}
}
extension PackageDescription.Product {
private init(json: JSON) {
guard case .dictionary(let dict) = json else { fatalError("unexpected item") }
guard case .string(let name)? = dict["name"] else { fatalError("missing name") }
let type: ProductType
switch dict["type"] {
case .string("exe")?:
type = .Executable
case .string("a")?:
type = .Library(.Static)
case .string("dylib")?:
type = .Library(.Dynamic)
case .string("test")?:
type = .Test
default:
fatalError("missing type")
}
guard case .array(let mods)? = dict["modules"] else { fatalError("missing modules") }
let modules: [String] = mods.map { module in
guard case JSON.string(let string) = module else { fatalError("invalid modules") }
return string
}
self.init(name: name, type: type, modules: modules)
}
static func fromJSON(_ json: JSON) -> [PackageDescription.Product] {
guard case .dictionary(let topLevelDict) = json else { fatalError("unexpected item") }
guard case .array(let products)? = topLevelDict["products"] else { fatalError("missing products") }
return products.map(Product.init)
}
}
func parseErrors(_ json: JSON) -> [String] {
guard case .dictionary(let topLevelDict) = json else { fatalError("unexpected item") }
guard case .array(let errors)? = topLevelDict["errors"] else { fatalError("missing errors") }
return errors.map { error in
guard case .string(let string) = error else { fatalError("unexpected item") }
return string
}
}
| apache-2.0 | 66213769483623c86299351db75152ce | 40.707042 | 161 | 0.649737 | 4.7823 | false | false | false | false |
avinassh/FoodPin | FoodPin/ReviewViewController.swift | 1 | 2489 | //
// ReviewViewController.swift
// FoodPin
//
// Created by avi on 14/02/15.
// Copyright (c) 2015 avi. All rights reserved.
//
import UIKit
class ReviewViewController: UIViewController {
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var dialogView: UIView!
var backgroundImage: NSData!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// sets the background to the restarunat's image. this data has been
// sent by detail view, in prepareSegue
backgroundImageView.image = UIImage(data: backgroundImage)
// following lines add blur effect
var blurEffect = UIBlurEffect(style: .Dark)
var blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
backgroundImageView.addSubview(blurEffectView)
// scales down the view when loaded. and then we use grow effect
let scale = CGAffineTransformMakeScale(0.0, 0.0)
// move the dialog down and out of the view, for slide up effect
let translate = CGAffineTransformMakeTranslation(0, 500)
// combine both the effects:
dialogView.transform = CGAffineTransformConcat(scale, translate)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
// following lines add grow effect to the scaled down version of dialogview
// UIView.animateWithDuration(0.7, delay: 0.0, options: nil, animations: {
// spring animation
UIView.animateWithDuration(0.7, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: {
let scale = CGAffineTransformMakeScale(1.0, 1.0)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.dialogView.transform = CGAffineTransformConcat(scale, translate)
}, completion: nil)
}
/*
// 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.
}
*/
}
| mit | 9c6dfb085ba3e25136b37ed6aca190d6 | 37.292308 | 136 | 0.675773 | 5.08998 | false | false | false | false |
blokadaorg/blokada | ios/App/Inbox/InboxService.swift | 1 | 2765 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
class InboxService {
static let shared = InboxService()
private let log = Logger("Inbox")
private let version = 1
private var messages = [Message]()
private init() {
self.messages = InboxHistory.load().messages
}
private var onUpdated = { (messages: [Message], responding: Bool) in }
func setOnUpdated(callback: @escaping ([Message], Bool) -> Void) {
onMain {
self.onUpdated = callback
callback(self.messages, false)
}
}
func resetChat() {
InboxHistory.empty().persist()
messages = InboxHistory.load().messages
self.onUpdated(messages, false)
}
func newMessage(_ text: String) {
self.messages.append(Message.fromMe(text))
self.onUpdated(self.messages, true)
InboxHistory(messages: self.messages, version: self.version).persist()
processUserMessage(text)
}
private func processUserMessage(_ text: String) {
onBackground {
sleep(2)
if let resp = cannedResponses[text] {
self.playMessages(resp)
} else {
var found = false
for word in text.split(separator: " ") {
if !found {
let sanitized = word.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
if let resp = cannedResponses[sanitized] {
found = true
self.playMessages(resp)
}
}
}
if !found && text.count > 2 {
self.playMessages([fallbackMessage])
} else if !found {
self.playMessages(["Ok"])
}
}
}
}
private func playMessages(_ messages: [String]) {
onBackground {
for msg in messages {
onMain {
self.messages.append(Message.fromBlokada(msg))
self.onUpdated(self.messages, !(msg == messages.last ?? "") )
InboxHistory(messages: self.messages, version: self.version).persist()
// SharedActionsService.shared.newMessage()
}
// Give time to read
sleep(UInt32((Double(msg.count) / 50.0) * 3.0))
}
}
}
}
| mpl-2.0 | 67c6b926d93077a92be0d698a70432f6 | 28.72043 | 105 | 0.527496 | 4.606667 | false | false | false | false |
alexcurylo/ScreamingParty | ScreamingParty/ScreamingParty/Classes/Then.swift | 1 | 2476 | /*
Then.swift
Source:
https://github.com/devxoul/Then v1.0.3
References:
http://khanlou.com/2016/06/configuration-in-swift/
*/
// The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public protocol Then {}
extension Then where Self: Any {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
- parameter block: Closure operating on Self
- returns: Self
*/
public func then(_ block: @noescape (inout Self) -> Void) -> Self {
var copy = self
block(©)
return copy
}
}
///* 'Type of expression is ambiguous without more context' in Swift 3???
extension Then where Self: AnyObject {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
- parameter block: Closure operating on Self
- returns: Self
*/
public func then(_ block: @noescape (Self) -> Void) -> Self {
block(self)
return self
}
}
//*/
extension NSObject: Then {}
| mit | 119c0f921bf50bd1a2b8668041c309ed | 29.567901 | 81 | 0.664782 | 4.405694 | false | false | false | false |
liuxuan30/OJProblems | OCOJ/OCOJ/LinkedListSolution.swift | 1 | 6133 | //
// LinkedListSolution.swift
// OCOJ
//
// Created by Xuan on 3/3/16.
// Copyright © 2016 Wingzero. All rights reserved.
//
import Foundation
public class ListNode: NSObject
{
var val: Int = 0
var next: ListNode? = nil
public init(_ val: Int) {
self.val = val
self.next = nil
}
public init(_ val: Int, next: ListNode?) {
self.val = val
self.next = next
}
public override var description: String {
return String(format: "val: \(val), next: \(next)")
}
}
public class LinkedListSolution: Solution
{
func generateTestCase(nums: [Int]) -> ListNode {
var head: ListNode? = nil
for i in (0..<nums.count).reverse()
{
let num = nums[i]
let node = ListNode(num, next: head)
head = node
}
return head!
}
/**
2. Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/
func addTwoNumbers(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var l1 = l1
var l2 = l2
var flag = 0
let head = ListNode(-1) // dummy head
var current: ListNode? = head
while l1 != nil || l2 != nil {
var val = 0
if l1 != nil {val += l1!.val}
if l2 != nil { val += l2!.val}
val += flag
if val >= 10 {
flag = 1
val = val - 10
} else {
flag = 0
}
let node = ListNode(val)
current?.next = node
current = current?.next
l1 = l1?.next
l2 = l2?.next
}
if flag == 1 {
current?.next = ListNode(1)
}
return head.next
}
/**
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
*/
func mergeTwoLists(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
guard l1 != nil && l2 != nil else { return l1 == nil ? l2 : l1 }
var temp1: ListNode? = l1
var temp2: ListNode? = l2
var root: ListNode?
if temp1?.val <= temp2?.val
{
root = temp1
temp1 = temp1?.next
}
else
{
root = temp2
temp2 = temp2?.next
}
var current: ListNode? = root
while temp1 != nil && temp2 != nil
{
if temp1!.val <= temp2!.val
{
current?.next = temp1
current = temp1
temp1 = temp1?.next
}
else
{
current?.next = temp2
current = temp2
temp2 = temp2?.next
}
}
if temp1 == nil
{
while temp2 != nil
{
current?.next = temp2
current = temp2
temp2 = current?.next
}
}
if temp2 == nil
{
while temp1 != nil
{
current?.next = temp1
current = temp1
temp1 = current?.next
}
}
return root
}
/**
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
*/
func swapPairs(head: ListNode?) -> ListNode? {
var newHead = head
var previous: ListNode? = nil
var current = newHead
while current?.next != nil
{
let next = current!.next!
current!.next = next.next
next.next = current
if previous != nil
{
previous!.next = next
}
else
{
newHead = next
}
previous = next.next
current = previous?.next
}
return newHead
}
/**
206. Reverse Linked List
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
func reverseListIterate(head: ListNode?) -> ListNode? {
var current: ListNode? = head
var next: ListNode? = current?.next
var previous: ListNode? = nil
while current != nil
{
current?.next = previous
previous = current
current = next
next = next?.next
}
return previous
}
// this is brilliant without looping first to get head
func reverseList(head: ListNode?) -> ListNode? {
guard head?.next != nil else { return head }
let current = head?.next
let newHead = reverseList(current)
head?.next = nil
current?.next = head
return newHead
}
/**
237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
*/
func deleteNode(inout node: ListNode?)
{
while node?.next != nil
{
node!.val = node!.next!.val
if node?.next?.next == nil
{
node!.next = nil // safe to unwrap it here
}
else
{
node = node!.next!
}
}
}
}
| mit | d9a8d5e05d7708e8351b30ffafb75aea | 26.253333 | 213 | 0.484018 | 4.472648 | false | false | false | false |
khizkhiz/swift | test/1_stdlib/NSObject.swift | 2 | 6970 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
//===----------------------------------------------------------------------===//
// NSObject ==
//===----------------------------------------------------------------------===//
func printEquality<T : Equatable>(lhs: T, _ rhs: T, _ lhsName: String, _ rhsName: String) {
if lhs == lhs {
print("\(lhsName) == \(lhsName)")
}
if lhs != lhs {
print("\(lhsName) != \(lhsName)")
}
if lhs == rhs {
print("\(lhsName) == \(rhsName)")
}
if lhs != rhs {
print("\(lhsName) != \(rhsName)")
}
}
func printIdentity(lhs: AnyObject, _ rhs: AnyObject, _ lhsName: String, _ rhsName: String) {
if lhs === lhs {
print("\(lhsName) === \(lhsName)")
}
if lhs !== lhs {
print("\(lhsName) !== \(lhsName)")
}
if lhs === rhs {
print("\(lhsName) === \(rhsName)")
}
if lhs !== rhs {
print("\(lhsName) !== \(rhsName)")
}
}
print("NoisyEqual ==")
class NoisyEqual : NSObject {
override func isEqual(rhs: AnyObject?) -> Bool {
print("wow much equal")
return super.isEqual(rhs)
}
}
let n1 = NoisyEqual.init()
let n2 = NoisyEqual.init()
printIdentity(n1, n2, "n1", "n2")
printEquality(n1, n2, "n1", "n2")
print("done NoisyEqual ==")
// CHECK: NoisyEqual ==
// CHECK-NEXT: n1 === n1
// CHECK-NEXT: n1 !== n2
// CHECK-NEXT: wow much equal
// CHECK-NEXT: n1 == n1
// CHECK-NEXT: wow much equal
// CHECK-NEXT: wow much equal
// CHECK-NEXT: wow much equal
// CHECK-NEXT: n1 != n2
// CHECK-NEXT: done NoisyEqual ==
print("NSObject ==")
let o1 = NSObject.init()
let o2 = NSObject.init()
printIdentity(o1, o2, "o1", "o2")
printEquality(o1, o2, "o1", "o2")
printIdentity(o1, 10, "o1", "10")
printEquality(o1, 10, "o1", "10")
printIdentity(10, o1, "10", "o1")
printEquality(10, o1, "10", "o1")
print("done NSObject ==")
// CHECK: NSObject ==
// CHECK-NEXT: o1 === o1
// CHECK-NEXT: o1 !== o2
// CHECK-NEXT: o1 == o1
// CHECK-NEXT: o1 != o2
// CHECK-NEXT: o1 === o1
// CHECK-NEXT: o1 !== 10
// CHECK-NEXT: o1 == o1
// CHECK-NEXT: o1 != 10
// CHECK-NEXT: 10 === 10
// CHECK-NEXT: 10 !== o1
// CHECK-NEXT: 10 == 10
// CHECK-NEXT: 10 != o1
// CHECK: done NSObject ==
print("NSMutableString ==")
let s1 = NSMutableString.init(string:"hazcam")
let s2 = NSMutableString.init(string:"hazcam")
printIdentity(s1, s2, "s1", "s2")
printEquality(s1, s2, "s1", "s2")
print("mutate")
s2.append("navcam")
printIdentity(s1, s2, "s1", "s2")
printEquality(s1, s2, "s1", "s2")
print("done NSMutableString ==")
// CHECK: NSMutableString ==
// CHECK-NEXT: s1 === s1
// CHECK-NEXT: s1 !== s2
// CHECK-NEXT: s1 == s1
// CHECK-NEXT: s1 == s2
// CHECK-NEXT: mutate
// CHECK-NEXT: s1 === s1
// CHECK-NEXT: s1 !== s2
// CHECK-NEXT: s1 == s1
// CHECK-NEXT: s1 != s2
// CHECK-NEXT: done NSMutableString ==
//===----------------------------------------------------------------------===//
// NSObject hashValue
//===----------------------------------------------------------------------===//
func printHashValue<T : Hashable>(x: T, _ name: String) {
print("\(name) hashes to \(x.hashValue)")
}
print("NSMutableString hashValue")
print("\(s1.hashValue)")
print("\(s1.hash)")
s1.append("pancam")
print("\(s1.hashValue)")
print("\(s1.hash)")
print("done NSMutableString hashValue")
// CHECK: NSMutableString hashValue
// CHECK-NEXT: [[H1:[0-9]+]]
// CHECK-NEXT: [[H1]]
// CHECK-NEXT: [[H2:[0-9]+]]
// CHECK-NEXT: [[H2]]
// CHECK-NEXT: done NSMutableString hashValue
class NoisyHash : NSObject {
override var hash : Int {
print("so hash")
return super.hash
}
}
print("NoisyHash hashValue")
let nh = NoisyHash.init()
printHashValue(nh, "nh")
print("done NoisyHash hashValue")
// CHECK: NoisyHash hashValue
// CHECK-NEXT: so hash
// CHECK-NEXT: nh hashes to {{[0-9]+}}
// CHECK: done NoisyHash hashValue
class ValueLike : NSObject {
var x: Int
init(int: Int) {
x = int
super.init()
}
override func isEqual(rhs: AnyObject?) -> Bool {
if let rhs2 = rhs as? ValueLike {
return x == rhs2.x
}
return false
}
override var hash : Int {
return x
}
}
print("ValueLike hashValue")
let sh1 = ValueLike.init(int:10)
let sh2 = ValueLike.init(int:20)
let sh3 = ValueLike.init(int:10)
printIdentity(sh1, sh2, "sh1", "sh2")
printIdentity(sh1, sh3, "sh1", "sh3")
printIdentity(sh2, sh3, "sh2", "sh3")
printEquality(sh1, sh2, "sh1", "sh2")
printEquality(sh1, sh3, "sh1", "sh3")
printEquality(sh2, sh3, "sh2", "sh3")
printEquality(sh1.hashValue, sh2.hashValue, "sh1 hash", "sh2 hash")
printEquality(sh1.hashValue, sh3.hashValue, "sh1 hash", "sh3 hash")
printEquality(sh2.hashValue, sh3.hashValue, "sh2 hash", "sh3 hash")
var dict = Dictionary<ValueLike, Int>()
dict[sh1] = sh1.x
dict[sh2] = sh2.x
print("sh1 \(dict[sh1]!)")
print("sh2 \(dict[sh2]!)")
print("sh3 \(dict[sh3]!)")
print("done ValueLike hashValue")
// CHECK: ValueLike hashValue
// CHECK-NEXT: sh1 === sh1
// CHECK-NEXT: sh1 !== sh2
// CHECK-NEXT: sh1 === sh1
// CHECK-NEXT: sh1 !== sh3
// CHECK-NEXT: sh2 === sh2
// CHECK-NEXT: sh2 !== sh3
// CHECK-NEXT: sh1 == sh1
// CHECK-NEXT: sh1 != sh2
// CHECK-NEXT: sh1 == sh1
// CHECK-NEXT: sh1 == sh3
// CHECK-NEXT: sh2 == sh2
// CHECK-NEXT: sh2 != sh3
// CHECK-NEXT: sh1 hash == sh1 hash
// CHECK-NEXT: sh1 hash != sh2 hash
// CHECK-NEXT: sh1 hash == sh1 hash
// CHECK-NEXT: sh1 hash == sh3 hash
// CHECK-NEXT: sh2 hash == sh2 hash
// CHECK-NEXT: sh2 hash != sh3 hash
// CHECK-NEXT: sh1 10
// CHECK-NEXT: sh2 20
// CHECK-NEXT: sh3 10
// CHECK-NEXT: done ValueLike hashValue
// Native Swift objects should not have nontrivial structors from ObjC's point
// of view.
class NativeSwift {}
class GenericNativeSwift<T> {}
var native: AnyObject = NativeSwift()
if native.responds(to: ".cxx_construct") {
print("SwiftObject has nontrivial constructor")
} else {
print("no nontrivial constructor") // CHECK-NEXT: no nontrivial constructor
}
if native.responds(to: ".cxx_destruct") {
print("SwiftObject has nontrivial destructor")
} else {
print("no nontrivial destructor") // CHECK-NEXT: no nontrivial destructor
}
native = GenericNativeSwift<Int>()
if native.responds(to: ".cxx_construct") {
print("SwiftObject has nontrivial constructor")
} else {
print("no nontrivial constructor") // CHECK-NEXT: no nontrivial constructor
}
if native.responds(to: ".cxx_destruct") {
print("SwiftObject has nontrivial destructor")
} else {
print("no nontrivial destructor") // CHECK-NEXT: no nontrivial destructor
}
class D : NSObject {}
print(D.self) // CHECK-NEXT: D
print(_getSuperclass(D.self) == NSObject.self) // CHECK-NEXT: true
print(_getSuperclass(_getSuperclass(D.self)!) == nil) // CHECK-NEXT: true
class E : NSString {}
print( // CHECK-NEXT: true
_getSuperclass(E.self) == NSString.self)
print( // CHECK-NEXT: true
_getSuperclass(_getSuperclass(E.self)!) == NSObject.self)
print( // CHECK-NEXT: true
_getSuperclass(_getSuperclass(_getSuperclass(E.self)!)!) == nil)
| apache-2.0 | 54ce12e8e2d3fab6eb25bcdd8bf5feea | 25.401515 | 92 | 0.612339 | 3.089539 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/01282-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 1 | 1680 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
s))
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
f
e)
func f<g>() -> (g, g -> g) -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}
class d: f{ class func i {}
enum S<T> {
case C(T, () -> ())
}
var x1 = 1
var f1: Int -> Int = {
return $0
}
let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in
return f(x)
}(x1, f1)
let crashes: Int = { x, f in
return f(x)
}(x1, f1)
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
func c<d {
enum c {
func e
var _ = e
}
}
protocol A {
}
struct B : A {
}
struct C<D, E: A where D.C == E> {
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
pealias e = a<c<h>, d>
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
struct A<T> {
let a: [(T, () -> ())] = []
}
func a<T>() {
enum b {
case c
}
}
func a(b: Int = 0) {
}
let c = a
c
| apache-2.0 | 883a20a5ebe60364cee2497f70e23d76 | 12.44 | 87 | 0.539881 | 2.295082 | false | false | false | false |
oleander/bitbar | Tests/PluginTests/RotatorTests.swift | 1 | 1857 | import Quick
import Nimble
import Parser
import Async
import Parser
import SharedTests
@testable import Plugin
class RotHost: Rotatable {
var result: [Text] = []
var rotator: Rotator!
init() {
rotator = Rotator(every: 1, delegate: self)
}
func rotator(didRotate text: Text) {
result.append(text)
}
func stop() {
rotator.stop()
}
func start() {
rotator.start()
}
func set(_ items: [Text]) {
try? rotator.set(text: items)
}
func deallocate() {
rotator = nil
}
}
class RotatorTests: QuickSpec {
override func spec() {
Nimble.AsyncDefaults.Timeout = 6
// Nimble.AsyncDefaults.PollInterval = 0.1
let text: [Text] = [.text1, .text2, .text3]
describe("non empty list") {
var host: RotHost!
beforeEach {
host = RotHost()
}
it("should handle a list of items") {
host.set(text)
expect(host.result).toEventually(cyclicSubset(of: text))
}
it("should stop updating") {
host.set(text)
host.stop()
expect(host.result).toEventually(equal([.text1]))
}
it("should be able to resume") {
host.set(text)
host.stop()
host.start()
expect(host.result).toEventually(cyclicSubset(of: text))
}
it("does not rotate if deallocated") {
host.set(text)
host.deallocate()
expect(host.result).toEventually(beEmpty())
}
it("restarts when reaching the end") {
host.set(text)
expect(host.result).toEventually(cyclicSubset(of: text + text))
}
it("does not rotate with one item") {
host.set([.text1])
waitUntil(timeout: 10) { done in
Async.main(after: 5) {
expect(host.result).to(cyclicSubset(of: [.text1]))
done()
}
}
}
}
}
}
| mit | a724b61a475a3401349a9df6662b3f0b | 19.406593 | 71 | 0.57189 | 3.66996 | false | false | false | false |
pjcau/LocalNotifications_Over_iOS10 | Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Math.swift | 1 | 6061 | // SwiftDate
// Manage Date/Time & Timezone in Swift
//
// Created by: Daniele Margutti
// Email: <[email protected]>
// Web: <http://www.danielemargutti.com>
//
// Licensed under MIT License.
import Foundation
// MARK: - DateInRegion Private Extension
extension DateInRegion {
/// Return a `DateComponent` object from a given set of `Calendar.Component` object with associated values and a specific region
///
/// - parameter values: calendar components to set (with their values)
/// - parameter multipler: optional multipler (by default is nil; to make an inverse component value it should be multipled by -1)
/// - parameter region: optional region to set
///
/// - returns: a `DateComponents` object
internal static func componentsFrom(values: [Calendar.Component : Int], multipler: Int? = nil, setRegion region: Region? = nil) -> DateComponents {
var cmps = DateComponents()
if region != nil {
cmps.calendar = region!.calendar
cmps.calendar!.locale = region!.locale
cmps.timeZone = region!.timeZone
}
values.forEach { pair in
if pair.key != .timeZone && pair.key != .calendar {
cmps.setValue( (multipler == nil ? pair.value : pair.value * multipler!), for: pair.key)
}
}
return cmps
}
/// Create a new DateInRegion by adding specified DateComponents to self.
/// If fails it return `nil`o object.
///
/// - Parameter dateComponents: date components to add
/// - Returns: a new instance of DateInRegion expressed in same region
public func add(components dateComponents: DateComponents) -> DateInRegion? {
let newDate = self.region.calendar.date(byAdding: dateComponents, to: self.absoluteDate)
if newDate == nil { return nil }
return DateInRegion(absoluteDate: newDate!, in: self.region)
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically.
///
/// - Parameters:
/// - startDate: starting date
/// - endDate: ending date
/// - components: components to add
/// - normalize: normalize both start and end date at the start of the specified component (if nil, normalization is skipped)
/// - Returns: an array of DateInRegion objects
public static func dates(between startDate: DateInRegion, and endDate: DateInRegion, increment components: DateComponents) -> [DateInRegion]? {
guard startDate.region.calendar == endDate.region.calendar else {
return nil
}
var dates: [DateInRegion] = []
var currentDate = startDate
while (currentDate <= endDate) {
dates.append(currentDate)
guard let c_date = currentDate.add(components: components) else {
return nil
}
currentDate = c_date
}
return dates
}
/// Adjust time of the date by rounding to the next `value` interval.
/// Interval can be `seconds` or `minutes` and you can specify the type of rounding function to use.
///
/// - Parameters:
/// - value: value to round
/// - type: type of rounding
public func roundAt(_ value: IntervalType, type: IntervalRoundingType = .ceil) {
var roundedInterval: TimeInterval = 0
let rounded_abs_date = self.absoluteDate
let seconds = value.seconds
switch type {
case .round:
roundedInterval = (rounded_abs_date.timeIntervalSinceReferenceDate / seconds).rounded() * seconds
case .ceil:
roundedInterval = ceil(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds
case .floor:
roundedInterval = floor(rounded_abs_date.timeIntervalSinceReferenceDate / seconds) * seconds
}
self.absoluteDate = Date(timeIntervalSinceReferenceDate: roundedInterval)
}
/// Return the difference between two dates expressed using passed time components.
///
/// - Parameters:
/// - components: time units to get
/// - refDate: reference date
/// - calendar: calendar to use, `nil` to user `Date.defaultRegion.calendar`
/// - Returns: components dictionary
// #NEW
public func components(_ components: [Calendar.Component], to refDate: DateInRegion) -> [Calendar.Component : Int] {
guard self.region.calendar == refDate.region.calendar else {
debugPrint("[SwiftDate] Date must have the same calendar")
return [:]
}
let cmps = self.region.calendar.dateComponents(componentsToSet(components), from: self.absoluteDate, to: refDate.absoluteDate)
return cmps.toComponentsDict()
}
/// Return the difference between two dates expressed in passed time unit.
/// This operation take care of the calendar in which dates are expressed (must be equal) differently
/// from the TimeInterval `in` function
///
/// - Parameters:
/// - component: component to get
/// - refDate: reference date
/// - Returns: difference expressed in given component
public func component(_ component: Calendar.Component, to refDate: DateInRegion) -> Int? {
return self.components([component], to: refDate)[component]
}
}
// MARK: - DateInRegion Support for math operation
// These functions allows us to make something like
// `let newDate = (date - 3.days + 3.months)`
// We can sum algebrically a `DateInRegion` object with a calendar component.
public func + (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
let nextDate = lhs.region.calendar.date(byAdding: rhs, to: lhs.absoluteDate)
return DateInRegion(absoluteDate: nextDate!, in: lhs.region)
}
public func - (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
return lhs + (-rhs)
}
public func + (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
let cmps = DateInRegion.componentsFrom(values: rhs)
return lhs + cmps
}
public func - (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
var invertedCmps: [Calendar.Component : Int] = [:]
rhs.forEach { invertedCmps[$0.key] = -$0.value }
return lhs + invertedCmps
}
public func - (lhs: DateInRegion, rhs: DateInRegion) -> TimeInterval {
return DateTimeInterval(start: rhs.absoluteDate, end: lhs.absoluteDate).duration
}
| mit | 387ab9267ef8815370c5570c0504cd54 | 36.407407 | 148 | 0.716502 | 3.965969 | false | false | false | false |
danielgindi/Charts | Source/Charts/Utils/ViewPortHandler.swift | 2 | 15895 | //
// ViewPortHandler.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Class that contains information about the charts current viewport settings, including offsets, scale & translation levels, ...
@objc(ChartViewPortHandler)
open class ViewPortHandler: NSObject
{
/// matrix used for touch events
@objc open private(set) var touchMatrix = CGAffineTransform.identity
/// this rectangle defines the area in which graph values can be drawn
@objc open private(set) var contentRect = CGRect()
@objc open private(set) var chartWidth: CGFloat = 0
@objc open private(set) var chartHeight: CGFloat = 0
/// minimum scale value on the y-axis
@objc open private(set) var minScaleY: CGFloat = 1.0
/// maximum scale value on the y-axis
@objc open private(set) var maxScaleY = CGFloat.greatestFiniteMagnitude
/// minimum scale value on the x-axis
@objc open private(set) var minScaleX: CGFloat = 1.0
/// maximum scale value on the x-axis
@objc open private(set) var maxScaleX = CGFloat.greatestFiniteMagnitude
/// contains the current scale factor of the x-axis
@objc open private(set) var scaleX: CGFloat = 1.0
/// contains the current scale factor of the y-axis
@objc open private(set) var scaleY: CGFloat = 1.0
/// current translation (drag / pan) distance on the x-axis
@objc open private(set) var transX: CGFloat = 0
/// current translation (drag / pan) distance on the y-axis
@objc open private(set) var transY: CGFloat = 0
/// offset that allows the chart to be dragged over its bounds on the x-axis
private var transOffsetX: CGFloat = 0
/// offset that allows the chart to be dragged over its bounds on the x-axis
private var transOffsetY: CGFloat = 0
/// Constructor - don't forget calling setChartDimens(...)
@objc public init(width: CGFloat, height: CGFloat)
{
super.init()
setChartDimens(width: width, height: height)
}
@objc open func setChartDimens(width: CGFloat, height: CGFloat)
{
let offsetLeft = self.offsetLeft
let offsetTop = self.offsetTop
let offsetRight = self.offsetRight
let offsetBottom = self.offsetBottom
chartHeight = height
chartWidth = width
restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom)
}
@objc open var hasChartDimens: Bool
{
return chartHeight > 0.0
&& chartWidth > 0.0
}
@objc open func restrainViewPort(offsetLeft: CGFloat, offsetTop: CGFloat, offsetRight: CGFloat, offsetBottom: CGFloat)
{
contentRect.origin.x = offsetLeft
contentRect.origin.y = offsetTop
contentRect.size.width = chartWidth - offsetLeft - offsetRight
contentRect.size.height = chartHeight - offsetBottom - offsetTop
}
@objc open var offsetLeft: CGFloat
{
return contentRect.origin.x
}
@objc open var offsetRight: CGFloat
{
return chartWidth - contentRect.size.width - contentRect.origin.x
}
@objc open var offsetTop: CGFloat
{
return contentRect.origin.y
}
@objc open var offsetBottom: CGFloat
{
return chartHeight - contentRect.size.height - contentRect.origin.y
}
@objc open var contentTop: CGFloat
{
return contentRect.origin.y
}
@objc open var contentLeft: CGFloat
{
return contentRect.origin.x
}
@objc open var contentRight: CGFloat
{
return contentRect.origin.x + contentRect.size.width
}
@objc open var contentBottom: CGFloat
{
return contentRect.origin.y + contentRect.size.height
}
@objc open var contentWidth: CGFloat
{
return contentRect.size.width
}
@objc open var contentHeight: CGFloat
{
return contentRect.size.height
}
@objc open var contentCenter: CGPoint
{
return CGPoint(x: contentRect.origin.x + contentRect.size.width / 2.0, y: contentRect.origin.y + contentRect.size.height / 2.0)
}
// MARK: - Scaling/Panning etc.
/// Zooms by the specified zoom factors.
@objc open func zoom(scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform
{
return touchMatrix.scaledBy(x: scaleX, y: scaleY)
}
/// Zooms around the specified center
@objc open func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) -> CGAffineTransform
{
return touchMatrix.translatedBy(x: x, y: y)
.scaledBy(x: scaleX, y: scaleY)
.translatedBy(x: -x, y: -y)
}
/// Zooms in by 1.4, x and y are the coordinates (in pixels) of the zoom center.
@objc open func zoomIn(x: CGFloat, y: CGFloat) -> CGAffineTransform
{
return zoom(scaleX: 1.4, scaleY: 1.4, x: x, y: y)
}
/// Zooms out by 0.7, x and y are the coordinates (in pixels) of the zoom center.
@objc open func zoomOut(x: CGFloat, y: CGFloat) -> CGAffineTransform
{
return zoom(scaleX: 0.7, scaleY: 0.7, x: x, y: y)
}
/// Zooms out to original size.
@objc open func resetZoom() -> CGAffineTransform
{
return zoom(scaleX: 1.0, scaleY: 1.0, x: 0.0, y: 0.0)
}
/// Sets the scale factor to the specified values.
@objc open func setZoom(scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform
{
var matrix = touchMatrix
matrix.a = scaleX
matrix.d = scaleY
return matrix
}
/// Sets the scale factor to the specified values. x and y is pivot.
@objc open func setZoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) -> CGAffineTransform
{
var matrix = touchMatrix
matrix.a = 1.0
matrix.d = 1.0
matrix = matrix.translatedBy(x: x, y: y)
.scaledBy(x: scaleX, y: scaleY)
.translatedBy(x: -x, y: -y)
return matrix
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
@objc open func fitScreen() -> CGAffineTransform
{
minScaleX = 1.0
minScaleY = 1.0
return .identity
}
/// Translates to the specified point.
@objc open func translate(pt: CGPoint) -> CGAffineTransform
{
let translateX = pt.x - offsetLeft
let translateY = pt.y - offsetTop
let matrix = touchMatrix.concatenating(CGAffineTransform(translationX: -translateX, y: -translateY))
return matrix
}
/// Centers the viewport around the specified position (x-index and y-value) in the chart.
/// Centering the viewport outside the bounds of the chart is not possible.
/// Makes most sense in combination with the setScaleMinima(...) method.
@objc open func centerViewPort(pt: CGPoint, chart: ChartViewBase)
{
let translateX = pt.x - offsetLeft
let translateY = pt.y - offsetTop
let matrix = touchMatrix.concatenating(CGAffineTransform(translationX: -translateX, y: -translateY))
refresh(newMatrix: matrix, chart: chart, invalidate: true)
}
/// call this method to refresh the graph with a given matrix
@objc @discardableResult open func refresh(newMatrix: CGAffineTransform, chart: ChartViewBase, invalidate: Bool) -> CGAffineTransform
{
touchMatrix = newMatrix
// make sure scale and translation are within their bounds
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
chart.setNeedsDisplay()
return touchMatrix
}
/// limits the maximum scale and X translation of the given matrix
private func limitTransAndScale(matrix: inout CGAffineTransform, content: CGRect)
{
// min scale-x is 1
scaleX = min(max(minScaleX, matrix.a), maxScaleX)
// min scale-y is 1
scaleY = min(max(minScaleY, matrix.d), maxScaleY)
let width = content.width
let height = content.height
let maxTransX = -width * (scaleX - 1.0)
transX = min(max(matrix.tx, maxTransX - transOffsetX), transOffsetX)
let maxTransY = height * (scaleY - 1.0)
transY = max(min(matrix.ty, maxTransY + transOffsetY), -transOffsetY)
matrix.tx = transX
matrix.a = scaleX
matrix.ty = transY
matrix.d = scaleY
}
/// Sets the minimum scale factor for the x-axis
@objc open func setMinimumScaleX(_ xScale: CGFloat)
{
minScaleX = max(xScale, 1)
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
/// Sets the maximum scale factor for the x-axis
@objc open func setMaximumScaleX(_ xScale: CGFloat)
{
maxScaleX = xScale == 0 ? .greatestFiniteMagnitude : xScale
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
/// Sets the minimum and maximum scale factors for the x-axis
@objc open func setMinMaxScaleX(minScaleX: CGFloat, maxScaleX: CGFloat)
{
self.minScaleX = max(minScaleX, 1)
self.maxScaleX = maxScaleX == 0 ? .greatestFiniteMagnitude : maxScaleX
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
/// Sets the minimum scale factor for the y-axis
@objc open func setMinimumScaleY(_ yScale: CGFloat)
{
minScaleY = max(yScale, 1)
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
/// Sets the maximum scale factor for the y-axis
@objc open func setMaximumScaleY(_ yScale: CGFloat)
{
maxScaleY = yScale == 0 ? .greatestFiniteMagnitude : yScale
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
@objc open func setMinMaxScaleY(minScaleY: CGFloat, maxScaleY: CGFloat)
{
self.minScaleY = max(minScaleY, 1)
self.maxScaleY = maxScaleY == 0 ? .greatestFiniteMagnitude : maxScaleY
limitTransAndScale(matrix: &touchMatrix, content: contentRect)
}
// MARK: - Boundaries Check
@objc open func isInBoundsX(_ x: CGFloat) -> Bool
{
return isInBoundsLeft(x) && isInBoundsRight(x)
}
@objc open func isInBoundsY(_ y: CGFloat) -> Bool
{
return isInBoundsTop(y) && isInBoundsBottom(y)
}
/**
A method to check whether coordinate lies within the viewport.
- Parameters:
- point: a coordinate.
*/
@objc open func isInBounds(point: CGPoint) -> Bool
{
return isInBounds(x: point.x, y: point.y)
}
@objc open func isInBounds(x: CGFloat, y: CGFloat) -> Bool
{
return isInBoundsX(x) && isInBoundsY(y)
}
@objc open func isInBoundsLeft(_ x: CGFloat) -> Bool
{
return contentRect.origin.x <= x + 1.0
}
@objc open func isInBoundsRight(_ x: CGFloat) -> Bool
{
let x = floor(x * 100.0) / 100.0
return (contentRect.origin.x + contentRect.size.width) >= x - 1.0
}
@objc open func isInBoundsTop(_ y: CGFloat) -> Bool
{
return contentRect.origin.y <= y
}
@objc open func isInBoundsBottom(_ y: CGFloat) -> Bool
{
let normalizedY = floor(y * 100.0) / 100.0
return (contentRect.origin.y + contentRect.size.height) >= normalizedY
}
/**
A method to check whether a line between two coordinates intersects with the view port by using a linear function.
Linear function (calculus): `y = ax + b`
Note: this method will not check for collision with the right edge of the view port, as we assume lines run from left
to right (e.g. `startPoint < endPoint`).
- Parameters:
- startPoint: the start coordinate of the line.
- endPoint: the end coordinate of the line.
*/
@objc open func isIntersectingLine(from startPoint: CGPoint, to endPoint: CGPoint) -> Bool
{
// If start- and/or endpoint fall within the viewport, bail out early.
if isInBounds(point: startPoint) || isInBounds(point: endPoint) { return true }
// check if x in bound when it's a vertical line
if startPoint.x == endPoint.x { return isInBoundsX(startPoint.x) }
// Calculate the slope (`a`) of the line (e.g. `a = (y2 - y1) / (x2 - x1)`).
let a = (endPoint.y - startPoint.y) / (endPoint.x - startPoint.x)
// Calculate the y-correction (`b`) of the line (e.g. `b = y1 - (a * x1)`).
let b = startPoint.y - (a * startPoint.x)
// Check for colission with the left edge of the view port (e.g. `y = (a * minX) + b`).
// if a is 0, it's a horizontal line; checking b here is still valid, as b is `point.y` all the time
if isInBoundsY((a * contentRect.minX) + b) { return true }
// Skip unnecessary check for collision with the right edge of the view port
// (e.g. `y = (a * maxX) + b`), as such a line will either begin inside the view port,
// or intersect the left, top or bottom edges of the view port. Leaving this logic here for clarity's sake:
// if isInBoundsY((a * contentRect.maxX) + b) { return true }
// While slope `a` can theoretically never be `0`, we should protect against division by zero.
guard a != 0 else { return false }
// Check for collision with the bottom edge of the view port (e.g. `x = (maxY - b) / a`).
if isInBoundsX((contentRect.maxY - b) / a) { return true }
// Check for collision with the top edge of the view port (e.g. `x = (minY - b) / a`).
if isInBoundsX((contentRect.minY - b) / a) { return true }
// This line does not intersect the view port.
return false
}
/// if the chart is fully zoomed out, return true
@objc open var isFullyZoomedOut: Bool
{
return isFullyZoomedOutX && isFullyZoomedOutY
}
/// `true` if the chart is fully zoomed out on it's y-axis (vertical).
@objc open var isFullyZoomedOutY: Bool
{
return !(scaleY > minScaleY || minScaleY > 1.0)
}
/// `true` if the chart is fully zoomed out on it's x-axis (horizontal).
@objc open var isFullyZoomedOutX: Bool
{
return !(scaleX > minScaleX || minScaleX > 1.0)
}
/// Set an offset in pixels that allows the user to drag the chart over it's bounds on the x-axis.
@objc open func setDragOffsetX(_ offset: CGFloat)
{
transOffsetX = offset
}
/// Set an offset in pixels that allows the user to drag the chart over it's bounds on the y-axis.
@objc open func setDragOffsetY(_ offset: CGFloat)
{
transOffsetY = offset
}
/// `true` if both drag offsets (x and y) are zero or smaller.
@objc open var hasNoDragOffset: Bool
{
return transOffsetX <= 0.0 && transOffsetY <= 0.0
}
/// `true` if the chart is not yet fully zoomed out on the x-axis
@objc open var canZoomOutMoreX: Bool
{
return scaleX > minScaleX
}
/// `true` if the chart is not yet fully zoomed in on the x-axis
@objc open var canZoomInMoreX: Bool
{
return scaleX < maxScaleX
}
/// `true` if the chart is not yet fully zoomed out on the y-axis
@objc open var canZoomOutMoreY: Bool
{
return scaleY > minScaleY
}
/// `true` if the chart is not yet fully zoomed in on the y-axis
@objc open var canZoomInMoreY: Bool
{
return scaleY < maxScaleY
}
}
| apache-2.0 | b3a4820015947195cd0942cf87db120b | 32.747346 | 137 | 0.623844 | 4.256829 | false | false | false | false |
dcunited001/SpectraNu | Spectra/SpectraXML/NodesSpec.swift | 1 | 15595 | //
// NodesSpec.swift
//
//
// Created by David Conner on 3/10/16.
//
//
@testable import Spectra
import Quick
import Nimble
import Fuzi
import Swinject
import ModelIO
class SpectraNodeSpec: QuickSpec {
override func spec() {
let parsedEnums = Container()
let spectraEnumXSD = SpectraXSD.readXSD("SpectraEnums")!
let spectraXSD = SpectraXSD()
spectraXSD.parseXSD(spectraEnumXSD, container: parsedEnums)
let parsedNodes = Container(parent: parsedEnums)
let testBundle = NSBundle(forClass: SpectraNodeSpec.self)
let spectraParser = SpectraParser(nodes: parsedNodes)
let spectraXML = SpectraParser.readXML(testBundle, filename: "SpectraXMLSpec", bundleResourceName: nil)!
spectraParser.parseXML(spectraXML)
describe("VertexAttribute") {
let attrPos = spectraParser.getVertexAttribute("pos_float4")!
let attrTex = spectraParser.getVertexAttribute("tex_float2")!
let attrRgb = spectraParser.getVertexAttribute("rgb_float4")!
let attrRgbInt = spectraParser.getVertexAttribute("rgb_int4")!
let attrAniso = spectraParser.getVertexAttribute("aniso_float4")!
let attrCustomLabel = spectraParser.getVertexAttribute("test_custom_label")!
let attrImmutable = spectraParser.getVertexAttribute("test_immutable")!
it("can parse vertex attribute nodes") {
// for now, deferring assignment of bufferIndex and offset to MDLVertexDescriptor
expect(attrPos.name) == MDLVertexAttributePosition
expect(attrTex.name) == MDLVertexAttributeTextureCoordinate
expect(attrRgb.name) == MDLVertexAttributeColor
expect(attrAniso.name) == MDLVertexAttributeAnisotropy
}
it("can create attributes with custom labels") {
expect(attrCustomLabel.name) == "custom"
}
it("reads the correct MDLVertexFormat") {
expect(attrPos.format) == MDLVertexFormat.Float4
expect(attrTex.format) == MDLVertexFormat.Float2
expect(attrRgb.format) == MDLVertexFormat.Float4
expect(attrRgbInt.format) == MDLVertexFormat.Int4
expect(attrAniso.format) == MDLVertexFormat.Float4
expect(attrImmutable.format) == MDLVertexFormat.Int
}
// TODO: decide on whether copies should be immutable
// it("retains immutable copies which are not changed") {
// let origIndex = attrImmutable.bufferIndex
// attrImmutable.bufferIndex = origIndex + 1
// let attrImmutable2 = spectraParser.getVertexAttribute("test_immutable")!
// expect(attrImmutable.bufferIndex) != attrImmutable2.bufferIndex
// expect(attrImmutable2.bufferIndex) == origIndex
// }
}
describe("VertexDescriptor") {
let attrPos = spectraParser.getVertexAttribute("pos_float4")!
let attrTex = spectraParser.getVertexAttribute("tex_float2")!
let vertDescPosTex = spectraParser.getVertexDescriptor("vert_pos_tex_float")!
let vertDescPosRgb = spectraParser.getVertexDescriptor("vert_pos_rgb_float")!
it("can parse vertex descriptor with references to vertex attributes") {
let pos1 = vertDescPosTex.attributes[0]
let tex1 = vertDescPosTex.attributes[1]
let pos2 = vertDescPosRgb.attributes[0]
let rgb2 = vertDescPosRgb.attributes[1]
expect(pos1.format) == MDLVertexFormat.Float4
expect(tex1.format) == MDLVertexFormat.Float2
expect(pos2.format) == MDLVertexFormat.Float4
expect(rgb2.format) == MDLVertexFormat.Int4
expect(vertDescPosTex.attributes[0].name) == "position"
expect(vertDescPosTex.attributes[1].name) == "textureCoordinate"
expect(vertDescPosRgb.attributes[0].name) == "position"
expect(vertDescPosRgb.attributes[1].name) == "color"
}
it("can parse a descriptor with a packed array-of-struct indexing") {
let packedDescNode = spectraParser.getVertexDescriptor("vertdesc_packed")!
let packedDesc = packedDescNode.generate()
let pos = packedDesc.attributeNamed("position")!
let tex = packedDesc.attributeNamed("textureCoordinate")!
let aniso = packedDesc.attributeNamed("anisotropy")!
expect(pos.format) == MDLVertexFormat.Float4
expect(tex.format) == MDLVertexFormat.Float2
expect(aniso.format) == MDLVertexFormat.Float4
expect(pos.offset) == 0
expect(tex.offset) == 16
expect(aniso.offset) == 24
expect(pos.bufferIndex) == 0
expect(tex.bufferIndex) == 0
expect(aniso.bufferIndex) == 0
}
it("can parse a descriptor with an unpacked struct-of-array indexing (each attribute has a buffer)") {
let unpackedDescNode = spectraParser.getVertexDescriptor("vertdesc_unpacked")!
let unpackedDesc = unpackedDescNode.generate()
let pos = unpackedDesc.attributeNamed("position")!
let tex = unpackedDesc.attributeNamed("textureCoordinate")!
let aniso = unpackedDesc.attributeNamed("anisotropy")!
expect(pos.format) == MDLVertexFormat.Float4
expect(tex.format) == MDLVertexFormat.Float2
expect(aniso.format) == MDLVertexFormat.Float4
expect(pos.offset) == 0
expect(tex.offset) == 0
expect(aniso.offset) == 0
expect(pos.bufferIndex) == 0
expect(tex.bufferIndex) == 1
expect(aniso.bufferIndex) == 2
}
it("can parse a more complex layout") {
let complexDescNode = spectraParser.getVertexDescriptor("vertdesc_complex")!
let complexDesc = complexDescNode.generate()
let pos = complexDesc.attributeNamed("position")!
let tex = complexDesc.attributeNamed("textureCoordinate")!
let aniso = complexDesc.attributeNamed("anisotropy")!
let rgb = complexDesc.attributeNamed("color")!
expect(pos.format) == MDLVertexFormat.Float4
expect(tex.format) == MDLVertexFormat.Float2
expect(aniso.format) == MDLVertexFormat.Float4
expect(rgb.format) == MDLVertexFormat.Float4
expect(pos.offset) == 0
expect(tex.offset) == 0
expect(aniso.offset) == 8
expect(rgb.offset) == 0
expect(pos.bufferIndex) == 0
expect(tex.bufferIndex) == 1
expect(aniso.bufferIndex) == 1
expect(rgb.bufferIndex) == 2
}
}
describe("Transform") {
let xformTranslate = spectraParser.getTransform("xform_translate")!
let xformRotate = spectraParser.getTransform("xform_rotate")!
let xformScale = spectraParser.getTransform("xform_scale")!
let xformShear = spectraParser.getTransform("xform_shear")!
// let xformCompose1: MDLTransform = spectraParser.getTransform("xform_compose1")!
// let xformCompose2: MDLTransform = spectraParser.getTransform("xform_compose2")!
it("parses translation/rotation/scale/shear") {
//TODO: rotation with degrees
expect(SpectraSimd.compareFloat3(xformTranslate.translation, with: float3(10.0, 20.0, 30.0))).to(beTrue())
expect(SpectraSimd.compareFloat3(xformRotate.rotation, with: float3(0.25, 0.50, 1.0))).to(beTrue())
expect(SpectraSimd.compareFloat3(xformScale.scale, with: float3(2.0, 2.0, 2.0))).to(beTrue())
expect(SpectraSimd.compareFloat3(xformShear.shear, with: float3(10.0, 10.0, 1.0))).to(beTrue())
}
pending("correctly composes multiple operations") {
// check that translate/rotate/scale/shear is calculated correctly when composed
}
}
describe("Camera") {
let lens1 = spectraParser.getPhysicalLens("lens1")!
let lens2 = spectraParser.getPhysicalLens("lens2")!
let lens3 = spectraParser.getPhysicalLens("lens3")!
let physImg1 = spectraParser.getPhysicalImagingSurface("phys_img1")!
let physImg2 = spectraParser.getPhysicalImagingSurface("phys_img2")!
// camera with defaults
// camera with lens applied
// camera with physImg applied
// camera with lookAt applied
let defaultCam = spectraParser.getCamera("default")!
let cam1 = spectraParser.getCamera("cam1")!
let cam2 = spectraParser.getCamera("cam2")!
let cam3 = spectraParser.getCamera("cam3")!
let cam4 = spectraParser.getCamera("cam4")!
let defaultStereoCam = spectraParser.getStereoscopicCamera("default")!
let stereoCam1 = spectraParser.getStereoscopicCamera("stereo_cam1")!
let stereoCam2 = spectraParser.getStereoscopicCamera("stereo_cam2")!
describe("PhysicalLens") {
it("can specify Physical Lens parameters") {
expect(lens1.barrelDistortion) == 0.1
expect(lens1.fisheyeDistortion) == 0.5
expect(lens2.focalLength) == 77.0
expect(lens2.fStop) == 7.0
expect(lens2.maximumCircleOfConfusion) == 0.10
expect(lens3.apertureBladeCount) == 7
}
}
describe("PhysicalImagingSurface") {
it("can specify Physical Imaging Surface parameters") {
expect(physImg1.sensorVerticalAperture) == 24
expect(physImg1.sensorAspect) == 2.0
let expectedFlash = float3([0.1, 0.1, 0.1])
let expectedExposure = float3([1.5, 1.5, 1.5])
expect(SpectraSimd.compareFloat3(physImg2.flash!, with: float3([0.1, 0.1, 0.1]))).to(beTrue())
expect(SpectraSimd.compareFloat3(physImg2.exposure!, with: float3([1.5, 1.5, 1.5]))).to(beTrue())
}
}
describe("Camera") {
it("manages the inherited MDLObject properties") {
// transform
// parent
}
it("loads default values") {
expect(defaultCam.nearVisibilityDistance) == 0.1
expect(defaultCam.farVisibilityDistance) == 1000.0
expect(defaultCam.fieldOfView) == Float(53.999996185302734375)
}
it("is created with near-visibility-distance, far-visibility-distance and field-of-view") {
// these are required and produce a corresponding projection matrix (formerly perspective)
}
it("can be set to look at a position and look from a position") {
// look-at (and optionally look-from)
}
it("can have a transform attached to it") {
}
}
describe("StereoscopicCamera") {
it("loads default values") {
expect(defaultStereoCam.nearVisibilityDistance) == 0.1
expect(defaultStereoCam.farVisibilityDistance) == 1000.0
expect(defaultStereoCam.fieldOfView) == Float(53.999996185302734375)
// TODO: default stereo values
expect(defaultStereoCam.interPupillaryDistance) == 63.0
expect(defaultStereoCam.leftVergence) == 0.0
expect(defaultStereoCam.rightVergence) == 0.0
expect(defaultStereoCam.overlap) == 0.0
}
it("is created by additionally specifying interPupillaryDistance, overlap & left/right vergence") {
}
// it can attach a physical-lens
// it can attach a physical-imaging-surface
}
}
describe("Texture") {
}
describe("TextureFilter") {
let wrapClamp = MDLMaterialTextureWrapMode.Clamp
let wrapRepeat = MDLMaterialTextureWrapMode.Repeat
let wrapMirror = MDLMaterialTextureWrapMode.Mirror
let linear = MDLMaterialTextureFilterMode.Linear
let nearest = MDLMaterialTextureFilterMode.Nearest
let mipmapLinear = MDLMaterialMipMapFilterMode.Linear
let mipmapNearest = MDLMaterialMipMapFilterMode.Nearest
it("parses the correct defaults") {
let defaultFilter = spectraParser.getTextureFilter("default")!
expect(defaultFilter.rWrapMode) == wrapClamp
expect(defaultFilter.tWrapMode) == wrapClamp
expect(defaultFilter.sWrapMode) == wrapClamp
}
it("parses other texture filters") {
let filterClamp = spectraParser.getTextureFilter("filter_clamp")!
let filterRepeat = spectraParser.getTextureFilter("filter_repeat")!
let filterMirror = spectraParser.getTextureFilter("filter_mirror")!
let filterLinear = spectraParser.getTextureFilter("filter_linear")!
let filterNearest = spectraParser.getTextureFilter("filter_nearest")!
expect(filterClamp.rWrapMode) == wrapClamp
expect(filterClamp.tWrapMode) == wrapClamp
expect(filterClamp.sWrapMode) == wrapClamp
expect(filterRepeat.rWrapMode) == wrapRepeat
expect(filterRepeat.tWrapMode) == wrapRepeat
expect(filterRepeat.sWrapMode) == wrapRepeat
expect(filterMirror.rWrapMode) == wrapMirror
expect(filterMirror.tWrapMode) == wrapMirror
expect(filterMirror.sWrapMode) == wrapMirror
expect(filterLinear.minFilter) == linear
expect(filterLinear.magFilter) == linear
expect(filterLinear.mipFilter) == mipmapLinear
expect(filterNearest.minFilter) == nearest
expect(filterNearest.magFilter) == nearest
expect(filterNearest.mipFilter) == mipmapNearest
}
it("generates a MDLTextureFilter") {
}
}
describe("TextureSampler") {
// texture: MDLTexture
// hardwareFilter: MDLTextureFilter
// transform: MDLTransform (translate/scale/rotate textures relative to their surfaces)
// TODO: MDLTextureSampler => MTLTextureSampler
it("parses texture samplers") {
}
it("generates a MDLTextureSampler") {
}
}
}
} | mit | 148bad465b7796063e1dd3b918cf4603 | 43.181303 | 122 | 0.577365 | 4.78521 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.