repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mightydeveloper/swift | test/Serialization/Inputs/def_class.swift | 10 | 3395 | public class Empty {}
public class TwoInts {
public var x, y : Int
required public init(a : Int, b : Int) {
x = a
y = b
}
}
public class ComputedProperty {
public var value : Int {
get {
var result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
public var readOnly : Int {
return 42
}
public init() {}
}
// Generics
public class Pair<A, B> {
public var first : A
public var second : B
public init(a : A, b : B) {
first = a
second = b
}
}
public class GenericCtor<U> {
public init<T>(_ t : T) {}
public func doSomething<T>(t : T) {}
}
// Protocols
public protocol Resettable {
func reset()
}
public extension Resettable {
final func doReset() { self.reset() }
}
public class ResettableIntWrapper : Resettable {
public var value : Int
public init() { value = 0 }
public func reset() {
var zero = 0
value = zero
}
}
public protocol Computable {
func compute()
}
public typealias Cacheable = protocol<Resettable, Computable>
public protocol SpecialResettable : Resettable, Computable {}
public protocol PairLike {
typealias FirstType
typealias SecondType
func getFirst() -> FirstType
func getSecond() -> SecondType
}
public extension PairLike where FirstType : Cacheable {
final func cacheFirst() { }
}
public protocol ClassProto : class {}
@objc public protocol ObjCProtoWithOptional {
optional func optionalMethod()
optional var optionalVar: Int { get }
optional subscript (i: Int) -> Int { get }
}
public class OptionalImplementer : ObjCProtoWithOptional {
public func unrelated() {}
public init() {}
}
// Inheritance
public class StillEmpty : Empty, Resettable {
public func reset() {}
public override init() {}
}
public class BoolPair<T> : Pair<Bool, Bool>, PairLike {
public init() { super.init(a: false, b: false) }
public func bothTrue() -> Bool {
return first && second
}
public func getFirst() -> Bool { return first }
public func getSecond() -> Bool { return second }
}
public class SpecialPair<A> : Pair<Int, Int>, Computable {
public func compute() {}
}
public class OtherPair<A, B> : PairLike {
public var first : A
public var second : B
public init(a : A, b : B) {
first = a
second = b
}
public typealias FirstType = Bool
public typealias SecondType = Bool
public func getFirst() -> Bool { return true }
public func getSecond() -> Bool { return true }
}
public class OtherBoolPair<T> : OtherPair<Bool, Bool> {
}
public class RequiresPairLike<P : PairLike> { }
public func getReqPairLike() -> RequiresPairLike<OtherBoolPair<Bool>> {
return RequiresPairLike<OtherBoolPair<Bool>>()
}
// Subscripts
public class ReadonlySimpleSubscript {
public subscript(x : Int) -> Bool {
return true
}
public init() {}
}
public class ComplexSubscript {
public subscript(x : Int, y : Bool) -> Int {
set(newValue) {
// do nothing!
}
get {
return 0
}
}
public init() {}
}
// Destructor
public class Resource {
public init() { }
deinit {}
}
// Ownership
public class ResourceSharer {
// FIXME: Cannot perform in-class initialization here
public unowned var alwaysPresent : Resource
public weak var maybePresent : Resource?
public init (res: Resource) {
self.alwaysPresent = res
self.maybePresent = nil
}
}
| apache-2.0 | 719cfde0b7e984e1e94c8e61a255a0c2 | 17.351351 | 72 | 0.654786 | 3.810325 | false | false | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/Filters/Twirl.swift | 2 | 2510 | // Copyright © 2014 C4
//
// 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 CoreImage
/// Rotates pixels around a point to give a twirling effect.
///
/// ````
/// let logo = Image("logo")
/// logo.apply(Twirl())
/// canvas.add(logo)
/// ````
public struct Twirl: Filter {
/// The name of the Core Image filter.
public let filterName = "CITwirlDistortion"
/// The center of the twirl effet. Defaults to {0,0}
public var center: Point = Point()
/// The radius of the twirl effect. Defaults to 100.0
public var radius: Double = 100.0
/// The angle of the twirl effect. Defaults to 𝞹
public var angle: Double = M_PI
///Initializes a new filter
public init() {}
/// Applies the properties of the receiver to create a new CIFilter object
///
/// - parameter inputImage: The image to use as input to the filter.
/// - returns: The new CIFilter object.
public func createCoreImageFilter(_ inputImage: CIImage) -> CIFilter {
let filter = CIFilter(name: filterName)!
filter.setDefaults()
filter.setValue(radius, forKey:"inputRadius")
filter.setValue(angle, forKey:"inputAngle")
let filterSize = inputImage.extent.size
let vector = CIVector(x: CGFloat(center.x) * filterSize.width, y: CGFloat(1.0 - center.y) * filterSize.height)
filter.setValue(vector, forKey:"inputCenter")
filter.setValue(inputImage, forKey: "inputImage")
return filter
}
}
| mit | 9e63dad5eb6255505012936170d4d7a6 | 42.964912 | 118 | 0.701915 | 4.283761 | false | false | false | false |
airsoftdavid/Quickcast | front_end/QuickCast/QuickCast/Dota2CurrentGamesTableViewController.swift | 1 | 4297 | //
// Dota2CurrentGamesTableViewController.swift
// QuickCast
//
// Created by David Chen on 5/6/16.
// Copyright © 2016 David Chen. All rights reserved.
//
import UIKit
import SwiftyJSON
<<<<<<< Updated upstream
=======
class Dota2CurrentGamesTableViewController: UITableViewController {
var NumberofRows = 10
var simpleData = [String]()
>>>>>>> Stashed changes
class Dota2CurrentGamesTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumberofRows
}
func parseJSON(){
let path : String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
//change next line to URL when getting from server
let jsonData = NSData(contentsOfFile: path) as NSData!
let parsedJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
let team1 = parsedJSON["dire_team"]["team_name"].string as String!
let team2 = parsedJSON["radiant_team"]["team_name"].string as String!
let team1wins = parsedJSON["dire_series_wins"].string as String!
let team2wins = parsedJSON["radiant_series_wins"].string as String!
simpleData.append(team1)
simpleData.append(team2)
simpleData.append(team1wins)
simpleData.append(team2wins)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath)
cell.textLabel?.text = simpleData[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | fcc9d96e28b54a9f7ff1cb95a6d7c412 | 33.645161 | 157 | 0.679004 | 5.31026 | false | false | false | false |
regini/inSquare | inSquareAppIOS/inSquareAppIOS/RecentsViewController.swift | 1 | 6700 | //
// RecentsViewController.swift
// inSquare
//
// Created by Alessandro Steri on 05/03/16.
// Copyright © 2016 Alessandro Steri. All rights reserved.
//
import UIKit
import Alamofire
class RecentsViewController: UIViewController, UITableViewDelegate
{
var recentSquares = JSON(data: NSData())
//values to pass by cell chatButton tap, updated when the button is tapped
var squareId:String = String()
var squareName:String = String()
var squareLatitude:Double = Double()
var squareLongitude:Double = Double()
@IBOutlet var recentTableView: UITableView!
@IBAction func unwindToRec(segue: UIStoryboardSegue)
{
}
override func viewDidLoad() {
super.viewDidLoad()
//UIApplication.sharedApplication().statusBarStyle = .Default
request(.GET, "\(serverMainUrl)/recentsquares/\(serverId)").validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
// print("RECSQUARES \(value)")
self.recentSquares = JSON(value)
// for (index, value):(String, JSON) in self.jsonSq
// {
// }
self.recentTableView.reloadData()
}
case .Failure(let error):
print(error)
//cambia con analitics
// Answers.logCustomEventWithName("Error",
// customAttributes: ["Error Debug Description": error.debugDescription])
}
}//ENDREQUEST
// Do any additional setup after loading the view.
}//END VDL
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//inutile?
updateRecentSquares()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//inutile?
recentTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return recentSquares.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.recentTableView.dequeueReusableCellWithIdentifier("recCell", forIndexPath: indexPath) as! RecentTableViewCell
//print("qwerty \(self.favouriteSquare[indexPath.row]["_source"]["lastMessageDate"])")
cell.squareName.text = self.recentSquares[indexPath.row]["_source"]["name"].string
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString("\(self.recentSquares[indexPath.row]["_source"]["lastMessageDate"].string!)")
// print(date)
let newDateFormatter = NSDateFormatter()
newDateFormatter.locale = NSLocale.currentLocale()
newDateFormatter.dateFormat = "hh:mm (dd-MMM)"
var convertedDate = newDateFormatter.stringFromDate(date!)
cell.squareActive.text = "Active: \(convertedDate)"
//cell.goInSquare(cell)
cell.tapped = { [unowned self] (selectedCell) -> Void in
let path = tableView.indexPathForRowAtPoint(selectedCell.center)!
let selectedSquare = self.recentSquares[path.row]
// print("the selected item is \(selectedSquare)")
self.squareId = selectedSquare["_id"].string!
self.squareName = selectedSquare["_source"]["name"].string!
let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",")
let latitude = (coordinates[0] as NSString).doubleValue
let longitude = (coordinates[1] as NSString).doubleValue
self.squareLatitude = latitude
self.squareLongitude = longitude
self.performSegueWithIdentifier("chatFromRec", sender: self)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as! RecentTableViewCell
let selectedSquare = self.recentSquares[indexPath!.row]
//let path = tableView.indexPathForRowAtPoint(selectedCell.center)!
print("the selected item is \(selectedSquare)")
self.squareId = selectedSquare["_id"].string!
self.squareName = selectedSquare["_source"]["name"].string!
let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",")
let latitude = (coordinates[0] as NSString).doubleValue
let longitude = (coordinates[1] as NSString).doubleValue
self.squareLatitude = latitude
self.squareLongitude = longitude
self.performSegueWithIdentifier("chatFromRec", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}//END DRMW
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
{
if (segue.identifier == "chatFromRec") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
print("chatFromFav")
print(squareId)
print(squareName)
print(squareLatitude)
print(squareLongitude)
//var detailVC = segue!.destinationViewController as! SquareMessViewController
//var detailVC = segue!.destinationViewController as! NavigationToJSQViewController
// let detailVC = detailNC.topViewController as! inSquareViewController
let navVC = segue.destinationViewController as! UINavigationController
let detailVC = navVC.viewControllers.first as! SquareMessViewController
detailVC.viewControllerNavigatedFrom = segue.sourceViewController
detailVC.squareName = self.squareName
detailVC.squareId = self.squareId
detailVC.squareLatitude = self.squareLatitude
detailVC.squareLongitude = self.squareLongitude
}
}
}//END VC
| mit | 318b66f3bc0816972788ece584646297 | 36.216667 | 133 | 0.612032 | 5.667513 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/UIKit/UITableView+Binding.swift | 1 | 1985 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
private var dataSource_key = 0
private var b_editing_key = 0
public extension UITableView {
func b_configure<Item: Equatable>(_ items: Subscribable<[Item]>, block: (TableViewDataSource<Item>) -> Void) {
let dataSource = TableViewDataSource(subscribable: items, view: self)
block(dataSource)
setAssociatedObjectProperty(self, &dataSource_key, value: dataSource as AnyObject)
self.delegate = dataSource
self.dataSource = dataSource
}
var b_editing: BindableProperty<UITableView, Bool> {
associatedObjectProperty(self, &b_editing_key) { _ in
BindableProperty(self, setter: { control, value -> Void in
control.isEditing = value
})
}
}
}
| mit | fd0adc75a50211aea747d514ecb0e05d | 37.921569 | 114 | 0.688161 | 4.563218 | false | false | false | false |
kareman/FootlessParser | Sources/FootlessParser/StringParser.swift | 1 | 5777 | //
// StringParser.swift
// FootlessParser
//
// Released under the MIT License (MIT), http://opensource.org/licenses/MIT
//
// Copyright (c) 2015 NotTooBad Software. All rights reserved.
//
import Foundation
/** Match a single character. */
public func char (_ c: Character) -> Parser<Character, Character> {
return satisfy(expect: String(c)) { $0 == c }
}
/** Join two strings */
public func extend (_ a: String) -> (String) -> String {
return { b in a + b }
}
/** Join a character with a string. */
public func extend (_ a: Character) -> (String) -> String {
return { b in String(a) + b }
}
/** Apply character parser once, then repeat until it fails. Returns a string. */
public func oneOrMore <T> (_ p: Parser<T, Character>) -> Parser<T, String> {
return { (cs: [Character]) in String(cs) } <^> oneOrMore(p)
}
/** Repeat character parser until it fails. Returns a string. */
public func zeroOrMore <T> (_ p: Parser<T,Character>) -> Parser<T,String> {
return optional( oneOrMore(p), otherwise: "" )
}
/** Repeat character parser 'n' times and return as string. If 'n' == 0 it always succeeds and returns "". */
public func count <T> (_ n: Int, _ p: Parser<T,Character>) -> Parser<T,String> {
return n == 0 ? pure("") : extend <^> p <*> count(n-1, p)
}
/**
Repeat parser as many times as possible within the given range.
count(2...2, p) is identical to count(2, p)
- parameter r: A positive closed integer range.
*/
public func count <T> (_ r: ClosedRange<Int>, _ p: Parser<T,Character>) -> Parser<T,String> {
precondition(r.lowerBound >= 0, "Count must be >= 0")
return extend <^> count(r.lowerBound, p) <*> ( count(r.count-1, p) <|> zeroOrMore(p) )
}
/**
Repeat parser as many times as possible within the given range.
count(2..<3, p) is identical to count(2, p)
- parameter r: A positive half open integer range.
*/
public func count <T> (_ r: Range<Int>, _ p: Parser<T,Character>) -> Parser<T,String> {
precondition(r.lowerBound >= 0, "Count must be >= 0")
return extend <^> count(r.lowerBound, p) <*> ( count(r.count-1, p) <|> zeroOrMore(p) )
}
/**
Match a string
- parameter: string to match
- note: consumes either the full string or nothing, even on a partial match.
*/
public func string (_ s: String) -> Parser<Character, String> {
let count = s.count
return Parser { input in
guard input.startIndex < input.endIndex else {
throw ParseError.Mismatch(input, s, "EOF")
}
guard let endIndex = input.index(input.startIndex, offsetBy: count, limitedBy: input.endIndex) else {
throw ParseError.Mismatch(input, s, String(input))
}
let next = input[input.startIndex..<endIndex]
if s.elementsEqual(next) {
return (s, input.dropFirst(count))
} else {
throw ParseError.Mismatch(input, s, String(next))
}
}
}
/** Succeed if the next character is in the provided string. */
public func oneOf (_ s: String) -> Parser<Character,Character> {
return oneOf(Set(s))
}
/** Succeed if the next character is _not_ in the provided string. */
public func noneOf (_ s: String) -> Parser<Character,Character> {
return noneOf(Set(s))
}
/**
Produces a character if the character and succeeding do not match any of the strings.
- parameter: strings to _not_ match
- note: consumes only produced characters
*/
public func noneOf(_ strings: [String]) -> Parser<Character, Character> {
return Parser { input in
guard let next = input.first else {
throw ParseError.Mismatch(input, "anything but \(strings)", "EOF")
}
for string in strings {
guard string.first == next else { continue }
let offset = string.count
guard input.count >= offset else { continue }
let endIndex = input.index(input.startIndex, offsetBy: offset)
guard endIndex <= input.endIndex else { continue }
let peek = input[input.startIndex..<endIndex]
if string.elementsEqual(peek) { throw ParseError.Mismatch(input, "anything but \(string)", string) }
}
return (next, input.dropFirst())
}
}
public func char(_ set: CharacterSet, name: String) -> Parser<Character, Character> {
return satisfy(expect: name) {
return String($0).rangeOfCharacter(from: set) != nil
}
}
/**
Parse all of the string with parser.
Failure to consume all of input will result in a ParserError.
- parameter p: A parser of characters.
- parameter input: A string.
- returns: Output from the parser.
- throws: A ParserError.
*/
public func parse <A> (_ p: Parser<Character, A>, _ s: String) throws -> A {
return try (p <* eof()).parse(AnyCollection(s)).output
}
public func print(error: ParseError<Character>, in s: String) {
if case ParseError<Character>.Mismatch(let remainder, let expected, let actual) = error {
let index = s.index(s.endIndex, offsetBy: -remainder.count)
let (lineRange, row, pos) = position(of: index, in: s)
let line = s[lineRange.lowerBound..<lineRange.upperBound].trimmingCharacters(in: CharacterSet.newlines)
print("An error occurred when parsing this line:")
print(line)
print(String(repeating: " ", count: pos - 1) + "^")
print("\(row):\(pos) Expected '\(expected)', actual '\(actual)'")
}
}
func position(of index: Substring.Index, in string: String) -> (line: Range<Substring.Index>, row: Int, pos: Int) {
var head = string.startIndex..<string.startIndex
var row = 0
while head.upperBound <= index {
head = string.lineRange(for: head.upperBound..<head.upperBound)
row += 1
}
return (head, row, string.distance(from: head.lowerBound, to: index) + 1)
}
| mit | 9c5495b8f0d8ac90be9c108ead5ea762 | 35.563291 | 115 | 0.639778 | 3.778286 | false | false | false | false |
xu6148152/binea_project_for_ios | Cassini/Cassini/ViewController.swift | 1 | 987 | //
// ViewController.swift
// Cassini
//
// Created by Binea Xu on 6/21/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let ivc = segue.destinationViewController as? ImageViewController{
if let identifier = segue.identifier{
switch identifier{
case "earth":
ivc.imageURL = DemoURL.NASA.Earth
ivc.title = identifier
case "cassini":
ivc.imageURL = DemoURL.NASA.Cassini
ivc.title = identifier
case "saturn":
ivc.title = identifier
ivc.imageURL = DemoURL.NASA.Saturn
default: break
}
}
}
}
}
| mit | 896e7fdd7da5923b037f44e8a9cd7b79 | 26.416667 | 81 | 0.488349 | 5.453039 | false | false | false | false |
nsdictionary/CFCityPickerVC | CFCityPickerVC/CFCityPickerVC/Controller/CitySearchResultVC.swift | 4 | 1973 | //
// CitySearchResultVC.swift
// CFCityPickerVC
//
// Created by 冯成林 on 15/8/6.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class CitySearchResultVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
var touchBeganAction: (()->())!
var tableViewScrollAction: (()->())!
var tableViewDidSelectedRowAction: ((cityModel: CFCityPickerVC.CityModel)->())!
var cityModels: [CFCityPickerVC.CityModel]!{didSet{dataPrepare()}}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
}
}
extension CitySearchResultVC{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if cityModels == nil {return 0}
return cityModels.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = CFCityCell.cityCellInTableView(tableView)
cell.cityModel = cityModels[indexPath.item]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableViewDidSelectedRowAction?(cityModel: cityModels[indexPath.row])
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if self.cityModels == nil {return nil}
return "共检索到\(self.cityModels.count)到记录"
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
touchBeganAction?()
}
func dataPrepare(){
self.tableView.hidden = self.cityModels == nil
self.tableView.reloadData()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
tableViewScrollAction?()
}
}
| mit | 4945e662b48ca1c40c0d77f1102ef561 | 23.620253 | 109 | 0.643188 | 4.987179 | false | false | false | false |
T-Pham/UITextField-Navigation | UITextField-Navigation/Classes/NavigationFieldToolbar.swift | 1 | 2692 | //
// NavigationFieldToolbar.swift
// UITextField-Navigation
//
// Created by Thanh Pham on 2/10/17.
// Copyright © 2017 Thanh Pham. All rights reserved.
//
import UIKit
protocol NavigationFieldToolbarDelegate: class {
func navigationFieldToolbarDidTapPreviousButton(_ navigationFieldToolbar: NavigationFieldToolbar)
func navigationFieldToolbarDidTapNextButton(_ navigationFieldToolbar: NavigationFieldToolbar)
func navigationFieldToolbarDidTapDoneButton(_ navigationFieldToolbar: NavigationFieldToolbar)
}
/// Class for the `inputAccessoryView`.
public class NavigationFieldToolbar: UIToolbar {
weak var navigationDelegate: NavigationFieldToolbarDelegate?
/// Holds the previous button.
@objc public let previousButton: NavigationFieldToolbarButtonItem
/// Holds the next button.
@objc public let nextButton: NavigationFieldToolbarButtonItem
/// Holds the done button.
@objc public let doneButton: NavigationFieldToolbarButtonItem
/// Has not been implemented. Use `init()` instead.
required public init?(coder aDecoder: NSCoder) {
return nil
}
init() {
previousButton = NavigationFieldToolbarButtonItem(title: Config.previousButtonTitle, style: .plain, target: nil, action: nil)
nextButton = NavigationFieldToolbarButtonItem(title: Config.nextButtonTitle, style: .plain, target: nil, action: nil)
doneButton = NavigationFieldToolbarButtonItem(title: Config.doneButtonTitle, style: .plain, target: nil, action: nil)
super.init(frame: CGRect.zero)
previousButton.isEnabled = false
previousButton.target = self
previousButton.action = #selector(previousButtonDidTap)
nextButton.isEnabled = false
nextButton.target = self
nextButton.action = #selector(nextButtonDidTap)
doneButton.target = self
doneButton.action = #selector(doneButtonDidTap)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
items = [previousButton, nextButton, flexibleSpace, doneButton]
sizeToFit()
}
@objc func previousButtonDidTap() {
if let navigationDelegate = navigationDelegate {
navigationDelegate.navigationFieldToolbarDidTapPreviousButton(self)
}
}
@objc func nextButtonDidTap() {
if let navigationDelegate = navigationDelegate {
navigationDelegate.navigationFieldToolbarDidTapNextButton(self)
}
}
@objc func doneButtonDidTap() {
if let navigationDelegate = navigationDelegate {
navigationDelegate.navigationFieldToolbarDidTapDoneButton(self)
}
}
}
| mit | 6b574bfe9d16a976bc283b6fc3ddf1ff | 34.88 | 133 | 0.726867 | 5.225243 | false | false | false | false |
wgywgy/SimpleActionSheet | CustomSheet/Source/ActionSheet.swift | 1 | 8684 | //
// ActionSheet.swift
// CustomSheet
//
// Created by wuguanyu on 16/9/23.
// Copyright © 2016年 wuguanyu. All rights reserved.
//
import UIKit
public enum ActionSheetCommonOption {
case blurBackground(Bool)
case darkBackgroundColor(Bool)
case bounceShow(Bool)
}
public enum ActionSheetOption {
case sepLineHeight(CGFloat)
case sepLineColor(UIColor)
case sepLineWidth(CGFloat)
case sepLineLeftMargin(CGFloat)
}
struct ScreenSize {
static let width = UIScreen.main.bounds.size.width
static let height = UIScreen.main.bounds.size.height
static let maxLength = max(ScreenSize.width, ScreenSize.height)
static let minLength = min(ScreenSize.width, ScreenSize.height)
}
open class ActionSheetController: UIViewController {
open var items = [ActionSheetItemModel]()
var closeAction: (() -> Void)?
var totalItemsHeight: CGFloat = 0
var actionSheetItemViews = [ActionSheetItemView]()
var sepLineViews = [UIView]()
// ActionSheetCommonOption var
var blurBackground = false
var darkBackgroundColor = true
var bounceShow = false
// ActionSheetOption var
var sepLineHeight: CGFloat = 1
var sepLineColor: UIColor = .lightGray
var sepLineWidth: CGFloat = ScreenSize.width
var sepLineLeftMargin: CGFloat = 0
@IBOutlet weak var maskBgView: UIView!
var containerWindow: UIWindow = {
let originFrame = CGRect(x: 0, y: -20, width: ScreenSize.width, height: 20)
let aWindow = UIWindow(frame: originFrame)
// aWindow.isHidden = false
aWindow.windowLevel = UIWindowLevelAlert
return aWindow
}()
fileprivate lazy var maskView: UIView = {
let aView: UIView
if self.blurBackground {
aView = self.createBlurView(frame: self.screenBounds)
} else {
aView = UIView(frame: self.screenBounds)
aView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
}
aView.alpha = 0
let maskViewTapGesture = UITapGestureRecognizer(target: self, action: #selector(maskViewWasTapped))
aView.addGestureRecognizer(maskViewTapGesture)
return aView
}()
fileprivate lazy var itemContainerView: UIView = {
let aItemContainerView = UIView()
aItemContainerView.backgroundColor = .white
return aItemContainerView
}()
func createSepLineView() -> UIView {
let aSepLineView = UIView()
aSepLineView.backgroundColor = sepLineColor
return aSepLineView
}
var screenBounds: CGRect {
get {
return UIScreen.main.bounds
}
}
open var preferredCommonStyle = [ActionSheetCommonOption]() {
didSet {
for option in preferredCommonStyle {
switch option {
case let .blurBackground(value):
blurBackground = value
case let .bounceShow(value):
bounceShow = value
case let .darkBackgroundColor(value):
darkBackgroundColor = value
}
}
}
}
open var preferredStyle = [ActionSheetOption]() {
didSet {
restoreProperty()
for option in preferredStyle {
switch option {
case let .sepLineHeight(value):
sepLineHeight = value
case let .sepLineColor(value):
sepLineColor = value
case let .sepLineWidth(value):
sepLineWidth = value
case let .sepLineLeftMargin(value):
sepLineLeftMargin = value
}
}
}
}
func restoreProperty() {
sepLineHeight = 1
sepLineColor = .lightGray
sepLineWidth = UIScreen.main.bounds.width
sepLineLeftMargin = 0
}
// Mark Action:
open func showInWindow(_ items: [ActionSheetItemModel]? = nil, preferredStyle: [ActionSheetOption]? = nil, closeBlock: (() -> Void)? = nil) {
let window = UIApplication.shared.delegate?.window
showInView(window!!, items: items, preferredStyle: preferredStyle, closeBlock: closeBlock)
}
open func showInView(_ targetView: UIView, items: [ActionSheetItemModel]? = nil, preferredStyle: [ActionSheetOption]? = nil, closeBlock: (() -> Void)? = nil) {
if let items = items {
self.items = items
}
self.closeAction = closeBlock
if let preferredStyle = preferredStyle {
self.preferredStyle = preferredStyle
}
maskView.frame = screenBounds
targetView.addSubview(maskView)
setupContainerView()
targetView.addSubview(itemContainerView)
itemContainerView.frame = CGRect(x: 0, y: screenBounds.height, width: screenBounds.width, height: totalItemsHeight)
if bounceShow {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.68, initialSpringVelocity: 0.7, options: .curveEaseOut, animations: {
self.maskView.alpha = 1.0
self.itemContainerView.frame = CGRect(x: 0, y: self.screenBounds.height - self.totalItemsHeight, width: self.screenBounds.width, height: self.totalItemsHeight)
})
} else {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.maskView.alpha = 1.0
self.itemContainerView.frame = CGRect(x: 0, y: self.screenBounds.height - self.totalItemsHeight, width: self.screenBounds.width, height: self.totalItemsHeight)
})
}
}
func setupContainerView() {
var currentPosition: CGFloat = 0
for i in (0 ..< items.count) {
let aItem = items[i]
let itemOriginPoint = CGPoint(x: 0, y: currentPosition)
let itemSize = CGSize(width: screenBounds.width, height: aItem.height)
let aItemView = ActionSheetItemView(frame: CGRect(origin: itemOriginPoint, size: itemSize))
aItemView.setStyle(aItem)
actionSheetItemViews.append(aItemView)
aItemView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ActionSheetController.buttonWasTapped(_:))))
itemContainerView.addSubview(aItemView)
currentPosition += aItem.height
if i < items.count - 1 {
let aSep = createSepLineView()
aSep.frame = CGRect(x: sepLineLeftMargin, y: currentPosition, width: sepLineWidth, height: sepLineHeight)
sepLineViews.append(aSep)
itemContainerView.addSubview(aSep)
currentPosition += sepLineHeight
}
}
totalItemsHeight = currentPosition
}
open func dismiss() {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.itemContainerView.frame = CGRect(x: 0, y: self.screenBounds.height, width: self.screenBounds.width, height: self.itemContainerView.frame.height)
self.maskView.alpha = 0
}) { (finish) in
self.itemContainerView.removeFromSuperview()
self.maskView.removeFromSuperview()
for actionSheetItemView in self.actionSheetItemViews {
actionSheetItemView.removeFromSuperview()
}
self.actionSheetItemViews.removeAll()
for sepLineView in self.sepLineViews {
sepLineView.removeFromSuperview()
}
self.sepLineViews.removeAll()
self.closeAction?()
}
}
}
extension ActionSheetController {
func createBlurView(frame: CGRect) -> UIView {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = frame
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return blurEffectView
}
}
extension ActionSheetController {
func maskViewWasTapped() {
dismiss()
}
func buttonWasTapped(_ sender: UITapGestureRecognizer) {
guard let aItemView = sender.view as? ActionSheetItemView else {
return
}
for item in items {
if aItemView.titleLabel.text == item.title {
item.selectAction?(self)
}
}
}
}
| mit | 6303145b60d7bdb731c66cd07bd1d8e1 | 33.585657 | 175 | 0.618362 | 5.032464 | false | false | false | false |
ZamzamInc/ZamzamKit | Sources/ZamzamUI/Extensions/View.swift | 1 | 8310 | //
// View.swift
// ZamzamUI
//
// Created by Basem Emara on 2021-01-02.
// Copyright © 2021 Zamzam Inc. All rights reserved.
//
import Combine
import SwiftUI
public extension View {
/// Adds a border to this view with the specified color, width, and radius.
func border(_ color: Color, width: CGFloat = 1, cornerRadius: CGFloat) -> some View {
let shape = RoundedRectangle(cornerRadius: cornerRadius)
return self
.clipShape(shape)
.overlay(shape.stroke(color, lineWidth: width))
}
}
public extension View {
/// Hides this view conditionally.
///
/// - Parameter condition: The condition to determine if the content should be applied.
/// - Returns: The modified view.
func hidden(_ condition: Bool) -> some View {
modifier(if: condition) { content in
content.hidden()
} else: { content in
content
}
}
}
public extension View {
/// Applies a modifier to a view.
///
/// someView
/// .modifier {
/// if #available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) {
/// $0.scrollDismissesKeyboard(.interactively)
/// } else {
/// $0
/// }
/// }
///
/// - Parameters:
/// - transform: The modifier to apply to the view.
/// - Returns: The modified view.
func modifier<Content>(@ViewBuilder _ transform: (Self) -> Content) -> Content {
transform(self)
}
}
public extension View {
/// Returns a type-erased view.
func eraseToAnyView() -> AnyView {
AnyView(self)
}
}
// MARK: - Receive
public extension View {
/// Adds a modifier for this view that fires an action when a specific value changes.
///
/// - Parameters:
/// - value: The value to check against when determining whether to run the closure.
/// - action: A concurrent closure to run when the value changes.
/// - newValue: The new value that failed the comparison check.
/// - Returns: A view that fires an action when the specified value changes.
func onChange<V>(
of value: V,
perform action: @escaping (_ newValue: V) async -> Void
) -> some View where V: Equatable {
onChange(of: value) { newValue in Task { await action(newValue) } }
}
}
public extension View {
/// Adds an action to perform when this view detects data emitted by the optional publisher.
///
/// - Parameters:
/// - publisher: The publisher to subscribe to.
/// - action: The action to perform when an event is emitted by `publisher`.
/// - Returns: A view that triggers action when publisher emits an event.
func onReceive<P>(
_ publisher: P?,
perform action: @escaping (P.Output) -> Void
) -> some View where P: Publisher, P.Failure == Never {
modifier(let: publisher) { $0.onReceive($1, perform: action) }
}
/// Adds an action to perform when this view detects data emitted by the given publisher.
///
/// - Parameters:
/// - publisher: The publisher to subscribe to.
/// - action: The action to perform when an event is emitted by `publisher`.
/// - Returns: A view that triggers an async action when publisher emits an event.
func onReceive<P>(
_ publisher: P?,
perform action: @escaping () async -> Void
) -> some View where P: Publisher, P.Failure == Never {
// Deprecate in favour of `.task` after converting publishers to `AsyncStream`
onReceive(publisher) { _ in Task { await action() } }
}
/// Adds an action to perform when this view detects data emitted by the given `ObservableObject`.
///
/// - Parameters:
/// - observableObject: The `ObservableObject` to subscribe to.
/// - action: The action to perform when an event is emitted by the `objectWillChange` publisher of the `ObservableObject`.
/// - Returns: A view that triggers an action when publisher emits an event.
func onReceive<O>(
_ observableObject: O,
perform action: @escaping () -> Void
) -> some View where O: ObservableObject {
onReceive(observableObject.objectWillChange) { _ in
DispatchQueue.main.async(execute: action)
}
}
}
// MARK: - Notification
public extension View {
/// Adds an action to perform when this view detects a notification emitted by the `NotificationCenter` publisher.
///
/// - Parameters:
/// - name: The name of the notification to publish.
/// - object: The object posting the named notification.
/// - action: The action to perform when the notification is emitted by publisher.
/// - Returns: View
func onNotification(
for name: Notification.Name,
object: AnyObject? = nil,
perform action: @escaping (Notification) -> Void
) -> some View {
// https://github.com/gtokman/ExtensionKit
onReceive(NotificationCenter.default.publisher(for: name, object: object).receive(on: DispatchQueue.main), perform: action)
}
/// Adds an action to perform when this view detects a notification emitted by the `NotificationCenter` publisher.
///
/// - Parameters:
/// - name: The name of the notification to publish.
/// - object: The object posting the named notification.
/// - action: The action to perform when the notification is emitted by publisher.
/// - Returns: View
func onNotification(
for name: Notification.Name,
object: AnyObject? = nil,
perform action: @escaping (Notification) async -> Void
) -> some View {
onReceive(NotificationCenter.default.publisher(for: name, object: object).receive(on: DispatchQueue.main)) { notification in
Task { await action(notification) }
}
}
/// Adds an action to perform when this view detects a notification emitted by the `NotificationCenter` publisher.
///
/// - Parameters:
/// - name: The name of the notification to publish.
/// - object: The object posting the named notification.
/// - action: The action to perform when the notification is emitted by publisher.
/// - Returns: View
func onNotification(
for name: Notification.Name,
object: AnyObject? = nil,
perform action: @escaping () async -> Void
) -> some View {
onReceive(NotificationCenter.default.publisher(for: name, object: object).receive(on: DispatchQueue.main)) { _ in
Task { await action() }
}
}
}
// MARK: - UI
public extension View {
/// Binds the height of the view to a property.
func assign(heightTo height: Binding<CGFloat>) -> some View {
background(
GeometryReader { geometry in
Color.clear
.onAppear { height.wrappedValue = geometry.size.height }
}
)
}
}
#if os(iOS)
struct RoundedRect: Shape {
let radius: CGFloat
let corners: UIRectCorner
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(
roundedRect: rect,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius)
)
return Path(path.cgPath)
}
}
public extension View {
/// Clips this view to its bounding frame, with the specified corner radius.
///
/// Text("Rounded Corners")
/// .frame(width: 175, height: 75)
/// .foregroundColor(Color.white)
/// .background(Color.black)
/// .cornerRadius(25, corners: [.topLeft, .topRight])
///
/// Creates and returns a new Bézier path object with a rectangular path rounded at the specified corners.
/// For rounding all corners, use the native `.cornerRadius(_ radius:)` function.
///
/// - Parameters:
/// - radius: The corner radius.
/// - corners: A bitmask value that identifies the corners that you want rounded.
/// You can use this parameter to round only a subset of the corners of the rectangle.
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape(RoundedRect(radius: radius, corners: corners))
}
}
#endif
| mit | 62cdd192890a4497a04f1ac00ad6d570 | 35.121739 | 132 | 0.616875 | 4.464267 | false | false | false | false |
belkhadir/Beloved | Beloved/User.swift | 1 | 1895 | //
// User.swift
// Beloved
//
// Created by Anas Belkhadir on 07/02/2016.
// Copyright © 2016 Anas Belkhadir. All rights reserved.
//
import Foundation
struct User{
//Base Authentication
var email:String? = nil
var password:String? = nil
var uid: String? = nil
//Base SingUp
var firstName: String? = nil
var lastName: String? = nil
var userName: String? = nil
var image64EncodeImage: String? = nil
var date: String? = nil
init(email:String?, password: String?) {
self.email = email!
self.password = password!
}
init(){
}
init(parameter: [String: AnyObject]){
userName = parameter[FirebaseHelper.JSONKEY.USERNAME] as? String
lastName = parameter[FirebaseHelper.JSONKEY.LAST_NAME] as? String
firstName = parameter[FirebaseHelper.JSONKEY.FIRST_NAME] as? String
email = parameter[FirebaseHelper.JSONKEY.EMAIL] as? String
image64EncodeImage = parameter[FirebaseHelper.JSONKEY.IMAGE] as? String
password = parameter[FirebaseHelper.JSONKEY.PASSWORD] as? String
date = parameter[FirebaseHelper.JSONKEY.DATE] as? String
uid = parameter[FirebaseHelper.JSONKEY.UID] as? String
}
init(email:String?, password: String?, firstName: String?,
lastName: String?, userName: String?){
self.email = email!
self.password = password!
self.firstName = firstName!
self.lastName = lastName!
self.userName = userName
}
}
//Tracking information of the user after singIn
class CurrentUser {
var user: User?
var currentUserConnected: CurrentUserConnected?
class func sharedInstance() -> CurrentUser {
struct Singleton {
static var sharedInstance = CurrentUser()
}
return Singleton.sharedInstance
}
}
| mit | 013252ab8335d907758fb43c72fce482 | 24.945205 | 79 | 0.63622 | 4.344037 | false | false | false | false |
lorentey/swift | test/expr/cast/metatype_casts.swift | 5 | 1662 | // RUN: %target-typecheck-verify-swift
func use<T>(_: T) {}
class C {}
class D: C {}
class E: P {}
class X {}
protocol P {}
protocol Q {}
protocol CP: class {}
let any: Any.Type = Int.self
use(any as! Int.Type)
use(any as! C.Type)
use(any as! D.Type)
use(any as! AnyObject.Type)
use(any as! AnyObject.Protocol)
use(any as! P.Type)
use(any as! P.Protocol)
let anyP: Any.Protocol = Any.self
use(anyP is Any.Type) // expected-warning{{always true}}
use(anyP as! Int.Type) // expected-warning{{always fails}}
let anyObj: AnyObject.Type = D.self
use(anyObj as! Int.Type) // expected-warning{{always fails}}
use(anyObj as! C.Type)
use(anyObj as! D.Type)
use(anyObj as! AnyObject.Protocol) // expected-warning{{always fails}}
use(anyObj as! P.Type)
use(anyObj as! P.Protocol) // expected-warning{{always fails}}
let c: C.Type = D.self
use(c as! D.Type)
use(c as! X.Type) // expected-warning{{always fails}}
use(c is AnyObject.Type) // expected-warning{{always true}}
use(c as! AnyObject.Type) // expected-warning{{always succeeds}} {{7-10=as}}
use(c as! AnyObject.Protocol) // expected-warning{{always fails}}
use(c as! CP.Type)
use(c as! CP.Protocol) // expected-warning{{always fails}}
use(c as! Int.Type) // expected-warning{{always fails}}
use(C.self as AnyObject.Protocol) // expected-error{{cannot convert value of type 'C.Type' to type 'AnyObject.Protocol' in coercion}}
use(C.self as AnyObject.Type)
use(C.self as P.Type) // expected-error{{cannot convert value of type 'C.Type' to type 'P.Type' in coercion}}
use(E.self as P.Protocol) // expected-error{{cannot convert value of type 'E.Type' to type 'P.Protocol' in coercion}}
use(E.self as P.Type)
| apache-2.0 | 76c6a8a04d3353f62cfea8ca564a72ab | 31.588235 | 133 | 0.701564 | 2.920914 | false | false | false | false |
bravelocation/daysleft | daysleft/View Models/DaysLeftViewModel.swift | 1 | 3127 | //
// WatchDaysLeftData.swift
// daysleft WatchKit Extension
//
// Created by John Pollard on 13/11/2019.
// Copyright © 2019 Brave Location Software. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
/// Protocol for handlers of view model actions
protocol ViewModelActionDelegate: AnyObject {
/// Share event is raised
func share()
/// Edit event is raised
func edit()
}
/// Main view model for display of days left settings
class DaysLeftViewModel: ObservableObject {
/// Current display values
@Published var displayValues: DisplayValues
/// Subscribers to change events
private var cancellables = [AnyCancellable]()
/// Data manager
let dataManager: AppSettingsDataManager
/// Delegate for view actions
var delegate: ViewModelActionDelegate?
/// Initialiser
/// - Parameter dataManager: Data manager
init(dataManager: AppSettingsDataManager) {
self.dataManager = dataManager
self.displayValues = DisplayValues(appSettings: self.dataManager.appSettings)
// Setup listener for iCloud setting change
let keyValueChangeSubscriber = NotificationCenter.default
.publisher(for: .AppSettingsUpdated)
.sink { _ in
self.userSettingsUpdated()
}
self.cancellables.append(keyValueChangeSubscriber)
self.updateViewData()
}
/// Update the view data on initialisation, or on a data update
func updateViewData() {
print("Updating view data...")
// Set the published properties based on the model
self.displayValues = DisplayValues(appSettings: self.dataManager.appSettings)
}
/// Called when share button is tapped
func share() {
if let delegate = delegate {
delegate.share()
}
}
/// Called when edit button is tapped
func edit() {
if let delegate = delegate {
delegate.edit()
}
}
/// Formats the given date in short format
/// - Parameter date: Date to format
/// - Returns: String with formatted date
func shortDateFormatted(date: Date) -> String {
let shortDateFormatter = DateFormatter()
shortDateFormatter.dateFormat = "EEE d MMM"
return shortDateFormatter.string(from: date)
}
/// Formats the given date in a format suitable for an accessibility label
/// - Parameter date: Date to format
/// - Returns: String with formatted date
func accessibilityDateFormatted(date: Date) -> String {
let accessibilityDateFormatter = DateFormatter()
accessibilityDateFormatter.dateFormat = "EEEE d MMM"
return accessibilityDateFormatter.string(from: date)
}
/// Event handler for data update
private func userSettingsUpdated() {
print("Received UserSettingsUpdated notification")
// Update view data on main thread
DispatchQueue.main.async {
self.updateViewData()
}
}
}
| mit | e81cc34357001fd14881738934adb722 | 28.490566 | 85 | 0.640435 | 5.316327 | false | false | false | false |
marcopolee/glimglam | Glimglam/AppDelegate.swift | 1 | 1389 | //
// AppDelegate.swift
// Glimglam
//
// Created by Tyrone Trevorrow on 12/10/17.
// Copyright © 2017 Marco Polee. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
class var shared: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
var window: UIWindow?
var navigationController: UINavigationController!
var watchBridge: WatchBridge!
let urlHandlers = URLHandlers()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let mainNavVC = window?.rootViewController as! UINavigationController
navigationController = mainNavVC
bootstrapContext()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url.absoluteString)
return urlHandlers.handleIncoming(url: url)
}
func bootstrapContext() {
let mainVC = navigationController.viewControllers.first as! ViewController
let context = CoreContext()
context.readFromKeychain()
mainVC.context = context
watchBridge = WatchBridge(context: context)
}
}
| mit | cce5f1a74244a881545851ac2956325d | 30.545455 | 144 | 0.696686 | 5.257576 | false | false | false | false |
tjw/swift | test/IRGen/objc_methods.swift | 3 | 5374 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// Protocol methods require extended method type encodings to capture block
// signatures and parameter object types.
@objc protocol Fooable {
func block(_: (Int) -> Int)
func block2(_: (Int,Int) -> Int)
func takesString(_: String) -> String
func takesArray(_: [AnyObject]) -> [AnyObject]
func takesDict(_: [NSObject: AnyObject]) -> [NSObject: AnyObject]
func takesSet(_: Set<NSObject>) -> Set<NSObject>
}
class Foo: Fooable {
func bar() {}
@objc func baz() {}
@IBAction func garply(_: AnyObject?) {}
@objc func block(_: (Int) -> Int) {}
@objc func block2(_: (Int,Int) -> Int) {}
@objc func takesString(_ x: String) -> String { return x }
@objc func takesArray(_ x: [AnyObject]) -> [AnyObject] { return x }
@objc func takesDict(_ x: [NSObject: AnyObject]) -> [NSObject: AnyObject] { return x }
@objc func takesSet(_ x: Set<NSObject>) -> Set<NSObject> { return x }
@objc func fail() throws {}
}
// CHECK: [[BAZ_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: [[GARPLY_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[BLOCK_SIGNATURE_TRAD:@.*]] = private unnamed_addr constant [12 x i8] c"v24@0:8@?16\00"
// CHECK-macosx: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"c24@0:8^@16\00"
// CHECK-ios: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK-tvos: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK: @_INSTANCE_METHODS__TtC12objc_methods3Foo = private constant { {{.*}}] } {
// CHECK: i32 24,
// CHECK: i32 9,
// CHECK: [9 x { i8*, i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(baz)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[BAZ_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*)* @"$S12objc_methods3FooC3bazyyFTo" to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(garply:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[GARPLY_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i8*)* @"$S12objc_methods3FooC6garplyyyyXlSgFTo" to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(block:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64)*)* @"$S12objc_methods3FooC5blockyyS2iXEFTo" to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(block2:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @"$S12objc_methods3FooC6block2yyS2i_SitXEFTo" to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(failAndReturnError:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[FAIL_SIGNATURE]], i64 0, i64 0),
// CHECK-macosx: i8* bitcast (i8 (i8*, i8*, %4**)* @"$S12objc_methods3FooC4failyyKFTo" to i8*)
// CHECK-ios: i8* bitcast (i1 (i8*, i8*, %4**)* @"$S12objc_methods3FooC4failyyKFTo" to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: [[BLOCK_SIGNATURE_EXT_1:@.*]] = private unnamed_addr constant [18 x i8] c"v24@0:8@?<q@?q>16\00"
// CHECK: [[BLOCK_SIGNATURE_EXT_2:@.*]] = private unnamed_addr constant [19 x i8] c"v24@0:8@?<q@?qq>16\00"
// CHECK: [[STRING_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSString\2224@0:8@\22NSString\2216\00"
// CHECK: [[ARRAY_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [29 x i8] c"@\22NSArray\2224@0:8@\22NSArray\2216\00"
// CHECK: [[DICT_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [39 x i8] c"@\22NSDictionary\2224@0:8@\22NSDictionary\2216\00"
// CHECK: [[SET_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [25 x i8] c"@\22NSSet\2224@0:8@\22NSSet\2216\00"
// CHECK: @_PROTOCOL_METHOD_TYPES__TtP12objc_methods7Fooable_ = private constant [6 x i8*] [
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[BLOCK_SIGNATURE_EXT_1]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[BLOCK_SIGNATURE_EXT_2]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[STRING_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([29 x i8], [29 x i8]* [[ARRAY_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([39 x i8], [39 x i8]* [[DICT_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([25 x i8], [25 x i8]* [[SET_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: ]
// rdar://16006333 - observing properties don't work in @objc classes
@objc
class ObservingAccessorTest : NSObject {
var bounds: Int = 0 {
willSet {}
didSet {}
}
}
| apache-2.0 | 4d73cc78ceef982fe417f0f8065fc21c | 57.413043 | 157 | 0.627279 | 2.852442 | false | false | false | false |
colemancda/SwiftSequence | SwiftSequence/Permutations.swift | 1 | 5980 | // MARK: - Common
public extension MutableCollectionType {
/// [Algorithm](https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order)
public mutating func nextLexPerm
(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> Self? {
for k in indices.reverse().dropFirst()
where isOrderedBefore(self[k], self[k.successor()]) {
for l in indices.reverse() where isOrderedBefore(self[k], self[l]) {
swap(&self[k], &self[l])
let r = (k.successor()..<endIndex)
for (x, y) in zip(r, r.reverse()) {
if x == y || x == y.successor() { return self }
swap(&self[x], &self[y])
}
}
}
return nil
}
}
public extension MutableCollectionType where Generator.Element : Comparable {
/// [Algorithm](https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order)
public mutating func nextLexPerm() -> Self? {
return nextLexPerm(<)
}
}
/// :nodoc:
public struct LexPermGen<C : MutableCollectionType> : GeneratorType {
private var col: C?
private let order: (C.Generator.Element, C.Generator.Element) -> Bool
/// :nodoc:
mutating public func next() -> C? {
defer { col = col?.nextLexPerm(order) }
return col
}
}
/// :nodoc:
public struct LexPermSeq<C : MutableCollectionType> : LazySequenceType {
private let col: C
private let order: (C.Generator.Element, C.Generator.Element) -> Bool
/// :nodoc:
public func generate() -> LexPermGen<C> {
return LexPermGen(col: col, order: order)
}
}
// MARK: - Eager
public extension SequenceType {
/// Returns an array of the permutations of self, ordered lexicographically, according
/// to the closure `isOrderedBefore`.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// [1, 2, 3].lexPermutations(<)
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
/// ```swift
/// [1, 2, 3].lexPermutations(>)
///
/// [[1, 2, 3]]
/// ```
public func lexPermutations
(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> [[Generator.Element]] {
return Array(LexPermSeq(col: Array(self), order: isOrderedBefore))
}
}
public extension MutableCollectionType where Generator.Element : Comparable {
/// Returns an array of the permutations of self, ordered lexicographically.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// [1, 2, 3].lexPermutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
/// ```swift
/// [3, 2, 1].lexPermutations()
///
/// [[3, 2, 1]]
/// ```
public func lexPermutations() -> [[Generator.Element]] {
return Array(LexPermSeq(col: Array(self), order: <))
}
}
public extension SequenceType {
/// Returns an array of the permutations of self.
/// ```swift
/// [1, 2, 3].permutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
public func permutations() -> [[Generator.Element]] {
var col = Array(self)
return Array(LexPermSeq(col: Array(col.indices), order: <).map { inds in inds.map{col[$0]} })
}
/// Returns an array of the permutations of length `n` of self.
/// ```swift
/// [1, 2, 3].permutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
public func permutations(n: Int) -> [[Generator.Element]] {
return Array(lazyCombos(n).flatMap { a in a.permutations() })
}
}
// MARK: - Lazy
public extension SequenceType {
/// Returns a lazy sequence of the permutations of self, ordered lexicographically,
/// according to the closure `isOrderedBefore`.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations(<)
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations(>)
///
/// [1, 2, 3]
/// ```
public func lazyLexPermutations(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool)
-> LexPermSeq<[Generator.Element]> {
return LexPermSeq(col: Array(self), order: isOrderedBefore)
}
}
public extension SequenceType where Generator.Element : Comparable {
/// Returns a lazy sequence of the permutations of self, ordered lexicographically.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations()
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([3, 2, 1]).lazyLexPermutations()
///
/// [3, 2, 1]
/// ```
public func lazyLexPermutations() -> LexPermSeq<[Generator.Element]> {
return LexPermSeq(col: Array(self), order: <)
}}
public extension SequenceType {
/// Returns a lazy sequence of the permutations of self.
/// - Note: The permutations are lexicographically ordered, based on the indices of self
/// ```swift
/// lazy([1, 2, 3]).lazyPermutations()
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([3, 2, 1]).lazyPermutations()
///
/// [3, 2, 1], [3, 1, 2], [2, 3, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3]
/// ```
public func lazyPermutations() -> LazyMapSequence<LexPermSeq<[Int]>, [Self.Generator.Element]> {
let col = Array(self)
return col.indices.lazyLexPermutations().map { $0.map { col[$0] } }
}
}
| mit | d4fc4c0a312b21311d834f0d889b9d10 | 31.150538 | 98 | 0.593813 | 3.468677 | false | false | false | false |
sai-prasanna/SWMessages | Example/SWMessagesExample/ViewController.swift | 1 | 6834 | //
// ViewController.swift
//
// Copyright (c) 2016-present Sai Prasanna R
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SWMessages
class ViewController: UIViewController {
override func viewDidLoad() {
SWMessage.sharedInstance.defaultViewController = self
edgesForExtendedLayout = .all
navigationController?.navigationBar.isTranslucent = true
}
@IBAction func didTapError(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationWithTitle("Something failed!",
subtitle: "Cannot open the pod bay doors",
type: .error)
}
@IBAction func didTapWarning(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationWithTitle("Warning",
subtitle: "Imminent singularity, please take shelter or wage Butlerian Jihad",
type: .warning)
}
@IBAction func didTapMessage(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationWithTitle("Info",
subtitle: "Humans are required to submit for mandatory inspection!",
type: .message)
}
@IBAction func didTapSuccess(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationWithTitle("Success",
subtitle: "1 Ring delivered to Mount Doom",
type: .success)
}
@IBAction func didTapWithButton(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Update available",
subtitle: "Please update our app. We added AI to replace you",
image: nil,
type: .success,
duration: .automatic,
callback: nil,
buttonTitle: "Update",
buttonCallback: { SWMessage.sharedInstance.showNotificationWithTitle("Thanks for updating", type: .success)},
atPosition: .top,
canBeDismissedByUser: true)
}
@IBAction func didTapToggleNav(_ sender: AnyObject) {
navigationController?.setNavigationBarHidden(!navigationController!.isNavigationBarHidden, animated: true)
}
@IBAction func didTapNavAlpha(_ sender: AnyObject) {
navigationController?.navigationBar.alpha = navigationController?.navigationBar.alpha == 1 ? 0.5 : 1
}
@IBAction func didTapToggleFullscreen(_ sender: AnyObject) {
edgesForExtendedLayout = edgesForExtendedLayout == UIRectEdge() ? .all : UIRectEdge()
}
@IBAction func didTapDismiss(_ sender: AnyObject) {
let _ = SWMessage.sharedInstance.dismissActiveNotification()
}
@IBAction func didTapInfinite(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Endless",
subtitle: "This message can not be dismissed and will not be hidden automatically. Tap the 'Dismiss' button to dismiss the currently shown message",
image: nil,
type: .success,
duration: .endless,
callback: nil,
buttonTitle: nil,
buttonCallback: nil,
atPosition: .top,
canBeDismissedByUser: false)
}
@IBAction func didTapLongMessage(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Long",
subtitle: "This message is displayed 10 seconds instead of the calculated value",
image: nil,
type: .success,
duration: .custom(10),
callback: nil,
buttonTitle: nil,
buttonCallback: nil,
atPosition: .top,
canBeDismissedByUser: false)
}
@IBAction func didTapText(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Long Text",
subtitle: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus",
image: nil,
type: .success,
duration: .automatic,
callback: nil,
buttonTitle: nil,
buttonCallback: nil,
atPosition: .top,
canBeDismissedByUser: false)
}
@IBAction func didTapCustomDesign(_ sender: AnyObject) {
let style: SWMessageView.Style = SWMessageView.Style(backgroundColor: UIColor.purple, textColor: UIColor.yellow)
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus",
subtitle: nil,
image: nil,
type: .message,
duration: .automatic,
callback: nil,
buttonTitle: nil,
buttonCallback: nil,
atPosition: .top,
canBeDismissedByUser: false,
overrideStyle: style)
}
@IBAction func didTapBottom(_ sender: AnyObject) {
SWMessage.sharedInstance.showNotificationInViewController(self,
title: "Bottom",
subtitle: "showing message at bottom of screen",
image: nil,
type: .success,
duration: .automatic,
callback: nil,
buttonTitle: nil,
buttonCallback: nil,
atPosition: .bottom,
canBeDismissedByUser: false)
}
}
| mit | aa045d4cbe27b922e8418211352c14bb | 38.964912 | 288 | 0.648668 | 4.98105 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Schedule/ScheduleService.swift | 1 | 5581 | //
// ScheduleService.swift
// HTWDD
//
// Created by Benjamin Herzog on 29.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
class ScheduleService: Service {
var auth: Auth?
struct Auth: Hashable, Codable {
enum Degree: String, Codable {
case bachelor, diplom, master
}
let year: String
let major: String
let group: String
let degree: Degree
func hash(into hasher: inout Hasher) {
hasher.combine(self.year.hashValue ^ self.major.hashValue ^ self.group.hashValue ^ self.degree.rawValue.hashValue)
}
static func ==(lhs: ScheduleService.Auth, rhs: ScheduleService.Auth) -> Bool {
return lhs.year == rhs.year && lhs.major == rhs.major && lhs.group == rhs.group && lhs.degree == rhs.degree
}
}
struct Information: Codable, Equatable {
let lectures: [Day: [AppLecture]]
let semesters: [SemesterInformation]
init(lectures: [Day: [Lecture]], semesters: [SemesterInformation], hidden: inout [Int: Bool], colors: inout [Int: UInt]) {
var counter = 0
self.lectures = lectures.mapValues({ Information.injectDomainLogic(lectures: $0, counter: &counter, hidden: &hidden, colors: &colors) })
self.semesters = semesters
}
private static func injectDomainLogic(lectures: [Lecture], counter: inout Int, hidden: inout [Int: Bool], colors: inout [Int: UInt]) -> [AppLecture] {
return lectures.map { l in
let hash = l.fullHash()
let savedHidden = hidden[hash] ?? false
let nameHash = l.name.hashValue
let savedColor = colors[nameHash]
let color = savedColor ?? UIColor.htw.scheduleColors[counter % UIColor.htw.scheduleColors.count].hex()
if savedColor == nil {
counter += 1
colors[nameHash] = color
}
// TODO: Inject hidden as well! (get matching value from array)
return AppLecture(lecture: l, color: color, hidden: savedHidden)
}
}
private enum CodingKeys : CodingKey {
case lectures, semesters
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.lectures = try values.decode(CodableDictionary.self, forKey: .lectures).decoded
self.semesters = try values.decode([SemesterInformation].self, forKey: .semesters)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(CodableDictionary(self.lectures), forKey: .lectures)
try container.encode(self.semesters, forKey: .semesters)
}
static func ==(lhs: Information, rhs: Information) -> Bool {
guard lhs.lectures.count == rhs.lectures.count else {
return false
}
let allSame = lhs.lectures.reduce(true) { p, n -> Bool in
guard let rhsHas = rhs.lectures[n.key] else {
return false
}
return p && rhsHas == n.value
}
return allSame && lhs.semesters == rhs.semesters
}
}
private let network = Network()
private var cachedInformation = [Auth: Information]()
private let persistenceService = PersistenceService()
func load(parameters: Auth) -> Observable<Information> {
return Observable.empty()
// self.auth = parameters
//
// if let cached = self.cachedInformation[parameters] {
// return Observable.just(cached)
// }
//
//// let lecturesObservable = Lecture.get(network: self.network, year: parameters.year, major: parameters.major, group: parameters.group)
//// .map(Lecture.groupByDay)
// var hidden = self.loadHidden()
// var colors = self.loadColors()
//
// //let informationObservable = SemesterInformation.get(network: self.network)
//
// let cached = self.persistenceService.loadScheduleCache()
// let internetLoading: Observable<Information> = Observable.combineLatest(lecturesObservable, informationObservable) { [weak self] l, s in
// let information = Information(lectures: l, semesters: s, hidden: &hidden, colors: &colors)
// self?.saveHidden(hidden)
// self?.saveColors(colors)
// self?.cachedInformation[parameters] = information
// self?.persistenceService.save(information)
// return information
// }
// return Observable.merge(cached, internetLoading).distinctUntilChanged()
}
// MARK: - Hidden lectures
private func loadHidden() -> [Int: Bool] {
return self.persistenceService.loadHidden()
}
private func saveHidden(_ hidden: [Int: Bool]) {
self.persistenceService.save(hidden)
}
// MARK: - Lecture Colors
private func loadColors() -> [Int: UInt] {
return self.persistenceService.loadScheduleColors()
}
private func saveColors(_ colors: [Int: UInt]) {
self.persistenceService.save(colors)
}
}
// MARK: - Dependency management
extension ScheduleService: HasSchedule {
var scheduleService: ScheduleService { return self }
}
| gpl-2.0 | b20ad052bb7713aca91625661a406ee2 | 35.470588 | 158 | 0.596774 | 4.411067 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Renderers/ChartXAxisRendererBarChart.swift | 2 | 5472 | //
// ChartXAxisRendererBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartXAxisRendererBarChart: ChartXAxisRenderer
{
internal weak var _chart: BarChartView!;
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer);
self._chart = chart;
}
/// draws the x-labels on the specified y-position
internal override func drawLabels(#context: CGContext, pos: CGFloat)
{
if (_chart.data === nil)
{
return;
}
var paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle;
paraStyle.alignment = .Center;
var labelAttrs = [NSFontAttributeName: _xAxis.labelFont,
NSForegroundColorAttributeName: _xAxis.labelTextColor,
NSParagraphStyleAttributeName: paraStyle];
var barData = _chart.data as! BarChartData;
var step = barData.dataSetCount;
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
var labelMaxSize = CGSize();
if (_xAxis.isWordWrapEnabled)
{
labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a;
}
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
var label = i >= 0 && i < _xAxis.values.count ? _xAxis.values[i] : nil;
if (label == nil)
{
continue;
}
position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace + barData.groupSpace / 2.0;
position.y = 0.0;
// consider groups (center label for each group)
if (step > 1)
{
position.x += (CGFloat(step) - 1.0) / 2.0;
}
position = CGPointApplyAffineTransform(position, valueToPixelMatrix);
if (viewPortHandler.isInBoundsX(position.x))
{
var labelns = label! as NSString;
if (_xAxis.isAvoidFirstLastClippingEnabled)
{
// avoid clipping of the last
if (i == _xAxis.values.count - 1)
{
var width = label!.sizeWithAttributes(labelAttrs).width;
if (width > viewPortHandler.offsetRight * 2.0
&& position.x + width > viewPortHandler.chartWidth)
{
position.x -= width / 2.0;
}
}
else if (i == 0)
{ // avoid clipping of the first
var width = label!.sizeWithAttributes(labelAttrs).width;
position.x += width / 2.0;
}
}
ChartUtils.drawMultilineText(context: context, text: label!, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize);
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderGridLines(#context: CGContext)
{
if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled)
{
return;
}
var barData = _chart.data as! BarChartData;
var step = barData.dataSetCount;
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor);
CGContextSetLineWidth(context, _xAxis.gridLineWidth);
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
for (var i = _minX; i < _maxX; i += _xAxis.axisLabelModulus)
{
position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace - 0.5;
position.y = 0.0;
position = CGPointApplyAffineTransform(position, valueToPixelMatrix);
if (viewPortHandler.isInBoundsX(position.x))
{
_gridLineSegmentsBuffer[0].x = position.x;
_gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop;
_gridLineSegmentsBuffer[1].x = position.x;
_gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2);
}
}
CGContextRestoreGState(context);
}
} | apache-2.0 | a517d0834301136cd810200d747d0153 | 34.771242 | 189 | 0.547697 | 5.359452 | false | false | false | false |
wfleming/SwiftLint | Source/SwiftLintFramework/Rules/CyclomaticComplexityRule.swift | 2 | 5194 | //
// CyclomaticComplexityRule.swift
// SwiftLint
//
// Created by Denis Lebedev on 24/01/2016.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct CyclomaticComplexityRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 10, error: 20)
public init() {}
public static let description = RuleDescription(
identifier: "cyclomatic_complexity",
name: "Cyclomatic Complexity",
description: "Complexity of function bodies should be limited.",
nonTriggeringExamples: [
"func f1() {\nif true {\nfor _ in 1..5 { } }\nif false { }\n}",
"func f(code: Int) -> Int {" +
"switch code {\n case 0: fallthrough\ncase 0: return 1\ncase 0: return 1\n" +
"case 0: return 1\ncase 0: return 1\ncase 0: return 1\ncase 0: return 1\n" +
"case 0: return 1\ncase 0: return 1\ndefault: return 1}}",
"func f1() {" +
"if true {}; if true {}; if true {}; if true {}; if true {}; if true {}\n" +
"func f2() {\n" +
"if true {}; if true {}; if true {}; if true {}; if true {}\n" +
"}}",
],
triggeringExamples: [
"func f1() {\n if true {\n if true {\n if false {}\n }\n" +
" }\n if false {}\n let i = 0\n\n switch i {\n case 1: break\n" +
" case 2: break\n case 3: break\n case 4: break\n default: break\n }\n" +
" for _ in 1...5 {\n guard true else {\n return\n }\n }\n}\n"
]
)
public func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
if !functionKinds.contains(kind) {
return []
}
let complexity = measureComplexity(file, dictionary: dictionary)
for parameter in configuration.params where complexity > parameter.value {
let offset = Int(dictionary["key.offset"] as? Int64 ?? 0)
return [StyleViolation(ruleDescription: self.dynamicType.description,
severity: parameter.severity,
location: Location(file: file, byteOffset: offset),
reason: "Function should have complexity \(configuration.warning) or less: " +
"currently complexity equals \(complexity)")]
}
return []
}
private func measureComplexity(file: File,
dictionary: [String: SourceKitRepresentable]) -> Int {
var hasSwitchStatements = false
let substructure = dictionary["key.substructure"] as? [SourceKitRepresentable] ?? []
let complexity = substructure.reduce(0) { complexity, subItem in
guard let subDict = subItem as? [String: SourceKitRepresentable],
kind = subDict["key.kind"] as? String else {
return complexity
}
if let declarationKid = SwiftDeclarationKind(rawValue: kind)
where functionKinds.contains(declarationKid) {
return complexity
}
if kind == "source.lang.swift.stmt.switch" {
hasSwitchStatements = true
}
return complexity +
Int(complexityStatements.contains(kind)) +
measureComplexity(file, dictionary: subDict)
}
if hasSwitchStatements {
return reduceSwitchComplexity(complexity, file: file, dictionary: dictionary)
}
return complexity
}
// Switch complexity is reduced by `fallthrough` cases
private func reduceSwitchComplexity(complexity: Int, file: File,
dictionary: [String: SourceKitRepresentable]) -> Int {
let bodyOffset = Int(dictionary["key.bodyoffset"] as? Int64 ?? 0)
let bodyLength = Int(dictionary["key.bodylength"] as? Int64 ?? 0)
let c = (file.contents as NSString)
.substringWithByteRange(start: bodyOffset, length: bodyLength) ?? ""
let fallthroughCount = c.componentsSeparatedByString("fallthrough").count - 1
return complexity - fallthroughCount
}
private let complexityStatements = [
"source.lang.swift.stmt.foreach",
"source.lang.swift.stmt.if",
"source.lang.swift.stmt.case",
"source.lang.swift.stmt.guard",
"source.lang.swift.stmt.for",
"source.lang.swift.stmt.repeatwhile",
"source.lang.swift.stmt.while"
]
private let functionKinds: [SwiftDeclarationKind] = [
.FunctionAccessorAddress,
.FunctionAccessorDidset,
.FunctionAccessorGetter,
.FunctionAccessorMutableaddress,
.FunctionAccessorSetter,
.FunctionAccessorWillset,
.FunctionConstructor,
.FunctionDestructor,
.FunctionFree,
.FunctionMethodClass,
.FunctionMethodInstance,
.FunctionMethodStatic,
.FunctionOperator,
.FunctionSubscript
]
}
| mit | 8f10ae97b71361d30338411d3f376c51 | 37.466667 | 96 | 0.581167 | 4.657399 | false | false | false | false |
YouareMylovelyGirl/Sina-Weibo | 新浪微博/新浪微博/Classes/Tools(工具)/WeiBoCommon.swift | 1 | 1227 | //
// WeiBoCommon.swift
// 新浪微博
//
// Created by 阳光 on 2017/6/7.
// Copyright © 2017年 YG. All rights reserved.
//
import Foundation
import UIKit
//MARK: - 应用程序信息
//应用程序ID
let APPKey = "1659422547"
//39190169
//2715e085a21ca4f1083f3ff2544ee6cc
//------
//1659422547
//470bfdc420e5cdbcca12a60ffffba2da
//应用程序加密信息
let APPSecret = "470bfdc420e5cdbcca12a60ffffba2da"
//回调地址 - 登录完成跳转的URL, 参数以get形式拼接
let RedirectURI = "http://baidu.com"
//MARK: - 全局通知定义
//用户需要登录通知
let UserShouldLoginNotification = "UserShouldLoginNotification"
//用户登录成功通知
let UserLoginSuccessNotification = "UserLoginSuccessNotification"
//MARK: - 微博配图视图内部常量
//1. 计算配图视图的宽度
//配图视图外侧的间距
let StatusPictureViewOutterMargin = CGFloat(12)
//配图视图内部图像视图的间距
let StatusPictureViewInnerMargin = CGFloat(3)
//视图的宽度
let StatusPictureViewWidth = UIScreen.main.bounds.size.width - 2 * StatusPictureViewOutterMargin
//每个Item默认的高度
let StatusPictureItemWidth = ((StatusPictureViewWidth) - 2 * StatusPictureViewInnerMargin) / 3
| apache-2.0 | 010f562de9cf371d60b581347223a150 | 18.8 | 96 | 0.768687 | 2.990937 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/LinearEquations/Indeterminate/VLinearEquationsIndeterminateControl.swift | 1 | 3305 | import UIKit
class VLinearEquationsIndeterminateControl:UIView
{
private weak var controller:CLinearEquationsIndeterminate!
private let kButtonsWidth:CGFloat = 100
private let kButtonMargin:CGFloat = 10
private let kCornerRadius:CGFloat = 15
init(controller:CLinearEquationsIndeterminate)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.backgroundColor = UIColor.squadRed
buttonCancel.setTitle(
NSLocalizedString("VLinearEquationsIndeterminateControl_buttonCancel", comment:""),
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonCancel.titleLabel!.font = UIFont.bold(
size:13)
buttonCancel.layer.cornerRadius = kCornerRadius
buttonCancel.addTarget(
self,
action:#selector(actionCancel(sender:)),
for:UIControlEvents.touchUpInside)
let buttonSave:UIButton = UIButton()
buttonSave.translatesAutoresizingMaskIntoConstraints = false
buttonSave.backgroundColor = UIColor.squadBlue
buttonSave.setTitle(
NSLocalizedString("VLinearEquationsIndeterminateControl_buttonSave", comment:""),
for:UIControlState.normal)
buttonSave.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonSave.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonSave.titleLabel!.font = UIFont.bold(
size:13)
buttonSave.layer.cornerRadius = kCornerRadius
buttonSave.addTarget(
self,
action:#selector(actionSave(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(buttonCancel)
addSubview(buttonSave)
NSLayoutConstraint.equalsVertical(
view:buttonCancel,
toView:self,
margin:kButtonMargin)
NSLayoutConstraint.leftToLeft(
view:buttonCancel,
toView:self,
constant:kButtonMargin)
NSLayoutConstraint.width(
view:buttonCancel,
constant:kButtonsWidth)
NSLayoutConstraint.equalsVertical(
view:buttonSave,
toView:self,
margin:kButtonMargin)
NSLayoutConstraint.rightToRight(
view:buttonSave,
toView:self,
constant:-kButtonMargin)
NSLayoutConstraint.width(
view:buttonSave,
constant:kButtonsWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionCancel(sender button:UIButton)
{
controller.cancel()
}
func actionSave(sender button:UIButton)
{
controller.save()
}
}
| mit | 96099bc0a08c6b3a44be815812fd1104 | 31.401961 | 95 | 0.628139 | 5.798246 | false | false | false | false |
RiBj1993/CodeRoute | TableViewController.swift | 1 | 3124 | //
// TableViewController.swift
// LoginForm
//
// Created by SwiftR on 06/03/2017.
// Copyright © 2017 vishalsonawane. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 1fd1c75de561630a66039ef9581d2730 | 31.873684 | 136 | 0.670509 | 5.302207 | false | false | false | false |
jiamao130/DouYuSwift | DouYuBroad/DouYuBroad/Home/Controller/AmuseViewController.swift | 1 | 1271 | //
// AmuseViewController.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/14.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorController {
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
}
extension AmuseViewController{
override func setupUI() {
super.setupUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
extension AmuseViewController{
override func loadData(){
baseVM = amuseVM
amuseVM.loadAmuseData {
self.collectionView.reloadData()
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
self.loadDataFinished()
}
}
}
| mit | fc0d3fe6c581a0fd7518748c5e2c44f7 | 21.5 | 97 | 0.63254 | 4.719101 | false | false | false | false |
wikimedia/wikipedia-ios | WMF Framework/ColumnarCollectionViewLayoutMetrics.swift | 4 | 4328 | public struct ColumnarCollectionViewLayoutMetrics {
public static let defaultItemLayoutMargins = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) // individual cells on each explore card
public static let defaultExploreItemLayoutMargins = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) // explore card cells
let boundsSize: CGSize
let layoutMargins: UIEdgeInsets
let countOfColumns: Int
let itemLayoutMargins: UIEdgeInsets
let readableWidth: CGFloat
let interSectionSpacing: CGFloat
let interColumnSpacing: CGFloat
let interItemSpacing: CGFloat
var shouldMatchColumnHeights = false
public static func exploreViewMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
let useTwoColumns = boundsSize.width >= 600 || (boundsSize.width > boundsSize.height && readableWidth >= 500)
let countOfColumns = useTwoColumns ? 2 : 1
let interColumnSpacing: CGFloat = useTwoColumns ? 20 : 0
let interItemSpacing: CGFloat = 35
let interSectionSpacing: CGFloat = useTwoColumns ? 20 : 0
let layoutMarginsForMetrics: UIEdgeInsets
let itemLayoutMargins: UIEdgeInsets
let defaultItemMargins = ColumnarCollectionViewLayoutMetrics.defaultExploreItemLayoutMargins
let topAndBottomMargin: CGFloat = 30 // space between top of navigation bar and first section
if useTwoColumns {
let itemMarginWidth = max(defaultItemMargins.left, defaultItemMargins.right)
let marginWidth = max(max(max(layoutMargins.left, layoutMargins.right), round(0.5 * (boundsSize.width - (readableWidth * CGFloat(countOfColumns))))), itemMarginWidth)
layoutMarginsForMetrics = UIEdgeInsets(top: topAndBottomMargin, left: marginWidth - itemMarginWidth, bottom: topAndBottomMargin, right: marginWidth - itemMarginWidth)
itemLayoutMargins = UIEdgeInsets(top: defaultItemMargins.top, left: itemMarginWidth, bottom: defaultItemMargins.bottom, right: itemMarginWidth)
} else {
let marginWidth = max(layoutMargins.left, layoutMargins.right)
itemLayoutMargins = UIEdgeInsets(top: defaultItemMargins.top, left: marginWidth, bottom: defaultItemMargins.bottom, right: marginWidth)
layoutMarginsForMetrics = UIEdgeInsets(top: topAndBottomMargin, left: 0, bottom: topAndBottomMargin, right: 0)
}
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: layoutMarginsForMetrics, countOfColumns: countOfColumns, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: interSectionSpacing, interColumnSpacing: interColumnSpacing, interItemSpacing: interItemSpacing, shouldMatchColumnHeights: false)
}
public static func tableViewMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets, interSectionSpacing: CGFloat = 0, interItemSpacing: CGFloat = 0) -> ColumnarCollectionViewLayoutMetrics {
let marginWidth = max(max(layoutMargins.left, layoutMargins.right), round(0.5 * (boundsSize.width - readableWidth)))
var itemLayoutMargins = ColumnarCollectionViewLayoutMetrics.defaultItemLayoutMargins
itemLayoutMargins.left = max(marginWidth, itemLayoutMargins.left)
itemLayoutMargins.right = max(marginWidth, itemLayoutMargins.right)
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: .zero, countOfColumns: 1, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: interSectionSpacing, interColumnSpacing: 0, interItemSpacing: interItemSpacing, shouldMatchColumnHeights: false)
}
public static func exploreCardMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
let itemLayoutMargins = ColumnarCollectionViewLayoutMetrics.defaultItemLayoutMargins
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: layoutMargins, countOfColumns: 1, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: 0, interColumnSpacing: 0, interItemSpacing: 0, shouldMatchColumnHeights: false)
}
}
| mit | bc4f3feb796933f111ea9dfaf21576ce | 82.230769 | 365 | 0.771719 | 5.450882 | false | false | false | false |
exercism/xswift | exercises/twelve-days/Sources/TwelveDays/TwelveDaysExample.swift | 1 | 1404 | struct TwelveDaysSong {
private static let ordinals = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]
private static let gifts = ["a Partridge in a Pear Tree", "two Turtle Doves", "three French Hens", "four Calling Birds", "five Gold Rings", "six Geese-a-Laying", "seven Swans-a-Swimming", "eight Maids-a-Milking", "nine Ladies Dancing", "ten Lords-a-Leaping", "eleven Pipers Piping", "twelve Drummers Drumming"]
static func verse(_ verseNumber: Int) -> String {
let ordinal = ordinals[verseNumber - 1]
var verse = "On the \(ordinal) day of Christmas my true love gave to me: "
verse += gifts(forNumber: verseNumber)
return verse
}
static func verses(_ start: Int, _ end: Int) -> String {
var verses = [String]()
for i in start...end {
verses.append(verse(i))
}
return verses.joined(separator: "\n")
}
static func sing() -> String {
return verses(1, 12)
}
private static func gifts(forNumber number: Int) -> String {
let gift = gifts[number - 1]
if number == 1 {
return "\(gift)."
} else if number == 2 {
return "\(gift), and \(gifts(forNumber: number - 1))"
} else {
return "\(gift), \(gifts(forNumber: number - 1))"
}
}
}
| mit | 75eed22b68502363c647f2df2246549c | 35 | 314 | 0.576211 | 3.527638 | false | false | false | false |
DungntVccorp/Game | game-server/Sources/game-server/OperationKeepAlive.swift | 1 | 698 | //
// OperationKeepAlive.swift
// P
//
// Created by Nguyen Dung on 5/3/17.
//
//
class OperationKeepAlive : ConcurrentOperation{
override func TcpExcute() -> (Int, replyMsg: GSProtocolMessage?) {
var rep = Pcomm_KeepAlive.Reply()
rep.apiReply.time = 1234
rep.apiReply.type = 0
do{
let data = try rep.serializedData()
let msg = GSProtocolMessage()
msg.headCodeId = GSProtocolMessageType.headCode.profile
msg.subCodeId = GSProtocolMessageType.subCode.profile_KeepAlive
msg.protoContent = data
return (0,msg)
}catch{
return (-1,nil)
}
}
}
| mit | 1073f6cc4cfcb61c9cd909cba241b29c | 25.846154 | 75 | 0.574499 | 4.081871 | false | false | false | false |
Benoitcn/Upli | Upli/Upli/SetUpProfileStep3.swift | 1 | 1167 | //
// SetUpProfileStep3.swift
// Upli
//
// Created by 王毅 on 15/5/12.
// Copyright (c) 2015年 Ted. All rights reserved.
//
import UIKit
class SetUpProfileStep3 {
var titleLabel: String
var pickval:NSArray
class func allSetUpProfileStep3() -> [SetUpProfileStep3] {
var setUpProfileStep3s = [SetUpProfileStep3]()
if let URL = NSBundle.mainBundle().URLForResource("SetUpProfileStep3Item", withExtension: "plist") {
if let sessionsFromPlist = NSArray(contentsOfURL: URL) {
for dictionary in sessionsFromPlist {
let setUpProfileStep3 = SetUpProfileStep3(dictionary: dictionary as! NSDictionary)
setUpProfileStep3s.append(setUpProfileStep3)
}
}
}
return setUpProfileStep3s
}
init(title: String,pickval:NSArray) {
self.titleLabel = title
self.pickval=pickval
}
convenience init(dictionary: NSDictionary) {
let title = dictionary["Title"] as? String
let pickval=dictionary["Pick"]as? NSArray
self.init(title: title!,pickval:pickval!)
}
}
| apache-2.0 | f99273a7a12d18ac01aa495f8a965525 | 27.317073 | 108 | 0.622739 | 4.221818 | false | false | false | false |
m-alani/contests | hackerrank/Pangrams.swift | 1 | 659 | //
// Pangrams.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/pangrams
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Get the input
let input = Array(String(readLine()!)!.lowercased().characters)
// Solve the mystery
var alphabet = Set("abcdefghijklmnopqrstuvwxyz".characters)
var output = "not pangram"
for letter in input {
alphabet.remove(letter)
if (alphabet.count == 0) {
output = "pangram"
break
}
}
// Print the output
print(output)
| mit | e18fd4140800727306ddbadf1966abf0 | 23.407407 | 118 | 0.708649 | 3.581522 | false | false | false | false |
maxbritto/cours-ios11-swift4 | swift_4_cours_complet.playground/Pages/Lazy.xcplaygroundpage/Contents.swift | 1 | 847 | //: [< Sommaire](Sommaire)
/*:
# Propriétés Lazy
---
### Maxime Britto - Swift 4
*/
struct Player {
var firstname:String
var lastname:String
var score = 0
lazy var fullname = firstname + " " + lastname
var fullname_computed: String {
return firstname + " " + lastname
}
lazy var fullname_computed_lazy: String = {
return firstname + " " + lastname
}()
init(firstname:String, lastname:String) {
self.firstname = firstname
self.lastname = lastname
}
}
var p1 = Player(firstname: "Arya", lastname: "Stark")
print(p1.fullname)
print(p1.fullname_computed)
print("fullname_computed_lazy : " + p1.fullname_computed_lazy)
p1.firstname = "Eddard"
print(p1.fullname_computed)
print("fullname_computed_lazy : " + p1.fullname_computed_lazy)
/*:
[< Sommaire](Sommaire)
*/
| apache-2.0 | 8387cd07ae667587eefbc73355b7cc2d | 22.472222 | 62 | 0.639053 | 3.477366 | false | false | false | false |
mbeloded/beaconDemo | PassKitApp/PassKitApp/Classes/UI/Category/CategoryView.swift | 1 | 3589 | //
// CategoryView.swift
// PassKitApp
//
// Created by Alexandr Chernyy on 10/3/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import UIKit
var cellIdentBanner = "CategoryBannerCell"
var cellIdentBannerDetails = "CategoryBannerDetailsCell"
class CategoryView: UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView:UITableView!
@IBOutlet var bannnerView:BannerView!
var owner:UIViewController!
var mall_id:String!
var category_id:String!
var items:Array<AnyObject> = []
func setupView(mall_id_:String, category_id_:String)
{
mall_id = mall_id_
category_id = category_id_
bannnerView.setupView(mall_id_)
items = CoreDataManager.sharedManager.loadData(RequestType.STORE, key:category_id)
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var item = items[indexPath.row] as StoreModel
var height:CGFloat = 0.0
if(item.isSelected)
{
height = 239.0
} else {
height = 118.0
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var item = items[indexPath.row] as StoreModel
var banners:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.BANNER, key: item.banner_id)
var banner:BannerModel!
if(banners.count > 0)
{
banner = banners[0] as BannerModel
}
var url:String = banner.image
var parsed_url:NSString = url.stringByReplacingOccurrencesOfString("%20", withString: " ", options: nil, range: nil)
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(parsed_url.lastPathComponent)");
println(pngPath)
var cell:UITableViewCell!
if(item.isSelected)
{
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentBannerDetails) as CategoryBannerDetailsCell!
if (cell == nil) {
cell = CategoryBannerDetailsCell(style:.Default, reuseIdentifier: cellIdentBannerDetails)
}
(cell as CategoryBannerDetailsCell).bannerView.image = UIImage(named: pngPath)
(cell as CategoryBannerDetailsCell).titleLabel.text = item.name
(cell as CategoryBannerDetailsCell).detailsLabel.text = item.details
} else {
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentBanner) as CategoryBannerCell!
if (cell == nil) {
cell = CategoryBannerCell(style:.Default, reuseIdentifier: cellIdentBanner)
}
(cell as CategoryBannerCell).bannerView.image = UIImage(named: pngPath)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
var item = items[indexPath.row] as StoreModel
if(item.isSelected)
{
item.isSelected = false
} else {
item.isSelected = true
}
tableView.reloadData()
// tableView.reloadRowsAtIndexPaths(indexPath, withRowAnimation: UITableViewRowAnimation.Automatic)
//owner?.performSegueWithIdentifier("showItems", sender: owner)
}
}
| gpl-2.0 | 58770b09fee18bf0a022fa9a5757b0b6 | 32.542056 | 127 | 0.646141 | 4.929945 | false | false | false | false |
byss/KBAPISupport | KBAPISupport/Core/Internal/InputStream+readAll.swift | 1 | 1398 | //
// InputStream+readAll.swift
// CPCommon
//
// Created by Kirill Bystrov on 9/18/18.
//
import Foundation
internal extension InputStream {
private enum Error: Swift.Error {
case unknownReadFailure;
}
internal func readAll (_ dataCallback: (UnsafeRawPointer, Int) throws -> ()) throws {
var buffer = vm_address_t (0);
guard (vm_allocate (mach_task_self_, &buffer, vm_page_size, VM_FLAGS_ANYWHERE) == KERN_SUCCESS) else {
return;
}
defer {
vm_deallocate (mach_task_self_, buffer, vm_page_size);
}
guard let bufferPointer = UnsafeMutablePointer <UInt8> (bitPattern: buffer) else {
return;
}
while (self.hasBytesAvailable) {
switch (self.read (bufferPointer, maxLength: .streamPassthroughBufferSize)) {
case 0:
return;
case -1:
throw self.streamError ?? Error.unknownReadFailure;
case (let readResult):
try dataCallback (UnsafeRawPointer (bufferPointer), readResult);
}
}
}
}
fileprivate extension Int {
fileprivate static let streamPassthroughBufferSize = Int (bitPattern: vm_page_size);
}
#if arch (i386) || arch (arm) || arch (arm64_32)
fileprivate extension UnsafeMutablePointer where Pointee == UInt8 {
fileprivate init? (bitPattern: vm_size_t) {
self.init (bitPattern: Int (bitPattern: bitPattern));
}
}
fileprivate extension Int {
fileprivate init (bitPattern: vm_size_t) {
self.init (bitPattern);
}
}
#endif
| mit | f36a80be3f67bf88f30a9be8f3ee9df9 | 23.526316 | 104 | 0.699571 | 3.434889 | false | false | false | false |
dougbeal/Cartography | Cartography/LayoutProxy.swift | 4 | 5418 | //
// LayoutProxy.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
import Foundation
public struct LayoutProxy {
/// The width of the view.
public var width: Dimension {
return Dimension(context, view, .Width)
}
/// The height of the view.
public var height: Dimension {
return Dimension(context, view, .Height)
}
/// The size of the view. This property affects both `width` and `height`.
public var size: Size {
return Size(context, [
Dimension(context, view, .Width),
Dimension(context, view, .Height)
])
}
/// The top edge of the view.
public var top: Edge {
return Edge(context, view, .Top)
}
/// The right edge of the view.
public var right: Edge {
return Edge(context, view, .Right)
}
/// The bottom edge of the view.
public var bottom: Edge {
return Edge(context, view, .Bottom)
}
/// The left edge of the view.
public var left: Edge {
return Edge(context, view, .Left)
}
/// All edges of the view. This property affects `top`, `bottom`, `leading`
/// and `trailing`.
public var edges: Edges {
return Edges(context, [
Edge(context, view, .Top),
Edge(context, view, .Leading),
Edge(context, view, .Bottom),
Edge(context, view, .Trailing)
])
}
/// The leading edge of the view.
public var leading: Edge {
return Edge(context, view, .Leading)
}
/// The trailing edge of the view.
public var trailing: Edge {
return Edge(context, view, .Trailing)
}
/// The horizontal center of the view.
public var centerX: Edge {
return Edge(context, view, .CenterX)
}
/// The vertical center of the view.
public var centerY: Edge {
return Edge(context, view, .CenterY)
}
/// The center point of the view. This property affects `centerX` and
/// `centerY`.
public var center: Point {
return Point(context, [
Edge(context, view, .CenterX),
Edge(context, view, .CenterY)
])
}
/// The baseline of the view.
public var baseline: Edge {
return Edge(context, view, .Baseline)
}
#if os(iOS) || os(tvOS)
/// The first baseline of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var firstBaseline: Edge {
return Edge(context, view, .FirstBaseline)
}
/// All edges of the view with their respective margins. This property
/// affects `topMargin`, `bottomMargin`, `leadingMargin` and
/// `trailingMargin`.
@available(iOS, introduced=8.0)
public var edgesWithinMargins: Edges {
return Edges(context, [
Edge(context, view, .TopMargin),
Edge(context, view, .LeadingMargin),
Edge(context, view, .BottomMargin),
Edge(context, view, .TrailingMargin)
])
}
/// The left margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var leftMargin: Edge {
return Edge(context, view, .LeftMargin)
}
/// The right margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var rightMargin: Edge {
return Edge(context, view, .RightMargin)
}
/// The top margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var topMargin: Edge {
return Edge(context, view, .TopMargin)
}
/// The bottom margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var bottomMargin: Edge {
return Edge(context, view, .BottomMargin)
}
/// The leading margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var leadingMargin: Edge {
return Edge(context, view, .LeadingMargin)
}
/// The trailing margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var trailingMargin: Edge {
return Edge(context, view, .TrailingMargin)
}
/// The horizontal center within the margins of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerXWithinMargins: Edge {
return Edge(context, view, .CenterXWithinMargins)
}
/// The vertical center within the margins of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerYWithinMargins: Edge {
return Edge(context, view, .CenterYWithinMargins)
}
/// The center point within the margins of the view. This property affects
/// `centerXWithinMargins` and `centerYWithinMargins`. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerWithinMargins: Point {
return Point(context, [
Edge(context, view, .CenterXWithinMargins),
Edge(context, view, .CenterYWithinMargins)
])
}
#endif
internal let context: Context
internal let view: View
/// The superview of the view, if it exists.
public var superview: LayoutProxy? {
if let superview = view.superview {
return LayoutProxy(context, superview)
} else {
return nil
}
}
init(_ context: Context, _ view: View) {
self.context = context
self.view = view
}
}
| mit | 1ff887ac20791795b1868640b6df4fe5 | 27.356021 | 79 | 0.608383 | 4.305246 | false | false | false | false |
babarqb/HackingWithSwift | project6a/Project2/ViewController.swift | 48 | 1952 | //
// ViewController.swift
// Project2
//
// Created by Hudzilla on 13/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var countries = [String]()
var correctAnswer = 0
var score = 0
override func viewDidLoad() {
super.viewDidLoad()
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
button1.layer.borderColor = UIColor.lightGrayColor().CGColor
button2.layer.borderColor = UIColor.lightGrayColor().CGColor
button3.layer.borderColor = UIColor.lightGrayColor().CGColor
askQuestion(nil)
}
func askQuestion(action: UIAlertAction!) {
countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String]
button1.setImage(UIImage(named: countries[0]), forState: .Normal)
button2.setImage(UIImage(named: countries[1]), forState: .Normal)
button3.setImage(UIImage(named: countries[2]), forState: .Normal)
correctAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3)
title = countries[correctAnswer].uppercaseString
}
@IBAction func buttonTapped(sender: UIButton) {
var title: String
if sender.tag == correctAnswer {
title = "Correct"
++score
} else {
title = "Wrong"
--score
}
let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion))
presentViewController(ac, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| unlicense | 42fd10f484a1ef3162bdbb9232402d6c | 26.097222 | 129 | 0.727319 | 3.751923 | false | false | false | false |
Monnoroch/Cuckoo | Generator/Source/CuckooGeneratorFramework/Tokens/Kinds.swift | 1 | 635 | //
// Kinds.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 30.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public enum Kinds: String {
case ProtocolDeclaration = "source.lang.swift.decl.protocol"
case InstanceMethod = "source.lang.swift.decl.function.method.instance"
case MethodParameter = "source.lang.swift.decl.var.parameter"
case ClassDeclaration = "source.lang.swift.decl.class"
case ExtensionDeclaration = "source.lang.swift.decl.extension"
case InstanceVariable = "source.lang.swift.decl.var.instance"
case Mark = "source.lang.swift.syntaxtype.comment.mark"
}
| mit | 21e428312696e25aad8ea9f351ec5843 | 34.222222 | 75 | 0.728707 | 3.729412 | false | false | false | false |
lennet/proNotes | app/proNotes/Document/PageView/Movable/MovableImageView.swift | 1 | 2707 | //
// MovableImageView.swift
// proNotes
//
// Created by Leo Thomas on 06/12/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
class MovableImageView: MovableView, ImageSettingsDelegate {
weak var imageView: UIImageView?
var imageLayer: ImageLayer? {
get {
return movableLayer as? ImageLayer
}
}
override init(frame: CGRect, movableLayer: MovableLayer, renderMode: Bool = false) {
super.init(frame: frame, movableLayer: movableLayer, renderMode: renderMode)
proportionalResize = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
proportionalResize = true
}
func setUpImageView() {
clipsToBounds = true
let imageView = UIImageView()
imageView.image = imageLayer?.image
addSubview(imageView)
self.imageView = imageView
}
override func setUpSettingsViewController() {
ImageSettingsViewController.delegate = self
SettingsViewController.sharedInstance?.currentType = .image
}
// MARK: - ImageSettingsDelegate
func removeImage() {
removeFromSuperview()
movableLayer?.removeFromPage()
SettingsViewController.sharedInstance?.currentType = .pageInfo
}
func getImage() -> UIImage? {
return imageLayer?.image
}
override func undoAction(_ oldObject: Any?) {
guard let image = oldObject as? UIImage else {
super.undoAction(oldObject)
return
}
updateImage(image)
if SettingsViewController.sharedInstance?.currentType == .image {
SettingsViewController.sharedInstance?.currentChildViewController?.update()
}
}
func updateImage(_ image: UIImage) {
guard imageView != nil else {
return
}
if let oldImage = imageLayer?.image {
if movableLayer != nil && movableLayer?.docPage != nil {
DocumentInstance.sharedInstance.registerUndoAction(oldImage, pageIndex: movableLayer!.docPage.index, layerIndex: movableLayer!.index)
}
}
let heightRatio = imageView!.bounds.height / imageView!.image!.size.height
let widthRatio = imageView!.bounds.width / imageView!.image!.size.width
imageView?.image = image
imageLayer?.image = image
frame.size.height = (image.size.height * heightRatio) + controlLength
frame.size.width = (image.size.width * widthRatio) + controlLength
movableLayer?.size = frame.size
layoutIfNeeded()
setNeedsDisplay()
saveChanges()
}
}
| mit | b905459dfdd5390b41217e09ff1e526f | 28.096774 | 149 | 0.63119 | 4.99262 | false | false | false | false |
RaviDesai/RSDRestServices | Pod/Classes/APIRequest.swift | 2 | 2349 | //
// APIRequest.swift
//
// Created by Ravi Desai on 6/10/15.
// Copyright (c) 2015 RSD. All rights reserved.
//
import Foundation
public class APIRequest<U: APIResponseParserProtocol> {
private var baseURL: NSURL?
private var endpoint: APIEndpoint
private var bodyEncoder: APIBodyEncoderProtocol?
private var additionalHeaders: [String: String]?
public private(set) var responseParser: U
public init(baseURL: NSURL?, endpoint: APIEndpoint, bodyEncoder: APIBodyEncoderProtocol?, responseParser: U, additionalHeaders: [String: String]?) {
self.baseURL = baseURL
self.endpoint = endpoint
self.bodyEncoder = bodyEncoder
self.additionalHeaders = additionalHeaders
self.responseParser = responseParser
}
public func URL() -> NSURL? {
return self.endpoint.URL(self.baseURL)
}
public func acceptTypes() -> String? {
return self.responseParser.acceptTypes?.joinWithSeparator(", ")
}
public func method() -> String {
return self.endpoint.method()
}
public func contentType() -> String? {
return self.bodyEncoder?.contentType()
}
public func body() -> NSData? {
return self.bodyEncoder?.body()
}
public func makeRequest() -> NSMutableURLRequest? {
var result: NSMutableURLRequest?
if let url = self.URL() {
let mutableRequest = NSMutableURLRequest(URL: url)
mutableRequest.HTTPMethod = self.method()
if let data = body() {
mutableRequest.HTTPBody = data;
NSURLProtocol.setProperty(data.copy(), forKey: "PostedData", inRequest: mutableRequest)
}
if let headers = self.additionalHeaders {
for header in headers {
mutableRequest.setValue(header.1, forHTTPHeaderField: header.0);
}
}
if let acceptTypes = self.acceptTypes() {
mutableRequest.setValue(acceptTypes, forHTTPHeaderField: "Accept")
}
if let contentType = self.contentType() {
mutableRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
}
result = mutableRequest
}
return result
}
} | mit | 8bdd60864dcd3d1e69a26f3fe8a35729 | 31.638889 | 152 | 0.605364 | 5.174009 | false | false | false | false |
Gericop/iCar | iCar/RefillDetailsViewController.swift | 1 | 2551 | //
// RefillDetailsViewController.swift
// iCar
//
// Created by Gergely Kőrössy on 09/12/15.
// Copyright © 2015 Gergely Kőrössy. All rights reserved.
//
import UIKit
import MapKit
class RefillDetailsViewController: UIViewController {
@IBOutlet weak var quantityField: UITextField!
@IBOutlet weak var unitPriceField: UITextField!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var typeField: UITextField!
@IBOutlet weak var odometerField: UITextField!
@IBOutlet weak var carField: UITextField!
@IBOutlet weak var locationMapView: MKMapView!
var refillLog : RefillLog?
override func viewDidLoad() {
super.viewDidLoad()
if let log = refillLog {
quantityField.text = String(log.refillQnty!)
unitPriceField.text = String(log.unitPrice!)
typeField.text = log.type
odometerField.text = String(log.odometer!) + "km"
refreshTotalPrice()
let car = log.car as! Car
carField.text = "\(car.name!) [\(car.licensePlate!)]"
/*let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
navigationItem.prompt = dateFormatter.stringFromDate(log.time!)*/
// setting map
let mapAnnotation = MapPointAnnotation()
let coords = CLLocationCoordinate2DMake(CLLocationDegrees(log.lat!), CLLocationDegrees(log.lon!))
mapAnnotation.setCoordinate(coords)
locationMapView.addAnnotation(mapAnnotation)
locationMapView.centerCoordinate = coords
}
}
func refreshTotalPrice() {
let quantityStr = quantityField.text
let unitPriceStr = unitPriceField.text
if quantityStr != "" && unitPriceStr != "" {
let quantity = Double(quantityStr!) ?? 0
let unitPrice = Double(unitPriceStr!) ?? 0
totalLabel.text = "\(quantity * unitPrice)"
}
}
// 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 != "AddRefillLog" {
let detailsVC = segue.destinationViewController as! RefillEditorViewController
detailsVC.refillLog = refillLog
//}
}
}
| apache-2.0 | dd491cb3912a025ca26e78faa6588951 | 32.064935 | 109 | 0.623331 | 4.992157 | false | false | false | false |
xuzhou524/Convenient-Swift | View/RootCalendarTableViewCell.swift | 1 | 1432 | //
// RootCalendarTableViewCell.swift
// Convenient-Swift
//
// Created by gozap on 16/7/18.
// Copyright © 2016年 xuzhou. All rights reserved.
//
import UIKit
class RootCalendarTableViewCell: UITableViewCell {
var calendar : LBCalendar!
var calendarContentView : LBCalendarContentView?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sebViewS()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.sebViewS()
}
func sebViewS(){
calendarContentView = LBCalendarContentView()
calendarContentView?.backgroundColor = XZSwiftColor.white
self.contentView.addSubview(calendarContentView!)
calendarContentView?.snp.makeConstraints({ (make) in
make.left.top.right.bottom.equalTo(self.contentView)
});
self.calendar = LBCalendar.init()
//self.calendar?.calendarAppearance().calendar().firstWeekday = 1 //Sunday ==1,Saturday == 7
self.calendar?.calendarAppearance().dayRectangularRatio = 9.00 / 10.00
self.calendar?.contentView = calendarContentView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 1e37573d929e7dc6ffdd12f5c6e74316 | 32.232558 | 101 | 0.671099 | 4.594855 | false | false | false | false |
ali-zahedi/AZViewer | AZViewer/AZImageLoader.swift | 1 | 3061 | //
// ImageLoader.swift
//
//
// Created by Ali Zahedi on 8/5/1395 AP.
// Copyright © 1395 Ali Zahedi. All rights reserved.
//
import Foundation
import UIKit
public class AZImageLoader {
var cache = NSCache<AnyObject, AnyObject>()
public static let shared = AZImageLoader()
private init() {} //This prevents others from using the default '()' initializer for this class.
public func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
let fileManager = FileManager.default
var check_currect_image: Bool = false
if fileManager.fileExists(atPath: self.getFileLocation(urlString: urlString).path) {
let image = UIImage(contentsOfFile: self.getFileLocation(urlString: urlString).path)
if image != nil {
check_currect_image = true
completionHandler(image, urlString)
}
}
if (!check_currect_image) {
func problemLoad(){
print("problem load url: \(urlString)")
completionHandler(UIImage(), urlString)
}
guard let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let url = URL(string: escapedAddress) else {
problemLoad()
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else {
problemLoad()
return
}
DispatchQueue.main.async() { () -> Void in
if let data = UIImagePNGRepresentation(image) {
try? data.write(to: self.getFileLocation(urlString: urlString), options: [])
completionHandler(image, urlString)
}
}
}.resume()
}
}
func getFileLocation(urlString: String) -> URL{
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let dataPath = documentsURL.appendingPathComponent("cache")
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error creating directory: \(error.localizedDescription)")
}
let nameOfFile: String = urlString.components(separatedBy: "/").last!
return dataPath.appendingPathComponent(nameOfFile)
}
}
| apache-2.0 | eb334f4bf0f3f61b91e96442978d22b2 | 35 | 171 | 0.554575 | 5.583942 | false | false | false | false |
PlutoMa/SwiftProjects | 018.Spotlight Search/SpotlightSearch/SpotlightSearch/AppDelegate.swift | 1 | 1485 | //
// AppDelegate.swift
// SpotlightSearch
//
// Created by Dareway on 2017/11/1.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let navi = UINavigationController.init(rootViewController: ViewController())
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = navi
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
let identifier = userActivity.userInfo?["kCSSearchableItemActivityIdentifier"] as! String
NotificationCenter.default.post(name: notificationName, object: self, userInfo: ["id":identifier])
return true
}
}
| mit | 950e4d25822a5f45d5fe879617285d2e | 28.64 | 147 | 0.710526 | 5.592453 | false | false | false | false |
weihongjiang/PROJECTTOWN | Town/Town/AppDelegate.swift | 1 | 3376 | //
// AppDelegate.swift
// Town
//
// Created by john.wei on 15/6/4.
// Copyright (c) 2015年 whj. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//var centerController:JACenterViewController!
// var leftController:JALeftViewController!
// var rightController:JARightViewController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var panelController = JASidePanelController()
var centerController = JACenterViewController()
var navController = UINavigationController(rootViewController:centerController)
navController.navigationBar.tintColor = UIColor.whiteColor()
navController.navigationBar.barTintColor = UIColor(red: 0, green: 176/255.0, blue: 232/255, alpha: 1.0)
let titleAtrr: NSDictionary = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
navController.navigationBar.titleTextAttributes = titleAtrr as? Dictionary
panelController.leftPanel = JALeftViewController()
panelController.rightPanel = JARightViewController()
panelController.centerPanel = navController
var tabbarController = UITabBarController()
self.window!.rootViewController = panelController
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:.
}
}
| apache-2.0 | a20f56d5fbce21bf6fd224720077a781 | 46.521127 | 285 | 0.736811 | 5.531148 | false | false | false | false |
shafiullakhan/Swift-Paper | Swift-Paper/Swift-Paper/ViewController.swift | 1 | 13123 | //
// ViewController.swift
// Swift-Paper
//
// Created by Shaf on 8/5/15.
// Copyright (c) 2015 Shaffiulla. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIGestureRecognizerDelegate,UITableViewDataSource,UITableViewDelegate,PaperBubleDelegate {
private var toogle = true;
private var bubble:PaperBuble?;
private var addfrd,noti,msg: UIImageView?;
var baseController = BaseCollection(collectionViewLayout: SmallLayout())
var slide: Int = 0
var mainView:UIView?
var topImage,reflected: UIImageView?
var galleryImages = ["one.jpg", "two.jpg", "three.png", "five.jpg", "one.jpg"]
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
//
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.baseController.collectionView?.frame = UIScreen.mainScreen().bounds;
self.view.addSubview(self.baseController.collectionView!)
// Init mainView
addMainView();
// ImageView on top
addTopImage();
// Reflect imageView
addReflectImage();
// Add Card Details
addCardDetails();
// First Load
changeSlide();
let timer = NSTimer(timeInterval: 5.0, target: self, selector: "changeSlide", userInfo: nil, repeats: true)
// notificaiton friedns and messsage
addNotificationTabs();
}
func addMainView(){
self.mainView = UIView(frame: self.view.bounds)
self.mainView?.clipsToBounds = true
self.mainView?.layer.cornerRadius = 4
self.view.insertSubview(self.mainView!, belowSubview: self.baseController.collectionView!)
}
func addTopImage(){
self.topImage = UIImageView(frame: CGRectMake(0, 0, self.view.frame.size.width, AppDelegate.sharedDelegate().itemHeight-256))
self.topImage?.contentMode = UIViewContentMode.ScaleAspectFill;
self.mainView?.addSubview(self.topImage!)
// Gradient to top image
var gradient = CAGradientLayer();
gradient.frame = self.topImage!.bounds;
gradient.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).CGColor,UIColor(white: 0, alpha: 0).CGColor];
self.topImage!.layer.insertSublayer(gradient, atIndex: 0);
// Content perfect pixel
var perfectPixelContent = UIView(frame: CGRectMake(0, 0, CGRectGetWidth(self.topImage!.bounds), 1));
perfectPixelContent.backgroundColor = UIColor(white: 1, alpha: 0.2);
self.topImage!.addSubview(perfectPixelContent);
}
func addReflectImage(){
self.reflected = UIImageView(frame: CGRectMake(0, CGRectGetHeight(self.topImage!.bounds), self.view.frame.size.width, self.view.frame.size.height/2))
self.mainView?.addSubview(self.reflected!)
self.reflected!.transform = CGAffineTransformMakeScale(1.0, -1.0);
// Gradient to reflected image
var gradientReflected = CAGradientLayer();
gradientReflected.frame = self.reflected!.bounds;
gradientReflected.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor,UIColor(white: 0, alpha: 0).CGColor];
self.reflected!.layer.insertSublayer(gradientReflected, atIndex: 0);
}
func addCardDetails(){
// Label logo
var logo = UILabel(frame: CGRectMake(15, 12, 100, 0))
logo.backgroundColor = UIColor.clearColor();
logo.textColor = UIColor.whiteColor();
logo.font = UIFont(name: "Helvetica-Bold", size: 22);
logo.text = "MMPaper";
logo.sizeToFit();
// Label Shadow
logo.clipsToBounds = false;
logo.layer.shadowOffset = CGSizeMake(0, 0);
logo.layer.shadowColor = UIColor.blackColor().CGColor;
logo.layer.shadowRadius = 1.0;
logo.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(logo);
// Label Title
var title = UILabel(frame: CGRectMake(15, logo.frame.origin.y + CGRectGetHeight(logo.frame) + 8, 290, 0))
title.backgroundColor = UIColor.clearColor();
title.textColor = UIColor.whiteColor();
title.font = UIFont(name: "Helvetica-Bold", size: 13);
title.text = "Mukesh Mandora";
title.sizeToFit();
// Label Shadow
title.clipsToBounds = false;
title.layer.shadowOffset = CGSizeMake(0, 0);
title.layer.shadowColor = UIColor.blackColor().CGColor;
title.layer.shadowRadius = 1.0;
title.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(title);
// Label SubTitle
var subTitle = UILabel(frame: CGRectMake(15, title.frame.origin.y + CGRectGetHeight(title.frame), 290, 0))
subTitle.backgroundColor = UIColor.clearColor();
subTitle.textColor = UIColor.whiteColor();
subTitle.font = UIFont(name: "Helvetica", size: 13);
subTitle.text = "Inspired from Paper by Facebook";
subTitle.lineBreakMode = .ByWordWrapping;
subTitle.numberOfLines = 0;
subTitle.sizeToFit();
// Label Shadow
subTitle.clipsToBounds = false;
subTitle.layer.shadowOffset = CGSizeMake(0, 0);
subTitle.layer.shadowColor = UIColor.blackColor().CGColor;
subTitle.layer.shadowRadius = 1.0;
subTitle.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(subTitle);
}
func addNotificationTabs(){
noti=UIImageView(frame: CGRectMake(self.view.frame.size.width-50, 20, 25, 25));
noti!.image = UIImage(named: "Tones-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
noti!.tintColor=UIColor.whiteColor();
noti?.userInteractionEnabled = true;
self.view.addSubview(noti!)
addfrd=UIImageView(frame: CGRectMake(noti!.frame.origin.x-50, 20, 25, 25));
addfrd!.image=UIImage(named: "Group-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
addfrd!.tintColor=UIColor.whiteColor();
addfrd?.userInteractionEnabled = true;
self.view.addSubview(addfrd!)
msg=UIImageView(frame: CGRectMake(addfrd!.frame.origin.x-50, 20, 25, 25));
msg!.image=UIImage(named: "Talk-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
msg!.tintColor=UIColor.whiteColor();
msg?.userInteractionEnabled = true;
self.view.addSubview(msg!)
var tapNoti=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapNoti.delegate=self;
noti?.addGestureRecognizer(tapNoti);
noti!.tag = 1;
var tapFrd=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapFrd.delegate=self;
addfrd?.addGestureRecognizer(tapFrd);
addfrd!.tag = 2;
var tapChat=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapChat.delegate=self;
msg?.addGestureRecognizer(tapChat);
msg!.tag = 3;
}
//MARK: Gesture Action
func tapBubble(sender: UIGestureRecognizer){
let tag = sender.view?.tag;
if tag == 1{
self.toogleHelpAction(self)
}
else if tag == 2{
actionBut2(self)
}
else{
actionbut3(self)
}
}
func toogleHelpAction(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, noti!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: noti!);
bubble!.delegate = self
bubble!.button1=noti;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==noti){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=noti;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func actionBut2(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, addfrd!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: addfrd!);
bubble!.delegate = self
bubble!.button1=addfrd;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==addfrd){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=addfrd;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func actionbut3(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, msg!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: msg!);
bubble!.delegate = self
bubble!.button1=msg;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==msg){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=msg;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func dismissBubble(){
toogle=true;
bubble=nil;
}
//MARK: Timer Action
func changeSlide(){
if slide > (galleryImages.count - 1){
slide = 0
}
let toImage = UIImage(named: galleryImages[slide])
UIView.transitionWithView(self.mainView!,
duration: 0.6,
options: UIViewAnimationOptions.TransitionCrossDissolve | UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.topImage?.image = toImage;
self.reflected?.image = toImage;
}, completion: nil)
slide++
}
//MARK: TableViewData Source
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30;
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
var view = UIView(frame: CGRectMake(0, 10, tableView.frame.size.width, 30))
view.backgroundColor = UIColor.whiteColor()
/* Create custom view to display section header... */
var result : UInt32 = 0
NSScanner(string: "0xe94c5e").scanHexInt(&result);
var label = UILabel(frame: CGRectMake(18, 10, 300, 20))
label.textAlignment = .Left
label.textColor = UIColor.blackColor();
label.font = UIFont(name: "HelveticaNeue", size: 20)
if(bubble!.button1==noti!){
label.text="Notification";
}
else if (bubble!.button1==addfrd!){
label.text="Friend Request";
}
else{
label.text="Chats";
}
label.textColor = UIColor.lightGrayColor();
view.addSubview(label)
view.backgroundColor = UIColor.whiteColor()
view.layer.cornerRadius = 5.0
view.clipsToBounds = false;
view.layer.masksToBounds = false
return view
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let simpleTableIdentifier = "SimpleTableCell"
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
}
cell?.backgroundColor = UIColor.clearColor()
return cell!;
}
}
| mit | baf2adb3d99800e7171574b836bc5cc3 | 34.563686 | 157 | 0.594757 | 4.633828 | false | false | false | false |
dreamsxin/swift | test/Parse/operators.swift | 3 | 2640 | // RUN: %target-parse-verify-swift -parse-stdlib
// This disables importing the stdlib intentionally.
infix operator == {
associativity left
precedence 110
}
infix operator & {
associativity left
precedence 150
}
infix operator => {
associativity right
precedence 100
}
struct Man {}
struct TheDevil {}
struct God {}
struct Five {}
struct Six {}
struct Seven {}
struct ManIsFive {}
struct TheDevilIsSix {}
struct GodIsSeven {}
struct TheDevilIsSixThenGodIsSeven {}
func == (x: Man, y: Five) -> ManIsFive {}
func == (x: TheDevil, y: Six) -> TheDevilIsSix {}
func == (x: God, y: Seven) -> GodIsSeven {}
func => (x: TheDevilIsSix, y: GodIsSeven) -> TheDevilIsSixThenGodIsSeven {}
func => (x: ManIsFive, y: TheDevilIsSixThenGodIsSeven) {}
func test1() {
Man() == Five() => TheDevil() == Six() => God() == Seven()
}
postfix operator *!* {}
prefix operator *!* {}
struct LOOK {}
struct LOOKBang {
func exclaim() {}
}
postfix func *!* (x: LOOK) -> LOOKBang {}
prefix func *!* (x: LOOKBang) {}
func test2() {
*!*LOOK()*!*
}
// This should be parsed as (x*!*).exclaim()
LOOK()*!*.exclaim()
prefix operator ^ {}
infix operator ^ {}
postfix operator ^ {}
postfix func ^ (x: God) -> TheDevil {}
prefix func ^ (x: TheDevil) -> God {}
func ^ (x: TheDevil, y: God) -> Man {}
var _ : TheDevil = God()^
var _ : God = ^TheDevil()
var _ : Man = TheDevil() ^ God()
var _ : Man = God()^ ^ ^TheDevil()
let _ = God()^TheDevil() // expected-error{{cannot convert value of type 'God' to expected argument type 'TheDevil'}}
postfix func ^ (x: Man) -> () -> God {
return { return God() }
}
var _ : God = Man()^() // expected-error{{cannot convert value of type 'Man' to expected argument type 'TheDevil'}}
func &(x : Man, y : Man) -> Man { return x } // forgive amp_prefix token
prefix operator ⚽️ {}
prefix func ⚽️(x: Man) { }
infix operator ?? {
associativity right
precedence 100
}
func ??(x: Man, y: TheDevil) -> TheDevil {
return y
}
func test3(a: Man, b: Man, c: TheDevil) -> TheDevil {
return a ?? b ?? c
}
// <rdar://problem/17821399> We don't parse infix operators bound on both
// sides that begin with ! or ? correctly yet.
infix operator !! {}
func !!(x: Man, y: Man) {}
let foo = Man()
let bar = TheDevil()
foo!!foo // expected-error{{cannot force unwrap value of non-optional type 'Man'}} {{4-5=}} expected-error{{consecutive statements}} {{6-6=;}}
// expected-warning @-1 {{expression of type 'Man' is unused}}
foo??bar // expected-error{{broken standard library}} expected-error{{consecutive statements}} {{6-6=;}}
// expected-warning @-1 {{expression of type 'TheDevil' is unused}}
| apache-2.0 | 2aa8060836395bf8084403a39a99f555 | 21.886957 | 142 | 0.637538 | 3.035755 | false | false | false | false |
rnystrom/GitHawk | Local Pods/GitHubAPI/GitHubAPI/Processing.swift | 1 | 1118 | //
// Processing.swift
// GitHubAPI
//
// Created by Ryan Nystrom on 3/3/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
internal func processResponse<T: Request>(
request: T,
input: Any? = nil,
response: HTTPURLResponse? = nil,
error: Error? = nil
) -> Result<T.ResponseType> {
guard error == nil else {
return .failure(error)
}
guard let input = input as? T.ResponseType.InputType else {
return .failure(ClientError.mismatchedInput)
}
do {
let output = try T.ResponseType(input: input, response: response)
return .success(output)
} catch {
return .failure(error)
}
}
internal func asyncProcessResponse<T: Request>(
request: T,
input: Any?,
response: HTTPURLResponse?,
error: Error?,
completion: @escaping (Result<T.ResponseType>) -> Void
) {
DispatchQueue.global().async {
let result = processResponse(request: request, input: input, response: response, error: error)
DispatchQueue.main.async {
completion(result)
}
}
}
| mit | 30307545f4a5999f26a45fe09b186eda | 24.386364 | 102 | 0.626679 | 4.047101 | false | false | false | false |
335g/TwitterAPIKit | Sources/APIs/MutesAPI.swift | 1 | 5352 | //
// Mutes.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/07.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
import APIKit
// MARK: Request
public protocol MutesRequestType: TwitterAPIRequestType {}
public protocol MutesGetRequestType: MutesRequestType {}
public protocol MutesPostRequestType: MutesRequestType {}
public extension MutesRequestType {
public var baseURL: NSURL {
return NSURL(string: "https://api.twitter.com/1.1/mutes/users")!
}
}
public extension MutesGetRequestType {
public var method: APIKit.HTTPMethod {
return .GET
}
}
public extension MutesPostRequestType {
public var method: APIKit.HTTPMethod {
return .POST
}
}
// MARK: API
public enum TwitterMutes {
///
/// https://dev.twitter.com/rest/reference/get/mutes/users/ids
///
public struct Ids: MutesGetRequestType {
public typealias Response = UserIDs
public let client: OAuthAPIClient
public var path: String {
return "/ids.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
cursorStr: String = "-1"){
self.client = client
self._parameters = ["cursor": cursorStr]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Ids.Response {
guard let
dictionary = object as? [String: AnyObject],
ids = UserIDs(dictionary: dictionary) else {
throw DecodeError.Fail
}
return ids
}
}
///
/// https://dev.twitter.com/rest/reference/get/mutes/users/list
///
public struct List: MutesGetRequestType {
public typealias Response = UsersList
public let client: OAuthAPIClient
public var path: String {
return "/list.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
cursorStr: String = "-1",
includeEntities: Bool = false,
skipStatus: Bool = true){
self.client = client
self._parameters = [
"cursor": cursorStr,
"include_entities": includeEntities,
"skip_status": skipStatus
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> List.Response {
guard let
dictionary = object as? [String: AnyObject],
list = UsersList(dictionary: dictionary) else {
throw DecodeError.Fail
}
return list
}
}
///
/// https://dev.twitter.com/rest/reference/post/mutes/users/create
///
public struct Create: MutesPostRequestType, SingleUserResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/create.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User){
self.client = client
self._parameters = [user.key: user.obj]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Users {
return try userFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/mutes/users/destroy
///
public struct Destroy: MutesPostRequestType, SingleUserResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/destory.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
let url = self.baseURL.absoluteString + self.path
let header = client.authHeader(self.method, url, parameters, false)
URLRequest.setValue(header, forHTTPHeaderField: "Authorization")
return URLRequest
}
public init(
_ client: OAuthAPIClient,
user: User){
self.client = client
self._parameters = [user.key: user.obj]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Users {
return try userFromObject(object, URLResponse)
}
}
} | mit | 8227d1e9f68a94f865f988dd0917151e | 28.234973 | 115 | 0.561039 | 5.228739 | false | false | false | false |
IndisputableLabs/Swifthereum | Swifthereum/Classes/Web3/Network/Resource.swift | 1 | 2092 | //
// Resource.swift
// Crisp
//
// Created by Ronald Mannak on 1/11/17.
// Copyright © 2017 A Puzzle A Day. All rights reserved.
//
import Foundation
public enum HttpMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case head = "HEAD"
}
public enum ParameterEncoding {
case json
/// Only use for GET, DELETE, and HEAD methods
case url
/// Only use for POST, PUT, PATCH methods
case body
public func contentType() -> String {
switch self {
case .json:
return "application/json"
case .url, .body:
return "application/x-www-form-urlencoded"
}
}
}
public struct Resource<A: Decodable> {
public let server: Server
public let method: String // E.g. "eth_sign"
public let headers: JSONDictionary?
public let parameters: Decodable? // E.g. ["0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "0xdeadbeaf"]
public let httpMethod: HttpMethod
public let encoding: ParameterEncoding
/**
Called by NetworkService to parse the data returned from the server. Depending on the kind of data we expect (e.g. JSON vs an image) we can set a suitable closure in the init.
*/
public let parse: (Data) throws -> A?
}
extension Resource {
public init(server: Server, method: String, parameters: Decodable? = nil, headers: JSONDictionary? = nil, httpMethod: HttpMethod = .post, encoding: ParameterEncoding = .json) {
self.server = server
self.method = method
self.headers = headers
self.parameters = parameters
self.httpMethod = httpMethod
self.encoding = encoding
parse = { data in
let encodedData = try JSONDecoder().decode(A.self, from: data)
return encodedData
}
}
public init(server: Server, method: Method) {
self.init(server: server, method: method.method, parameters: method.parameters)
}
}
| mit | b14de2c4edcdd0e15405bb5c2f5d0869 | 28.871429 | 184 | 0.615017 | 4.108055 | false | false | false | false |
3pillarlabs/ios-horizontalmenu | Sources/SelectionController.swift | 1 | 4144 | //
// SelectionController.swift
// TPGHorizontalMenu
//
// Created by Horatiu Potra on 02/03/2017.
// Copyright © 2017 3Pillar Global. All rights reserved.
//
import UIKit
protocol SelectionControllerDelegate: class {
func selectionController(selectionController: SelectionController, didSelect index:Int)
}
/// An object which is reponsible with the control of menu items highlighting and selection.
class SelectionController {
unowned var menuDataSource: MenuDataSource
weak var delegate: SelectionControllerDelegate?
private var gestures: [UITapGestureRecognizer] = []
private var controls: [UIControl] = []
private var highlightedItem: Highlightable? {
didSet {
if var oldValue = oldValue {
oldValue.isHighlighted = false
}
if var highlightedItem = highlightedItem {
highlightedItem.isHighlighted = true
}
}
}
private var selectedItem: Selectable? {
didSet {
if var oldValue = oldValue {
oldValue.isSelected = false
}
if var selectedItem = selectedItem {
selectedItem.isSelected = true
}
}
}
init(menuDataSource: MenuDataSource) {
self.menuDataSource = menuDataSource
}
func resetItemsHandling() {
clearTargets()
addTargets()
}
func selectItem(at index: Int) {
guard menuDataSource.items.isValid(index: index) else { return }
let item = menuDataSource.items[index]
select(view: item.view)
}
// MARK: Actions
@objc private func viewDidTouchUpInside(_ sender: Any) {
var targetIndex: Int?
var targetView: UIView?
switch sender {
case let view as UIView:
targetIndex = index(for: view)
targetView = view
case let gesture as UIGestureRecognizer:
targetIndex = index(for: gesture.view)
targetView = gesture.view
default:
break
}
select(view: targetView)
if let index = targetIndex {
delegate?.selectionController(selectionController: self, didSelect: index)
}
}
@objc private func gestureDidChangeState(_ gesture: UIGestureRecognizer) {
switch gesture.state {
case .began:
highlight(view: gesture.view)
case .ended:
viewDidTouchUpInside(gesture)
fallthrough
case .failed:
fallthrough
case .cancelled:
highlightedItem = nil
default:
break
}
}
// MARK: Private functionality
private func index(for view: UIView?) -> Int? {
guard let view = view else { return nil }
return menuDataSource.items.index(where: { $0.view == view })
}
private func clearTargets() {
for gesture in gestures {
gesture.removeTarget(self, action: nil)
}
gestures = []
for control in controls {
control.removeTarget(self, action: nil, for: .allEvents)
}
controls = []
}
private func addTargets() {
for item in menuDataSource.items {
item.view.isExclusiveTouch = true
if let itemControl = item.view as? UIControl {
itemControl.addTarget(self, action: #selector(viewDidTouchUpInside(_:)), for: .touchUpInside)
} else {
let gesture = SelectGestureRecognizer(target: self, action: #selector(gestureDidChangeState(_:)))
item.view.isUserInteractionEnabled = true
item.view.addGestureRecognizer(gesture)
}
}
}
private func highlight(view: UIView?) {
if let highlightableView = view as? Highlightable {
highlightedItem = highlightableView
}
}
private func select(view: UIView?) {
if let selectableView = view as? Selectable {
selectedItem = selectableView
}
}
}
| mit | 8aeb1e068057d9e80af21a159b869307 | 28.382979 | 113 | 0.583152 | 5.217884 | false | false | false | false |
toddkramer/Archiver | Sources/CGRect+ArchiveRepresentable.swift | 1 | 1856 | //
// CGRect+ArchiveRepresentable.swift
//
// Copyright (c) 2016 Todd Kramer (http://www.tekramer.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreGraphics
extension CGRect: ArchiveRepresentable {
private struct Key {
static let origin = "origin"
static let size = "size"
}
public var archiveValue: Archive {
return [
Key.origin: origin.archiveValue,
Key.size: size.archiveValue
]
}
public init(archive: Archive) {
guard let origin = archive[Key.origin] as? Archive,
let size = archive[Key.size] as? Archive else {
self = .zero
return
}
self.origin = CGPoint(archive: origin)
self.size = CGSize(archive: size)
}
}
| mit | 1c8075cad1912c742be8f035da48a639 | 34.692308 | 81 | 0.685345 | 4.356808 | false | false | false | false |
basheersubei/swift-t | turbine/code/export/math.swift | 2 | 2903 | /*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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
*/
// Mathematical functions
#ifndef MATH_SWIFT
#define MATH_SWIFT
float PI = 3.14159265358979323846;
float E = 2.7182818284590452354;
@pure @builtin_op=FLOOR
(float o) floor (float i) "turbine" "0.0.2" "floor";
@pure @builtin_op=CEIL
(float o) ceil (float i) "turbine" "0.0.2" "ceil";
@pure @builtin_op=ROUND
(float o) round (float i) "turbine" "0.0.2" "round";
@pure @builtin_op=LOG
(float o) log (float i) "turbine" "0.0.2" "log_e";
@pure @builtin_op=EXP
(float o) exp (float i) "turbine" "0.0.2" "exp";
@pure @builtin_op=SQRT
(float o) sqrt (float i) "turbine" "0.0.2" "sqrt";
@pure @builtin_op=IS_NAN
(boolean o) is_nan (float i) "turbine" "0.0.2" "is_nan";
@pure @builtin_op=IS_NAN
(boolean o) isNaN (float i) "turbine" "0.0.2" "is_nan";
@pure @builtin_op=ABS_INT
(int o) abs_integer (int i) "turbine" "0.0.2" "abs_integer";
@pure @builtin_op=ABS_INT
(int o) abs (int i) "turbine" "0.0.2" "abs_integer";
@pure @builtin_op=ABS_FLOAT
(float o) abs_float (float i) "turbine" "0.0.2" "abs_float";
@pure @builtin_op=ABS_FLOAT
(float o) abs (float i) "turbine" "0.0.2" "abs_float";
@pure
(float o) cbrt (float i) {
o = pow(i, 1.0/3.0);
}
@pure @builtin_op=LOG
(float o) ln (float x) "turbine" "0.7.0" "log_e";
@pure
(float o) log10 (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::log10 <<x>> ]"
];
@pure
(float o) log (float x, float base) "turbine" "0.7.0" [
"set <<o>> [ expr {log(<<x>>)/log(<<base>>)} ]"
];
@pure
(float o) sin (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::sin <<x>> ]"
];
@pure
(float o) cos (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::cos <<x>> ]"
];
@pure
(float o) tan (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::tan <<x>> ]"
];
@pure
(float o) asin (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::asin <<x>> ]"
];
@pure
(float o) acos (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::acos <<x>> ]"
];
@pure
(float o) atan (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::atan <<x>> ]"
];
@pure
(float o) atan2 (float y, float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::atan2 <<y>> <<x>> ]"
];
#endif
| apache-2.0 | cf51d913e8a37de04db07a640639a4ea | 27.184466 | 75 | 0.595246 | 2.537587 | false | false | false | false |
jwolkovitzs/AMScrollingNavbar | Source/ScrollingNavigationController.swift | 1 | 25011 | import UIKit
/**
Scrolling Navigation Bar delegate protocol
*/
@objc public protocol ScrollingNavigationControllerDelegate: NSObjectProtocol {
/// Called when the state of the navigation bar changes
///
/// - Parameters:
/// - controller: the ScrollingNavigationController
/// - state: the new state
@objc optional func scrollingNavigationController(_ controller: ScrollingNavigationController, didChangeState state: NavigationBarState)
/// Called when the state of the navigation bar is about to change
///
/// - Parameters:
/// - controller: the ScrollingNavigationController
/// - state: the new state
@objc optional func scrollingNavigationController(_ controller: ScrollingNavigationController, willChangeState state: NavigationBarState)
}
/**
The state of the navigation bar
- collapsed: the navigation bar is fully collapsed
- expanded: the navigation bar is fully visible
- scrolling: the navigation bar is transitioning to either `Collapsed` or `Scrolling`
*/
@objc public enum NavigationBarState: Int {
case collapsed, expanded, scrolling
}
/**
The direction of scrolling that the navigation bar should be collapsed.
The raw value determines the sign of content offset depending of collapse direction.
- scrollUp: scrolling up direction
- scrollDown: scrolling down direction
*/
@objc public enum NavigationBarCollapseDirection: Int {
case scrollUp = -1
case scrollDown = 1
}
/**
The direction of scrolling that a followe should follow when the navbar is collapsing.
The raw value determines the sign of content offset depending of collapse direction.
- scrollUp: scrolling up direction
- scrollDown: scrolling down direction
*/
@objc public enum NavigationBarFollowerCollapseDirection: Int {
case scrollUp = -1
case scrollDown = 1
}
/**
Wraps a view that follows the navigation bar, providing the direction that the view should follow
*/
@objcMembers
open class NavigationBarFollower: NSObject {
public weak var view: UIView?
public var direction = NavigationBarFollowerCollapseDirection.scrollUp
public init(view: UIView, direction: NavigationBarFollowerCollapseDirection = .scrollUp) {
self.view = view
self.direction = direction
}
}
/**
A custom `UINavigationController` that enables the scrolling of the navigation bar alongside the
scrolling of an observed content view
*/
@objcMembers
open class ScrollingNavigationController: UINavigationController, UIGestureRecognizerDelegate {
/**
Returns the `NavigationBarState` of the navigation bar
*/
open var state: NavigationBarState {
get {
if navigationBar.frame.origin.y <= -navbarFullHeight {
return .collapsed
} else if navigationBar.frame.origin.y >= statusBarHeight {
return .expanded
} else {
return .scrolling
}
}
}
/**
Determines whether the navbar should scroll when the content inside the scrollview fits
the view's size. Defaults to `false`
*/
open var shouldScrollWhenContentFits = false
/**
Determines if the navbar should expand once the application becomes active after entering background
Defaults to `true`
*/
open var expandOnActive = true
/**
Determines if the navbar scrolling is enabled.
Defaults to `true`
*/
open var scrollingEnabled = true
/**
The delegate for the scrolling navbar controller
*/
open weak var scrollingNavbarDelegate: ScrollingNavigationControllerDelegate?
/**
An array of `NavigationBarFollower`s that will follow the navbar
*/
open var followers: [NavigationBarFollower] = []
/**
Determines if the top content inset should be updated with the navbar's delta movement. This should be enabled when dealing with table views with floating headers.
It can however cause issues in certain configurations. If the issues arise, set this to false
Defaults to `true`
*/
open var shouldUpdateContentInset = true
/**
Determines if the navigation bar should scroll while following a UITableView that is in edit mode.
Defaults to `false`
*/
open var shouldScrollWhenTableViewIsEditing = false
/// Holds the percentage of the navigation bar that is hidde. At 0 the navigation bar is fully visible, at 1 fully hidden. CGFloat with values from 0 to 1
open var percentage: CGFloat {
get {
return (navigationBar.frame.origin.y - statusBarHeight) / (-navbarFullHeight - statusBarHeight)
}
}
/// Stores some metadata of a UITabBar if one is passed in the followers array
internal struct TabBarMock {
var isTranslucent: Bool = false
var origin: CGPoint = .zero
init(origin: CGPoint, translucent: Bool) {
self.origin = origin
self.isTranslucent = translucent
}
}
open fileprivate(set) var gestureRecognizer: UIPanGestureRecognizer?
fileprivate var sourceTabBar: TabBarMock?
fileprivate var previousOrientation: UIDeviceOrientation = UIDevice.current.orientation
var delayDistance: CGFloat = 0
var maxDelay: CGFloat = 0
var scrollableView: UIView?
var lastContentOffset = CGFloat(0.0)
var scrollSpeedFactor: CGFloat = 1
var collapseDirectionFactor: CGFloat = 1 // Used to determine the sign of content offset depending of collapse direction
var previousState: NavigationBarState = .expanded // Used to mark the state before the app goes in background
/**
Start scrolling
Enables the scrolling by observing a view
- parameter scrollableView: The view with the scrolling content that will be observed
- parameter delay: The delay expressed in points that determines the scrolling resistance. Defaults to `0`
- parameter scrollSpeedFactor : This factor determines the speed of the scrolling content toward the navigation bar animation
- parameter collapseDirection : The direction of scrolling that the navigation bar should be collapsed
- parameter followers: An array of `NavigationBarFollower`s that will follow the navbar. The wrapper holds the direction that the view will follow
*/
open func followScrollView(_ scrollableView: UIView, delay: Double = 0, scrollSpeedFactor: Double = 1, collapseDirection: NavigationBarCollapseDirection = .scrollDown, followers: [NavigationBarFollower] = []) {
guard self.scrollableView == nil else {
// Restore previous state. UIKit restores the navbar to its full height on view changes (e.g. during a modal presentation), so we need to restore the status once UIKit is done
switch previousState {
case .collapsed:
hideNavbar(animated: false)
case .expanded:
showNavbar(animated: false)
default: break
}
return
}
self.scrollableView = scrollableView
gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ScrollingNavigationController.handlePan(_:)))
gestureRecognizer?.maximumNumberOfTouches = 1
gestureRecognizer?.delegate = self
gestureRecognizer?.cancelsTouchesInView = false
scrollableView.addGestureRecognizer(gestureRecognizer!)
previousOrientation = UIDevice.current.orientation
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.willResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.didBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.didRotate(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.windowDidBecomeVisible(_:)), name: UIWindow.didBecomeVisibleNotification, object: nil)
maxDelay = CGFloat(delay)
delayDistance = CGFloat(delay)
scrollingEnabled = true
// Save TabBar state (the state is changed during the transition and restored on compeltion)
if let tab = followers.map({ $0.view }).first(where: { $0 is UITabBar }) as? UITabBar {
self.sourceTabBar = TabBarMock(origin: CGPoint(x: tab.frame.origin.x, y: CGFloat(round(tab.frame.origin.y))), translucent: tab.isTranslucent)
}
self.followers = followers
self.scrollSpeedFactor = CGFloat(scrollSpeedFactor)
self.collapseDirectionFactor = CGFloat(collapseDirection.rawValue)
}
/**
Hide the navigation bar
- parameter animated: If true the scrolling is animated. Defaults to `true`
- parameter duration: Optional animation duration. Defaults to 0.1
*/
open func hideNavbar(animated: Bool = true, duration: TimeInterval = 0.1) {
guard let _ = self.scrollableView, let visibleViewController = self.visibleViewController else { return }
guard state == .expanded else {
updateNavbarAlpha()
return
}
gestureRecognizer?.isEnabled = false
let animations = {
self.scrollWithDelta(self.fullNavbarHeight, ignoreDelay: true)
visibleViewController.view.setNeedsLayout()
if self.navigationBar.isTranslucent {
let currentOffset = self.contentOffset
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y + self.navbarHeight)
}
}
if animated {
UIView.animate(withDuration: duration, animations: animations) { _ in
self.gestureRecognizer?.isEnabled = true
}
} else {
animations()
gestureRecognizer?.isEnabled = true
}
}
/**
Show the navigation bar
- parameter animated: If true the scrolling is animated. Defaults to `true`
- parameter duration: Optional animation duration. Defaults to 0.1
*/
open func showNavbar(animated: Bool = true, duration: TimeInterval = 0.1) {
guard let _ = self.scrollableView, let visibleViewController = self.visibleViewController else { return }
guard state == .collapsed else {
updateNavbarAlpha()
return
}
gestureRecognizer?.isEnabled = false
let animations = {
self.lastContentOffset = 0
self.scrollWithDelta(-self.fullNavbarHeight, ignoreDelay: true)
visibleViewController.view.setNeedsLayout()
if self.navigationBar.isTranslucent {
let currentOffset = self.contentOffset
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y - self.navbarHeight)
}
}
if animated {
UIView.animate(withDuration: duration, animations: animations) { _ in
self.gestureRecognizer?.isEnabled = true
}
} else {
animations()
gestureRecognizer?.isEnabled = true
}
}
/**
Stop observing the view and reset the navigation bar
- parameter showingNavbar: If true the navbar is show, otherwise it remains in its current state. Defaults to `true`
*/
open func stopFollowingScrollView(showingNavbar: Bool = true) {
if showingNavbar {
showNavbar(animated: true)
}
if let gesture = gestureRecognizer {
scrollableView?.removeGestureRecognizer(gesture)
}
scrollableView = .none
gestureRecognizer = .none
scrollingNavbarDelegate = .none
scrollingEnabled = false
let center = NotificationCenter.default
center.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
center.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
// MARK: - Gesture recognizer
func handlePan(_ gesture: UIPanGestureRecognizer) {
if let tableView = scrollableView as? UITableView, !shouldScrollWhenTableViewIsEditing && tableView.isEditing {
return
}
if let superview = scrollableView?.superview {
let translation = gesture.translation(in: superview)
let delta = (lastContentOffset - translation.y) / scrollSpeedFactor
if !checkSearchController(delta) {
lastContentOffset = translation.y
return
}
if gesture.state != .failed {
lastContentOffset = translation.y
if shouldScrollWithDelta(delta) {
scrollWithDelta(delta)
}
}
}
if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed {
checkForPartialScroll()
lastContentOffset = 0
}
}
// MARK: - Fullscreen handling
func windowDidBecomeVisible(_ notification: Notification) {
showNavbar()
}
// MARK: - Rotation handler
func didRotate(_ notification: Notification) {
let newOrientation = UIDevice.current.orientation
// Show the navbar if the orantation is the same (the app just got back from background) or if there is a switch between portrait and landscape (and vice versa)
if (previousOrientation == newOrientation) || (previousOrientation.isPortrait && newOrientation.isLandscape) || (previousOrientation.isLandscape && newOrientation.isPortrait) {
showNavbar()
}
previousOrientation = newOrientation
}
/**
UIContentContainer protocol method.
Will show the navigation bar upon rotation or changes in the trait sizes.
*/
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
showNavbar()
}
// MARK: - Notification handler
func didBecomeActive(_ notification: Notification) {
if expandOnActive {
showNavbar(animated: false)
} else {
if previousState == .collapsed {
hideNavbar(animated: false)
}
}
}
func willResignActive(_ notification: Notification) {
previousState = state
}
/// Handles when the status bar changes
func willChangeStatusBar() {
showNavbar(animated: true)
}
// MARK: - Scrolling functions
private func shouldScrollWithDelta(_ delta: CGFloat) -> Bool {
let scrollDelta = delta
// Do not hide too early
if contentOffset.y < ((navigationBar.isTranslucent ? -fullNavbarHeight : 0) + scrollDelta) {
return false
}
// Check for rubberbanding
if scrollDelta < 0 {
if let scrollableView = scrollableView , contentOffset.y + scrollableView.frame.size.height > contentSize.height && scrollableView.frame.size.height < contentSize.height {
// Only if the content is big enough
return false
}
}
return true
}
private func scrollWithDelta(_ delta: CGFloat, ignoreDelay: Bool = false) {
var scrollDelta = delta
let frame = navigationBar.frame
// View scrolling up, hide the navbar
if scrollDelta > 0 {
// Update the delay
if !ignoreDelay {
delayDistance -= scrollDelta
// Skip if the delay is not over yet
if delayDistance > 0 {
return
}
}
// No need to scroll if the content fits
if !shouldScrollWhenContentFits && state != .collapsed &&
(scrollableView?.frame.size.height)! >= contentSize.height {
return
}
// Compute the bar position
if frame.origin.y - scrollDelta < -navbarFullHeight {
scrollDelta = frame.origin.y + navbarFullHeight
}
// Detect when the bar is completely collapsed
if frame.origin.y <= -navbarFullHeight {
delayDistance = maxDelay
}
}
if scrollDelta < 0 {
// Update the delay
if !ignoreDelay {
delayDistance += scrollDelta
// Skip if the delay is not over yet
if delayDistance > 0 && maxDelay < contentOffset.y {
return
}
}
// Compute the bar position
if frame.origin.y - scrollDelta > statusBarHeight {
scrollDelta = frame.origin.y - statusBarHeight
}
// Detect when the bar is completely expanded
if frame.origin.y >= statusBarHeight {
delayDistance = maxDelay
}
}
updateSizing(scrollDelta)
updateNavbarAlpha()
restoreContentOffset(scrollDelta)
updateFollowers()
updateContentInset(scrollDelta)
let newState = state
if newState != previousState {
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: newState)
navigationBar.isUserInteractionEnabled = (newState == .expanded)
}
previousState = newState
}
/// Adjust the top inset (useful when a table view has floating headers, see issue #219
private func updateContentInset(_ delta: CGFloat) {
if self.shouldUpdateContentInset, let contentInset = scrollView()?.contentInset, let scrollInset = scrollView()?.scrollIndicatorInsets {
scrollView()?.contentInset = UIEdgeInsets(top: contentInset.top - delta, left: contentInset.left, bottom: contentInset.bottom, right: contentInset.right)
scrollView()?.scrollIndicatorInsets = UIEdgeInsets(top: scrollInset.top - delta, left: scrollInset.left, bottom: scrollInset.bottom, right: scrollInset.right)
}
}
private func updateFollowers() {
followers.forEach {
guard let tabBar = $0.view as? UITabBar else {
let height = $0.view?.frame.height ?? 0
var safeArea: CGFloat = 0
if #available(iOS 11.0, *) {
// Account for the safe area for footers and toolbars at the bottom of the screen
safeArea = ($0.direction == .scrollDown) ? (topViewController?.view.safeAreaInsets.bottom ?? 0) : 0
}
switch $0.direction {
case .scrollDown:
$0.view?.transform = CGAffineTransform(translationX: 0, y: percentage * (height + safeArea))
case .scrollUp:
$0.view?.transform = CGAffineTransform(translationX: 0, y: -(statusBarHeight - navigationBar.frame.origin.y))
}
return
}
tabBar.isTranslucent = true
tabBar.transform = CGAffineTransform(translationX: 0, y: percentage * tabBar.frame.height)
// Set the bar to its original state if it's in its original position
if let originalTabBar = sourceTabBar, originalTabBar.origin.y == round(tabBar.frame.origin.y) {
tabBar.isTranslucent = originalTabBar.isTranslucent
}
}
}
private func updateSizing(_ delta: CGFloat) {
guard let topViewController = self.topViewController else { return }
var frame = navigationBar.frame
// Move the navigation bar
frame.origin = CGPoint(x: frame.origin.x, y: frame.origin.y - delta)
navigationBar.frame = frame
// Resize the view if the navigation bar is not translucent
if !navigationBar.isTranslucent {
let navBarY = navigationBar.frame.origin.y + navigationBar.frame.size.height
frame = topViewController.view.frame
frame.origin = CGPoint(x: frame.origin.x, y: navBarY)
frame.size = CGSize(width: frame.size.width, height: view.frame.size.height - (navBarY) - tabBarOffset)
topViewController.view.frame = frame
}
}
private func restoreContentOffset(_ delta: CGFloat) {
if navigationBar.isTranslucent || delta == 0 {
return
}
// Hold the scroll steady until the navbar appears/disappears
if let scrollView = scrollView() {
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y - delta), animated: false)
}
}
private func checkForPartialScroll() {
let frame = navigationBar.frame
var duration = TimeInterval(0)
var delta = CGFloat(0.0)
// Scroll back down
let threshold = statusBarHeight - (frame.size.height / 2)
if navigationBar.frame.origin.y >= threshold {
delta = frame.origin.y - statusBarHeight
let distance = delta / (frame.size.height / 2)
duration = TimeInterval(abs(distance * 0.2))
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: state)
} else {
// Scroll up
delta = frame.origin.y + navbarFullHeight
let distance = delta / (frame.size.height / 2)
duration = TimeInterval(abs(distance * 0.2))
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: state)
}
delayDistance = maxDelay
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: {
self.updateSizing(delta)
self.updateFollowers()
self.updateNavbarAlpha()
self.updateContentInset(delta)
}, completion: { _ in
self.navigationBar.isUserInteractionEnabled = (self.state == .expanded)
self.scrollingNavbarDelegate?.scrollingNavigationController?(self, didChangeState: self.state)
})
}
private func updateNavbarAlpha() {
guard let navigationItem = topViewController?.navigationItem else { return }
let frame = navigationBar.frame
// Change the alpha channel of every item on the navbr
let alpha = 1 - percentage
// Hide all the possible titles
navigationItem.titleView?.alpha = alpha
navigationBar.tintColor = navigationBar.tintColor.withAlphaComponent(alpha)
navigationItem.leftBarButtonItem?.tintColor = navigationItem.leftBarButtonItem?.tintColor?.withAlphaComponent(alpha)
navigationItem.rightBarButtonItem?.tintColor = navigationItem.rightBarButtonItem?.tintColor?.withAlphaComponent(alpha)
navigationItem.leftBarButtonItems?.forEach { $0.tintColor = $0.tintColor?.withAlphaComponent(alpha) }
navigationItem.rightBarButtonItems?.forEach { $0.tintColor = $0.tintColor?.withAlphaComponent(alpha) }
if let titleColor = navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] as? UIColor {
navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] = titleColor.withAlphaComponent(alpha)
} else {
let blackAlpha = UIColor.black.withAlphaComponent(alpha)
if navigationBar.titleTextAttributes == nil {
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: blackAlpha]
} else {
navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] = blackAlpha
}
}
// Hide all possible button items and navigation items
func shouldHideView(_ view: UIView) -> Bool {
let className = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
var viewNames = ["UINavigationButton", "UINavigationItemView", "UIImageView", "UISegmentedControl"]
if #available(iOS 11.0, *) {
viewNames.append(navigationBar.prefersLargeTitles ? "UINavigationBarLargeTitleView" : "UINavigationBarContentView")
} else {
viewNames.append("UINavigationBarContentView")
}
return viewNames.contains(className)
}
func setAlphaOfSubviews(view: UIView, alpha: CGFloat) {
if let label = view as? UILabel {
label.textColor = label.textColor.withAlphaComponent(alpha)
} else if let label = view as? UITextField {
label.textColor = label.textColor?.withAlphaComponent(alpha)
} else if view.classForCoder == NSClassFromString("_UINavigationBarContentView") {
// do nothing
} else {
view.alpha = alpha
}
view.subviews.forEach { setAlphaOfSubviews(view: $0, alpha: alpha) }
}
navigationBar.subviews
.filter(shouldHideView)
.forEach { setAlphaOfSubviews(view: $0, alpha: alpha) }
// Hide the left items
navigationItem.leftBarButtonItem?.customView?.alpha = alpha
navigationItem.leftBarButtonItems?.forEach { $0.customView?.alpha = alpha }
// Hide the right items
navigationItem.rightBarButtonItem?.customView?.alpha = alpha
navigationItem.rightBarButtonItems?.forEach { $0.customView?.alpha = alpha }
}
private func checkSearchController(_ delta: CGFloat) -> Bool {
if #available(iOS 11.0, *) {
if let searchController = topViewController?.navigationItem.searchController, delta > 0 {
if searchController.searchBar.frame.height != 0 {
return false
}
}
}
return true
}
// MARK: - UIGestureRecognizerDelegate
/**
UIGestureRecognizerDelegate function. Begin scrolling only if the direction is vertical (prevents conflicts with horizontal scroll views)
*/
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { return true }
let velocity = gestureRecognizer.velocity(in: gestureRecognizer.view)
return abs(velocity.y) > abs(velocity.x)
}
/**
UIGestureRecognizerDelegate function. Enables the scrolling of both the content and the navigation bar
*/
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
/**
UIGestureRecognizerDelegate function. Only scrolls the navigation bar with the content when `scrollingEnabled` is true
*/
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return scrollingEnabled
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | 938b3db69bf7508196d25f2e8fc029f4 | 36.274218 | 212 | 0.712007 | 5.007207 | false | false | false | false |
machelix/Lightbox | Source/LightboxView.swift | 1 | 4780 | import UIKit
public class LightboxView: UIView {
public var minimumZoomScale: CGFloat = 1
public var maximumZoomScale: CGFloat = 3
var lastZoomScale: CGFloat = -1
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.userInteractionEnabled = true
return imageView
}()
lazy var scrollView: UIScrollView = { [unowned self] in
let scrollView = UIScrollView(frame: CGRectZero)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.multipleTouchEnabled = true
scrollView.minimumZoomScale = self.minimumZoomScale
scrollView.maximumZoomScale = self.maximumZoomScale
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
var imageConstraintLeading: NSLayoutConstraint!
var imageConstraintTrailing: NSLayoutConstraint!
var imageConstraintTop: NSLayoutConstraint!
var imageConstraintBottom: NSLayoutConstraint!
var constraintsAdded = false
// MARK: - Initialization
public init(frame: CGRect, image: UIImage? = nil) {
super.init(frame: frame)
imageView.image = image
let config = LightboxConfig.sharedInstance.config
backgroundColor = config.backgroundColor
minimumZoomScale = config.zoom.minimumScale
maximumZoomScale = config.zoom.maximumScale
scrollView.addSubview(self.imageView)
addSubview(scrollView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
public override func didMoveToSuperview() {
setUpConstraints()
}
// MARK: - Public methods
public func updateViewLayout() {
if constraintsAdded {
updateImageConstraints()
updateZoom()
}
}
// MARK: - Autolayout
public func setUpConstraints() {
if !constraintsAdded {
let layoutAttributes: [NSLayoutAttribute] = [.Leading, .Trailing, .Top, .Bottom]
for layoutAttribute in layoutAttributes {
addConstraint(NSLayoutConstraint(item: self.scrollView, attribute: layoutAttribute,
relatedBy: .Equal, toItem: self, attribute: layoutAttribute,
multiplier: 1, constant: 0))
}
imageConstraintLeading = NSLayoutConstraint(item: imageView, attribute: .Leading,
relatedBy: .Equal, toItem: scrollView, attribute: .Leading,
multiplier: 1, constant: 0)
imageConstraintTrailing = NSLayoutConstraint(item: imageView, attribute: .Trailing,
relatedBy: .Equal, toItem: scrollView, attribute: .Trailing,
multiplier: 1, constant: 0)
imageConstraintTop = NSLayoutConstraint(item: imageView, attribute: .Top,
relatedBy: .Equal, toItem: scrollView, attribute: .Top,
multiplier: 1, constant: 0)
imageConstraintBottom = NSLayoutConstraint(item: imageView, attribute: .Bottom,
relatedBy: .Equal, toItem: scrollView, attribute: .Bottom,
multiplier: 1, constant: 0)
addConstraints([imageConstraintLeading, imageConstraintTrailing,
imageConstraintTop, imageConstraintBottom])
layoutIfNeeded()
scrollView.contentSize = CGSize(width: frame.size.width, height: frame.size.height)
constraintsAdded = true
}
}
public func updateImageConstraints() {
if let image = imageView.image {
// Center image
var hPadding = (bounds.size.width - scrollView.zoomScale * image.size.width) / 2
if hPadding < 0 {
hPadding = 0
}
var vPadding = (bounds.size.height - scrollView.zoomScale * image.size.height) / 2
if vPadding < 0 {
vPadding = 0
}
for constraint in [imageConstraintLeading, imageConstraintTrailing] { constraint.constant = hPadding }
for constraint in [imageConstraintTop, imageConstraintBottom] { constraint.constant = vPadding }
layoutIfNeeded()
}
}
// MARK: - Zoom
public func updateZoom() {
if let image = imageView.image {
var minimumZoom = min(
bounds.size.width / image.size.width,
bounds.size.height / image.size.height)
if minimumZoom > 1 {
minimumZoom = 1
}
scrollView.minimumZoomScale = minimumZoom
if minimumZoom == lastZoomScale {
minimumZoom += 0.000001
}
scrollView.zoomScale = minimumZoom
lastZoomScale = minimumZoom
}
}
}
// MARK: - UIScrollViewDelegate
extension LightboxView: UIScrollViewDelegate {
public func scrollViewDidZoom(scrollView: UIScrollView) {
updateImageConstraints()
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| mit | c5096871ff1497f7258f025d2398fd67 | 28.146341 | 108 | 0.70251 | 5.031579 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Dashboard/Cards/Quick Start/QuickStartChecklistView.swift | 1 | 6008 | import UIKit
import WordPressShared
// A view representing the progress on a Quick Start checklist. Built according to old design specs.
//
// This view is used to display multiple Quick Start tour collections per Quick Start card.
//
// This view can be deleted once we've fully migrated to using NewQuicksTartChecklistView.
// See QuickStartChecklistConfigurable for more details.
//
final class QuickStartChecklistView: UIView, QuickStartChecklistConfigurable {
var tours: [QuickStartTour] = []
var blog: Blog?
var onTap: (() -> Void)?
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
labelStackView,
progressIndicatorView
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.spacing = Metrics.mainStackViewSpacing
return stackView
}()
private lazy var labelStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
titleLabel,
subtitleLabel
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = Metrics.labelStackViewSpacing
return stackView
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = WPStyleGuide.serifFontForTextStyle(.body, fontWeight: .semibold)
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = Metrics.labelMinimumScaleFactor
label.textColor = .text
return label
}()
private lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = WPStyleGuide.fontForTextStyle(.callout)
label.textColor = .textSubtle
return label
}()
private lazy var progressIndicatorView: ProgressIndicatorView = {
let appearance = ProgressIndicatorView.Appearance(
size: Metrics.progressIndicatorViewSize,
lineColor: .primary,
trackColor: .separator
)
let view = ProgressIndicatorView(appearance: appearance)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.isAccessibilityElement = false
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
startObservingQuickStart()
}
required init?(coder: NSCoder) {
fatalError("Not implemented")
}
deinit {
stopObservingQuickStart()
}
func configure(collection: QuickStartToursCollection, blog: Blog) {
self.tours = collection.tours
self.blog = blog
titleLabel.text = collection.title
isAccessibilityElement = true
accessibilityTraits = .button
accessibilityHint = collection.hint
updateViews()
}
}
extension QuickStartChecklistView {
private func setupViews() {
addSubview(mainStackView)
pinSubviewToAllEdges(mainStackView, insets: Metrics.mainStackViewInsets)
let tap = UITapGestureRecognizer(target: self, action: #selector(didTap))
addGestureRecognizer(tap)
}
private func updateViews() {
guard let blog = blog,
let title = titleLabel.text else {
return
}
let completedToursCount = QuickStartTourGuide.shared.countChecklistCompleted(in: tours, for: blog)
if completedToursCount == tours.count {
titleLabel.attributedText = NSAttributedString(string: title, attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue])
titleLabel.textColor = .textSubtle
} else {
titleLabel.attributedText = NSAttributedString(string: title, attributes: [:])
titleLabel.textColor = .text
}
let subtitle = String(format: Strings.subtitleFormat, completedToursCount, tours.count)
subtitleLabel.text = subtitle
// VoiceOver: Adding a period after the title to create a pause between the title and the subtitle
accessibilityLabel = "\(title). \(subtitle)"
let progress = Double(completedToursCount) / Double(tours.count)
progressIndicatorView.updateProgressLayer(with: progress)
}
private func startObservingQuickStart() {
NotificationCenter.default.addObserver(forName: .QuickStartTourElementChangedNotification, object: nil, queue: nil) { [weak self] notification in
guard let userInfo = notification.userInfo,
let element = userInfo[QuickStartTourGuide.notificationElementKey] as? QuickStartTourElement,
element == .tourCompleted else {
return
}
self?.updateViews()
}
}
private func stopObservingQuickStart() {
NotificationCenter.default.removeObserver(self)
}
@objc private func didTap() {
onTap?()
}
}
extension QuickStartChecklistView {
private enum Metrics {
static let mainStackViewInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
static let mainStackViewSpacing = 16.0
static let labelStackViewSpacing = 4.0
static let progressIndicatorViewSize = 24.0
static let labelMinimumScaleFactor = 0.5
}
private enum Strings {
static let subtitleFormat = NSLocalizedString("%1$d of %2$d completed",
comment: "Format string for displaying number of completed quickstart tutorials. %1$d is number completed, %2$d is total number of tutorials available.")
}
}
| gpl-2.0 | 8aeeaf093615893ec9bf73a5ddfc57bf | 33.728324 | 207 | 0.668941 | 5.614953 | false | false | false | false |
weizhangCoder/DYZB_ZW | DYZB_ZW/DYZB_ZW/Classes/Main/Controller/CustomNavigationController.swift | 1 | 1795 | //
// CustomNavigationController.swift
// DYZB_ZW
//
// Created by 张三 on 1/11/17.
// Copyright © 2017年 jyall. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.获取系统的Pop手势
guard let systemGes = interactivePopGestureRecognizer else{ return }
// 2.获取手势添加到的View中
guard let gesView = systemGes.view else {
return
}
// 3.获取target/action
// 3.1.利用运行时机制查看所有的属性名称
/*
var count : UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
*/
let targets = systemGes.value(forKey: "targets") as? [NSObject]
guard let targetObjc = targets?.first else {
return
}
// 3.2.取出target
guard let target = targetObjc.value(forKey: "target") else { return }
// 3.3.取出Action
let action = Selector(("handleNavigationTransition:"))
// 4.创建自己的Pan手势
let panGes = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGes)
panGes.addTarget(target, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
// 隐藏要push的控制器的tabbar
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
| mit | 8bbb59880fc4612d057192db6dc51e7c | 24.484848 | 90 | 0.583829 | 4.65928 | false | false | false | false |
narner/AudioKit | Examples/macOS/AudioUnitManager/AudioUnitManager/AudioUnitToolbar.swift | 1 | 1594 | //
// AudioUnitToolbar.swift
// AudioUnitManager
//
// Created by Ryan Francesconi on 10/8/17.
// Copyright © 2017 Ryan Francesconi. All rights reserved.
//
import AVFoundation
import Cocoa
class AudioUnitToolbar: NSView {
@IBInspectable var backgroundColor: NSColor?
var audioUnit: AVAudioUnit?
var bypassButton: NSButton?
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
initialize()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
initialize()
}
private func initialize() {
bypassButton = NSButton()
bypassButton!.frame = NSRect(x: 2, y: 2, width: 60, height: 16)
bypassButton!.controlSize = .mini
bypassButton!.bezelStyle = .rounded
bypassButton!.font = NSFont.systemFont(ofSize: 9)
bypassButton!.setButtonType(.pushOnPushOff)
bypassButton!.action = #selector(handleBypass)
bypassButton!.target = self
bypassButton!.title = "Bypass"
addSubview(bypassButton!)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if let bgColor = backgroundColor {
bgColor.setFill()
let rect = NSMakeRect(0, 0, bounds.width, bounds.height)
//let rectanglePath = NSBezierPath( roundedRect: rect, xRadius: 3, yRadius: 3)
rect.fill()
}
}
@objc func handleBypass() {
Swift.print("bypass: \(bypassButton!.state)")
audioUnit?.auAudioUnit.shouldBypassEffect = bypassButton!.state == .on
}
}
| mit | 20a870fc49995932486ed9baf2acdd57 | 26.465517 | 90 | 0.634024 | 4.38843 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommentTalentCell.swift | 1 | 2892 | //
// RecommentTalentCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/31.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommentTalentCell: UITableViewCell {
var cellArray:[RecipeRecommendWidgetData]?
var clickClosure:RecipClickClosure?{
didSet{
shorwData()
}
}
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var fansLabel: UILabel!
func shorwData()
{
//
if cellArray?.count > 0
{
let imgData = cellArray![0]
if imgData.type == "image"
{
imgView.kf_setImageWithURL(NSURL(string: imgData.content!), placeholderImage: UIImage(named: "sdefaultImage"))
}
}
//
if cellArray?.count > 1
{
let nameData = cellArray![1]
if nameData.type == "text"
{
nameLabel.text = nameData.content
}
}
//
if cellArray?.count > 2
{
let descData = cellArray![2]
if descData.type == "text"
{
descLabel.text = descData.content
}
}
//
if cellArray?.count > 3
{
let fansData = cellArray![3]
if fansData.type == "text"
{
fansLabel.text = fansData.content
}
}
//
let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
addGestureRecognizer(tap)
}
//创建cell
class func createTalentCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, cellArray:[RecipeRecommendWidgetData]?) ->RecommentTalentCell
{
let cellID = "recommentTalentCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommentTalentCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommentTalentCell", owner: nil, options: nil).last as? RecommentTalentCell
}
cell?.cellArray = cellArray!
return cell!
}
func tapClick()
{
if cellArray?.count > 0
{
let imgData = cellArray![0]
if clickClosure != nil && imgData.link != nil
{
clickClosure!(imgData.link!)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
imgView.layer.cornerRadius = 35
imgView.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 4c9d704e1bad5201f60d27f6c9d03395 | 24.052174 | 152 | 0.539049 | 4.891341 | false | false | false | false |
hashier/transfer.sh-mac | transfer.sh/DestinationView.swift | 1 | 2235 | //
// DestinationView.swift
// transfer.sh
//
// Created by Christopher Loessl on 2016-10-16.
// Copyright © 2016 chl. All rights reserved.
//
import Foundation
import Cocoa
protocol DestinationViewDelegate {
func processFileURLs(_ urls: [URL])
}
private let lineWidth: CGFloat = 6.0
class DestinationView: NSView {
private var isReceivingDrag = false {
didSet {
needsDisplay = true
}
}
var delegate: DestinationViewDelegate?
private var acceptedTypes = [kUTTypeFileURL as String]
// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PasteboardGuide106/Articles/pbReading.html
private lazy var filteringOptions = [NSPasteboardURLReadingFileURLsOnlyKey : true]
override func awakeFromNib() {
setup()
}
private func setup() {
self.register(forDraggedTypes: acceptedTypes)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if isReceivingDrag {
NSColor.selectedControlColor.set()
let path = NSBezierPath(rect: bounds)
path.lineWidth = lineWidth
path.stroke()
}
}
private func shouldAllowDrag(_ draggingInfo: NSDraggingInfo) -> Bool {
var canAccept = false
let pasteBoard = draggingInfo.draggingPasteboard()
if pasteBoard.canReadObject(forClasses: [NSURL.self], options: filteringOptions) {
canAccept = true
}
return canAccept
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
let allow = shouldAllowDrag(sender)
isReceivingDrag = allow
return allow ? .copy : NSDragOperation()
}
override func draggingExited(_ sender: NSDraggingInfo?) {
isReceivingDrag = false
}
override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool {
isReceivingDrag = false
let pasteBoard = draggingInfo.draggingPasteboard()
if let urls = pasteBoard.readObjects(forClasses: [NSURL.self], options: filteringOptions) as? [URL], !urls.isEmpty {
delegate?.processFileURLs(urls)
return true
}
return false
}
}
| mit | 2be0d406fa3e7d4f7ee02514344b05cc | 25.282353 | 124 | 0.654879 | 4.793991 | false | false | false | false |
Romdeau4/16POOPS | Helps_Kitchen_iOS/Help's Kitchen/HomeViewController.swift | 1 | 2867 | //
// HomeViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/13/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class HomeViewController: UIViewController {
let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL)
override func viewDidLoad() {
super.viewDidLoad()
checkStatus()
}
override func viewDidAppear(_ animated: Bool){
checkStatus()
}
func checkStatus() {
let uid = FIRAuth.auth()?.currentUser?.uid
if uid == nil {
handleLogout()
}else{
ref.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
for userType in snapshot.children {
let currentUserType = userType as! FIRDataSnapshot
for user in currentUserType.children {
let currentUser = user as! FIRDataSnapshot
if currentUser.key == uid {
switch currentUserType.key{
case "Host":
let hostController = HostSeatingController()
let navController = CustomNavigationController(rootViewController: hostController)
self.present(navController, animated: true, completion: nil)
case "Server":
let serverController = ServerTabBarController()
self.present(serverController, animated: true, completion: nil)
case "Kitchen":
let kitchenController = KitchenOrderListController()
let navController = CustomNavigationController(rootViewController: kitchenController)
self.present(navController, animated: true, completion: nil)
//TODO Add Kitchen ViewController
default:
self.handleLogout()
}
}
}
}
})
}
}
func handleLogout() {
do{
try FIRAuth.auth()?.signOut()
}catch let logoutError {
print(logoutError)
}
let loginViewController = LoginViewController()
present(loginViewController, animated: true, completion: nil)
}
}
| mit | 9b89160a104fc02e7f48c21efadf588b | 33.53012 | 121 | 0.452547 | 6.990244 | false | false | false | false |
lkzhao/Hero | Sources/Extensions/CALayer+Hero.swift | 1 | 2091 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// 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.
#if canImport(UIKit)
import UIKit
internal extension CALayer {
// return all animations running by this layer.
// the returned value is mutable
var animations: [(String, CAAnimation)] {
if let keys = animationKeys() {
// swiftlint:disable:next force_cast
return keys.map { return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation) }
}
return []
}
func flatTransformTo(layer: CALayer) -> CATransform3D {
var layer = layer
var trans = layer.transform
while let superlayer = layer.superlayer, superlayer != self, !(superlayer.delegate is UIWindow) {
trans = CATransform3DConcat(superlayer.transform, trans)
layer = superlayer
}
return trans
}
func removeAllHeroAnimations() {
guard let keys = animationKeys() else { return }
for animationKey in keys where animationKey.hasPrefix("hero.") {
removeAnimation(forKey: animationKey)
}
}
}
#endif
| mit | 25645dee4ff4552e9a4dc6edab424096 | 36.339286 | 101 | 0.722621 | 4.411392 | false | false | false | false |
thecb4/SwifterCSV | Sources/ParserHelpers.swift | 1 | 1209 |
//
// Parser.swift
// SwifterCSV
//
// Created by Will Richardson on 11/04/16.
// Copyright © 2016 JavaNut13. All rights reserved.
//
extension CSV {
/// List of dictionaries that contains the CSV data
public var rows: [[String: String]] {
if _rows == nil {
parse()
}
return _rows!
}
/// Parse the file and call a block for each row, passing it as a dictionary
public func enumerateAsDict(_ block: @escaping ([String: String]) -> ()) {
let enumeratedHeader = header.enumerated()
enumerateAsArray { fields in
var dict = [String: String]()
for (index, head) in enumeratedHeader {
dict[head] = index < fields.count ? fields[index] : ""
}
block(dict)
}
}
/// Parse the file and call a block on each row, passing it in as a list of fields
public func enumerateAsArray(_ block: @escaping ([String]) -> ()) {
self.enumerateAsArray(block, limitTo: nil, startAt: 1)
}
private func parse() {
var rows = [[String: String]]()
enumerateAsDict { dict in
rows.append(dict)
}
_rows = rows
}
}
| mit | a36687a0a233df6c480d3ac39c53ac82 | 25.844444 | 86 | 0.56043 | 4.165517 | false | false | false | false |
superman-coder/pakr | pakr/pakr/Model/Web/Bookmark.swift | 1 | 992 | //
// Created by Huynh Quang Thao on 4/9/16.
// Copyright (c) 2016 Pakr. All rights reserved.
//
import Foundation
import Parse
class Bookmark:Post, ParseModelProtocol {
let PKTopicId = "topicId"
var topicId: String!
var topic: Topic!
init(userId: String!, topicId: String!, topic: Topic!) {
self.topicId = topicId
self.topic = topic
super.init(userId: userId)
}
required init(pfObject: PFObject) {
topicId = pfObject[PKTopicId] as! String
let userId = pfObject[Bookmark.PKPostUser].objectId
super.init(userId: userId)
self.dateCreated = pfObject.createdAt
self.postId = pfObject.objectId
}
func toPFObject() -> PFObject {
let pfObject = PFObject(className: Constants.Table.Bookmark)
pfObject[Bookmark.PKPostUser] = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
pfObject[PKTopicId] = topicId
return pfObject
}
}
| apache-2.0 | 60ef656962fb1dc8eca8acd283d8b9ed | 26.555556 | 114 | 0.653226 | 4.03252 | false | false | false | false |
allsome/LSYPaper | LSYPaper/BigNewsDetailCell.swift | 1 | 33155 | //
// NewsDetailCell.swift
// LSYPaper
//
// Created by 梁树元 on 1/9/16.
// Copyright © 2016 allsome.love. All rights reserved.
//
import UIKit
import AVFoundation
public let bottomViewDefaultHeight:CGFloat = 55
private let transform3Dm34D:CGFloat = 1900.0
private let newsViewWidth:CGFloat = (SCREEN_WIDTH - 50) / 2
private let shiningImageHeight:CGFloat = (SCREEN_WIDTH - 50) * 296 / 325
private let newsViewY:CGFloat = SCREEN_HEIGHT - 20 - bottomViewDefaultHeight - newsViewWidth * 2
private let endAngle:CGFloat = CGFloat(M_PI) / 2.5
private let startAngle:CGFloat = CGFloat(M_PI) / 3.3
private let animateDuration:Double = 0.25
private let minScale:CGFloat = 0.97
private let maxFoldAngle:CGFloat = 1.0
private let minFoldAngle:CGFloat = 0.75
private let translationYForView:CGFloat = SCREEN_WIDTH - newsViewY
private let normalScale:CGFloat = SCREEN_WIDTH / (newsViewWidth * 2)
private let baseShadowRedius:CGFloat = 50.0
private let emitterWidth:CGFloat = 35.0
private let realShiningBGColor:UIColor = UIColor(white: 0.0, alpha: 0.4)
class BigNewsDetailCell: UICollectionViewCell {
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var upperScreenShot: UIImageView!
@IBOutlet weak var baseScreenShot: UIImageView!
@IBOutlet weak var baseLayerViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var webViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var realShiningView: UIView!
@IBOutlet weak var realBaseView: UIView!
@IBOutlet weak var totalView: UIView!
@IBOutlet weak var shiningViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var newsViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var coreViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak private var shadowView: UIView!
@IBOutlet weak private var shiningView: UIView!
@IBOutlet weak private var shiningImage: UIImageView!
@IBOutlet weak private var baseLayerView: UIView!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var newsView: UIView!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var commentButton: UIButton!
@IBOutlet weak var summaryLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var labelView: UIView!
private var panNewsView:UIPanGestureRecognizer = UIPanGestureRecognizer()
private var panWebView:UIPanGestureRecognizer = UIPanGestureRecognizer()
private var tapSelf:UITapGestureRecognizer = UITapGestureRecognizer()
private var topLayer:CALayer = CALayer()
private var bottomLayer:CALayer = CALayer()
private var isHasRequest:Bool = false
private var isLike:Bool = false
private var isShare:Bool = false {
didSet {
if isShare == true {
LSYPaperPopView.showPopViewWith(CGRect(x: 0, y: SCREEN_HEIGHT - 47 - sharePopViewHeight, width: SCREEN_WIDTH, height: sharePopViewHeight), viewMode: LSYPaperPopViewMode.share,inView: totalView, frontView: bottomView, revokeOption: { () -> Void in
self.shareButton.addPopSpringAnimation()
self.revokePopView()
})
}else {
LSYPaperPopView.hidePopView(totalView)
}
}
}
private var isComment:Bool = false {
didSet {
if isComment == true {
LSYPaperPopView.showPopViewWith(CGRect(x: 0, y: SCREEN_HEIGHT - commentPopViewHeight - 47, width: SCREEN_WIDTH, height: commentPopViewHeight), viewMode: LSYPaperPopViewMode.comment,inView: totalView, frontView: bottomView,revokeOption: { () -> Void in
self.revokePopView()
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.labelView.alpha = 1.0
}, completion: { (stop:Bool) -> Void in
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.labelView.alpha = 0.0
})
})
})
}else {
LSYPaperPopView.hidePopView(totalView)
}
}
}
var isDarkMode:Bool = false {
didSet {
if isDarkMode == true {
tapSelf.isEnabled = true
sendCoreViewToBack()
LSYPaperPopView.showBackgroundView(totalView)
if isLike == false {
likeButton.setImage(UIImage(named: "LikePhoto"), for: UIControlState())
}
commentButton.setImage(UIImage(named: "CommentPhoto"), for: UIControlState())
shareButton.setImage(UIImage(named: "SharePhoto"), for: UIControlState())
summaryLabel.textColor = UIColor.white
commentLabel.textColor = UIColor.white
}else {
tapSelf.isEnabled = false
LSYPaperPopView.hideBackgroundView(totalView, completion: { () -> Void in
self.bringCoreViewToFront()
})
if isLike == false {
likeButton.setImage(UIImage(named: "Like"), for: UIControlState())
}
commentButton.setImage(UIImage(named: "Comment"), for: UIControlState())
shareButton.setImage(UIImage(named: "Share"), for: UIControlState())
summaryLabel.textColor = UIColor.lightGray
commentLabel.textColor = UIColor.lightGray
}
}
}
private var locationInSelf:CGPoint = CGPoint.zero
private var translationInSelf:CGPoint = CGPoint.zero
private var velocityInSelf:CGPoint = CGPoint.zero
private var transform3D:CATransform3D = CATransform3DIdentity
private var transformConcat:CATransform3D {
return CATransform3DConcat(CATransform3DRotate(transform3D, transform3DAngle, 1, 0, 0), CATransform3DMakeTranslation(translationInSelf.x, 0, 0))
}
private var foldScale:CGFloat {
let a = (normalScale - 1) / ((maxFoldAngle - minFoldAngle) * CGFloat(M_PI))
let b = 1 - (normalScale - 1) * minFoldAngle / (maxFoldAngle - minFoldAngle)
return a * transform3DAngleFold + b <= 1 ? 1 : a * transform3DAngleFold + b
}
private var transformConcatFold:CATransform3D {
return CATransform3DConcat(CATransform3DConcat(CATransform3DRotate(transform3D, transform3DAngleFold, 1, 0, 0), CATransform3DMakeTranslation(translationInSelf.x / foldScale, translationYForView / foldScale, 0)), CATransform3DMakeScale(foldScale, foldScale, 1))
}
private var transformEndedConcat:CATransform3D {
let scale = normalScale
return CATransform3DConcat(CATransform3DConcat(CATransform3DRotate(transform3D, CGFloat(M_PI), 1, 0, 0), CATransform3DMakeTranslation(0, translationYForView / scale, 0)), CATransform3DMakeScale(scale, scale, 1))
}
private var transform3DAngle:CGFloat {
let cosUpper = locationInSelf.y - newsViewY >= (newsViewWidth * 2) ? (newsViewWidth * 2) : locationInSelf.y - newsViewY
return acos(cosUpper / (newsViewWidth * 2))
+ asin((locationInSelf.y - newsViewY) / transform3Dm34D)
}
private var transform3DAngleFold:CGFloat {
let cosUpper = locationInSelf.y - SCREEN_WIDTH
return acos(cosUpper / SCREEN_WIDTH)
}
private var webViewRequest:URLRequest {
return URLRequest(url: URL(string: "https://github.com")!)
}
private var soundID:SystemSoundID {
var soundID:SystemSoundID = 0
let path = Bundle.main.path(forResource: "Pop", ofType: "wav")
let baseURL = URL(fileURLWithPath: path!)
AudioServicesCreateSystemSoundID(baseURL, &soundID)
return soundID
}
@IBOutlet weak var likeView: UIView!
@IBOutlet weak var alphaView: UIView!
@IBOutlet weak var coreView: UIView!
private var explosionLayer:CAEmitterLayer = CAEmitterLayer()
private var chargeLayer:CAEmitterLayer = CAEmitterLayer()
var unfoldWebViewOption:(() -> Void)?
var foldWebViewOption:(() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = true
layer.cornerRadius = CORNER_REDIUS
labelView.layer.masksToBounds = true
labelView.layer.cornerRadius = CORNER_REDIUS
totalView.layer.masksToBounds = true
totalView.layer.cornerRadius = cellGap * 2
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2)
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowRadius = 1.0
baseLayerView.layer.shadowColor = UIColor.black.cgColor
baseLayerView.layer.shadowOffset = CGSize(width: 0, height: baseShadowRedius)
baseLayerView.layer.shadowOpacity = 0.8
baseLayerView.layer.shadowRadius = baseShadowRedius
baseLayerView.alpha = 0.0
newsView.layer.shadowColor = UIColor.clear.cgColor
newsView.layer.shadowOffset = CGSize(width: 0, height: baseShadowRedius)
newsView.layer.shadowOpacity = 0.4
newsView.layer.shadowRadius = baseShadowRedius
upperScreenShot.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0)
let pan = UIPanGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleNewsPanGesture(_:)))
pan.delegate = self
newsView.addGestureRecognizer(pan)
panNewsView = pan
let tap = UITapGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleNewsTapGesture(_:)))
newsView.addGestureRecognizer(tap)
transform3D.m34 = -1 / transform3Dm34D
webViewHeightConstraint.constant = SCREEN_WIDTH * 2
webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, SCREEN_WIDTH * 2 - SCREEN_HEIGHT, 0)
let webViewPan = UIPanGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleWebPanGesture(_:)))
webViewPan.delegate = self
webView.addGestureRecognizer(webViewPan)
panWebView = webViewPan
let tapContent = UITapGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleContentTapGesture(_:)))
contentView.addGestureRecognizer(tapContent)
tapContent.isEnabled = false
tapSelf = tapContent
// heavily refer to MCFireworksView by Matthew Cheok
let explosionCell = CAEmitterCell()
explosionCell.name = "explosion"
explosionCell.alphaRange = 0.2
explosionCell.alphaSpeed = -1.0
explosionCell.lifetime = 0.5
explosionCell.lifetimeRange = 0.0
explosionCell.birthRate = 0
explosionCell.velocity = 44.00
explosionCell.velocityRange = 7.00
explosionCell.contents = UIImage(named: "Sparkle")?.cgImage
explosionCell.scale = 0.05
explosionCell.scaleRange = 0.02
let explosionLayer = CAEmitterLayer()
explosionLayer.name = "emitterLayer"
explosionLayer.emitterShape = kCAEmitterLayerCircle
explosionLayer.emitterMode = kCAEmitterLayerOutline
explosionLayer.emitterSize = CGSize(width: emitterWidth, height: 0)
let center = CGPoint(x: likeView.bounds.midX, y: likeView.bounds.midY)
explosionLayer.emitterPosition = center
explosionLayer.emitterCells = [explosionCell]
explosionLayer.masksToBounds = false
likeView.layer.addSublayer(explosionLayer)
self.explosionLayer = explosionLayer
let chargeCell = CAEmitterCell()
chargeCell.name = "charge"
chargeCell.alphaRange = 0.20
chargeCell.alphaSpeed = -1.0
chargeCell.lifetime = 0.3
chargeCell.lifetimeRange = 0.1
chargeCell.birthRate = 0
chargeCell.velocity = -60.0
chargeCell.velocityRange = 0.00
chargeCell.contents = UIImage(named: "Sparkle")?.cgImage
chargeCell.scale = 0.05
chargeCell.scaleRange = 0.02
let chargeLayer = CAEmitterLayer()
chargeLayer.name = "emitterLayer"
chargeLayer.emitterShape = kCAEmitterLayerCircle
chargeLayer.emitterMode = kCAEmitterLayerOutline
chargeLayer.emitterSize = CGSize(width: emitterWidth - 10, height: 0)
chargeLayer.emitterPosition = center
chargeLayer.emitterCells = [chargeCell]
chargeLayer.masksToBounds = false
likeView.layer.addSublayer(chargeLayer)
self.chargeLayer = chargeLayer
}
func handleContentTapGesture(_ recognizer:UITapGestureRecognizer) {
revokePopView()
}
func handleNewsTapGesture(_ recognizer:UITapGestureRecognizer) {
anchorPointSetting()
baseLayerView.alpha = 1.0
realBaseView.alpha = 0.5
locationInSelf = CGPoint(x: 0, y: SCREEN_HEIGHT - 9.5)
gestureStateChangedSetting(transform3DAngle)
tapNewsView()
}
func handleWebPanGesture(_ recognizer:UIPanGestureRecognizer) {
locationInSelf = recognizer.location(in: self)
translationInSelf = recognizer.translation(in: self)
if recognizer.state == UIGestureRecognizerState.began {
baseScreenShot.image = self.getSubImageFrom(self.getWebViewScreenShot(), frame: CGRect(x: 0, y: SCREEN_WIDTH, width: SCREEN_WIDTH, height: SCREEN_WIDTH))
upperScreenShot.image = self.getSubImageFrom(self.getWebViewScreenShot(), frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH))
webView.scrollView.panGestureRecognizer.isEnabled = false
webView.alpha = 0.0
let ratio = (M_PI - Double(transform3DAngleFold)) / M_PI
let alpha:CGFloat = transform3DAngleFold / CGFloat(M_PI) >= 0.5 ? 1.0 : 0.0
UIView.animate(withDuration: (animateDuration * 2 + 0.2) * ratio, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformConcatFold
self.shiningView.layer.transform = self.transformConcatFold
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(self.foldScale, self.foldScale, 1), CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.realBaseView.alpha = 0.5
self.realShiningView.alpha = 0.5
self.upperScreenShot.alpha = alpha
}, completion: { (stop:Bool) -> Void in
})
}else if recognizer.state == UIGestureRecognizerState.changed && webView.scrollView.panGestureRecognizer.isEnabled == false {
newsView.layer.transform = transformConcatFold
shiningView.layer.transform = transformConcatFold
baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(foldScale, foldScale, 1), CATransform3DMakeTranslation(translationInSelf.x, translationYForView, 0))
shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (transform3DAngleFold - startAngle) / (endAngle - startAngle))
gestureStateChangedSetting(transform3DAngleFold)
}else if (recognizer.state == UIGestureRecognizerState.cancelled || recognizer.state == UIGestureRecognizerState.ended) && webView.scrollView.panGestureRecognizer.isEnabled == false{
webView.scrollView.panGestureRecognizer.isEnabled = true
velocityInSelf = recognizer.velocity(in: self)
if self.velocityInSelf.y < 0 {
if transform3DAngleFold / CGFloat(M_PI) < 0.5 {
UIView.animate(withDuration: animateDuration * Double((CGFloat(M_PI) - transform3DAngleFold) / CGFloat(M_PI * 2)), delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
self.shiningView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
}, completion: { (stop:Bool) -> Void in
self.upperScreenShot.alpha = 1.0
self.shiningImage.alpha = 0.0
self.realShiningView.alpha = 1.0
self.shiningView.backgroundColor = UIColor.white
self.realShiningView.backgroundColor = realShiningBGColor
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.shadowView.layer.shadowColor = UIColor.clear.cgColor
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(self.foldScale, self.foldScale, 1), CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView / ((normalScale)), 0))
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeTranslation(0, translationYForView / ((normalScale)), 0),CATransform3DMakeScale(normalScale, normalScale, 1))
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
}, completion: { (stop:Bool) -> Void in
if self.velocityInSelf.y <= 0 {
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
}
})
})
}else {
baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(foldScale, foldScale, 1), CATransform3DMakeTranslation(translationInSelf.x, translationYForView / ((normalScale)), 0))
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeTranslation(0, translationYForView / ((normalScale)), 0),CATransform3DMakeScale(normalScale, normalScale, 1))
self.shiningImage.alpha = 0.0
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
},completion: { (stop:Bool) -> Void in
if self.velocityInSelf.y <= 0 {
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
}
})
}
}else {
self.normalLayoutNewsView()
}
}
}
func handleNewsPanGesture(_ recognizer:UIPanGestureRecognizer) {
locationInSelf = recognizer.location(in: self)
if recognizer.state == UIGestureRecognizerState.began {
anchorPointSetting()
translationInSelf = recognizer.translation(in: self)
UIView.animate(withDuration: animateDuration * 2 + 0.2, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformConcat
self.shiningView.layer.transform = self.transformConcat
self.shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (self.transform3DAngle - startAngle) / (endAngle - startAngle))
self.totalView.transform = CGAffineTransform(scaleX: minScale, y: minScale)
self.baseLayerView.alpha = 1.0
self.realBaseView.alpha = 0.5
}, completion: { (stop:Bool) -> Void in
})
}else if recognizer.state == UIGestureRecognizerState.changed {
translationInSelf = recognizer.translation(in: self)
newsView.layer.transform = transformConcat
shiningView.layer.transform = transformConcat
baseLayerView.layer.transform = CATransform3DMakeTranslation(translationInSelf.x, 0, 0)
shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (transform3DAngle - startAngle) / (endAngle - startAngle))
gestureStateChangedSetting(transform3DAngle)
}else if (recognizer.state == UIGestureRecognizerState.cancelled || recognizer.state == UIGestureRecognizerState.ended){
velocityInSelf = recognizer.velocity(in: self)
if self.velocityInSelf.y <= 0 {
if transform3DAngle / CGFloat(M_PI) < 0.5 {
tapNewsView()
}else {
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(normalScale, normalScale, 1), CATransform3DMakeTranslation(0, translationYForView, 0))
self.shiningImage.alpha = 0.0
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
},completion: { (stop:Bool) -> Void in
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
})
}
}else {
self.normalLayoutNewsView()
}
}
}
func revokePopView() {
isDarkMode = false
if isShare == true {
isShare = false
}else {
isComment = false
}
}
}
private extension BigNewsDetailCell {
@IBAction func showCommentOrNot(_ sender: UIButton) {
if isComment == false {
if isDarkMode == false {
isDarkMode = true
}else {
isShare = false
}
}else {
isDarkMode = false
}
if sender.tag != 1 {
commentButton.addSpringAnimation()
}
isComment = !isComment
}
@IBAction func showShareOrNot(_ sender: AnyObject) {
if isShare == false {
if isDarkMode == false {
isDarkMode = true
}else {
isComment = false
}
}else {
isDarkMode = false
}
shareButton.addSpringAnimation()
isShare = !isShare
}
@IBAction func likeOrNot(_ sender: AnyObject) {
if isLike == false {
likeButton.addSpringAnimation(1.3, durationArray: [0.05,0.1,0.23,0.195,0.155,0.12], delayArray: [0.0,0.0,0.1,0.0,0.0,0.0], scaleArray: [0.75,1.8,0.8,1.0,0.95,1.0])
chargeLayer.setValue(100, forKeyPath: "emitterCells.charge.birthRate")
delay((0.05 + 0.1 + 0.23) * 1.3, closure: { () -> Void in
self.chargeLayer.setValue(0, forKeyPath: "emitterCells.charge.birthRate")
self.explosionLayer.setValue(1000, forKeyPath: "emitterCells.explosion.birthRate")
self.delay(0.1, closure: { () -> Void in
self.explosionLayer.setValue(0, forKeyPath: "emitterCells.explosion.birthRate")
})
AudioServicesPlaySystemSound(self.soundID)
})
likeButton.setImage(UIImage(named: "Like-Blue"), for: UIControlState())
self.commentLabel.text = "Awesome!"
self.commentLabel.addFadeAnimation()
}else {
likeButton.addSpringAnimation()
let image = isDarkMode == false ? UIImage(named: "Like") : UIImage(named: "LikePhoto")
likeButton.setImage(image, for: UIControlState())
self.commentLabel.text = "Write a comment"
self.commentLabel.addFadeAnimation()
}
isLike = !isLike
}
private func bringCoreViewToFront() {
totalView.backgroundColor = UIColor.white
contentView.backgroundColor = UIColor.clear
contentView.bringSubview(toFront: coreView)
contentView.bringSubview(toFront: webView)
}
private func sendCoreViewToBack() {
totalView.backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.white
contentView.sendSubview(toBack: coreView)
}
private func loadWebViewRequest() {
if self.isHasRequest == false {
self.webView.loadRequest(self.webViewRequest)
self.isHasRequest = true
}
}
private func anchorPointSetting() {
newsView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
newsViewBottomConstraint.constant = newsViewWidth
shiningView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
shiningViewBottomConstraint.constant = newsViewWidth
baseLayerView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
baseLayerViewBottomConstraint.constant = newsViewWidth
}
private func getWebViewScreenShot() -> UIImage{
UIGraphicsBeginImageContextWithOptions(webView.frame.size, false, 1.0)
webView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
private func getSubImageFrom(_ originImage:UIImage,frame:CGRect) -> UIImage {
let imageRef = originImage.cgImage
let subImageRef = imageRef?.cropping(to: frame)
UIGraphicsBeginImageContext(frame.size)
let context = UIGraphicsGetCurrentContext()
context?.draw(in: frame, image: subImageRef!)
let subImage = UIImage(cgImage: subImageRef!)
UIGraphicsEndImageContext();
return subImage;
}
private func tapNewsView() {
UIView.animate(withDuration: animateDuration * Double((CGFloat(M_PI) - transform3DAngleFold) / CGFloat(M_PI * 2)), delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, 0, 0))
self.shiningView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, 0, 0))
self.shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (self.transform3DAngle - startAngle) / (endAngle - startAngle))
}, completion: { (stop:Bool) -> Void in
self.shiningImage.alpha = 0.0
self.realShiningView.alpha = 0.5
self.upperScreenShot.alpha = 1.0
self.shiningView.backgroundColor = UIColor.white
self.realShiningView.backgroundColor = realShiningBGColor
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.shadowView.layer.shadowColor = UIColor.clear.cgColor
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(normalScale, normalScale, 1), CATransform3DMakeTranslation(0, translationYForView, 0))
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
}, completion: { (stop:Bool) -> Void in
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
})
})
}
private func normalLayoutNewsView() {
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DIdentity
self.shiningView.layer.transform = CATransform3DIdentity
self.shiningImage.transform = CGAffineTransform.identity
self.totalView.transform = CGAffineTransform.identity
self.baseLayerView.layer.transform = CATransform3DIdentity
self.shiningImage.alpha = 1.0
self.baseLayerView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.shiningView.backgroundColor = UIColor.clear
self.newsView.layer.shadowColor = UIColor.clear.cgColor
self.shadowView.layer.shadowColor = UIColor.black.cgColor
},completion: { (stop:Bool) -> Void in
if (self.foldWebViewOption != nil) {
self.foldWebViewOption!()
}
})
}
private func gestureStateChangedSetting(_ targetAngle:CGFloat) {
if targetAngle / CGFloat(M_PI) >= 0.5 {
upperScreenShot.alpha = 1.0
shiningImage.alpha = 0
realShiningView.alpha = 0.5
shiningView.backgroundColor = UIColor.white
realShiningView.backgroundColor = realShiningBGColor
newsView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowColor = UIColor.clear.cgColor
}else {
upperScreenShot.alpha = 0.0
shiningImage.alpha = 1
realShiningView.alpha = 0.0
shiningView.backgroundColor = UIColor.clear
newsView.layer.shadowColor = UIColor.clear.cgColor
shadowView.layer.shadowColor = UIColor.black.cgColor
}
}
}
extension BigNewsDetailCell:UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panWebView && otherGestureRecognizer == webView.scrollView.panGestureRecognizer {
if (webView.scrollView.contentOffset.y <= 0 && webView.scrollView.panGestureRecognizer.velocity(in: self).y >= 0) || webView.scrollView.panGestureRecognizer.location(in: self).y <= 100 {
return true
}else {
return false
}
} else {
return false
}
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panNewsView {
if (panNewsView.velocity(in: self).y >= 0) || fabs(panNewsView.velocity(in: self).x) >= fabs(panNewsView.velocity(in: self).y) {
return false
}else {
return true
}
}else {
return true
}
}
}
| mit | ae534cf59842e90a3d329ec330f4aa02 | 51.783439 | 268 | 0.632768 | 4.824334 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressShared/WordPressShared/Languages.swift | 2 | 7253 | import Foundation
import NSObject_SafeExpectations
/// This helper class allows us to map WordPress.com LanguageID's into human readable language strings.
///
public class WordPressComLanguageDatabase: NSObject {
// MARK: - Public Properties
/// Languages considered 'popular'
///
public let popular: [Language]
/// Every supported language
///
public let all: [Language]
/// Returns both, Popular and All languages, grouped
///
public let grouped: [[Language]]
// MARK: - Public Methods
/// Designated Initializer: will load the languages contained within the `Languages.json` file.
///
public override init() {
// Parse the json file
let path = Bundle(for: WordPressComLanguageDatabase.self).path(forResource: filename, ofType: "json")
let raw = try! Data(contentsOf: URL(fileURLWithPath: path!))
let parsed = try! JSONSerialization.jsonObject(with: raw, options: [.mutableContainers, .mutableLeaves]) as? NSDictionary
// Parse All + Popular: All doesn't contain Popular. Otherwise the json would have dupe data. Right?
let parsedAll = Language.fromArray(parsed!.array(forKey: Keys.all) as! [NSDictionary])
let parsedPopular = Language.fromArray(parsed!.array(forKey: Keys.popular) as! [NSDictionary])
let merged = parsedAll + parsedPopular
// Done!
popular = parsedPopular
all = merged.sorted { $0.name < $1.name }
grouped = [popular] + [all]
}
/// Returns the Human Readable name for a given Language Identifier
///
/// - Parameter languageId: The Identifier of the language.
///
/// - Returns: A string containing the language name, or an empty string, in case it wasn't found.
///
public func nameForLanguageWithId(_ languageId: Int) -> String {
return find(id: languageId)?.name ?? ""
}
/// Returns the Language with a given Language Identifier
///
/// - Parameter id: The Identifier of the language.
///
/// - Returns: The language with the matching Identifier, or nil, in case it wasn't found.
///
public func find(id: Int) -> Language? {
return all.first(where: { $0.id == id })
}
/// Returns the current device language as the corresponding WordPress.com language ID.
/// If the language is not supported, it returns 1 (English).
///
/// This is a wrapper for Objective-C, Swift code should use deviceLanguage directly.
///
@objc(deviceLanguageId)
public func deviceLanguageIdNumber() -> NSNumber {
return NSNumber(value: deviceLanguage.id)
}
/// Returns the slug string for the current device language.
/// If the language is not supported, it returns "en" (English).
///
/// This is a wrapper for Objective-C, Swift code should use deviceLanguage directly.
///
@objc(deviceLanguageSlug)
public func deviceLanguageSlugString() -> String {
return deviceLanguage.slug
}
/// Returns the current device language as the corresponding WordPress.com language.
/// If the language is not supported, it returns English.
///
public var deviceLanguage: Language {
let variants = LanguageTagVariants(string: deviceLanguageCode)
for variant in variants {
if let match = self.languageWithSlug(variant) {
return match
}
}
return languageWithSlug("en")!
}
/// Searches for a WordPress.com language that matches a language tag.
///
fileprivate func languageWithSlug(_ slug: String) -> Language? {
let search = languageCodeReplacements[slug] ?? slug
// Use lazy evaluation so we stop filtering as soon as we got the first match
return all.lazy.filter({ $0.slug == search }).first
}
/// Overrides the device language. For testing purposes only.
///
func _overrideDeviceLanguageCode(_ code: String) {
deviceLanguageCode = code.lowercased()
}
// MARK: - Public Nested Classes
/// Represents a Language supported by WordPress.com
///
public class Language: Equatable {
/// Language Unique Identifier
///
public let id: Int
/// Human readable Language name
///
public let name: String
/// Language's Slug String
///
public let slug: String
/// Localized description for the current language
///
public var description: String {
return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.identifier, value: slug) ?? name
}
/// Designated initializer. Will fail if any of the required properties is missing
///
init?(dict: NSDictionary) {
guard let unwrappedId = dict.number(forKey: Keys.identifier)?.intValue,
let unwrappedSlug = dict.string(forKey: Keys.slug),
let unwrappedName = dict.string(forKey: Keys.name) else {
id = Int.min
name = String()
slug = String()
return nil
}
id = unwrappedId
name = unwrappedName
slug = unwrappedSlug
}
/// Given an array of raw languages, will return a parsed array.
///
public static func fromArray(_ array: [NSDictionary]) -> [Language] {
return array.flatMap {
return Language(dict: $0)
}
}
public static func == (lhs: Language, rhs: Language) -> Bool {
return lhs.id == rhs.id
}
}
// MARK: - Private Variables
/// The device's current preferred language, or English if there's no preferred language.
///
fileprivate lazy var deviceLanguageCode: String = {
return NSLocale.preferredLanguages.first?.lowercased() ?? "en"
}()
// MARK: - Private Constants
fileprivate let filename = "Languages"
// (@koke 2016-04-29) I'm not sure how correct this mapping is, but it matches
// what we do for the app translations, so they will at least be consistent
fileprivate let languageCodeReplacements: [String: String] = [
"zh-hans": "zh-cn",
"zh-hant": "zh-tw"
]
// MARK: - Private Nested Structures
/// Keys used to parse the raw languages.
///
fileprivate struct Keys {
static let popular = "popular"
static let all = "all"
static let identifier = "i"
static let slug = "s"
static let name = "n"
}
}
/// Provides a sequence of language tags from the specified string, from more to less specific
/// For instance, "zh-Hans-HK" will yield `["zh-Hans-HK", "zh-Hans", "zh"]`
///
private struct LanguageTagVariants: Sequence {
let string: String
func makeIterator() -> AnyIterator<String> {
var components = string.components(separatedBy: "-")
return AnyIterator {
guard !components.isEmpty else {
return nil
}
let current = components.joined(separator: "-")
components.removeLast()
return current
}
}
}
| gpl-2.0 | 67de14c2abbb1507fa8e9ed6c36a12aa | 31.968182 | 129 | 0.612988 | 4.812873 | false | false | false | false |
duliodenis/cs193p-Winter-2015 | assignment-1-calculator/Calculator/Calculator/ViewController.swift | 1 | 2852 | //
// ViewController.swift
// Calculator
//
// Created by Dulio Denis on 1/26/15.
// Copyright (c) 2015 ddApps. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var history: UILabel!
var operandStack = Array<Double>()
var operationStack = Array<Double>()
var userIsInTheMiddleOfTypingANumber = false
var decimalUsed = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
println("digit = \(digit)")
if userIsInTheMiddleOfTypingANumber {
if digit == "." && decimalUsed == true {
return
} else if digit == "." && decimalUsed == false {
decimalUsed = true
}
display.text = display.text! + digit
} else {
userIsInTheMiddleOfTypingANumber = true
if digit == "." {
decimalUsed = true
display.text = "0."
} else {
display.text = digit
}
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation { $0 * $1 }
case "÷": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "−": performOperation { $1 - $0 }
case "√": performOperation { sqrt($0) }
case "sin": performOperation { sin($0) }
case "cos": performOperation { cos($0) }
case "∏": displayValue = M_PI
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
decimalUsed = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
history.text = ""
for element in operandStack {
history.text = history.text! + "\(element), "
}
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
decimalUsed = false
}
}
}
| mit | 4b1782d717657f91f2c52c10d2b745da | 27.158416 | 90 | 0.537975 | 5.170909 | false | false | false | false |
peigen/iLife | iLife/SecondVC.swift | 1 | 4385 | //
// SecondVC.swift
// CleanUp
//
// Created by peigen on 14-6-21.
// Copyright (c) 2014 Peigen.info. All rights reserved.
//
import Foundation
import UIKit
class SecondVC: BaseVC {
// UIView
@IBOutlet var usedToScrollView: UIScrollView
@IBOutlet var appScrollView: UIScrollView
@IBOutlet var callScrollView: UIScrollView
@IBOutlet var unkownScrollView: UIScrollView
// UIViewController
var appImges : Array<String> = ["com_sina_weibo_icon.png","com_tencent_mm_icon.png","com_eg_android_AlipayGphone_icon.png","com_android_chrome_icon.png","com_youku_phone_icon.png"]
var iphoneCalls : Array<String> = ["IMG_0883.JPG"]
override func viewDidLoad() {
super.viewDidLoad()
var background : UIImage = UIImage(named:"bookshelf.png")
UIGraphicsBeginImageContext(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-64));
background.drawInRect(CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64))
background = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// background.resizableImageWithCapInsets(background.capInsets, resizingMode: UIImageResizingMode.Stretch)
// = CGSize(SCREEN_WIDTH,SCREEN_HEIGHT)
self.view.backgroundColor = UIColor(patternImage: background)
initView()
initButton()
}
func setScrollView(scrollView : UIScrollView, yAxis : CGFloat) {
scrollView.frame = CGRectMake( ORIGINAL_POINT, yAxis, SCREEN_WIDTH, scrollViewHeight)
scrollView.contentSize = CGSize(width: SCREEN_WIDTH*2, height: scrollViewHeight)
// scrollView.backgroundColor = backgroundColor
scrollView.pagingEnabled = false
scrollView.bounces = true
}
func initView(){
self.view.frame = CGRectMake(ORIGINAL_POINT, ORIGINAL_POINT, SCREEN_WIDTH, SCREEN_HEIGHT)
// 0. used to
var usedToYAxis = space
setScrollView(usedToScrollView, yAxis: usedToYAxis)
// 1. app view
var appYAxis = usedToYAxis + scrollViewHeight
setScrollView(appScrollView, yAxis: appYAxis)
// 2. call view
var callYAxis = appYAxis + scrollViewHeight
setScrollView(callScrollView, yAxis: callYAxis)
// 3. unkown view
var unkownYAxis = callYAxis + scrollViewHeight
setScrollView(unkownScrollView, yAxis: unkownYAxis)
}
func initButton(){
var x = 30
for i in 0..4{
// title
initLabel(usedToScrollView, text: "App Manage", align: NSTextAlignment.Center)
// more
// button
var button = UIButton.buttonWithType(.Custom) as UIButton
button.frame = CGRect(x: x ,y: 40,width: 57,height: 57)
button.setImage(UIImage(named:appImges[i]),forState: .Normal)
button.addTarget(self, action: "onAction:", forControlEvents: .TouchUpInside)
// button.tag = i
addScrollView(button)
x += 57+10;
}
}
func initButton(i:Int,x:Int) {
//
// initLabel(usedToScrollView, text: <#String#>, align: <#NSTextAlignment#>)
}
func initLabel(view : UIView , text : String ,align : NSTextAlignment){
// title
var titleLabel : UILabel = UILabel(frame:CGRect(origin: CGPointMake(0.0, 0.0), size: CGSizeMake(150,20)))
titleLabel.textAlignment = align
titleLabel.text = text
titleLabel.textColor = UIColor.redColor()
view.addSubview(titleLabel)
}
func addScrollView(button : UIButton){
usedToScrollView.addSubview(button)
// appScrollView.addSubview(button)
// callScrollView.addSubview(button)
// unkownScrollView.addSubview(button)
}
func onAction(btn:UIButton)
{
if(btn.tag == 0)
{
openWeiboAction(btn)
}
if(btn.tag == 1)
{
openWeixinAction(btn)
}
if(btn.tag == 2)
{
openAlipayAction(btn)
}
if(btn.tag == 3)
{
openChromeAction(btn)
}
if(btn.tag == 4)
{
openYoukuAction(btn)
}
}
func openWeiboAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "weibo://"))
}
func openWeixinAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "weixin://"))
}
func openAlipayAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "alipays://"))
}
func openChromeAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "googlechrome://"))
}
func openYoukuAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "YouKu://"))
}
func callYayaAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel:18629091151"))
}
} | gpl-3.0 | a0fc4a0179d3de90db683eddb5f0383e | 25.107143 | 181 | 0.71699 | 3.463665 | false | false | false | false |
benbahrenburg/KeyStorage | KeyStorage/Classes/KeyChainInfo.swift | 1 | 5586 | //
// KeyStorage - Simplifying securely saving key information
// KeyChainInfo.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2019 bencoding.com. All rights reserved.
//
import Foundation
import Security
/**
Contains information related to the Keychain
*/
public struct KeyChainInfo {
/**
Struct returned from getAccessGroupInfo with information related to the Keychain Group.
*/
public struct AccessGroupInfo {
/// App ID Prefix
public var prefix: String
/// Keycahin Group
public var keyChainGroup: String
/// Raw kSecAttrAccessGroup value returned from Keychain
public var rawValue: String
}
/**
Enum to used determine error details
*/
public enum errorDetail: Error {
/// No password provided or available
case noPassword
/// Incorrect data provided as part of the password return
case unexpectedPasswordData
/// Incorrect data provided for a non password Keychain item
case unexpectedItemData
/// Unknown error returned by keychain
case unhandledError(status: OSStatus)
}
/**
Enum to used map the accessibility of keychain items.
For example, if whenUnlockedThisDeviceOnly the item data can
only be accessed once the device has been unlocked after a restart.
*/
public enum accessibleOption: RawRepresentable {
case whenUnlocked,
afterFirstUnlock,
whenUnlockedThisDeviceOnly,
afterFirstUnlockThisDeviceOnly,
whenPasscodeSetThisDeviceOnly
public init?(rawValue: String) {
switch rawValue {
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case String(kSecAttrAccessibleWhenUnlocked):
self = .whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case String(kSecAttrAccessibleAfterFirstUnlock):
self = .afterFirstUnlock
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = .whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = .afterFirstUnlockThisDeviceOnly
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly):
self = .whenPasscodeSetThisDeviceOnly
default:
self = .afterFirstUnlockThisDeviceOnly
}
}
/// Convert Enum to String Const
public var rawValue: String {
switch self {
case .whenUnlocked:
return String(kSecAttrAccessibleWhenUnlocked)
case .afterFirstUnlock:
return String(kSecAttrAccessibleAfterFirstUnlock)
case .whenPasscodeSetThisDeviceOnly:
return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .whenUnlockedThisDeviceOnly:
return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .afterFirstUnlockThisDeviceOnly:
return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
}
}
}
}
| mit | d6a522e7ae8a273b7604e9be2ec33290 | 37.253425 | 92 | 0.594449 | 6.861179 | false | false | false | false |
geojow/beeryMe | beeryMe/PubView.swift | 1 | 955 | //
// PubViews.swift
// beeryMe
//
// Created by George Jowitt on 23/11/2017.
// Copyright © 2017 George Jowitt. All rights reserved.
//
import Foundation
import MapKit
class PubView: MKAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let pub = newValue as? Pub else { return }
canShowCallout = true
calloutOffset = CGPoint(x: -5, y: 5)
if let pubImage = pub.image {
image = pubImage
} else {
image = nil
}
let btn = UIButton(type: .infoLight)
btn.setImage(image, for: .normal)
btn.tintColor = nil
leftCalloutAccessoryView = btn
let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero,
size: CGSize(width: 30, height: 30)))
mapsButton.setBackgroundImage(UIImage(named: "maps-icon"), for: UIControlState())
rightCalloutAccessoryView = mapsButton
}
}
}
| mit | 03f2865ce89f6ea8bbb1935ad1e41a88 | 25.5 | 87 | 0.606918 | 4.147826 | false | false | false | false |
Mattmlm/codepathInstagramFeed | InstagramFeed/PhotoDetailsViewController.swift | 1 | 2064 | //
// PhotoDetailsViewController.swift
// InstagramFeed
//
// Created by admin on 9/17/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class PhotoDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var imageURL : String?
@IBOutlet weak var photoDetailsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.photoDetailsTableView.delegate = self;
self.photoDetailsTableView.dataSource = self;
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 320;
} else {
return tableView.rowHeight;
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("photoDetailsCell")
if indexPath.row == 0 {
if let imageURL = self.imageURL {
cell!.imageView?.contentMode = .ScaleAspectFit;
cell!.imageView?.setImageWithURL(NSURL(string: imageURL)!);
}
}
return cell!;
}
/*
// 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 | 646d9f4f0928878a5a720155fffe1911 | 29.338235 | 109 | 0.64954 | 5.457672 | false | false | false | false |
DrabWeb/Azusa | Azusa.Previous/Azusa/Utilities/AZMusicUtilities.swift | 1 | 2328 | //
// AZMusicUtilities.swift
// Azusa
//
// Created by Ushio on 12/7/16.
//
import Foundation
/// General music related utilities for Azusa
struct AZMusicUtilities {
// MARK: - Functions
/// Returns the hours, minutes and seconds from the given amount of seconds
///
/// - Parameter seconds: The seconds to use
/// - Returns: The hours, minutes and seconds of `seconds`
static func hoursMinutesSeconds(from seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60);
}
/// Returns the display string for given seconds
///
/// - Parameter seconds: The seconds to get the display time from
/// - Returns: The display string for the given seconds(e.g. 1:40, 0:32, 1:05:42, etc.)
static func secondsToDisplayTime(_ seconds : Int) -> String {
/// The hours, minutes and seconds from `seconds`
let hoursMinutesSeconds = AZMusicUtilities.hoursMinutesSeconds(from: seconds);
/// The display string for the hours
var hoursString : String = "";
/// The display string for the minutes
var minutesString : String = "";
/// The display string for the seconds
var secondsString : String = "";
// If there is at least one hour...
if(hoursMinutesSeconds.0 > 0) {
// Set the hours string to the hour count
hoursString = String(hoursMinutesSeconds.0);
}
// Set the minutes string to minutes, zero padded by one
minutesString = String(format: "%01d", hoursMinutesSeconds.1);
// Set the seconds string to seconds, zero padded by two
secondsString = String(format: "%02d", hoursMinutesSeconds.2);
// If the hours string is set...
if(hoursString != "") {
// Set minutes string to have two zero padding
minutesString = String(format: "%02d", hoursMinutesSeconds.1);
// Return the display string
return "\(hoursString):\(minutesString):\(secondsString)";
}
// If the hours string isn't set...
else {
// Return the display string as is
return "\(minutesString):\(secondsString)";
}
}
}
| gpl-3.0 | f8ffb8b2ec427d3e68a37e5c0272b9d3 | 34.272727 | 91 | 0.587199 | 4.609901 | false | false | false | false |
biohazardlover/ROer | Roer/Monster+DatabaseRecord.swift | 1 | 14649 |
import CoreData
import CoreSpotlight
import MobileCoreServices
extension Monster {
var displayRace: String? {
guard let race = race else { return nil }
switch race {
case 0:
return "Monster.Race.Formless".localized
case 1:
return "Monster.Race.Undead".localized
case 2:
return "Monster.Race.Brute".localized
case 3:
return "Monster.Race.Plant".localized
case 4:
return "Monster.Race.Insect".localized
case 5:
return "Monster.Race.Fish".localized
case 6:
return "Monster.Race.Demon".localized
case 7:
return "Monster.Race.DemiHuman".localized
case 8:
return "Monster.Race.Angel".localized
case 9:
return "Monster.Race.Dragon".localized
case 10:
return "Monster.Race.Player".localized
default:
return nil
}
}
var displayProperty: String? {
guard let element = element else { return nil }
let level = element.intValue / 20
switch element {
case 20, 40, 60, 80:
return "Property.Neutral".localized + " \(level)"
case 21, 41, 61, 81:
return "Property.Water".localized + " \(level)"
case 22, 42, 62, 82:
return "Property.Earth".localized + " \(level)"
case 23, 43, 63, 83:
return "Property.Fire".localized + " \(level)"
case 24, 44, 64, 84:
return "Property.Wind".localized + " \(level)"
case 25, 45, 65, 85:
return "Property.Poison".localized + " \(level)"
case 26, 46, 66, 86:
return "Property.Holy".localized + " \(level)"
case 27, 47, 67, 87:
return "Property.Shadow".localized + " \(level)"
case 28, 48, 68, 88:
return "Property.Ghost".localized + " \(level)"
case 29, 49, 69, 89:
return "Property.Undead".localized + " \(level)"
default:
return nil
}
}
var displaySize: String? {
guard let scale = scale else { return nil }
switch scale {
case 0:
return "Monster.Size.Small".localized
case 1:
return "Monster.Size.Medium".localized
case 2:
return "Monster.Size.Large".localized
default:
return nil
}
}
var displayAttackDelay: String? {
guard let aDelay = aDelay else { return nil }
let attackDelay = aDelay.floatValue / 1000.0
return "\(attackDelay)s"
}
var displayAttack: String? {
guard let atk1 = atk1, let atk2 = atk2 else { return nil }
return "\(atk1)-\(atk2)"
}
var displayBaseExperiencePerHP: String? {
guard let exp = exp, let hp = hp else { return nil }
let baseExperiencePerHP = exp.floatValue / hp.floatValue
return NSString(format: "%.3f:1", baseExperiencePerHP) as String
}
var displayJobExperiencePerHP: String? {
guard let jexp = jexp, let hp = hp else { return nil }
let jobExperiencePerHP = jexp.floatValue / hp.floatValue
return NSString(format: "%.3f:1", jobExperiencePerHP) as String
}
var displayModes: NSAttributedString? {
guard let mode = mode else { return nil }
var modes = [String]()
let modeMask = mode.intValue
if modeMask & 1 << 0 == 0 {
modes.append("Monster.Mode.Immovable".localized)
}
if modeMask & 1 << 1 != 0 {
modes.append("Monster.Mode.Looter".localized)
}
if modeMask & 1 << 2 != 0 {
modes.append("Monster.Mode.Aggressive".localized)
}
if modeMask & 1 << 3 != 0 {
modes.append("Monster.Mode.Assist".localized)
}
if modeMask & 1 << 4 != 0 {
modes.append("Monster.Mode.CastSensorIdle".localized)
}
if modeMask & 1 << 5 != 0 {
modes.append("Monster.Mode.ImmuneToStatusChange".localized)
}
if modeMask & 1 << 6 != 0 {
modes.append("Monster.Mode.Plant".localized)
}
if modeMask & 1 << 7 == 0 {
modes.append("Monster.Mode.NonAttacker".localized)
}
if modeMask & 1 << 8 != 0 {
modes.append("Monster.Mode.Detector".localized)
}
if modeMask & 1 << 9 != 0 {
modes.append("Monster.Mode.CastSensorChase".localized)
}
if modeMask & 1 << 10 != 0 {
modes.append("Monster.Mode.ChangeChase".localized)
}
if modeMask & 1 << 11 != 0 {
modes.append("Monster.Mode.Angry".localized)
}
if modeMask & 1 << 12 != 0 {
modes.append("Monster.Mode.ChangeTargetAttack".localized)
}
if modeMask & 1 << 13 != 0 {
modes.append("Monster.Mode.ChangeTargetChase".localized)
}
if modeMask & 1 << 14 != 0 {
modes.append("Monster.Mode.TargetWeak".localized)
}
if modeMask & 1 << 15 != 0 {
modes.append("Monster.Mode.RandomTarget".localized)
}
if modeMask & 1 << 16 != 0 {
modes.append("Monster.Mode.IgnoreMelee".localized)
}
if modeMask & 1 << 17 != 0 {
modes.append("Monster.Mode.IgnoreMagic".localized)
}
if modeMask & 1 << 18 != 0 {
modes.append("Monster.Mode.IgnoreRange".localized)
}
if modeMask & 1 << 19 != 0 {
modes.append("Monster.Mode.BossTypeImmunityToSkills".localized)
}
if modeMask & 1 << 20 != 0 {
modes.append("Monster.Mode.IgnoreMisc".localized)
}
if modeMask & 1 << 21 != 0 {
modes.append("Monster.Mode.KnockbackImmune".localized)
}
if modeMask & 1 << 22 != 0 {
modes.append("Monster.Mode.NoRandomWalk".localized)
}
if modeMask & 1 << 23 != 0 {
modes.append("Monster.Mode.NoCastSkill".localized)
}
modes = modes.map { "- " + $0 }
return NSAttributedString(string: modes.joined(separator: "\n"))
}
}
extension Monster {
var onMaps: [DatabaseRecordCellInfo] {
guard let monsterSpawnGroups = monsterSpawnGroups else {return [] }
var onMaps = [DatabaseRecordCellInfo]()
for monsterSpawnGroup in monsterSpawnGroups {
guard let map = monsterSpawnGroup.map else {
continue
}
onMaps.append((map, monsterSpawnGroup.displaySpawn))
}
return onMaps
}
var drops: [(id: NSNumber, per: NSNumber)] {
var drops: [(id: NSNumber?, per: NSNumber?)] = [(drop1id, drop1per), (drop2id, drop2per), (drop3id, drop3per), (drop4id, drop4per), (drop5id, drop5per), (drop6id, drop6per), (drop7id, drop7per), (drop8id, drop8per), (drop9id, drop9per), (dropCardid, dropCardper), (mvp1id, mvp1per), (mvp2id, mvp2per), (mvp3id, mvp3per)]
drops = drops.filter { $0.id != nil && $0.per != nil && $0.id != 0 }
return drops.map { ($0.id!, $0.per!) }
}
var dropItems: [DatabaseRecordCellInfo] {
var dropItems = [DatabaseRecordCellInfo]()
let drops: [(id: NSNumber?, per: NSNumber?)] = [(drop1id, drop1per), (drop2id, drop2per), (drop3id, drop3per), (drop4id, drop4per), (drop5id, drop5per), (drop6id, drop6per), (drop7id, drop7per), (drop8id, drop8per), (drop9id, drop9per), (dropCardid, dropCardper)]
for drop in drops {
if let dropId = drop.id , dropId != 0, let dropPer = drop.per {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", dropId)
if let item = (try? managedObjectContext?.fetch(fetchRequest))??.first {
dropItems.append((item, dropRateWithPer(dropPer)))
}
}
}
dropItems.sort { (dropItem1, dropItem2) -> Bool in
return (dropItem1.databaseRecord as! Item).id?.intValue ?? 0 < (dropItem2.databaseRecord as! Item).id?.intValue ?? 0
}
return dropItems
}
var mvpDropItems: [DatabaseRecordCellInfo] {
var mvpDropItems = [DatabaseRecordCellInfo]()
let mvpDrops: [(id: NSNumber?, per: NSNumber?)] = [(mvp1id, mvp1per), (mvp2id, mvp2per), (mvp3id, mvp3per)]
for mvpDrop in mvpDrops {
if let mvpDropId = mvpDrop.id , mvpDropId != 0, let mvpDropPer = mvpDrop.per {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", mvpDropId)
if let item = (try? managedObjectContext?.fetch(fetchRequest))??.first {
mvpDropItems.append((item, dropRateWithPer(mvpDropPer)))
}
}
}
mvpDropItems.sort { (mvpDropItem1, mvpDropItem2) -> Bool in
return (mvpDropItem1.databaseRecord as! Item).id?.intValue ?? 0 < (mvpDropItem2.databaseRecord as! Item).id?.intValue ?? 0
}
return mvpDropItems
}
}
extension Monster {
var monsterSpawnGroups: [MonsterSpawnGroup]? {
guard let id = id else { return nil }
let fetchRequest = NSFetchRequest<MonsterSpawn>(entityName: "MonsterSpawn")
fetchRequest.predicate = NSPredicate(format: "monsterID == %@", id)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "mapName", ascending: true)]
guard let monsterSpawns = (try? managedObjectContext?.fetch(fetchRequest)) ?? nil else { return nil }
return MonsterSpawnGroup.monsterSpawnGroupsWithMonsterSpawns(monsterSpawns)
}
}
extension Monster {
var localizedName: String? {
if let id = id {
if let localizedName = Localization.preferred.monsters[id.stringValue] {
return localizedName
}
}
return kROName
}
}
extension Monster: DatabaseRecord {
var smallImageURL: URL? {
return nil
}
var largeImageURL: URL? {
if let id = id {
return URL(string: "http://file5.ratemyserver.net/mobs/\(id).gif")
} else {
return nil
}
}
var displayName: String? {
return localizedName
}
var recordDetails: DatabaseRecordDetails {
var attributeGroups = [DatabaseRecordAttributeGroup]()
attributeGroups.appendAttribute(("Monster.HP".localized, hp))
attributeGroups.appendAttribute(("Monster.Level".localized, lv))
attributeGroups.appendAttribute(("Monster.Race".localized, displayRace?.utf8))
attributeGroups.appendAttribute(("Monster.Property".localized, displayProperty?.utf8))
attributeGroups.appendAttribute(("Monster.Size".localized, displaySize?.utf8))
attributeGroups.appendAttribute(("Monster.Hit100".localized, hit100))
attributeGroups.appendAttribute(("Monster.Flee95".localized, flee95))
attributeGroups.appendAttribute(("Monster.WalkSpeed".localized, speed))
attributeGroups.appendAttribute(("Monster.AttackDelay".localized, displayAttackDelay?.utf8))
attributeGroups.appendAttribute(("Monster.Attack".localized, displayAttack?.utf8))
attributeGroups.appendAttribute(("Monster.Defence".localized, def))
attributeGroups.appendAttribute(("Monster.MagicDefence".localized, mdef))
attributeGroups.appendAttribute(("Monster.AttackRange".localized, range1)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.SpellRange".localized, range2)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.SightRange".localized, range3)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.BaseExperience".localized, exp))
attributeGroups.appendAttribute(("Monster.JobExperience".localized, jexp))
attributeGroups.appendAttribute(("Monster.MVPExperience".localized, mexp != nil && mexp!.intValue > 0 ? mexp : nil))
attributeGroups.appendAttribute(("Monster.BaseExperiencePerHP".localized, displayBaseExperiencePerHP?.utf8))
attributeGroups.appendAttribute(("Monster.JobExperiencePerHP".localized, displayJobExperiencePerHP?.utf8))
attributeGroups.appendAttribute(("Monster.DelayAfterHit".localized, dMotion))
attributeGroups.appendAttributes([("Monster.Str".localized, str), ("Monster.Agi".localized, agi), ("Monster.Vit".localized, vit)])
attributeGroups.appendAttributes([("Monster.Int".localized, int), ("Monster.Dex".localized, dex), ("Monster.Luk".localized, luk)])
var recordDetails = DatabaseRecordDetails()
recordDetails.appendTitle(displayName != nil && id != nil ? "\(displayName!) #\(id!)" : "", section: .attributeGroups(attributeGroups))
recordDetails.appendTitle("Monster.OnMaps".localized, section: .databaseRecords(onMaps))
recordDetails.appendTitle("Monster.Modes".localized, section: .description(displayModes))
recordDetails.appendTitle("Monster.Drops".localized, section: .databaseRecords(dropItems))
recordDetails.appendTitle("Monster.MVPDrops".localized, section: .databaseRecords(mvpDropItems))
return recordDetails
}
func correspondingDatabaseRecord(in managedObjectContext: NSManagedObjectContext) -> DatabaseRecord? {
guard let id = id else { return nil }
let request = NSFetchRequest<Monster>(entityName: "Monster")
request.predicate = NSPredicate(format: "%K == %@", "id", id)
let results = try? managedObjectContext.fetch(request)
return results?.first
}
}
extension Monster: Searchable {
var searchableItem: CSSearchableItem {
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
searchableItemAttributeSet.title = localizedName
searchableItemAttributeSet.contentDescription = nil
searchableItemAttributeSet.thumbnailData = nil
return CSSearchableItem(uniqueIdentifier: "Monster/" + (id?.stringValue ?? ""), domainIdentifier: nil, attributeSet: searchableItemAttributeSet)
}
}
| mit | 4e0b50423bdb511101765b9824a8940e | 38.379032 | 328 | 0.593897 | 4.376755 | false | false | false | false |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/examples/login/Example/AppDelegate.swift | 1 | 1539 | //
// AppDelegate.swift
// LoginSample
//
// Created by Måns Bernhardt on 2018-04-12.
// Copyright © 2018 iZettle. All rights reserved.
//
import UIKit
import Flow
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let bag = DisposeBag()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = UIViewController()
let loginButton = UIButton(type: UIButtonType.system)
loginButton.setTitle("Show Login Controller", for: .normal)
let stack = UIStackView(arrangedSubviews: [loginButton])
stack.alignment = .center
vc.view = stack
let window = UIWindow(frame: UIScreen.main.bounds)
self.window = window
window.backgroundColor = .white
window.rootViewController = vc
window.makeKeyAndVisible()
bag += loginButton.onValue {
let login = LoginController()
let nc = UINavigationController(rootViewController: login)
vc.present(nc, animated: true, completion: nil)
login.runLogin().onValue { user in
print("Login succeeded with user", user)
}.onError { error in
print("Login failed with error", error)
}.always {
nc.dismiss(animated: true, completion: nil)
}
}
return true
}
}
| mit | 5cbc4159ad528887834d87ca15706f50 | 27.462963 | 144 | 0.607027 | 5.192568 | false | false | false | false |
crossroadlabs/ExpressCommandLine | swift-express/Core/Steps/CopyDirectoryContents.swift | 1 | 4005 | //===--- CopyDirectoryContents.swift ----------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line 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.
//
//Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===------------------------------------------------------------------===//
import Foundation
import Regex
//Copy contents of directory into another. Ignoring .git folder
//Input: inputFolder
//Input: outputFolder
//Output:
// copiedItems: Array<String>
// outputFolder: String
struct CopyDirectoryContents : Step {
let dependsOn = [Step]()
let excludeList:[Regex]
let alreadyExistsError = "CopyDirectoryContents: Output folder already exists."
func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] {
guard let inputFolder = params["inputFolder"] as? String else {
throw SwiftExpressError.BadOptions(message: "CopyDirectoryContents: No inputFolder option.")
}
guard let outputFolder = params["outputFolder"] as? String else {
throw SwiftExpressError.BadOptions(message: "CopyDirectoryContents: No outputFolder option.")
}
do {
if FileManager.isDirectoryExists(outputFolder) || FileManager.isFileExists(outputFolder) {
throw SwiftExpressError.BadOptions(message: alreadyExistsError)
} else {
try FileManager.createDirectory(outputFolder, createIntermediate: true)
}
var copiedItems = [String]()
let contents = try FileManager.listDirectory(inputFolder)
for item in contents {
let ignore = excludeList.reduce(false, combine: { (prev, r) -> Bool in
return prev || r.matches(item)
})
if ignore {
continue
}
try FileManager.copyItem(inputFolder.addPathComponent(item), toDirectory: outputFolder)
copiedItems.append(item)
}
return ["copiedItems": copiedItems, "outputFolder": outputFolder]
} catch let err as SwiftExpressError {
throw err
} catch let err as NSError {
throw SwiftExpressError.SomeNSError(error: err)
} catch {
throw SwiftExpressError.UnknownError(error: error)
}
}
func cleanup(params: [String : Any], output: StepResponse) throws {
}
func revert(params: [String : Any], output: [String : Any]?, error: SwiftExpressError?) {
switch error {
case .BadOptions(let message)?:
if message == alreadyExistsError {
return
}
fallthrough
default:
if let outputFolder = params["outputFolder"] as? String {
do {
try FileManager.removeItem(outputFolder)
} catch {
print("CopyDirectoryContents: Can't remove output folder on revert \(outputFolder)")
}
}
}
}
init(excludeList: [String]? = nil) {
if excludeList != nil {
self.excludeList = excludeList!.map({ str -> Regex in
return str.r!
})
} else {
self.excludeList = ["\\.git$".r!]
}
}
} | gpl-3.0 | 9851fc4e6f021f3c52975f7c959ad6b4 | 37.152381 | 105 | 0.59226 | 5.056818 | false | false | false | false |
ZulwiyozaPutra/Alien-Adventure-Tutorial | Alien Adventure/MostCommonCharacter.swift | 1 | 1106 | //
// MostCommonCharacter.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func mostCommonCharacter(inventory: [UDItem]) -> Character? {
var characters = [Character: Int]()
var mostCommonCharacter: Character? = nil
var mostCommonCharacterOccurance: Int = 0
for item in inventory {
for character in item.name.characters {
if characters[character] == nil {
characters[character] = 1
} else {
characters[character]! += 1
}
}
}
for item in characters {
if item.value >= mostCommonCharacterOccurance {
mostCommonCharacter = item.key
mostCommonCharacterOccurance = item.value
}
}
print("mostCommonCharacter is \(mostCommonCharacter!)")
return mostCommonCharacter
}
}
| mit | f756992823331c58c174cca8cb1c5331 | 25.309524 | 65 | 0.512217 | 5.815789 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/RealmSwift/RealmSwift/Util.swift | 32 | 4656 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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
import Realm
// MARK: Internal Helpers
// Swift 3.1 provides fixits for some of our uses of unsafeBitCast
// to use unsafeDowncast instead, but the bitcast is required.
internal func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
return unsafeBitCast(x, to: type)
}
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) {
NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatches(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
extension Object {
// Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
// but actually operate on `RLMObjectBase`. Do not expose cast value to user.
internal func unsafeCastToRLMObject() -> RLMObject {
return unsafeBitCast(self, to: RLMObject.self)
}
}
// MARK: CustomObjectiveCBridgeable
internal func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T {
if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
return BridgeableType.bridging(objCValue: x) as! T
} else {
return x as! T
}
}
internal func dynamicBridgeCast<T>(fromSwift x: T) -> Any {
if let x = x as? CustomObjectiveCBridgeable {
return x.objCValue
} else {
return x
}
}
// Used for conversion from Objective-C types to Swift types
internal protocol CustomObjectiveCBridgeable {
/* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber`
* At this point, use `as! [SwiftType]` to cast between. */
static func bridging(objCValue: Any) -> Self
var objCValue: Any { get }
}
extension Int8: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int8 {
return (objCValue as! NSNumber).int8Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int16: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int16 {
return (objCValue as! NSNumber).int16Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int32: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int32 {
return (objCValue as! NSNumber).int32Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int64: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int64 {
return (objCValue as! NSNumber).int64Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Optional: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Optional {
if objCValue is NSNull {
return nil
} else {
return .some(dynamicBridgeCast(fromObjectiveC: objCValue))
}
}
var objCValue: Any {
if let value = self {
return value
} else {
return NSNull()
}
}
}
// MARK: AssistedObjectiveCBridgeable
internal protocol AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self
var bridged: (objectiveCValue: Any, metadata: Any?) { get }
}
| mit | 331947fc2b105d1ed639629d63266c12 | 31.788732 | 111 | 0.646478 | 4.451243 | false | false | false | false |
lightsprint09/LADVSwift | LADVSwift/ResultAttachment+JSONDecodeable.swift | 1 | 561 | //
// ResultAttachment+JSONDecodeable.swift
// LADVSwift
//
// Created by Lukas Schmidt on 01.06.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
extension ResultAttachement: JSONCodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
name = try decoder.decode("name")
let urlString: String = try decoder.decode("url")
url = URL(string: urlString)!
fileType = try decoder.decode("type")
obsolete = try decoder.decode("obsolete")
}
}
| mit | 0488d60078c1dbdedd46c2b0349f083d | 25.666667 | 57 | 0.6625 | 3.971631 | false | false | false | false |
theappbusiness/TABScrollingContentView | Pods/TABSwiftLayout/Sources/Deprecations.swift | 1 | 4780 | //
// Deprecations.swift
// TABSwiftLayout
//
// Created by Daniela Bulgaru on 13/09/2016.
// Copyright © 2016 TheAppBusiness. All rights reserved.
//
import Foundation
extension View {
@available(*, deprecated:2.0.0, renamed: "pin(edges:toView:relation:margins:priority:)")
public func pin(_ edges: EdgeMask, toView view: View, relation: NSLayoutRelation = .equal, margins: EdgeMargins = EdgeMargins(), priority: LayoutPriority = LayoutPriorityRequired) -> [NSLayoutConstraint] {
return pin(edges: edges, toView: view, relation: relation, margins: margins, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "pin(edge:toEdge:ofView:relation:margin:priority:)")
public func pin(_ edge: Edge, toEdge: Edge, ofView view: View, relation: NSLayoutRelation = .equal, margin: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return pin(edge: edge, toEdge: toEdge, ofView: view, relation: relation, margin: margin, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "align(axis:relativeTo:offset:priority:)")
public func align(_ axis: Axis, relativeTo view: View, offset: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return align(axis: axis, relativeTo: view, offset: offset, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:ofViews:ratio:priority:)")
public func size(_ axis: Axis, ofViews views: [View], ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired) -> [NSLayoutConstraint] {
return size(axis: axis, ofViews: views, ratio: ratio, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:relatedBy:size:priority:)")
public func size(_ axis: Axis, relatedBy relation: NSLayoutRelation, size: CGFloat, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return self.size(axis: axis, relatedBy: relation, size: size, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:relativeTo:ofView:ratio:priority:)")
public func size(_ axis: Axis, relativeTo otherAxis: Axis, ofView view: View, ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return size(axis: axis, relativeTo: otherAxis, ofView: view, ratio: ratio, priority: priority)
}
}
extension View {
@available(*, deprecated:2.0.0, renamed: "alignEdges(edges:toView:)")
public func alignEdges(_ edges: EdgeMask, toView: View) {
align(edges: edges, toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignTop(toView:)")
public func alignTop(_ toView: View) -> NSLayoutConstraint {
return alignTop(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignLeft(toView:)")
public func alignLeft(_ toView: View) -> NSLayoutConstraint {
return alignLeft(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignBottom(toView:)")
public func alignBottom(_ toView: View) -> NSLayoutConstraint {
return alignBottom(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignRight(toView:)")
public func alignRight(_ toView: View) -> NSLayoutConstraint {
return alignRight(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignHorizontally(toView:)")
public func alignHorizontally(_ toView: View) -> NSLayoutConstraint {
return alignHorizontally(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignVertically(toView:)")
public func alignVertically(_ toView: View) -> NSLayoutConstraint {
return alignVertically(toView: toView)
}
}
extension View {
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "align") public func center(_ axis: Axis, relativeTo view: View, offset: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return align(axis, relativeTo: view, offset: offset, priority: priority)
}
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "alignVertically") public func centerVertically(toView: View) -> NSLayoutConstraint {
return alignVertically(toView: toView)
}
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "alignHorizontally") public func centerHorizontally(toView: View) -> NSLayoutConstraint {
return alignHorizontally(toView: toView)
}
}
public extension View {
@available(*, deprecated:2.0.0, renamed: "constraints(forTrait:)")
public func constraintsForTrait(_ trait: ConstraintsTraitMask) -> [NSLayoutConstraint] {
return constraints(forTrait: trait)
}
@available(*, deprecated:2.0.0, renamed: "contains(trait:)")
public func containsTraits(_ trait: ConstraintsTraitMask) -> Bool {
return contains(trait: trait)
}
}
| mit | 10facb1fb0341e00d60bf40684e1d266 | 41.669643 | 218 | 0.716886 | 4.10567 | false | false | false | false |
hollance/swift-algorithm-club | Tree/Tree.playground/Contents.swift | 3 | 1442 | //: Playground - noun: a place where people can play
let tree = TreeNode<String>(value: "beverages")
let hotNode = TreeNode<String>(value: "hot")
let coldNode = TreeNode<String>(value: "cold")
let teaNode = TreeNode<String>(value: "tea")
let coffeeNode = TreeNode<String>(value: "coffee")
let chocolateNode = TreeNode<String>(value: "cocoa")
let blackTeaNode = TreeNode<String>(value: "black")
let greenTeaNode = TreeNode<String>(value: "green")
let chaiTeaNode = TreeNode<String>(value: "chai")
let sodaNode = TreeNode<String>(value: "soda")
let milkNode = TreeNode<String>(value: "milk")
let gingerAleNode = TreeNode<String>(value: "ginger ale")
let bitterLemonNode = TreeNode<String>(value: "bitter lemon")
tree.addChild(hotNode)
tree.addChild(coldNode)
hotNode.addChild(teaNode)
hotNode.addChild(coffeeNode)
hotNode.addChild(chocolateNode)
coldNode.addChild(sodaNode)
coldNode.addChild(milkNode)
teaNode.addChild(blackTeaNode)
teaNode.addChild(greenTeaNode)
teaNode.addChild(chaiTeaNode)
sodaNode.addChild(gingerAleNode)
sodaNode.addChild(bitterLemonNode)
tree
teaNode.parent
teaNode.parent!.parent
extension TreeNode where T: Equatable {
func search(_ value: T) -> TreeNode? {
if value == self.value {
return self
}
for child in children {
if let found = child.search(value) {
return found
}
}
return nil
}
}
tree.search("cocoa")
tree.search("chai")
tree.search("bubbly")
| mit | 9fb29f2201414f83002771abbbd311a8 | 23.033333 | 61 | 0.730236 | 3.204444 | false | false | false | false |
idomizrachi/Regen | regen/Images/ImagesClassGeneratorSwift.swift | 1 | 2309 | //
// ImagesClassGeneratorSwift.swift
// regen
//
// Created by Ido Mizrachi on 5/10/17.
//
import Foundation
class ImagesClassGeneratorSwift: ImagesClassGenerator {
func generateClass(fromImagesTree imagesTree: Tree<ImageNodeItem>, generatedFile: String) {
Logger.debug("\tGenerating images swift class: started")
let filename = generatedFile + ".swift"
var file = ""
FileUtils.deleteFileAt(filePath: filename)
let className = String(NSString(string: generatedFile).lastPathComponent)
file += "import Foundation\n\n"
for folder in imagesTree.children {
generateClassX(node: folder, file: &file)
}
file += "\n"
file += "class \(className) {\n"
file += " static let shared = \(className)()\n"
file += " private init() {}\n"
file += "\n"
generateFoldersProperties(node: imagesTree, file: &file)
file += "\n"
generateAssetsProperties(node: imagesTree, file: &file)
file += "}\n"
FileUtils.append(filePath: filename, content: file)
Logger.debug("\tGenerating images swift class: finished")
Logger.info("\tCreated: \(filename)")
}
func generateClassX(node: TreeNode<ImageNodeItem>, file: inout String) {
for folder in node.children {
generateClassX(node: folder, file: &file)
}
file += "class \(node.item.folderClass) {\n\n"
generateFoldersProperties(node: node, file: &file)
if (node.children.count > 0) {
file += "\n"
}
generateAssetsProperties(node: node, file: &file)
file += "}\n"
}
func generateFoldersProperties(node: TreeNode<ImageNodeItem>, file: inout String) {
for folder in node.children {
file += " let \(folder.item.folder.propertyName()) = \(folder.item.folderClass)()\n"
}
}
func generateAssetsProperties(node: TreeNode<ImageNodeItem>, file: inout String) {
for image in node.item.images {
file += " let \(image.propertyName) = \"\(image.name)\"\n"
}
}
}
| mit | 3d78918aa1c878368826ae36400f8c7f | 28.227848 | 99 | 0.557817 | 4.431862 | false | false | false | false |
maxoll90/FSwift | ios8-example/FSwift-Sample/Pods/FSwift/FSwift/Time/Timer.swift | 3 | 1198 | //
// Timer.swift
// FSwift
//
// Created by Kelton Person on 10/4/14.
// Copyright (c) 2014 Kelton. All rights reserved.
//
import Foundation
public class Timer {
let interval: NSTimeInterval
let repeats: Bool
let f: (Timer) -> Void
var isRunning: Bool = false
private var timer: NSTimer?
public init(interval: NSTimeInterval, repeats: Bool, f: (Timer) -> Void) {
self.interval = interval
self.repeats = repeats
self.f = f
}
@objc func tick() {
if self.timer != nil {
self.f(self)
}
if !self.repeats {
self.stop()
}
}
public func start() {
if self.timer == nil {
self.timer = NSTimer(timeInterval: interval, target:self, selector: Selector("tick"), userInfo: nil, repeats: repeats)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)
self.isRunning = true
}
}
public func stop() {
self.timer?.invalidate()
self.timer = nil
self.isRunning = false
}
public var running: Bool {
return self.isRunning
}
}
| mit | 069dfb5610bde16ae6e95e1a7ff382a3 | 21.185185 | 130 | 0.556761 | 4.21831 | false | false | false | false |
zbw209/- | StudyNotes/Pods/Alamofire/Source/AFError.swift | 5 | 36558 | //
// AFError.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
public enum AFError: Error {
/// The underlying reason the `.multipartEncodingFailed` error occurred.
public enum MultipartEncodingFailureReason {
/// The `fileURL` provided for reading an encodable body part isn't a file `URL`.
case bodyPartURLInvalid(url: URL)
/// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension.
case bodyPartFilenameInvalid(in: URL)
/// The file at the `fileURL` provided was not reachable.
case bodyPartFileNotReachable(at: URL)
/// Attempting to check the reachability of the `fileURL` provided threw an error.
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
/// The file at the `fileURL` provided is actually a directory.
case bodyPartFileIsDirectory(at: URL)
/// The size of the file at the `fileURL` provided was not returned by the system.
case bodyPartFileSizeNotAvailable(at: URL)
/// The attempt to find the size of the file at the `fileURL` provided threw an error.
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
/// An `InputStream` could not be created for the provided `fileURL`.
case bodyPartInputStreamCreationFailed(for: URL)
/// An `OutputStream` could not be created when attempting to write the encoded data to disk.
case outputStreamCreationFailed(for: URL)
/// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`.
case outputStreamFileAlreadyExists(at: URL)
/// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`.
case outputStreamURLInvalid(url: URL)
/// The attempt to write the encoded body data to disk failed with an underlying error.
case outputStreamWriteFailed(error: Error)
/// The attempt to read an encoded body part `InputStream` failed with underlying system error.
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the `.parameterEncodingFailed` error occurred.
public enum ParameterEncodingFailureReason {
/// The `URLRequest` did not have a `URL` to encode.
case missingURL
/// JSON serialization failed with an underlying system error during the encoding process.
case jsonEncodingFailed(error: Error)
/// Custom parameter encoding failed due to the associated `Error`.
case customEncodingFailed(error: Error)
}
/// The underlying reason the `.parameterEncoderFailed` error occurred.
public enum ParameterEncoderFailureReason {
/// Possible missing components.
public enum RequiredComponent {
/// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding.
case url
/// The `HTTPMethod` could not be extracted from the passed `URLRequest`.
case httpMethod(rawValue: String)
}
/// A `RequiredComponent` was missing during encoding.
case missingRequiredComponent(RequiredComponent)
/// The underlying encoder failed with the associated error.
case encoderFailed(error: Error)
}
/// The underlying reason the `.responseValidationFailed` error occurred.
public enum ResponseValidationFailureReason {
/// The data file containing the server response did not exist.
case dataFileNil
/// The data file containing the server response at the associated `URL` could not be read.
case dataFileReadFailed(at: URL)
/// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a
/// wildcard type.
case missingContentType(acceptableContentTypes: [String])
/// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`.
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
/// The response status code was not acceptable.
case unacceptableStatusCode(code: Int)
/// Custom response validation failed due to the associated `Error`.
case customValidationFailed(error: Error)
}
/// The underlying reason the response serialization error occurred.
public enum ResponseSerializationFailureReason {
/// The server response contained no data or the data was zero length.
case inputDataNilOrZeroLength
/// The file containing the server response did not exist.
case inputFileNil
/// The file containing the server response could not be read from the associated `URL`.
case inputFileReadFailed(at: URL)
/// String serialization failed using the provided `String.Encoding`.
case stringSerializationFailed(encoding: String.Encoding)
/// JSON serialization failed with an underlying system error.
case jsonSerializationFailed(error: Error)
/// A `DataDecoder` failed to decode the response due to the associated `Error`.
case decodingFailed(error: Error)
/// A custom response serializer failed due to the associated `Error`.
case customSerializationFailed(error: Error)
/// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type.
case invalidEmptyResponse(type: String)
}
/// Underlying reason a server trust evaluation error occurred.
public enum ServerTrustFailureReason {
/// The output of a server trust evaluation.
public struct Output {
/// The host for which the evaluation was performed.
public let host: String
/// The `SecTrust` value which was evaluated.
public let trust: SecTrust
/// The `OSStatus` of evaluation operation.
public let status: OSStatus
/// The result of the evaluation operation.
public let result: SecTrustResultType
/// Creates an `Output` value from the provided values.
init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
self.host = host
self.trust = trust
self.status = status
self.result = result
}
}
/// No `ServerTrustEvaluator` was found for the associated host.
case noRequiredEvaluator(host: String)
/// No certificates were found with which to perform the trust evaluation.
case noCertificatesFound
/// No public keys were found with which to perform the trust evaluation.
case noPublicKeysFound
/// During evaluation, application of the associated `SecPolicy` failed.
case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
/// During evaluation, setting the associated anchor certificates failed.
case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
/// During evaluation, creation of the revocation policy failed.
case revocationPolicyCreationFailed
/// `SecTrust` evaluation failed with the associated `Error`, if one was produced.
case trustEvaluationFailed(error: Error?)
/// Default evaluation failed with the associated `Output`.
case defaultEvaluationFailed(output: Output)
/// Host validation failed with the associated `Output`.
case hostValidationFailed(output: Output)
/// Revocation check failed with the associated `Output` and options.
case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
/// Certificate pinning failed.
case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
/// Public key pinning failed.
case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
/// Custom server trust evaluation failed due to the associated `Error`.
case customEvaluationFailed(error: Error)
}
/// The underlying reason the `.urlRequestValidationFailed`
public enum URLRequestValidationFailureReason {
/// URLRequest with GET method had body data.
case bodyDataInGETRequest(Data)
}
/// `UploadableConvertible` threw an error in `createUploadable()`.
case createUploadableFailed(error: Error)
/// `URLRequestConvertible` threw an error in `asURLRequest()`.
case createURLRequestFailed(error: Error)
/// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
/// `Request` was explicitly cancelled.
case explicitlyCancelled
/// `URLConvertible` type failed to create a valid `URL`.
case invalidURL(url: URLConvertible)
/// Multipart form encoding failed.
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
/// `ParameterEncoding` threw an error during the encoding process.
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
/// `ParameterEncoder` threw an error while running the encoder.
case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
/// `RequestAdapter` threw an error during adaptation.
case requestAdaptationFailed(error: Error)
/// `RequestRetrier` threw an error during the request retry process.
case requestRetryFailed(retryError: Error, originalError: Error)
/// Response validation failed.
case responseValidationFailed(reason: ResponseValidationFailureReason)
/// Response serialization failed.
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
/// `ServerTrustEvaluating` instance threw an error during trust evaluation.
case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
/// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
case sessionDeinitialized
/// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
case sessionInvalidated(error: Error?)
/// `URLSessionTask` completed with error.
case sessionTaskFailed(error: Error)
/// `URLRequest` failed validation.
case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
}
extension Error {
/// Returns the instance cast as an `AFError`.
public var asAFError: AFError? {
return self as? AFError
}
/// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
guard let afError = self as? AFError else {
fatalError(message(), file: file, line: line)
}
return afError
}
/// Casts the instance as `AFError` or returns `defaultAFError`
func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
return self as? AFError ?? defaultAFError()
}
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the instance is `.sessionDeinitialized`.
public var isSessionDeinitializedError: Bool {
if case .sessionDeinitialized = self { return true }
return false
}
/// Returns whether the instance is `.sessionInvalidated`.
public var isSessionInvalidatedError: Bool {
if case .sessionInvalidated = self { return true }
return false
}
/// Returns whether the instance is `.explicitlyCancelled`.
public var isExplicitlyCancelledError: Bool {
if case .explicitlyCancelled = self { return true }
return false
}
/// Returns whether the instance is `.invalidURL`.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncoderError: Bool {
if case .parameterEncoderFailed = self { return true }
return false
}
/// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
/// properties will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestAdaptationError: Bool {
if case .requestAdaptationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
/// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isServerTrustEvaluationError: Bool {
if case .serverTrustEvaluationFailed = self { return true }
return false
}
/// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestRetryError: Bool {
if case .requestRetryFailed = self { return true }
return false
}
/// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateUploadableError: Bool {
if case .createUploadableFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateURLRequestError: Bool {
if case .createURLRequestFailed = self { return true }
return false
}
/// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
/// contain the associated values.
public var isDownloadedFileMoveError: Bool {
if case .downloadedFileMoveFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isSessionTaskError: Bool {
if case .sessionTaskFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
guard case let .invalidURL(url) = self else { return nil }
return url
}
/// The `URL` associated with the error.
public var url: URL? {
guard case let .multipartEncodingFailed(reason) = self else { return nil }
return reason.url
}
/// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
/// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
/// `.responseSerializationFailed`, `.requestRetryFailed` errors.
public var underlyingError: Error? {
switch self {
case let .multipartEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncoderFailed(reason):
return reason.underlyingError
case let .requestAdaptationFailed(error):
return error
case let .requestRetryFailed(retryError, _):
return retryError
case let .responseValidationFailed(reason):
return reason.underlyingError
case let .responseSerializationFailed(reason):
return reason.underlyingError
case let .serverTrustEvaluationFailed(reason):
return reason.underlyingError
case let .sessionInvalidated(error):
return error
case let .createUploadableFailed(error):
return error
case let .createURLRequestFailed(error):
return error
case let .downloadedFileMoveFailed(error, _, _):
return error
case let .sessionTaskFailed(error):
return error
case .explicitlyCancelled,
.invalidURL,
.sessionDeinitialized,
.urlRequestValidationFailed:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.acceptableContentTypes
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseContentType
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseCode
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
guard case let .responseSerializationFailed(reason) = self else { return nil }
return reason.failedStringEncoding
}
/// The `source` URL of a `.downloadedFileMoveFailed` error.
public var sourceURL: URL? {
guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil }
return source
}
/// The `destination` URL of a `.downloadedFileMoveFailed` error.
public var destinationURL: URL? {
guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil }
return destination
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case let .jsonEncodingFailed(error),
let .customEncodingFailed(error):
return error
case .missingURL:
return nil
}
}
}
extension AFError.ParameterEncoderFailureReason {
var underlyingError: Error? {
switch self {
case let .encoderFailed(error):
return error
case .missingRequiredComponent:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case let .bodyPartURLInvalid(url),
let .bodyPartFilenameInvalid(url),
let .bodyPartFileNotReachable(url),
let .bodyPartFileIsDirectory(url),
let .bodyPartFileSizeNotAvailable(url),
let .bodyPartInputStreamCreationFailed(url),
let .outputStreamCreationFailed(url),
let .outputStreamFileAlreadyExists(url),
let .outputStreamURLInvalid(url),
let .bodyPartFileNotReachableWithError(url, _),
let .bodyPartFileSizeQueryFailedWithError(url, _):
return url
case .outputStreamWriteFailed,
.inputStreamReadFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .bodyPartFileNotReachableWithError(_, error),
let .bodyPartFileSizeQueryFailedWithError(_, error),
let .outputStreamWriteFailed(error),
let .inputStreamReadFailed(error):
return error
case .bodyPartURLInvalid,
.bodyPartFilenameInvalid,
.bodyPartFileNotReachable,
.bodyPartFileIsDirectory,
.bodyPartFileSizeNotAvailable,
.bodyPartInputStreamCreationFailed,
.outputStreamCreationFailed,
.outputStreamFileAlreadyExists,
.outputStreamURLInvalid:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case let .missingContentType(types),
let .unacceptableContentType(types, _):
return types
case .dataFileNil,
.dataFileReadFailed,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseContentType: String? {
switch self {
case let .unacceptableContentType(_, responseType):
return responseType
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseCode: Int? {
switch self {
case let .unacceptableStatusCode(code):
return code
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.customValidationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customValidationFailed(error):
return error
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.unacceptableStatusCode:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case let .stringSerializationFailed(encoding):
return encoding
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed(_),
.jsonSerializationFailed(_),
.decodingFailed(_),
.customSerializationFailed(_),
.invalidEmptyResponse:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .jsonSerializationFailed(error),
let .decodingFailed(error),
let .customSerializationFailed(error):
return error
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed,
.stringSerializationFailed,
.invalidEmptyResponse:
return nil
}
}
}
extension AFError.ServerTrustFailureReason {
var output: AFError.ServerTrustFailureReason.Output? {
switch self {
case let .defaultEvaluationFailed(output),
let .hostValidationFailed(output),
let .revocationCheckFailed(output, _):
return output
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.trustEvaluationFailed,
.certificatePinningFailed,
.publicKeyPinningFailed,
.customEvaluationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customEvaluationFailed(error):
return error
case let .trustEvaluationFailed(error):
return error
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.defaultEvaluationFailed,
.hostValidationFailed,
.revocationCheckFailed,
.certificatePinningFailed,
.publicKeyPinningFailed:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .explicitlyCancelled:
return "Request explicitly cancelled."
case let .invalidURL(url):
return "URL is not valid: \(url)"
case let .parameterEncodingFailed(reason):
return reason.localizedDescription
case let .parameterEncoderFailed(reason):
return reason.localizedDescription
case let .multipartEncodingFailed(reason):
return reason.localizedDescription
case let .requestAdaptationFailed(error):
return "Request adaption failed with error: \(error.localizedDescription)"
case let .responseValidationFailed(reason):
return reason.localizedDescription
case let .responseSerializationFailed(reason):
return reason.localizedDescription
case let .requestRetryFailed(retryError, originalError):
return """
Request retry failed with retry error: \(retryError.localizedDescription), \
original error: \(originalError.localizedDescription)
"""
case .sessionDeinitialized:
return """
Session was invalidated without error, so it was likely deinitialized unexpectedly. \
Be sure to retain a reference to your Session for the duration of your requests.
"""
case let .sessionInvalidated(error):
return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
case let .serverTrustEvaluationFailed(reason):
return "Server trust evaluation failed due to reason: \(reason.localizedDescription)"
case let .urlRequestValidationFailed(reason):
return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
case let .createUploadableFailed(error):
return "Uploadable creation failed with error: \(error.localizedDescription)"
case let .createURLRequestFailed(error):
return "URLRequest creation failed with error: \(error.localizedDescription)"
case let .downloadedFileMoveFailed(error, source, destination):
return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
case let .sessionTaskFailed(error):
return "URLSessionTask failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case let .jsonEncodingFailed(error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case let .customEncodingFailed(error):
return "Custom parameter encoder failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncoderFailureReason {
var localizedDescription: String {
switch self {
case let .missingRequiredComponent(component):
return "Encoding failed due to a missing request component: \(component)"
case let .encoderFailed(error):
return "The underlying encoder failed with the error: \(error)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case let .bodyPartURLInvalid(url):
return "The URL provided is not a file URL: \(url)"
case let .bodyPartFilenameInvalid(url):
return "The URL provided does not have a valid filename: \(url)"
case let .bodyPartFileNotReachable(url):
return "The URL provided is not reachable: \(url)"
case let .bodyPartFileNotReachableWithError(url, error):
return """
The system returned an error while checking the provided URL for reachability.
URL: \(url)
Error: \(error)
"""
case let .bodyPartFileIsDirectory(url):
return "The URL provided is a directory: \(url)"
case let .bodyPartFileSizeNotAvailable(url):
return "Could not fetch the file size from the provided URL: \(url)"
case let .bodyPartFileSizeQueryFailedWithError(url, error):
return """
The system returned an error while attempting to fetch the file size from the provided URL.
URL: \(url)
Error: \(error)
"""
case let .bodyPartInputStreamCreationFailed(url):
return "Failed to create an InputStream for the provided URL: \(url)"
case let .outputStreamCreationFailed(url):
return "Failed to create an OutputStream for URL: \(url)"
case let .outputStreamFileAlreadyExists(url):
return "A file already exists at the provided URL: \(url)"
case let .outputStreamURLInvalid(url):
return "The provided OutputStream URL is invalid: \(url)"
case let .outputStreamWriteFailed(error):
return "OutputStream write failed with error: \(error)"
case let .inputStreamReadFailed(error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case let .inputFileReadFailed(url):
return "Response could not be serialized, input file could not be read: \(url)."
case let .stringSerializationFailed(encoding):
return "String could not be serialized with encoding: \(encoding)."
case let .jsonSerializationFailed(error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case let .invalidEmptyResponse(type):
return """
Empty response could not be serialized to type: \(type). \
Use Empty as the expected type for such responses.
"""
case let .decodingFailed(error):
return "Response could not be decoded because of error:\n\(error.localizedDescription)"
case let .customSerializationFailed(error):
return "Custom response serializer failed with error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case let .dataFileReadFailed(url):
return "Response could not be validated, data file could not be read: \(url)."
case let .missingContentType(types):
return """
Response Content-Type was missing and acceptable content types \
(\(types.joined(separator: ","))) do not match "*/*".
"""
case let .unacceptableContentType(acceptableTypes, responseType):
return """
Response Content-Type "\(responseType)" does not match any acceptable types: \
\(acceptableTypes.joined(separator: ",")).
"""
case let .unacceptableStatusCode(code):
return "Response status code was unacceptable: \(code)."
case let .customValidationFailed(error):
return "Custom response validation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ServerTrustFailureReason {
var localizedDescription: String {
switch self {
case let .noRequiredEvaluator(host):
return "A ServerTrustEvaluating value is required for host \(host) but none was found."
case .noCertificatesFound:
return "No certificates were found or provided for evaluation."
case .noPublicKeysFound:
return "No public keys were found or provided for evaluation."
case .policyApplicationFailed:
return "Attempting to set a SecPolicy failed."
case .settingAnchorCertificatesFailed:
return "Attempting to set the provided certificates as anchor certificates failed."
case .revocationPolicyCreationFailed:
return "Attempting to create a revocation policy failed."
case let .trustEvaluationFailed(error):
return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")"
case let .defaultEvaluationFailed(output):
return "Default evaluation failed for host \(output.host)."
case let .hostValidationFailed(output):
return "Host validation failed for host \(output.host)."
case let .revocationCheckFailed(output, _):
return "Revocation check failed for host \(output.host)."
case let .certificatePinningFailed(host, _, _, _):
return "Certificate pinning failed for host \(host)."
case let .publicKeyPinningFailed(host, _, _, _):
return "Public key pinning failed for host \(host)."
case let .customEvaluationFailed(error):
return "Custom trust evaluation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.URLRequestValidationFailureReason {
var localizedDescription: String {
switch self {
case let .bodyDataInGETRequest(data):
return """
Invalid URLRequest: Requests with GET method cannot have body data:
\(String(decoding: data, as: UTF8.self))
"""
}
}
}
| mit | 98691a6d7c1e2220b237b0a49c20070b | 42.521429 | 144 | 0.664095 | 5.509872 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Tools/Network/NetworkTool.swift | 2 | 829 | //
// NetworkTool.swift
// XMTV
//
// Created by Mac on 2017/1/4.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTool {
class func request(type: MethodType, urlString: String, paramters: [String: Any]? = nil, finishedCallback: @escaping (_ result: Any) -> ()) {
// 获取类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
// 发送网络请求
Alamofire.request(urlString, method: method, parameters: paramters).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error)
return
}
// 回调
finishedCallback(result as AnyObject)
}
}
}
| apache-2.0 | fde42043ae53595a191be7b29463b860 | 24.870968 | 145 | 0.594763 | 4.221053 | false | false | false | false |
Ceroce/SwiftRay | SwiftRay/SwiftRay/Camera.swift | 1 | 1924 | //
// Camera.swift
// SwiftRay
//
// Created by Renaud Pradenc on 23/11/2016.
// Copyright © 2016 Céroce. All rights reserved.
//
import Darwin // Maths
struct Camera {
let lookFrom: Vec3
let lowerLeft: Vec3
let horizontal: Vec3
let vertical: Vec3
let u: Vec3
let v: Vec3
let aperture: Float
let startTime: Float
let endTime: Float
// yFov in degres. aspectRatio = width/height
init(lookFrom: Vec3, lookAt: Vec3, up: Vec3, yFov: Float, aspectRatio: Float, aperture: Float, focusDistance: Float, startTime: Float, endTime: Float) {
self.lookFrom = lookFrom
self.aperture = aperture
let theta = rad(yFov)
let halfHeight = tanf(theta/2)
let halfWidth = aspectRatio * halfHeight
let w = normalize(lookFrom - lookAt) // Direction of the camera
u = normalize(cross(up, w))
v = cross(w, u)
lowerLeft = lookFrom - halfWidth*focusDistance*u - halfHeight*focusDistance*v - focusDistance*w
horizontal = 2 * halfWidth * focusDistance * u
vertical = 2 * halfHeight * focusDistance * v
self.startTime = startTime
self.endTime = endTime
}
func ray(s: Float, t: Float) -> Ray {
// Depth of field is simulated by offsetting the origin of the ray randomly
let defocus = (aperture/2.0) * randPointOnUnitDisc()
let offset: Vec3 = u * defocus.x + v * defocus.y
let time = self.startTime + random01()*(endTime-startTime)
return Ray(origin: lookFrom+offset, direction: lowerLeft + s*horizontal + t*vertical - lookFrom - offset, time: time)
}
// Uses a rejection method
func randPointOnUnitDisc() -> Vec3 {
var p: Vec3
repeat {
p = 2 * Vec3(random01(), random01(), 0) - Vec3(1, 1, 0)
} while dot(p, p) >= 1.0
return p
}
}
| mit | a609fa4718d06627892e3c927b39f3d0 | 30 | 156 | 0.600937 | 3.783465 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/MapTab/StopMap.swift | 1 | 2724 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import GoogleMaps
import SwiftUI
import UIKit
/// This view that the user sees when tapping on the map tab.
struct StopMap: View {
@EnvironmentObject var modelData: ModelData
@State var selectedMarker: GMSMarker?
@State var markers: [GMSMarker] = []
@State private var zoom: Float = 15
@State var currentPage: Int = 0
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
MapViewControllerBridge(
markers: $markers,
selectedMarker: $selectedMarker,
zoom: $zoom
)
.frame(maxWidth: .infinity, alignment: .leading)
.onAppear {
markers = StopMap.buildMarkers(modelData: modelData)
}
PageViewController(
pages: modelData.stops.map({
StopPage(stop: $0).environmentObject(modelData)
}),
currentPage: $currentPage
)
.frame(height: 120)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 0))
}
.navigationTitle(Text("Your itinerary"))
.onChange(of: selectedMarker) { newSelectedMarker in
if let stopId = newSelectedMarker?.userData as? String {
if let stopIndex = modelData.stops.firstIndex(where: { $0.stopInfo.stopId == stopId }) {
currentPage = stopIndex
}
}
}
}
}
func mapViewControllerBridge(
_ bridge: MapViewControllerBridge,
didTapOnMarker marker: GMSMarker
) {
if let stopId = marker.userData as? String,
let stopIndex = modelData.stops.firstIndex(where: { $0.stopInfo.stopId == stopId })
{
currentPage = stopIndex
}
}
private static func buildMarkers(modelData: ModelData) -> [GMSMarker] {
return modelData.stops.map({ CustomMarker.makeMarker(stop: $0) })
}
init() {
// Ensure Google Maps SDK is initialized.
let _ = LMFSDriverSampleApp.googleMapsInited
}
}
struct StopMap_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
StopMap()
.environmentObject(ModelData(filename: "test_manifest"))
}
}
| apache-2.0 | a31ca5d39835dec250e08d56e277faf6 | 30.310345 | 98 | 0.663363 | 4.344498 | false | false | false | false |
RxSwiftCommunity/Action | Sources/Action/Action+Internal.swift | 1 | 1188 | import Foundation
import RxSwift
internal struct AssociatedKeys {
static var Action = "rx_action"
static var DisposeBag = "rx_disposeBag"
}
// Note: Actions performed in this extension are _not_ locked
// So be careful!
internal extension NSObject {
// A dispose bag to be used exclusively for the instance's rx.action.
var actionDisposeBag: DisposeBag {
var disposeBag: DisposeBag
if let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag {
disposeBag = lookup
} else {
disposeBag = DisposeBag()
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return disposeBag
}
// Resets the actionDisposeBag to nil, disposeing of any subscriptions within it.
func resetActionDisposeBag() {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
// Uses objc_sync on self to perform a locked operation.
func doLocked(_ closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
}
| mit | b50dc3afbfecc2eeca4429c326996af8 | 31.108108 | 118 | 0.678451 | 4.695652 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Home/TopSitesPanel.swift | 2 | 10666 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
private let ThumbnailIdentifier = "Thumbnail"
private let RowIdentifier = "Row"
private let SeparatorKind = "separator"
private let SeparatorIdentifier = "separator"
private let ThumbnailSectionPadding: CGFloat = 8
private let SeparatorColor = UIColor(rgb: 0xcccccc)
private let DefaultImage = "defaultFavicon"
class TopSitesPanel: UIViewController, UICollectionViewDelegate, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var collection: TopSitesCollectionView!
private var dataSource: TopSitesDataSource!
private let layout = TopSitesLayout()
var profile: Profile! {
didSet {
let options = QueryOptions(filter: nil, filterType: .None, sort: .Frecency)
profile.history.get(options, complete: { (data) -> Void in
self.dataSource.data = data
self.dataSource.profile = self.profile
self.collection.reloadData()
})
}
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
layout.setupForOrientation(toInterfaceOrientation)
collection.setNeedsLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = TopSitesDataSource(profile: profile, data: Cursor(status: .Failure, msg: "Nothing loaded yet"))
layout.registerClass(TopSitesSeparator.self, forDecorationViewOfKind: SeparatorKind)
collection = TopSitesCollectionView(frame: self.view.frame, collectionViewLayout: layout)
collection.backgroundColor = UIColor.whiteColor()
collection.delegate = self
collection.dataSource = dataSource
collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier)
collection.registerClass(TwoLineCollectionViewCell.self, forCellWithReuseIdentifier: RowIdentifier)
collection.keyboardDismissMode = .OnDrag
view.addSubview(collection)
collection.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let site = dataSource?.data[indexPath.item] as? Site {
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: site.url)!)
}
}
}
private class TopSitesCollectionView: UICollectionView {
private override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// Hide the keyboard if this view is touched.
window?.rootViewController?.view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
}
private class TopSitesLayout: UICollectionViewLayout {
private let AspectRatio: CGFloat = 1.25 // Ratio of width:height.
private var thumbnailRows = 3
private var thumbnailCols = 2
private var thumbnailCount: Int { return thumbnailRows * thumbnailCols }
private var width: CGFloat { return self.collectionView?.frame.width ?? 0 }
private var thumbnailWidth: CGFloat { return width / CGFloat(thumbnailCols) - (ThumbnailSectionPadding * 2) / CGFloat(thumbnailCols) }
private var thumbnailHeight: CGFloat { return thumbnailWidth / AspectRatio }
private var count: Int {
if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource {
return dataSource.data.count
}
return 0
}
private var topSectionHeight: CGFloat {
let maxRows = ceil(Float(count) / Float(thumbnailCols))
let rows = min(Int(maxRows), thumbnailRows)
return thumbnailHeight * CGFloat(rows) + ThumbnailSectionPadding * 2
}
override init() {
super.init()
setupForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupForOrientation(orientation: UIInterfaceOrientation) {
if orientation.isLandscape {
thumbnailRows = 2
thumbnailCols = 3
} else {
thumbnailRows = 3
thumbnailCols = 2
}
}
private func getIndexAtPosition(#y: CGFloat) -> Int {
if y < topSectionHeight {
let row = Int(y / thumbnailHeight)
return min(count - 1, max(0, row * thumbnailCols))
}
return min(count - 1, max(0, Int((y - topSectionHeight) / AppConstants.DefaultRowHeight + CGFloat(thumbnailCount))))
}
override func collectionViewContentSize() -> CGSize {
if count <= thumbnailCount {
let row = floor(Double(count / thumbnailCols))
return CGSize(width: width, height: topSectionHeight)
}
let bottomSectionHeight = CGFloat(count - thumbnailCount) * AppConstants.DefaultRowHeight
return CGSize(width: width, height: topSectionHeight + bottomSectionHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let start = getIndexAtPosition(y: rect.origin.y)
let end = getIndexAtPosition(y: rect.origin.y + rect.height)
var attrs = [UICollectionViewLayoutAttributes]()
if start == -1 || end == -1 {
return attrs
}
for i in start...end {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let attr = layoutAttributesForItemAtIndexPath(indexPath)
attrs.append(attr)
if i >= thumbnailCount - 1 {
let decoration = layoutAttributesForDecorationViewOfKind(SeparatorKind, atIndexPath: indexPath)
attrs.append(decoration)
}
}
return attrs
}
// Set the frames for the row separators.
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let decoration = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, withIndexPath: indexPath)
let rowIndex = indexPath.item - thumbnailCount + 1
let rowYOffset = CGFloat(rowIndex) * AppConstants.DefaultRowHeight
let y = topSectionHeight + rowYOffset
decoration.frame = CGRectMake(0, y, width, 0.5)
return decoration
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let i = indexPath.item
if i < thumbnailCount {
// Set the top thumbnail frames.
let row = floor(Double(i / thumbnailCols))
let col = i % thumbnailCols
let x = CGFloat(thumbnailWidth * CGFloat(col)) + ThumbnailSectionPadding
let y = CGFloat(row) * thumbnailHeight + ThumbnailSectionPadding
attr.frame = CGRectMake(x, y, thumbnailWidth, thumbnailHeight)
} else {
// Set the bottom row frames.
let rowYOffset = CGFloat(i - thumbnailCount) * AppConstants.DefaultRowHeight
let y = CGFloat(topSectionHeight + rowYOffset)
attr.frame = CGRectMake(0, y, width, AppConstants.DefaultRowHeight)
}
return attr
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
class TopSitesDataSource: NSObject, UICollectionViewDataSource {
var data: Cursor
var profile: Profile
init(profile: Profile, data: Cursor) {
self.data = data
self.profile = profile
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
private func setDefaultThumbnailBackground(cell: ThumbnailCell) {
cell.imageView.image = UIImage(named: "defaultFavicon")!
cell.imageView.contentMode = UIViewContentMode.Center
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let site = data[indexPath.item] as! Site
// Cells for the top site thumbnails.
if indexPath.item < 6 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell
cell.textLabel.text = site.title.isEmpty ? site.url : site.title
if let thumbs = profile.thumbnails as? SDWebThumbnails {
cell.imageView.moz_getImageFromCache(site.url, cache: thumbs.cache, completed: { (img, err, type, url) -> Void in
if img != nil {
return
}
self.setDefaultThumbnailBackground(cell)
})
} else {
setDefaultThumbnailBackground(cell)
}
cell.isAccessibilityElement = true
cell.accessibilityLabel = cell.textLabel.text
return cell
}
// Cells for the remainder of the top sites list.
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RowIdentifier, forIndexPath: indexPath) as! TwoLineCollectionViewCell
cell.textLabel.text = site.title.isEmpty ? site.url : site.title
cell.detailTextLabel.text = site.url
cell.isAccessibilityElement = true
cell.accessibilityLabel = "\(cell.textLabel.text!), \(cell.detailTextLabel.text!)"
if let icon = site.icon {
cell.imageView.sd_setImageWithURL(NSURL(string: icon.url)!)
} else {
cell.imageView.image = UIImage(named: DefaultImage)
}
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: SeparatorIdentifier, forIndexPath: indexPath) as! UICollectionReusableView
}
}
private class TopSitesSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = SeparatorColor
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | e9148ecc393ca8d9740ae1fbf8e6de22 | 39.709924 | 171 | 0.675417 | 5.395043 | false | false | false | false |
cottonBuddha/Qsic | Qsic/config.swift | 1 | 3287 | //
// config.swift
// Qsic
//
// Created by cottonBuddha on 2017/8/27.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
import Darwin.ncurses
public let KEY_A_LOW: Int32 = 97
public let KEY_B_LOW: Int32 = 98
public let KEY_C_LOW: Int32 = 99
public let KEY_D_LOW: Int32 = 100
public let KEY_E_LOW: Int32 = 101
public let KEY_F_LOW: Int32 = 102
public let KEY_G_LOW: Int32 = 103
public let KEY_H_LOW: Int32 = 104
public let KEY_I_LOW: Int32 = 105
public let KEY_J_LOW: Int32 = 106
public let KEY_K_LOW: Int32 = 107
public let KEY_L_LOW: Int32 = 108
public let KEY_M_LOW: Int32 = 109
public let KEY_N_LOW: Int32 = 110
public let KEY_O_LOW: Int32 = 111
public let KEY_P_LOW: Int32 = 112
public let KEY_Q_LOW: Int32 = 113
public let KEY_R_LOW: Int32 = 114
public let KEY_S_LOW: Int32 = 115
public let KEY_T_LOW: Int32 = 116
public let KEY_U_LOW: Int32 = 117
public let KEY_V_LOW: Int32 = 118
public let KEY_W_LOW: Int32 = 119
public let KEY_X_LOW: Int32 = 120
public let KEY_Y_LOW: Int32 = 121
public let KEY_Z_LOW: Int32 = 122
public let KEY_L_ANGLE_EN: Int32 = 44
public let KEY_R_ANGLE_EN: Int32 = 46
public let KEY_L_ANGLE_ZH: Int32 = 140
public let KEY_R_ANGLE_ZH: Int32 = 130
public let EN_L_C_BRACE: Int32 = 91
public let EN_R_C_BRACE: Int32 = 93
public let ZH_L_C_BRACE: Int32 = 144
public let ZH_R_C_BRACE: Int32 = 145
public let KEY_SLASH_EN: Int32 = 47
public let KEY_SLASH_ZH: Int32 = 129
public let KEY_NUMBER_ONE: Int32 = 49
public let KEY_NUMBER_TWO: Int32 = 50
public let KEY_NUMBER_THREE: Int32 = 51
public let KEY_ENTER: Int32 = 10
public let KEY_SPACE: Int32 = 32
public let KEY_COMMA: Int32 = 39
public let KEY_DOT: Int32 = 46
/**
向上移动
*/public let CMD_UP = KEY_UP
/**
向下移动
*/public let CMD_DOWN = KEY_DOWN
/**
上一页
*/public let CMD_LEFT = KEY_LEFT
/**
下一页
*/public let CMD_RIGHT = KEY_RIGHT
/**
选中
*/public let CMD_ENTER = KEY_ENTER
/**
退出
*/public let CMD_QUIT = KEY_Q_LOW
/**
退出且退出登录
*/public let CMD_QUIT_LOGOUT = KEY_W_LOW
/**
返回上一级菜单
*/public let CMD_BACK = (KEY_SLASH_ZH,KEY_SLASH_EN)
/**
播放/暂停
*/public let CMD_PLAY_PAUSE = KEY_SPACE
/**
下一首
*/public let CMD_PLAY_NEXT = (KEY_R_ANGLE_EN,KEY_R_ANGLE_ZH)
/**
上一首
*/public let CMD_PLAY_PREVIOUS = (KEY_L_ANGLE_EN,KEY_L_ANGLE_ZH)
/**
音量+
*/public let CMD_VOLUME_ADD = (EN_R_C_BRACE,ZH_R_C_BRACE)
/**
音量-
*/public let CMD_VOLUME_MINUS = (EN_L_C_BRACE,ZH_L_C_BRACE)
/**
添加到收藏
*/public let CMD_ADD_LIKE = KEY_A_LOW
/**
搜索
*/public let CMD_SEARCH = KEY_S_LOW
/**
登录
*/public let CMD_LOGIN = KEY_D_LOW
/**
当前播放列表
*/public let CMD_PLAY_LIST = KEY_F_LOW
/**
打开GitHub
*/public let CMD_GITHUB = KEY_G_LOW
/**
隐藏╭( ̄3 ̄)╯播放指示
*/public let CMD_HIDE_DANCER = KEY_H_LOW
/**
单曲循环
*/public let CMD_PLAYMODE_SINGLE = KEY_NUMBER_ONE
/**
顺序播放
*/public let CMD_PLAYMODE_ORDER = KEY_NUMBER_TWO
/**
随机播放
*/public let CMD_PLAYMODE_SHUFFLE = KEY_NUMBER_THREE
/**
相关设置的key
*/
//public let UD_POP_HINT = "UD_POP_HINT"
//public let UD_HIDE_DANCER = "UD_HIDE_DANCER"
public let UD_USER_NICKNAME = "UD_USER_NICKNAME"
public let UD_USER_ID = "UD_USER_ID"
| mit | 4c25a0807feb9f1c47b1bc51ef8ef1c1 | 18.757962 | 65 | 0.670213 | 2.495575 | false | false | false | false |
carambalabs/Paparajote | Example/Tests/Providers/GitLabProviderSpec.swift | 1 | 3607 | import Foundation
import Quick
import Nimble
import NSURL_QueryDictionary
@testable import Paparajote
class GitLabProviderSpec: QuickSpec {
override func spec() {
var subject: GitLabProvider!
var clientId: String!
var clientSecret: String!
var redirectUri: String!
var state: String!
var url: URL!
beforeEach {
clientId = "client_id"
clientSecret = "client_secret"
redirectUri = "redirect://works"
state = "asdg135125"
url = URL(string: "https://gitlab.com")!
subject = GitLabProvider(url: url, clientId: clientId, clientSecret: clientSecret, redirectUri: redirectUri, state: state)
}
describe("-authorization") {
it("should return the correct url") {
let expected = "https://gitlab.com/oauth/authorize?client_id=client_id&redirect_uri=redirect://works&response_type=code&state=asdg135125"
expect(subject.authorization().absoluteString) == expected
}
}
describe("-authentication") {
context("when there's no code in the url") {
it("should return nil") {
let url = URL(string: "\(redirectUri!)?state=abc")!
expect(subject.authentication(url)).to(beNil())
}
}
context("when there's no state in the url") {
it("should return nil") {
let url = URL(string: "\(redirectUri!)?code=abc")!
expect(subject.authentication(url)).to(beNil())
}
}
context("when it has code and state") {
var request: URLRequest!
beforeEach {
let url = URL(string: "\(redirectUri!)?code=abc&state=\(state!)")!
request = subject.authentication(url)
}
it("should return a request with the correct URL") {
let expected = "https://gitlab.com/oauth/token?client_id=client_id&client_secret=client_secret&code=abc&redirect_uri=redirect://works&grant_type=authorization_code"
expect(request.url?.absoluteString) == expected
}
it("should return a request with the a JSON Accept header") {
expect(request.value(forHTTPHeaderField: "Accept")) == "application/json"
}
it("should return a request with the POST method") {
expect(request.httpMethod) == "POST"
}
}
}
describe("-sessionAdapter") {
context("when the data has not the correct format") {
it("should return nil") {
let dictionary: [String: Any] = [:]
let data = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
expect(subject.sessionAdapter(data, URLResponse())).to(beNil())
}
}
context("when the data has the correct format") {
it("should return the session") {
let dictionary = ["access_token": "tooooken"]
let data = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
expect(subject.sessionAdapter(data, URLResponse())?.accessToken) == "tooooken"
}
}
}
}
}
| mit | 15d377ea37f63da318cc8a3b97130dba | 39.077778 | 184 | 0.515664 | 5.145506 | false | false | false | false |
craftsmanship-toledo/katangapp-ios | Katanga/Cells/NearBusStopCell.swift | 1 | 3714 | /**
* Copyright 2016-today Software Craftmanship Toledo
*
* 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.
*/
/*!
@author Víctor Galán
*/
import RxCocoa
import RxSwift
import UIKit
class NearBusStopCell: UITableViewCell {
public var busStopName: String {
set {
busStopNameLabel.text = newValue
}
get {
return busStopNameLabel.text ?? ""
}
}
public var distance: String {
set {
distanceLabel.text = newValue
}
get {
return distanceLabel.text ?? ""
}
}
public var bustStopTimes: [BusStopTime] {
set {
busStopsTimeDataSource.value.append(contentsOf: newValue)
}
get {
return busStopsTimeDataSource.value
}
}
public var routeItemClick: ((String) -> Void)?
public var busStopClick: (() -> Void)?
@IBOutlet private weak var busStopNameLabel: UILabel!
@IBOutlet weak var busStopIcon: UIImageView!
@IBOutlet private weak var containerView: UIView! {
didSet {
containerView.layer.cornerRadius = Constants.cornerRadius
containerView.layer.masksToBounds = true
}
}
@IBOutlet private weak var distanceLabel: UILabel!
@IBOutlet private weak var heightConstraint: NSLayoutConstraint!
@IBOutlet private weak var headerHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var tableView: UITableView! {
didSet {
tableView.register(BusComingCell.self)
tableView.rowHeight = Constants.rowHeight
}
}
private var disposeBag = DisposeBag()
private var busStopsTimeDataSource = Variable<[BusStopTime]>([])
private struct Constants {
static let cornerRadius: CGFloat = 10
static let rowHeight: CGFloat = 40
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
tableView.customizeTableView(withColor: .clear)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(busStopIconClick))
busStopIcon.addGestureRecognizer(gestureRecognizer)
busStopIcon.isUserInteractionEnabled = true
setupRx()
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
busStopsTimeDataSource.value = []
setupRx()
}
private func setupRx() {
busStopsTimeDataSource
.asObservable()
.bindTo(tableView.rx.items(cellType: BusComingCell.self)) { [weak self] _, element, cell in
cell.routeId = element.id
cell.time = element.minutes
cell.routeItemClick = self?.routeItemClick
}.addDisposableTo(disposeBag)
busStopsTimeDataSource
.asObservable()
.map { CGFloat($0.count) }
.filter { $0 > 0 }
.map { $0 * Constants.rowHeight + self.headerHeightConstraint.constant }
.bindTo(heightConstraint.rx.constant)
.addDisposableTo(disposeBag)
}
@objc private func busStopIconClick() {
busStopClick?()
}
}
| apache-2.0 | 4737f3909f70d1f03cac1656555b1ef3 | 26.094891 | 105 | 0.635776 | 4.995962 | false | false | false | false |
radazzouz/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 62031 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import Deferred
import XCTest
let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000
let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000)
// Start everything three months ago.
let baseInstantInMillis = Date.now() - threeMonthsInMillis
let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros
func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp {
return timestamp + UInt64(by)
}
func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp {
return timestamp + UInt64(by)
}
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class BaseHistoricalBrowserTable {
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
assert(false, "Should never be called.")
}
func exists(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
let err = db.executeChange(sql, withArgs: args)
return err == nil
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserTable that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserTableV6: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func CreateDomainsTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func CreateQueueTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV6: Table {
func create(_ db: SQLiteDBConnection) -> Bool {
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV7: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV7: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV8: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV8: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV10: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
}
}
extension BrowserTableV10: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON visits (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> { history.getSitesByFrecencyWithHistoryLimit(3)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, SectionCreator)] = [
(6, BrowserTableV6()),
(7, BrowserTableV7()),
(8, BrowserTableV8()),
(10, BrowserTableV10()),
]
let destination = BrowserTable()
for (version, table) in sources {
let db = BrowserDB(filename: "browser-v\(version).db", files: files)
XCTAssertTrue(
db.runWithConnection { (conn, err) in
XCTAssertTrue(table.create(conn), "Creating browser table version \(version)")
// And we can upgrade to the current version.
XCTAssertTrue(destination.updateTable(conn, from: table.version), "Upgrading browser table from version \(version)")
}.value.isSuccess
)
db.forceClose()
}
}
func testUpgradesWithData() {
let db = BrowserDB(filename: "browser-v6-data.db", files: files)
XCTAssertTrue(db.createOrUpdate(BrowserTableV6()) == .success, "Creating browser table version 6")
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
XCTAssertTrue(db.createOrUpdate(BrowserTable()) == .success, "Upgrading browser table from version 6")
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(10).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
var err: NSError? = nil
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
db.withWritableConnection(&err, callback: { (connection, err) -> Int in
let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"?, ?, ?, ?, ?, ?, ?"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
err = connection.executeChange(insert, withArgs: args)
return 0
})
// Now insert it again. This should update the domain
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link))
// DomainID isn't normally exposed, so we manually query to get it
let results = db.withReadableConnection(&err, callback: { (connection, err) -> Cursor<Int> in
let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: IntFactory, withArgs: args)
})
XCTAssertNotEqual(results[0]!, -1, "Domain id was updated")
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).bind({ (sites: Maybe<Cursor<Site>>) -> Success in
XCTAssert(sites.successValue!.count == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).upon({ (sites: Maybe<Cursor<Site>>) in
XCTAssert(sites.successValue!.count == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10, whereURLContains: filter)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date(), type: .icon)
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5)/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0)/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.updateTopSitesCacheIfInvalidated().value
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().value
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = history.computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
// MARK - Private Test Helper Methods
enum VisitOrigin {
case local
case remote
}
private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)")
site.guid = "abc\(i)def"
let baseMillis: UInt64 = baseInstantInMillis - 20000
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).value
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime)
}
}
}
func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.link)
switch from {
case .local:
history.addLocalVisit(visit).value
case .remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).value
}
}
| mpl-2.0 | 503692a731c35e45ab953a2016a7de10 | 42.838163 | 231 | 0.589431 | 4.851858 | false | false | false | false |
PDF417/pdf417-ios | Samples/pdf417-sample-Swift/pdf417-sample-Swift/CustomOverlay.swift | 1 | 2459 | //
// CustomOverlay.swift
// pdf417-sample-Swift
//
// Created by Dino Gustin on 06/03/2018.
// Copyright © 2018 Dino. All rights reserved.
//
import Pdf417Mobi
class CustomOverlay: MBBCustomOverlayViewController, MBBScanningRecognizerRunnerViewControllerDelegate {
static func initFromStoryboardWith() -> CustomOverlay {
let customOverlay: CustomOverlay = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CustomOverlay") as! CustomOverlay
return customOverlay
}
override func viewDidLoad() {
super.viewDidLoad()
super.scanningRecognizerRunnerViewControllerDelegate = self;
}
func recognizerRunnerViewControllerDidFinishScanning(_ recognizerRunnerViewController: UIViewController & MBBRecognizerRunnerViewController, state: MBBRecognizerResultState) {
/** This is done on background thread */
if state == .valid {
recognizerRunnerViewController.pauseScanning();
DispatchQueue.main.async {
var message: String = ""
var title: String = ""
for recognizer in self.recognizerCollection.recognizerList {
if ( recognizer.baseResult?.resultState == .valid ) {
let barcodeRecognizer = recognizer as? MBBBarcodeRecognizer
title = "QR Code"
message = (barcodeRecognizer?.result.stringData!)!
}
}
let alertController: UIAlertController = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
let okAction: UIAlertAction = UIAlertAction.init(title: "OK", style: UIAlertAction.Style.default,
handler: { (action) -> Void in
self.dismiss(animated: true, completion: nil)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
@IBAction func didTapClose(_ sender: Any) {
self.recognizerRunnerViewController?.overlayViewControllerWillCloseCamera(self);
self.dismiss(animated: true, completion: nil);
}
}
| apache-2.0 | a419ae4aae159eb4d4d7b69608ffad7f | 41.37931 | 179 | 0.594386 | 5.769953 | false | false | false | false |
isgustavo/AnimatedMoviesMakeMeCry | iOS/Animated Movies Make Me Cry/Pods/Firebase/Samples/database/DatabaseExampleSwift/PostDataSource.swift | 9 | 1775 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseUI
class PostDataSource: FirebaseTableViewDataSource {
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
refForIndex(UInt(indexPath.row)).removeValue()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.count() != 0 {
tableView.separatorStyle = .SingleLine
tableView.backgroundView = nil
}
return Int(self.count())
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let noDataLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No posts yet - why not add one?"
noDataLabel.textColor = UIColor.blackColor()
noDataLabel.textAlignment = .Center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .None
return 1
}
} | apache-2.0 | 61bf9f66cc4e275ca0b48d0ec0e27236 | 36 | 155 | 0.734085 | 4.539642 | false | false | false | false |
jemartti/Hymnal | Hymnal/ScheduleViewController.swift | 1 | 11474 | //
// ScheduleViewController.swift
// Hymnal
//
// Created by Jacob Marttinen on 5/6/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
import CoreData
// MARK: - ScheduleViewController: UITableViewController
class ScheduleViewController: UITableViewController {
// MARK: Properties
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var indicator: UIActivityIndicatorView!
var schedule: [ScheduleLineEntity]!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialiseUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if it's time to update the schedule
var forceFetch = false
if !UserDefaults.standard.bool(forKey: "hasFetchedSchedule") {
forceFetch = true
} else {
let lastScheduleFetch = UserDefaults.standard.double(forKey: "lastScheduleFetch")
if (lastScheduleFetch + 60*60*24 < NSDate().timeIntervalSince1970) {
forceFetch = true
}
}
// Check for existing Schedule in Model
let scheduleFR = NSFetchRequest<NSManagedObject>(entityName: "ScheduleLineEntity")
scheduleFR.sortDescriptors = [NSSortDescriptor(key: "sortKey", ascending: true)]
do {
let scheduleLineEntities = try appDelegate.stack.context.fetch(scheduleFR) as! [ScheduleLineEntity]
if scheduleLineEntities.count <= 0 || forceFetch {
schedule = [ScheduleLineEntity]()
fetchSchedule()
} else {
schedule = scheduleLineEntities
tableView.reloadData()
}
} catch _ as NSError {
alertUserOfFailure(message: "Data load failed.")
}
}
// UI+UX Functionality
private func initialiseUI() {
view.backgroundColor = .white
indicator = createIndicator()
// Set up the Navigation bar
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.stop,
target: self,
action: #selector(ScheduleViewController.returnToRoot)
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.refresh,
target: self,
action: #selector(ScheduleViewController.fetchSchedule)
)
navigationItem.title = "Schedule"
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = Constants.UI.Armadillo
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: Constants.UI.Armadillo
]
}
private func createIndicator() -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView(
style: UIActivityIndicatorView.Style.gray
)
indicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0);
indicator.center = view.center
view.addSubview(indicator)
indicator.bringSubviewToFront(view)
return indicator
}
private func alertUserOfFailure( message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(
title: "Action Failed",
message: message,
preferredStyle: UIAlertController.Style.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertAction.Style.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
@objc func returnToRoot() {
dismiss(animated: true, completion: nil)
}
// MARK: Data Management Functions
@objc func fetchSchedule() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
indicator.startAnimating()
MarttinenClient.sharedInstance().getSchedule() { (scheduleRaw, error) in
if error != nil {
self.alertUserOfFailure(message: "Data download failed.")
} else {
self.appDelegate.stack.performBackgroundBatchOperation { (workerContext) in
// Cleanup any existing data
let DelAllScheduleLineEntities = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "ScheduleLineEntity")
)
do {
try workerContext.execute(DelAllScheduleLineEntities)
}
catch {
self.alertUserOfFailure(message: "Data load failed.")
}
// Clear local properties
self.schedule = [ScheduleLineEntity]()
// We have to clear data in active contexts after performing batch operations
self.appDelegate.stack.reset()
DispatchQueue.main.async {
self.parseAndSaveSchedule(scheduleRaw)
self.tableView.reloadData()
UserDefaults.standard.set(true, forKey: "hasFetchedSchedule")
UserDefaults.standard.set(NSDate().timeIntervalSince1970, forKey: "lastScheduleFetch")
UserDefaults.standard.synchronize()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
}
}
}
private func parseAndSaveSchedule(_ scheduleRaw: [ScheduleLine]) {
for i in 0 ..< scheduleRaw.count {
let scheduleLineRaw = scheduleRaw[i]
let scheduleLineEntity = ScheduleLineEntity(context: self.appDelegate.stack.context)
scheduleLineEntity.sortKey = Int32(i)
scheduleLineEntity.isSunday = scheduleLineRaw.isSunday
scheduleLineEntity.locality = scheduleLineRaw.locality
var titleString = scheduleLineRaw.dateString + ": "
if let status = scheduleLineRaw.status {
titleString = titleString + status
} else if let localityPretty = scheduleLineRaw.localityPretty {
titleString = titleString + localityPretty
}
scheduleLineEntity.title = titleString
var subtitleString = ""
if let missionaries = scheduleLineRaw.missionaries {
subtitleString = subtitleString + missionaries
}
if scheduleLineRaw.with.count > 0 {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(with "
for i in 0 ..< scheduleLineRaw.with.count {
if i != 0 {
subtitleString = subtitleString + " and "
}
subtitleString = subtitleString + scheduleLineRaw.with[i]
}
subtitleString = subtitleString + ")"
}
if let isAM = scheduleLineRaw.am, let isPM = scheduleLineRaw.pm {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
if isAM && isPM {
subtitleString = subtitleString + "(AM & PM)"
} else if isAM {
subtitleString = subtitleString + "(AM Only)"
} else if isPM {
subtitleString = subtitleString + "(PM Only)"
}
}
if let comment = scheduleLineRaw.comment {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(" + comment + ")"
}
scheduleLineEntity.subtitle = subtitleString
self.schedule.append(scheduleLineEntity)
}
self.appDelegate.stack.save()
}
// MARK: Table View Data Source
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return schedule.count
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ScheduleLineTableViewCell"
)!
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
cell.textLabel?.text = scheduleLine.title!
cell.detailTextLabel?.text = scheduleLine.subtitle!
cell.backgroundColor = .white
cell.textLabel?.textColor = Constants.UI.Armadillo
cell.detailTextLabel?.textColor = Constants.UI.Armadillo
if scheduleLine.isSunday {
cell.textLabel?.textColor = .red
cell.detailTextLabel?.textColor = .red
}
return cell
}
override func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
// Only load information if the ScheduleLine refers to a specific locality
guard let key = scheduleLine.locality else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// Protect against missing locality
guard let locality = Directory.directory!.localities[key] else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// If we have location details, load the LocalityView
// Otherwise, jump straight to ContactView
if locality.hasLocationDetails {
let localityViewController = storyboard!.instantiateViewController(
withIdentifier: "LocalityViewController"
) as! LocalityViewController
localityViewController.locality = locality
navigationController!.pushViewController(localityViewController, animated: true)
} else {
let contactViewController = storyboard!.instantiateViewController(
withIdentifier: "ContactViewController"
) as! ContactViewController
contactViewController.locality = locality
navigationController!.pushViewController(contactViewController, animated: true)
}
}
}
| mit | 5fb49468454bc1d0d4428a7a576680f7 | 35.654952 | 111 | 0.560446 | 6.000523 | false | false | false | false |
nearspeak/iOS-SDK | NearspeakDemo/AppDelegate.swift | 1 | 6562 | //
// AppDelegate.swift
// NearspeakDemo
//
// Created by Patrick Steiner on 23.04.15.
// Copyright (c) 2015 Mopius. All rights reserved.
//
import UIKit
import CoreLocation
import NearspeakKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let api = NSKApi(devMode: false)
var pushedTags = Set<String>()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
setupNotifications()
if NSKManager.sharedInstance.checkForBeaconSupport() {
Log.debug("iBeacons supported")
NSKManager.sharedInstance.addCustomUUID("CEFCC021-E45F-4520-A3AB-9D1EA22873AD") // Nearspeak UUID
NSKManager.sharedInstance.startBeaconMonitoring()
} else {
Log.error("iBeacons not supported")
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Notifications
private func setupNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onEnterRegionNotification(_:)),
name: NSKConstants.managerNotificationRegionEnterKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onExitRegionNotification(_:)),
name: NSKConstants.managerNotificationRegionExitKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onNearbyTagsUpdatedNotification(_:)),
name: NSKConstants.managerNotificationNearbyTagsUpdatedKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onBluetoothOkNotification(_:)),
name: NSKConstants.managerNotificationBluetoothOkKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onBluetoothErrorNotification(_:)),
name: NSKConstants.managerNotificationBluetoothErrorKey,
object: nil)
}
func onBluetoothOkNotification(notification: NSNotification) {
Log.debug("Bluetooth OK")
}
func onBluetoothErrorNotification(notification: NSNotification) {
Log.debug("Bluetooth ERROR")
}
func onNearbyTagsUpdatedNotification(notification: NSNotification) {
// copy the nearbyTags from the shared instance
let nearbyTags = NSKManager.sharedInstance.nearbyTags
for tag in nearbyTags {
if let identifier = tag.tagIdentifier {
api.getTagById(tagIdentifier: identifier, requestCompleted: { (succeeded, tag) -> () in
if succeeded {
if let tag = tag {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if !self.pushedTags.contains(identifier) {
self.pushedTags.insert(identifier)
if let bodyText = tag.translation {
self.showLocalPushNotification(title: tag.titleString(), body: bodyText)
} else {
self.showLocalPushNotification(title: tag.titleString(), body: "Default Body")
}
}
})
}
}
})
}
}
}
func onEnterRegionNotification(notification: NSNotification) {
// start discovery to get more infos about the beacon
NSKManager.sharedInstance.startBeaconDiscovery(false)
}
func onExitRegionNotification(notification: NSNotification) {
// stop discovery
NSKManager.sharedInstance.stopBeaconDiscovery()
// reset already pushed tags
pushedTags.removeAll()
}
private func showLocalPushNotification(title notificationTitle: String, body notificationText: String) {
let notification = UILocalNotification()
notification.alertTitle = notificationTitle
if notificationText.isEmpty {
notification.alertBody = "Default Body Text"
} else {
notification.alertBody = notificationText
}
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}
| lgpl-3.0 | 9d4a62e8706a74a442f845e67c2d66f6 | 41.61039 | 285 | 0.646602 | 5.827709 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Other/GameKit Support/GKHelper.swift | 2 | 2946 | //
// GKHelper.swift
// WikiRaces
//
// Created by Andrew Finke on 6/24/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import Foundation
import GameKit
import WKRUIKit
#if !MULTIWINDOWDEBUG && !targetEnvironment(macCatalyst)
import FirebaseAnalytics
import FirebaseCrashlytics
#endif
class GKHelper {
enum AuthResult {
case controller(UIViewController)
case error(Error)
case isAuthenticated
}
static let shared = GKHelper()
private var pendingInvite: String?
var inviteHandler: ((String) -> Void)? {
didSet {
pushInviteToHandler()
}
}
private var pendingResult: AuthResult?
var authHandler: ((AuthResult) -> Void)? {
didSet {
pushResultToHandler()
}
}
public var isAuthenticated = false
// MARK: - Initalization -
private init() {}
// MARK: - Handlers -
private func pushResultToHandler() {
guard let result = pendingResult, let handler = authHandler else { return }
DispatchQueue.main.async {
handler(result)
}
pendingResult = nil
}
private func pushInviteToHandler() {
guard let invite = pendingInvite, let handler = inviteHandler else { return }
DispatchQueue.main.async {
handler(invite)
}
pendingInvite = nil
}
// MARK: - Helpers -
func start() {
guard !Defaults.isFastlaneSnapshotInstance else {
return
}
DispatchQueue.global().async {
GKLocalPlayer.local.authenticateHandler = { controller, error in
DispatchQueue.main.async {
if let error = error {
self.pendingResult = .error(error)
} else if let controller = controller {
self.pendingResult = .controller(controller)
} else if GKLocalPlayer.local.isAuthenticated {
self.pendingResult = .isAuthenticated
self.isAuthenticated = true
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {
WKRUIPlayerImageManager.shared.connected(to: GKLocalPlayer.local, completion: nil)
}
#if !MULTIWINDOWDEBUG && !targetEnvironment(macCatalyst)
let playerName = GKLocalPlayer.local.alias
Crashlytics.crashlytics().setUserID(playerName)
Analytics.setUserProperty(playerName, forName: "playerName")
#endif
} else {
fatalError()
}
self.pushResultToHandler()
}
}
}
}
func acceptedInvite(code: String) {
pendingInvite = code
pushInviteToHandler()
}
}
| mit | 870c11c5c83018e86f0f30ddb39967ba | 26.783019 | 110 | 0.551443 | 5.221631 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/14347-swift-sourcemanager-getmessage.swift | 11 | 2355 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
for {
protocol A? {
class
class A {
class
class
case c,
enum b {
n(v: A<T where T where g: A? {
case c,
( {
e( {
var b {
struct A {
let a {
class
class
class
let start = ( )
e( {
var d {
e( )
struct A {
class
class a {
class
class
func i{
class B<T {
var d {
enum b {
let start = ( {
let c = [ {
( )
case ,
class B {
enum b {
class
case c,
if true {
( )
enum S {
if true {
for {
class a<T where g: a = ( {
class
case ,
class
enum S {
( {
class A? {
class
let a {
class
(f: A
}
struct S<T : a = a<T {
class A {
class
let d {
if true {
( )
enum A {
class A? {
func D Void>(f: A
case ,
for {
enum A {
struct A {
let d {
var d {
func a( {
struct A {
if true {
case ,
if true {
(
class B {
class a {
for {
func b {
enum b {
let a {
class a = [ {
func b { func g {
class B<T where g: A {
var d {
class a {
class B<T where T : A
struct S<T {
case ,
( {
struct B<T where g: A? {
struct d
case ,
func g {
case ,
class
struct A {
class a
if true {
if true {
class A<d
case ,
let d {
class A<T {
enum S {
class
case c,
class
enum S {
var d {
{
var d {
let a {
case c,
class
struct B<T {
class
for {
var d {
let start = a<T : a {
n(v: A
( {
( )
class b {
class
if true {
class B<T {
func g {
class
struct d>(v: A<T where T {
class b {
(f: A {
class a<T {
var d {
}
class
{
class
class
class
class A {
var d {
func D Void>
case c,
struct B<T {
struct S<T : A
if true {
enum S {
(
class a<T {
class
e( {
func i{
B {
class A? {
for
class A {
enum b { func D Void>(f: A<T : A<T {
enum b {
struct B<T where T : a {
case ,
class
e( {
( {
{
class
}
func D Void>
}
if true {
struct A {
}
for {
class
case ,
case c,
case ,
B {
struct A {
class a {
class
case ,
enum b {
{
case c,
func g {
class B<T {
let a {
case c,
class a( {
class A<T : A<T where T : A<T : A<T where g: A? {
let c = [ {
struct A {
let d {
enum S {
struct B<d
case ,
struct d
let a {
class
{
class a {
}
class
n(f: A {
class a<T : A<T : A {
struct A {
func D Void>(
class
{
class
enum S {
class
enum S {
class b {
struct A {
case ,
var b { func g {
enum S {
{
struct A {
e( {
class
func i{
case ,
var b { func i{
class
class
case ,
for
enum b {
func b { func D Void>(
class
class
enum b {
case c,
class B<T {
case ,
class A {
class A {
| mit | 8e5f24ea1bdb3bac54b4eba7276303a5 | 8.534413 | 87 | 0.588535 | 2.28419 | false | false | false | false |
codefirst/SKK-for-iOS | SKK-Keyboard/ImitationKeyboard/KeyboardConnector.swift | 1 | 10093 | //
// KeyboardConnector.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
protocol Connectable {
func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint)
func attachmentDirection() -> Direction?
func attach(direction: Direction?) // call with nil to detach
}
// TODO: Xcode crashes
// <ConnectableView: UIView where ConnectableView: Connectable>
class KeyboardConnector: UIView, KeyboardView {
var start: UIView
var end: UIView
var startDir: Direction
var endDir: Direction
// TODO: temporary fix for Swift compiler crash
var startConnectable: Connectable
var endConnectable: Connectable
var convertedStartPoints: (CGPoint, CGPoint)!
var convertedEndPoints: (CGPoint, CGPoint)!
var color: UIColor { didSet { self.setNeedsDisplay() }}
var underColor: UIColor { didSet { self.setNeedsDisplay() }}
var borderColor: UIColor { didSet { self.setNeedsDisplay() }}
var drawUnder: Bool { didSet { self.setNeedsDisplay() }}
var drawBorder: Bool { didSet { self.setNeedsDisplay() }}
var drawShadow: Bool { didSet { self.setNeedsDisplay() }}
var _offset: CGPoint
// TODO: until bug is fixed, make sure start/end and startConnectable/endConnectable are the same object
init(start: UIView, end: UIView, startConnectable: Connectable, endConnectable: Connectable, startDirection: Direction, endDirection: Direction) {
self.start = start
self.end = end
self.startDir = startDirection
self.endDir = endDirection
self.startConnectable = startConnectable
self.endConnectable = endConnectable
self.color = UIColor.whiteColor()
self.underColor = UIColor.grayColor()
self.borderColor = UIColor.blackColor()
self.drawUnder = true
self.drawBorder = true
self.drawShadow = true
self._offset = CGPointZero
super.init(frame: CGRectZero)
self.userInteractionEnabled = false // TODO: why is this even necessary if it's under all the other views?
self.backgroundColor = UIColor.clearColor()
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.resizeFrame()
}
override func layoutSubviews() {
super.layoutSubviews()
self.resizeFrame()
self.setNeedsDisplay()
}
func generateConvertedPoints() {
if self.superview == nil {
return
}
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
self.convertedStartPoints = (
self.superview!.convertPoint(startPoints.0, fromView: self.start),
self.superview!.convertPoint(startPoints.1, fromView: self.start))
self.convertedEndPoints = (
self.superview!.convertPoint(endPoints.0, fromView: self.end),
self.superview!.convertPoint(endPoints.1, fromView: self.end))
}
func resizeFrame() {
generateConvertedPoints()
let buffer: CGFloat = 32
self._offset = CGPointMake(buffer/2, buffer/2)
let minX = min(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let minY = min(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let maxX = max(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let maxY = max(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let width = maxX - minX
let height = maxY - minY
self.frame = CGRectMake(minX - buffer/2, minY - buffer/2, width + buffer, height + buffer)
}
override func drawRect(rect: CGRect) {
// TODO: quick hack
resizeFrame()
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
var myConvertedStartPoints = (
self.convertPoint(startPoints.0, fromView: self.start),
self.convertPoint(startPoints.1, fromView: self.start))
let myConvertedEndPoints = (
self.convertPoint(endPoints.0, fromView: self.end),
self.convertPoint(endPoints.1, fromView: self.end))
if self.startDir == self.endDir {
let tempPoint = myConvertedStartPoints.0
myConvertedStartPoints.0 = myConvertedStartPoints.1
myConvertedStartPoints.1 = tempPoint
}
let ctx = UIGraphicsGetCurrentContext()
let csp = CGColorSpaceCreateDeviceRGB()
let path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.1.x, myConvertedEndPoints.1.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedStartPoints.1.x, myConvertedStartPoints.1.y)
CGPathCloseSubpath(path)
// for now, assuming axis-aligned attachment points
let isVertical = (self.startDir == Direction.Up || self.startDir == Direction.Down) && (self.endDir == Direction.Up || self.endDir == Direction.Down)
var midpoint: CGFloat
if isVertical {
midpoint = myConvertedStartPoints.0.y + (myConvertedEndPoints.1.y - myConvertedStartPoints.0.y) / 2
}
else {
midpoint = myConvertedStartPoints.0.x + (myConvertedEndPoints.1.x - myConvertedStartPoints.0.x) / 2
}
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(myConvertedStartPoints.0)
bezierPath.addCurveToPoint(
myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedStartPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedEndPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.1.y)))
bezierPath.addLineToPoint(myConvertedEndPoints.0)
bezierPath.addCurveToPoint(
myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedEndPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedStartPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.1.y)))
bezierPath.addLineToPoint(myConvertedStartPoints.0)
bezierPath.closePath()
let shadow = UIColor.blackColor().colorWithAlphaComponent(0.35)
let shadowOffset = CGSizeMake(0, 1.5)
let shadowBlurRadius: CGFloat = 12
// shadow is drawn separate from the fill
// http://stackoverflow.com/questions/6709064/coregraphics-quartz-drawing-shadow-on-transparent-alpha-path
// CGContextSaveGState(ctx)
// self.color.setFill()
// CGContextSetShadowWithColor(ctx, shadowOffset, shadowBlurRadius, shadow.CGColor)
// CGContextMoveToPoint(ctx, 0, 0);
// CGContextAddLineToPoint(ctx, self.bounds.width, 0);
// CGContextAddLineToPoint(ctx, self.bounds.width, self.bounds.height);
// CGContextAddLineToPoint(ctx, 0, self.bounds.height);
// CGContextClosePath(ctx);
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextClip(ctx)
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextDrawPath(ctx, kCGPathFillStroke)
// CGContextRestoreGState(ctx)
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextClip(ctx)
CGContextSaveGState(ctx)
UIColor.blackColor().setFill()
CGContextSetShadowWithColor(ctx, shadowOffset, shadowBlurRadius, shadow.CGColor)
bezierPath.fill()
CGContextRestoreGState(ctx)
if self.drawUnder {
CGContextTranslateCTM(ctx, 0, 1)
self.underColor.setFill()
CGContextAddPath(ctx, bezierPath.CGPath)
CGContextFillPath(ctx)
CGContextTranslateCTM(ctx, 0, -1)
}
self.color.setFill()
bezierPath.fill()
if self.drawBorder {
self.borderColor.setStroke()
CGContextSetLineWidth(ctx, 0.5)
CGContextMoveToPoint(ctx, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
CGContextAddCurveToPoint(
ctx,
(isVertical ? myConvertedStartPoints.0.x : midpoint),
(isVertical ? midpoint : myConvertedStartPoints.0.y),
(isVertical ? myConvertedEndPoints.1.x : midpoint),
(isVertical ? midpoint : myConvertedEndPoints.1.y),
myConvertedEndPoints.1.x,
myConvertedEndPoints.1.y)
CGContextStrokePath(ctx)
CGContextMoveToPoint(ctx, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
CGContextAddCurveToPoint(
ctx,
(isVertical ? myConvertedEndPoints.0.x : midpoint),
(isVertical ? midpoint : myConvertedEndPoints.0.y),
(isVertical ? myConvertedStartPoints.1.x : midpoint),
(isVertical ? midpoint : myConvertedStartPoints.1.y),
myConvertedStartPoints.1.x,
myConvertedStartPoints.1.y)
CGContextStrokePath(ctx)
}
}
}
| gpl-2.0 | 61410cecc5f05f83c47bae68b352df11 | 40.364754 | 157 | 0.641237 | 5.136387 | false | false | false | false |
maikotrindade/ios-basics | HelloWorld.playground/Contents.swift | 1 | 1483 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var myVariable = 123 //variable
let myConstant = 123456 //constant
let anExplicit : Int = 2
myVariable+=1000
//myConstant = 2 //Cannot assing a value to a constant
var someVariable : Int
//someVariable + = 4 // error: not initial value
var sampleText = "Welcome!"
print (sampleText)
var anOptionalInt : Int? = nil
anOptionalInt = 55
if anOptionalInt != nil {
print ("It has a value:\(anOptionalInt!)")
} else {
print ("It hasn't a value!")
}
var unwrappedOptionalInteger : Int!
unwrappedOptionalInteger = 4
var anInteger = 40
let aString = String(anInteger)
//Tuples
let aTuple = (1, "YES", 34, "NO")
let firstNumber = aTuple.0
let secondText = aTuple.3
//adding labels
let anotherTuple = (aNumber : 1111, aString : "My String")
let theOtherNumber = anotherTuple.aNumber
//Arrays
let arrayOfIntegers : [Int] = [1,2,3,4,5,6]
let mixedArray = [6,4, "String"]
var testArray = [1,2,3,4,5]
testArray.append(6)
testArray.insert(7, atIndex: 6)
testArray.removeLast()
testArray.removeAtIndex(1)
testArray.count
var arrayOfStrings = ["one","two","three","four"]
//Dictionary
var crew = [
"Captain" : "TPA",
"First Officer" : "TPB",
"Cabin Hostess" : "TPC",
"Cabin Hostes" : "TPD"]
crew["Captain"]
crew["Intern"] = "BBB"
crew.description
var aNumberDic = [1:"value"]
aNumberDic[21]="ok"
aNumberDic.description
| gpl-3.0 | 70b7d8e75a5f4b977be88784e9ca2a25 | 12.241071 | 58 | 0.670263 | 3.203024 | false | true | false | false |
huonw/swift | test/NameBinding/import-resolution-2.swift | 31 | 979 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/abcde.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/aeiou.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/asdf.swift
// RUN: %target-swift-frontend -emit-module -o %t -I %t %S/Inputs/letters.swift
// RUN: %target-swift-frontend -typecheck %s -I %t -sdk "" -verify
import letters
import aeiou
import struct asdf.A
import struct abcde.A
var uA : A // expected-error {{'A' is ambiguous for type lookup in this context}}
var uB : B = abcde.B()
var uC : C = letters.C(b: uB)
var uD : D = asdf.D()
var uE : E = aeiou.E()
var uF : F = letters.F()
var qA1 : aeiou.A
var qA2 : asdf.A
var qA3 : abcde.A
var uS : S // expected-error {{use of undeclared type 'S'}}
var qS1 : letters.S // expected-error {{no type named 'S' in module 'letters'}}
var qS2 : asdf.S // expected-error {{no type named 'S' in module 'asdf'}}
// but...!
letters.consumeS(letters.myS)
| apache-2.0 | 868b9753cf86329a046c41307aa2e102 | 33.964286 | 81 | 0.668029 | 2.638814 | false | false | false | false |
CaptainTeemo/Saffron | Saffron/ImageEditor.swift | 1 | 6380 | //
// ImageEditor.swift
// Saffron
//
// Created by CaptainTeemo on 5/3/16.
// Copyright © 2016 Captain Teemo. All rights reserved.
//
import Accelerate
extension UIImage {
func blur(with radius: CGFloat, iterations: Int = 2, ratio: CGFloat = 1.2, blendColor: UIColor? = nil) -> UIImage? {
if floorf(Float(size.width)) * floorf(Float(size.height)) <= 0.0 || radius <= 0 {
return self
}
var imageRef = cgImage
if !isARGB8888(imageRef: imageRef!) {
let context = createARGB8888BitmapContext(from: imageRef!)
let rect = CGRect(x: 0, y: 0, width: imageRef!.width, height: imageRef!.height)
context?.draw(imageRef!, in: rect)
imageRef = context?.makeImage()
}
var boxSize = UInt32(radius * scale * ratio)
if boxSize % 2 == 0 {
boxSize += 1
}
let height = imageRef!.height
let width = imageRef!.width
let rowBytes = imageRef!.bytesPerRow
let bytes = rowBytes * height
let inData = malloc(bytes)
var inBuffer = vImage_Buffer(data: inData, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
let outData = malloc(bytes)
var outBuffer = vImage_Buffer(data: outData, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
let tempFlags = vImage_Flags(kvImageEdgeExtend + kvImageGetTempBufferSize)
let tempSize = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, boxSize, boxSize, nil, tempFlags)
let tempBuffer = malloc(tempSize)
let provider = imageRef!.dataProvider
let copy = provider!.data
let source = CFDataGetBytePtr(copy)
memcpy(inBuffer.data, source, bytes)
let flags = vImage_Flags(kvImageEdgeExtend)
for _ in 0 ..< iterations {
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, tempBuffer, 0, 0, boxSize, boxSize, nil, flags)
let temp = inBuffer.data
inBuffer.data = outBuffer.data
outBuffer.data = temp
}
let colorSpace = imageRef!.colorSpace
let bitmapInfo = imageRef!.bitmapInfo
let bitmapContext = CGContext(data: inBuffer.data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: rowBytes, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
defer {
free(outBuffer.data)
free(tempBuffer)
free(inBuffer.data)
}
if let color = blendColor {
bitmapContext!.setFillColor(color.cgColor)
bitmapContext!.setBlendMode(CGBlendMode.plusLighter)
bitmapContext!.fill(CGRect(x: 0, y: 0, width: width, height: height))
}
if let bitmap = bitmapContext!.makeImage() {
return UIImage(cgImage: bitmap, scale: scale, orientation: imageOrientation)
}
return nil
}
private func isARGB8888(imageRef: CGImage) -> Bool {
let alphaInfo = imageRef.alphaInfo
let isAlphaOnFirstPlace = (CGImageAlphaInfo.first == alphaInfo || CGImageAlphaInfo.first == alphaInfo || CGImageAlphaInfo.noneSkipFirst == alphaInfo || CGImageAlphaInfo.noneSkipLast == alphaInfo)
return imageRef.bitsPerPixel == 32 && imageRef.bitsPerComponent == 8 && (imageRef.bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) > 0 && isAlphaOnFirstPlace
}
private func createARGB8888BitmapContext(from image: CGImage) -> CGContext? {
let pixelWidth = image.width
let pixelHeight = image.height
let bitmapBytesPerFow = pixelWidth * 4
let bitmapByCount = bitmapBytesPerFow * pixelHeight
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapData = UnsafeMutableRawPointer.allocate(bytes: bitmapByCount, alignedTo: bitmapByCount)
let context = CGContext(data: bitmapData, width: pixelWidth, height: pixelHeight, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerFow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
return context
}
func roundCorner(_ radius: CGFloat) -> UIImage? {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(roundedRect: rect, cornerRadius: radius)
context!.addPath(path.cgPath)
context!.clip()
draw(in: rect)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output
}
func oval() -> UIImage? {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(ovalIn: rect)
context!.addPath(path.cgPath)
context!.clip()
draw(in: rect)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output
}
func scaleToFill(_ targetSize: CGSize) -> UIImage {
let targetAspect = targetSize.width / targetSize.height
let aspect = size.width / size.height
var scaledSize = size
if targetAspect < aspect {
scaledSize.width = ceil(size.height * targetAspect)
} else {
scaledSize.height = ceil(size.width * targetAspect)
}
let cropRect = CGRect(origin: CGPoint(x: -abs(size.width - scaledSize.width) / 2, y: -abs(size.height - scaledSize.height) / 2), size: scaledSize)
UIGraphicsBeginImageContextWithOptions(scaledSize, false, UIScreen.main.nativeScale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(rect: CGRect(origin: CGPoint.zero, size: size)).cgPath
context!.addPath(path)
context!.clip()
draw(in: CGRect(origin: cropRect.origin, size: size))
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output!
}
}
| mit | 69dce9494a013a54a57ab8903e947ede | 39.373418 | 218 | 0.626587 | 5.003137 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.