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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TMTBO/TTAImagePickerController | TTAImagePickerController/Classes/Utils/UIImage+IconFont.swift | 1 | 3206 | //
// UIImage+IconFont.swift
// Pods-TTAImagePickerController_Example
//
// Created by TobyoTenma on 25/06/2017.
//
import UIKit
extension UIImage {
static func image(with iconfont: UIFont.IconFont, size: CGFloat = 15, tintColor: UIColor = .lightGray, backgroundColor: UIColor = .clear) -> UIImage {
let font = UIFont.iconfont(size: size)
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributes = [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: tintColor,
NSAttributedString.Key.backgroundColor: backgroundColor,
NSAttributedString.Key.paragraphStyle: style]
let attString = NSAttributedString(string: iconfont.rawValue, attributes: attributes)
let ctx = NSStringDrawingContext()
var textRect = attString.boundingRect(with: CGSize(width: font.pointSize, height: font.pointSize), options: .usesLineFragmentOrigin, context: ctx)
textRect.origin = .zero
UIGraphicsBeginImageContextWithOptions(textRect.size, false, UIScreen.main.scale)
attString.draw(in: textRect)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { fatalError("Can NOT generate the image with the IconFont: \(iconfont)") }
return image
}
static func image(with iconfont: UIFont.IconFont, in size: CGSize, tintColor: UIColor = .lightGray, backgroundColor: UIColor = .clear, cornerRadius: CGFloat = 0) -> UIImage {
let realSize = min(size.width, size.height)
let font = UIFont.iconfont(size: realSize)
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributes = [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: tintColor,
NSAttributedString.Key.backgroundColor: backgroundColor,
NSAttributedString.Key.paragraphStyle: style]
let attString = NSAttributedString(string: iconfont.rawValue, attributes: attributes)
let ctx = NSStringDrawingContext()
var textRect = attString.boundingRect(with: CGSize(width: font.pointSize, height: font.pointSize), options: .usesLineFragmentOrigin, context: ctx)
textRect.origin = .zero
UIGraphicsBeginImageContextWithOptions(textRect.size, false, UIScreen.main.scale)
let pathRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let path: UIBezierPath
if cornerRadius > 0 {
path = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRadius)
} else {
path = UIBezierPath(rect: pathRect)
}
backgroundColor.setFill()
path.fill()
attString.draw(in: textRect.offsetBy(dx: (size.width - textRect.width) / 2, dy: (size.height - textRect.height) / 2))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { fatalError("Can NOT generate the image with the IconFont: \(iconfont)") }
return image
}
}
| mit | ff48a41aa3ef02362a7da448336aa9d6 | 45.463768 | 178 | 0.650343 | 5.19611 | false | false | false | false |
stripe/stripe-ios | StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/Card/STPPostalCodeInputTextFieldFormatter.swift | 1 | 1552 | //
// STPPostalCodeInputTextFieldFormatter.swift
// StripePaymentsUI
//
// Created by Cameron Sabol on 10/30/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
import UIKit
class STPPostalCodeInputTextFieldFormatter: STPInputTextFieldFormatter {
var countryCode: String? = Locale.autoupdatingCurrent.regionCode
override func isAllowedInput(_ input: String, to string: String, at range: NSRange) -> Bool {
guard super.isAllowedInput(input, to: string, at: range),
input.rangeOfCharacter(from: .stp_invertedPostalCode) == nil,
let range = Range(range, in: string)
else {
return false
}
let proposed = string.replacingCharacters(in: range, with: input)
if countryCode == "US", proposed.count > 5 {
return false
}
return STPPostalCodeValidator.validationState(
forPostalCode: proposed,
countryCode: countryCode
) != .invalid
}
override func formattedText(
from input: String,
with defaultAttributes: [NSAttributedString.Key: Any]
) -> NSAttributedString {
return NSAttributedString(
string: STPPostalCodeValidator.formattedSanitizedPostalCode(
from: input.trimmingCharacters(in: .whitespacesAndNewlines),
countryCode: countryCode,
usage: .billingAddress
) ?? "",
attributes: defaultAttributes
)
}
}
| mit | 8452521f51861739503a7fb0540f3ff2 | 31.3125 | 97 | 0.640877 | 5.118812 | false | false | false | false |
normand1/DNFlyingBadge | Example/Tests/DNFlyingBadgesTests.swift | 1 | 1064 | //
// DNFlyingBadgesTests.swift
// DNFlyingBadges
//
// Created by David Norman on 6/10/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import DNFlyingBadges
class DNFlyingBadgesSpec : QuickSpec {
override func spec() {
describe("a default flying badge view", { () -> Void in
var flyingBadge = DNFlyingBadgesView()
beforeEach({ () -> () in
flyingBadge = DNFlyingBadgesView()
})
it("is 70 x 70 with an origin at 0,0") {
expect(flyingBadge.frame) == CGRectMake(0, 0, 70, 70)
}
it("can load images from the bundle") {
var path = NSBundle(forClass: flyingBadge.dynamicType).pathForResource("like", ofType: ".png")
var data = NSData(contentsOfFile: path!)
var mainImage = UIImage(contentsOfFile: path!)
expect(mainImage).notTo(beNil())
}
})
}
} | mit | d3ccc7bbe5722a3fed7f61e0a2202deb | 26.307692 | 110 | 0.529135 | 4.606061 | false | false | false | false |
dengJunior/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBTalentCell.swift | 1 | 3772 | //
// CBTalentCell.swift
// TestKitchen
//
// Created by 邓江洲 on 16/8/22.
// Copyright © 2016年 邓江洲. All rights reserved.
//
import UIKit
class CBTalentCell: UITableViewCell {
@IBOutlet weak var talentImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var fansLabel: UILabel!
var dataArray: Array<CBRecommendWidgeDataModel>?{
didSet{
showData()
}
}
func showData(){
if dataArray?.count > 0{
let imageModel = dataArray![0]
if imageModel.type == "image"{
let url = NSURL(string: imageModel.content!)
talentImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
if dataArray?.count > 1 {
let nameModel = dataArray![1]
if nameModel.type == "text"{
nameLabel.text = nameModel.content
}
}
if dataArray?.count > 2{
let descModel = dataArray![2]
if descModel.type == "text"{
descLabel.text = descModel.content
}
}
if dataArray?.count > 3 {
let fansModel = dataArray![3]
if fansModel.type == "text"{
fansLabel.text = fansModel.content
}
}
}
}
class func createTalentCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBTalentCell {
let cellId = "talentCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBTalentCell
if nil == cell{
cell = NSBundle.mainBundle().loadNibNamed("CBTalentCell", owner: nil, options: nil).last as? CBTalentCell
}
if listModel.widget_data?.count >= indexPath.row*4+4{
let array = NSArray(array: listModel.widget_data!)
let curArray = array.subarrayWithRange(NSMakeRange(indexPath.row*4, 4))
cell?.dataArray = curArray as? Array<CBRecommendWidgeDataModel>
}
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | f2c8f5a08bbeb04347eb4ad6840a09c1 | 18.773684 | 169 | 0.40165 | 6.769369 | false | false | false | false |
anicolaspp/rate-my-meetings-ios | RateMyMeetings/MeetingsTableViewController.swift | 1 | 10300 | //
// MeetingsTableViewController.swift
// RateMyMeetings
//
// Created by Nicolas Perez on 11/24/15.
// Copyright © 2015 Nicolas Perez. All rights reserved.
//
import UIKit
import EventKitUI
import CVCalendar
import Parse
class MeetingsTableViewController: UIViewController {
@IBOutlet weak var calendarView: CVCalendarView!
@IBOutlet weak var menuView: CVCalendarMenuView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var actionButton: UIBarButtonItem!
@IBOutlet weak var changeCalendarModeItemButton: UIBarButtonItem!
var _calendarView: CVCalendarView?
var user: User?
var eventManager: EventManager?
var events: [EKEvent] = []
var onlineEvents: [Event]? = []
var selectedCalendar: EKCalendar?
var calendarRepository = CalendarRepository()
var userRepository = UserRepository()
override func viewDidLoad() {
super.viewDidLoad()
self.eventManager = EventManager(user: self.user!, withCalendarRepository: self.calendarRepository)
self.checkCalendarAuthorizationStatus()
self.title = CVDate(date: NSDate()).globalDescription
self.calendarRepository.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Commit frames' updates
self.calendarView.commitCalendarViewUpdate()
self.menuView.commitMenuViewUpdate()
}
@IBAction func showCalendars(sender: UIBarButtonItem) {
let actionSheet = UIAlertController(title: "Actions", message: "Actions", preferredStyle: .ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Change Calendar", style: .Default, handler: { (action) -> Void in
self.showCalendarPicker()
}))
actionSheet.addAction(UIAlertAction(title: "Invite people to this calendar", style: .Default, handler: {(action) -> Void in
let calendarToShare = ["my website", NSURL(string: "http://www.google.com")!]
let avc = UIActivityViewController(activityItems: calendarToShare, applicationActivities: nil)
avc.setValue("Join my calendar to rate events together", forKey: "subject")
self.presentViewController(avc, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Destructive, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
@IBAction func changeCalendarViewMode(sender: AnyObject) {
changeCalendarMode()
}
func checkCalendarAuthorizationStatus() {
let status = EKEventStore.authorizationStatusForEntityType(EKEntityType.Event)
switch (status) {
case EKAuthorizationStatus.NotDetermined:
self.requestAccessToCalendar()
case EKAuthorizationStatus.Authorized:
if (self.eventManager!.calendar == nil) {
self.showCalendarPicker()
}
else {
self.loadEvents(NSDate())
self.calendarRepository.getEventForUser(self.user!, usingDate: NSDate())
}
case EKAuthorizationStatus.Restricted, EKAuthorizationStatus.Denied:
self.requestAccessToCalendar()
}
}
func requestAccessToCalendar() {
self.eventManager!.eventStore.requestAccessToEntityType(EKEntityType.Event, completion: {
(accessGranted: Bool, error: NSError?) in
if accessGranted == true {
dispatch_async(dispatch_get_main_queue(), {
self.showCalendarPicker()
})
} else {
dispatch_async(dispatch_get_main_queue(), {
//self.showCalendarPicker()
})
}
})
}
func loadEvents(currentDay: NSDate) {
self.events = self.eventManager!.getEventForDay(currentDay)
self.tableView.reloadData()
}
func showCalendarPicker() {
let calendarChooser = EKCalendarChooser(selectionStyle: .Single, displayStyle: .AllCalendars, entityType: .Event, eventStore: self.eventManager!.eventStore)
calendarChooser.showsDoneButton = true
calendarChooser.delegate = self
calendarChooser.modalPresentationStyle = .CurrentContext
if let c = self.eventManager!.calendar {
calendarChooser.selectedCalendars = [c]
}
let navControllerForCalendarChooser = UINavigationController(rootViewController: calendarChooser)
self.navigationController?.presentViewController(navControllerForCalendarChooser, animated: true, completion: nil)
}
func changeCalendarMode() {
switch self.calendarView.calendarMode! {
case CVCalendarViewPresentationMode.MonthView:
calendarView.changeMode(.WeekView)
changeCalendarModeItemButton.title = "Monthly"
case CVCalendarViewPresentationMode.WeekView:
calendarView.changeMode(.MonthView)
changeCalendarModeItemButton.title = "Weekly"
}
}
}
extension MeetingsTableViewController : EKCalendarChooserDelegate {
func calendarChooserDidFinish(calendarChooser: EKCalendarChooser) {
if let calendar = calendarChooser.selectedCalendars.first {
self.userRepository.setCalendar(calendar, forUser: self.user!)
self.eventManager?.calendar = calendar
self.loadEvents(NSDate())
calendarChooser.dismissViewControllerAnimated(true, completion: nil)
}
else {
let calendarSelectionAlert = UIAlertController(title: "Selection Error", message: "Please, select a calendar", preferredStyle: .Alert)
calendarSelectionAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
calendarChooser.presentViewController(calendarSelectionAlert, animated: true, completion: nil)
}
}
func calendarChooserDidCancel(calendarChooser: EKCalendarChooser) {
calendarChooser.dismissViewControllerAnimated(true, completion: nil)
}
}
extension MeetingsTableViewController : CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
func presentationMode() -> CalendarMode {
return .MonthView
}
func firstWeekday() -> Weekday {
return .Sunday
}
func dayOfWeekTextColor() -> UIColor {
return UIColor.blackColor()
}
func weekdaySymbolType() -> WeekdaySymbolType {
return .Short
}
func presentedDateUpdated(date: CVDate) {
self.title = date.globalDescription
let currentDate = date.convertedDate()?.atMidnight()
print(currentDate)
self.loadEvents(currentDate!)
self.calendarRepository.getEventForUser(self.user!, usingDate: currentDate!)
}
//
// func didShowNextMonthView(date: NSDate) {
// self.onlineEvents = self.calendarRepository.getEventForUser(self.user!, usingData: date)
// }
//
// func didShowPreviousMonthView(date: NSDate) {
// self.onlineEvents = self.calendarRepository.getEventForUser(self.user!, usingData: date)
// }
}
extension MeetingsTableViewController : CalendarRepositoryDelegate {
func user(user: User, didEventFetchComplete events: [Event]?) {
self.onlineEvents = events
}
}
extension MeetingsTableViewController : UITableViewDataSource, UITableViewDelegate {
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel?.text = self.events[indexPath.row].title
cell.detailTextLabel?.text = self.events[indexPath.row].startDate.formatted()
if (indexPath.row % 2 == 0) {
cell.backgroundColor = UIColor(white: 0.9, alpha: 0.1)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedEvent = self.events[indexPath.row]
let ratingController = self.storyboard?.instantiateViewControllerWithIdentifier("ratingController") as! RatingViewController
var event: Event?
print(self.onlineEvents)
if let matchedEvent = self.onlineEvents?.filter({ (x: Event) -> Bool in
print(x.eventName)
print(x.eventDate)
print("=========")
print(selectedEvent.title)
print(selectedEvent.startDate)
return(x.eventName == selectedEvent.title && x.eventDate == selectedEvent.startDate)
}).first {
event = matchedEvent
print(event)
}
else {
event = Event()
event!.setEvent(selectedEvent, inCalendar: self.calendarRepository.getInUseCalendarFor(self.user!))
self.onlineEvents?.append(event!)
}
let rating = self.calendarRepository.getRatingForEvent(event!)
ratingController.event = event
ratingController.overallRating = rating!
let backItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = backItem
self.navigationController?.pushViewController(ratingController, animated: true)
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 72cf0f3bfe423faa0b911319e7a3c21c | 32.767213 | 164 | 0.643363 | 5.403463 | false | false | false | false |
bluejava/GeoTools | GeoTools/GameViewController.swift | 1 | 6575 | //
// GameViewController.swift
// GeoTools
//
// Created by Glenn Crownover on 4/30/15.
// Copyright (c) 2015 bluejava. All rights reserved.
//
import SceneKit
import QuartzCore
class GameViewController: NSViewController
{
@IBOutlet weak var gameView: GameView!
override func awakeFromNib()
{
/* First, some boilerplate SceneKit setup - lights, camera, (action comes later) */
// create a new scene
let scene = SCNScene()
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = NSColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
/*
Here are the actual custom geometry test functions
*/
textureTileExample(scene.rootNode) // A parallelogram with stretched texture
textureTileExampleNonPar(scene.rootNode) // A non-parallel quadrilateral shape with tiled texture
textureTileExample3d(scene.rootNode) // A 3d custom shape with tiled texture
/* Now, some more boilerplate… */
// set the scene to the view
self.gameView!.scene = scene
// allows the user to manipulate the camera
self.gameView!.allowsCameraControl = true
// show statistics such as fps and timing information
self.gameView!.showsStatistics = true
// configure the view
self.gameView!.backgroundColor = NSColor.whiteColor()
}
// Always keep in mind the orientation of the verticies when looking at the face from the "front"
// With single-sided faces, we only see from the front side - so this is important.
// v1 --------------v0
// | __/ |
// | face __/ |
// | 1 __/ |
// | __/ face |
// | __/ 2 |
// v2 ------------- v3
// Two triangular faces are created from the 4 vertices - think of drawing the letter C when considering the order
// to enter your vertices - top right, then top left, then bottom left, then bottom right - But of course, this is
// relative only to your field of view - not the global coordinate system - "bottom" for your shape may be "up" in
// the world view!
// This function creates a quadrilateral shape with non-parallel sides. Note how the
// texture originates at v2 and tiles to the right, up and to the left seamlessly.
func textureTileExample(pnode: SCNNode)
{
// First, we create the 4 vertices for our custom geometry - note, they share a plane, but are otherwise irregular
var v0 = SCNVector3(x: 6, y: 6.0, z: 6)
var v1 = SCNVector3(x: 1, y: 4, z: 1)
var v2 = SCNVector3(x: 0, y: 0, z: 0)
var v3 = SCNVector3(x: 5, y: 2, z: 5)
// Now we create the GeometryBuilder - which allows us to add quads to make up a custom shape
var geobuild = GeometryBuilder(uvMode: GeometryBuilder.UVModeType.StretchToFitXY)
geobuild.addQuad(Quad(v0: v0,v1: v1,v2: v2,v3: v3)) // only the one quad for us today, thanks!
var geo = geobuild.getGeometry() // And here we get an SCNGeometry instance from our new shape
// Lets setup the diffuse, normal and specular maps - located in a subdirectory
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
// Now we simply create the node, position it, and add to our parent!
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: 5, y: 2, z: 0)
pnode.addChildNode(node)
}
// This function creates a quadrilateral shape with parallel sides to demonstrate
// a stretchedToFit texture mapping. Of course, since it is non-square, the texture is
// skewed.
func textureTileExampleNonPar(pnode: SCNNode)
{
var v0 = SCNVector3(x: 6, y: 6.0, z: 6)
var v1 = SCNVector3(x: 1, y: 4, z: 1)
var v2 = SCNVector3(x: 2, y: 0, z: 2)
var v3 = SCNVector3(x: 5, y: -2, z: 5)
var geobuild = GeometryBuilder(uvMode: GeometryBuilder.UVModeType.StretchToFitXY)
geobuild.addQuad(Quad(v0: v0,v1: v1,v2: v2,v3: v3)) // simple
var geo = geobuild.getGeometry()
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: 5, y: -6, z: 0)
pnode.addChildNode(node)
}
// And finally, here is a full 3d object with six sides. We only create the 8 vertices of the shape once,
// but they are replicated for each quad and then for each face as they have their own normals, texture coordinates, etc.
// But it sure makes our job easy at this point - just enter your vertices, build your quads and generate the shape!
func textureTileExample3d(pnode: SCNNode)
{
var f0 = SCNVector3(x: 6, y: 6.0, z: 2)
var f1 = SCNVector3(x: 1, y: 4, z: 2)
var f2 = SCNVector3(x: 2, y: 0, z: 2)
var f3 = SCNVector3(x: 5, y: -2, z: 2)
var b0 = SCNVector3(x: 6, y: 6.0, z: 0)
var b1 = SCNVector3(x: 1, y: 4, z: 0)
var b2 = SCNVector3(x: 2, y: 0, z: 0)
var b3 = SCNVector3(x: 5, y: -2, z: 0)
// Note: This uvMode will consider 1 by 1 coordinate units to coorespond with one full texture.
// This works great for drawing large irregularly shaped objects made with tile-able textures.
// The textures tile across each face without stretching or skewing regardless of size.
var geobuild = GeometryBuilder(uvMode: .SizeToWorldUnitsXY)
geobuild.addQuad(Quad(v0: f0,v1: f1,v2: f2,v3: f3)) // front
geobuild.addQuad(Quad(v0: b1,v1: b0,v2: b3,v3: b2)) // back
geobuild.addQuad(Quad(v0: b0,v1: b1,v2: f1,v3: f0)) // top
geobuild.addQuad(Quad(v0: f1,v1: b1,v2: b2,v3: f2)) // left
geobuild.addQuad(Quad(v0: b0,v1: f0,v2: f3,v3: b3)) // right
geobuild.addQuad(Quad(v0: f3,v1: f2,v2: b2,v3: b3)) // bottom
var geo = geobuild.getGeometry()
geo.materials = [ SCNUtils.getMat("diffuse.jpg", normalFilename: "normal.jpg", specularFilename: "specular.jpg", directory: "textures/brickTexture") ]
var node = SCNNode(geometry: geo)
node.position = SCNVector3(x: -5, y: 2, z: 0)
pnode.addChildNode(node)
}
}
| mit | d4d3f7b3a9911490d5f78fb1ee561be9 | 38.130952 | 152 | 0.687966 | 3.179971 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/OWSMessagesBubbleImageFactory.swift | 1 | 2279 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import JSQMessagesViewController
import SignalServiceKit
import SignalMessaging
@objc
class OWSMessagesBubbleImageFactory: NSObject {
static let shared = OWSMessagesBubbleImageFactory()
private let jsqFactory = JSQMessagesBubbleImageFactory()!
// TODO: UIView is a little bit expensive to instantiate.
// Can we cache this value?
private lazy var isRTL: Bool = {
return UIView().isRTL()
}()
public lazy var incoming: JSQMessagesBubbleImage = {
let color = UIColor.jsq_messageBubbleLightGray()!
return self.incoming(color: color)
}()
public lazy var outgoing: JSQMessagesBubbleImage = {
let color = UIColor.ows_materialBlue
return self.outgoing(color: color)
}()
public lazy var currentlyOutgoing: JSQMessagesBubbleImage = {
let color = UIColor.ows_fadedBlue
return self.outgoing(color: color)
}()
public lazy var outgoingFailed: JSQMessagesBubbleImage = {
let color = UIColor.gray
return self.outgoing(color: color)
}()
public func bubble(message: TSMessage) -> JSQMessagesBubbleImage {
if message is TSIncomingMessage {
return self.incoming
} else if let outgoingMessage = message as? TSOutgoingMessage {
switch outgoingMessage.messageState {
case .unsent:
return outgoingFailed
case .attemptingOut:
return currentlyOutgoing
default:
return outgoing
}
} else {
owsFail("Unexpected message type: \(message)")
return outgoing
}
}
private func outgoing(color: UIColor) -> JSQMessagesBubbleImage {
if isRTL {
return jsqFactory.incomingMessagesBubbleImage(with: color)
} else {
return jsqFactory.outgoingMessagesBubbleImage(with: color)
}
}
private func incoming(color: UIColor) -> JSQMessagesBubbleImage {
if isRTL {
return jsqFactory.outgoingMessagesBubbleImage(with: color)
} else {
return jsqFactory.incomingMessagesBubbleImage(with: color)
}
}
}
| gpl-3.0 | cc3ee56d7a30d63a5d042ccda4883233 | 28.986842 | 71 | 0.640193 | 5.504831 | false | false | false | false |
cuappdev/tempo | Tempo/TempoNotification.swift | 1 | 2497 | //
// TempoNotification.swift
// Tempo
//
// Created by Logan Allen on 2/21/17.
// Copyright © 2017 CUAppDev. All rights reserved.
//
import UIKit
import SwiftyJSON
enum NotificationType {
case Like
case Follower
case InternetConnectivity
}
protocol NotificationDelegate {
func didTapNotification(forNotification notif: TempoNotification, cell: NotificationTableViewCell?, postHistoryVC: PostHistoryTableViewController?)
}
class TempoNotification: NSObject {
let id: String?
let user: User?
let postId: String?
let message: String
let type: NotificationType
let date: Date?
var seen: Bool?
init(id: String?, user: User?, postId: String?, message: String, type: NotificationType, date: Date?, seen: Bool?) {
self.id = id
self.user = user
self.postId = postId
self.message = message
self.type = type
self.date = date
self.seen = seen
super.init()
}
// Initialization for tempo activity notification
convenience init(json: JSON) {
let id = json["id"].stringValue
let message = json["message"].stringValue
let seen = (json["seen"].intValue) == 0 ? false : true
let user = User(json: json["data"]["from"])
let postId = json["data"]["post_id"].stringValue
let type: NotificationType = json["data"]["type"].intValue == 1 ? .Like : .Follower
let dateString = json["created_at"].stringValue
let date = DateFormatter.parsingDateFormatter.date(from: dateString)
self.init(id: id, user: user, postId: postId, message: message, type: type, date: date, seen: seen)
}
// Initialization for internet connectivity
convenience init(msg: String, type: NotificationType = .InternetConnectivity) {
self.init(id: nil, user: nil, postId: nil, message: msg, type: type, date: nil, seen: nil)
}
override var description: String {
return message
}
var notificationDescription: String {
return "\(user!.name): \(message) for the post \(postId!)"
}
func relativeDate() -> String {
guard let date = date else { return "" }
let now = Date()
let seconds = max(0, Int(now.timeIntervalSince(date)))
if seconds < 60 {
return "\(seconds)s"
}
let minutes = seconds / 60
if minutes == 1 {
return "\(minutes)m"
}
if minutes < 60 {
return "\(minutes)m"
}
let hours: Int = minutes / 60
if hours == 1 {
return "\(hours)h"
}
if hours < 24 {
return "\(hours)h"
}
let days: Int = hours / 24
if days == 1 {
return "\(days)d"
}
return "\(days)d"
// return "2017-04-16T20:25:44.153Z"
}
}
| mit | b6d0eb47953bf92d9d6f1a91392b5f3a | 23.712871 | 148 | 0.672676 | 3.359354 | false | false | false | false |
enstulen/ARKitAnimation | Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisLabelGeneratorDate.swift | 1 | 1075 | //
// ChartAxisLabelGeneratorDate.swift
// SwiftCharts
//
// Created by ischuetz on 05/08/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartAxisLabelsGeneratorDate: ChartAxisLabelsGeneratorBase {
open let labelSettings: ChartLabelSettings
open let formatter: DateFormatter
public init(labelSettings: ChartLabelSettings, formatter: DateFormatter = ChartAxisLabelsGeneratorDate.defaultFormatter) {
self.labelSettings = labelSettings
self.formatter = formatter
}
open override func generate(_ scalar: Double) -> [ChartAxisLabel] {
let text = formatter.string(from: Date(timeIntervalSince1970: scalar))
return [ChartAxisLabel(text: text, settings: labelSettings)]
}
public static var defaultFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
return formatter
}()
open override func fonts(_ scalar: Double) -> [UIFont] {
return [labelSettings.font]
}
}
| mit | 7545f8e052b440605131801f090329bc | 28.833333 | 126 | 0.689013 | 5.114286 | false | false | false | false |
rastogigaurav/mTV | mTV/mTV/General/UICollectionView+Pagination.swift | 1 | 4823 | //
// UICollectionView+Pagination.swift
// mTV
//
// Created by Gaurav Rastogi on 6/26/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
protocol UICollectionViewPaginationDelegate{
func requestItemForPages(pageSet:NSSet) -> Void
func hasItemInPage(pageNo:Int) -> Bool
}
class UICollectionView_Pagination: UICollectionView {
var totalItemCount:Int!
var pageSize:Int!
var paginationDelegate:UICollectionViewPaginationDelegate?
var paginationEnabled:Bool!
private var shouldTrackScrollingVelocity:Bool!
private var lastContentOffset:Float!
private var lastOffsetCapturedTime:TimeInterval!
required override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize() -> Void{
totalItemCount = 0
pageSize = 0
paginationEnabled = false
shouldTrackScrollingVelocity = false
lastOffsetCapturedTime = 0
lastContentOffset = 0
}
func didScroll() -> Void {
if !paginationEnabled{
return
}
let distance = fabsf(Float(self.contentOffset.y) - lastContentOffset)
if shouldTrackScrollingVelocity == true && self.contentOffset.y > 0{
let currentTime = NSDate.timeIntervalSinceReferenceDate
//To calculate velocity We are capturing the distance scrolled in 3 seconds and if distance traversed is less than 10
//then we will make page request
if((currentTime - lastOffsetCapturedTime) > 3) {
if (distance < 10) {
shouldTrackScrollingVelocity = false;
self.requestPagesIfNeeded()
}
lastOffsetCapturedTime = currentTime;
}
}
lastContentOffset = Float(self.contentOffset.y);
}
func willBeginDragging() -> Void{
if !paginationEnabled{
return
}
shouldTrackScrollingVelocity = true
}
func endDragging(willDecelerate decelerate: Bool){
if !paginationEnabled{
return
}
if !decelerate && self.contentOffset.y > 0{
shouldTrackScrollingVelocity = true
self.requestPagesIfNeeded()
}
}
func willBeginDecelerating() -> Void{
if !paginationEnabled{
return
}
}
func endDecelerating() -> Void{
if !paginationEnabled{
return
}
if self.contentOffset.y > 0{
shouldTrackScrollingVelocity = true
self.requestPagesIfNeeded()
}
}
private func requestPagesIfNeeded() -> Bool{
if self.contentOffset.y <= 0 || paginationDelegate == nil{
return false
}
let currentPage = self.currentVisiblePage()
//process only if current page have something
if Int(currentPage * Int(pageSize)) < totalItemCount{
let pageSet = NSMutableSet()
if paginationDelegate!.hasItemInPage(pageNo: currentPage) == false{
pageSet.add(NSNumber(value: currentPage))
}
if Int(currentPage * Int(pageSize) + 1) <= totalItemCount{
if paginationDelegate!.hasItemInPage(pageNo: currentPage+1) == false{
pageSet.add(NSNumber(value: currentPage+1))
}
}
if currentPage > 0 && Int(Int(currentPage - 1) * Int(pageSize)) < totalItemCount{
if paginationDelegate!.hasItemInPage(pageNo: currentPage-1) == false{
pageSet.add(NSNumber(value: currentPage-1))
}
}
if pageSet.count > 0 {
paginationDelegate!.requestItemForPages(pageSet: pageSet)
return true
}
}
return false
}
private func currentVisiblePage() -> Int{
if !paginationEnabled{
return 0
}
let visibleCellsIndices:[UICollectionViewCell] = self.visibleCells
if visibleCellsIndices.count > 0{
if let lastVisibleCellIndex = self.indexPath(for: self.visibleCells.last!){
return self.pageNumberForItemAtRow(row: lastVisibleCellIndex.row)
}
}
return 0
}
private func pageNumberForItemAtRow(row:Int) -> Int{
if !paginationEnabled{
return 0
}
if pageSize > 0{
return (row / Int(pageSize!)) + 1
}
return 0
}
}
| mit | 19831328c69868702c88a0d32bde7f96 | 30.311688 | 129 | 0.585442 | 5.151709 | false | false | false | false |
cfraz89/RxSwift | Tests/RxSwiftTests/Anomalies.swift | 6 | 4326 | //
// Anomalies.swift
// Tests
//
// Created by Krunoslav Zaher on 10/22/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
import RxTest
import XCTest
import Dispatch
import class Foundation.Thread
/**
Makes sure github anomalies and edge cases don't surface up again.
*/
class AnomaliesTest: RxTest {
}
extension AnomaliesTest {
func test936() {
func performSharingOperatorsTest(share: @escaping (Observable<Int>) -> Observable<Int>) {
let queue = DispatchQueue(
label: "Test",
attributes: .concurrent // commenting this to use a serial queue remove the issue
)
for i in 0 ..< 10 {
let expectation = self.expectation(description: "wait until sequence completes")
queue.async {
let scheduler: SchedulerType = ConcurrentDispatchQueueScheduler(queue: queue, leeway: .milliseconds(5))
func makeSequence(label: String, period: RxTimeInterval) -> Observable<Int> {
return share(Observable<Int>.interval(period, scheduler: scheduler))
}
let _ = makeSequence(label: "main", period: 0.1)
.flatMapLatest { (index: Int) -> Observable<(Int, Int)> in
return makeSequence(label: "nested", period: 0.02).map { (index, $0) }
}
.take(10)
.mapWithIndex { ($1, $0.0, $0.1) }
.subscribe(
onNext: { _ in },
onCompleted: {
expectation.fulfill()
}
)
}
}
waitForExpectations(timeout: 10.0) { (e) in
XCTAssertNil(e)
}
}
for op in [
{ $0.shareReplay(1) },
{ $0.replay(1).refCount() },
{ $0.publish().refCount() },
{ $0.shareReplayLatestWhileConnected() }
] as [(Observable<Int>) -> Observable<Int>] {
performSharingOperatorsTest(share: op)
}
}
func testSeparationBetweenOnAndSubscriptionLocks() {
func performSharingOperatorsTest(share: @escaping (Observable<Int>) -> Observable<Int>) {
for i in 0 ..< 1 {
let expectation = self.expectation(description: "wait until sequence completes")
let queue = DispatchQueue(
label: "off main thread",
attributes: .concurrent
)
queue.async {
func makeSequence(label: String, period: RxTimeInterval) -> Observable<Int> {
let schedulerQueue = DispatchQueue(
label: "Test",
attributes: .concurrent
)
let scheduler: SchedulerType = ConcurrentDispatchQueueScheduler(queue: schedulerQueue, leeway: .milliseconds(0))
return share(Observable<Int>.interval(period, scheduler: scheduler))
}
let _ = Observable.of(
makeSequence(label: "main", period: 0.2),
makeSequence(label: "nested", period: 0.3)
).merge()
.take(1)
.subscribe(
onNext: { _ in
Thread.sleep(forTimeInterval: 0.4)
},
onCompleted: {
expectation.fulfill()
}
)
}
}
waitForExpectations(timeout: 2.0) { (e) in
XCTAssertNil(e)
}
}
for op in [
{ $0.shareReplay(1) },
{ $0.replay(1).refCount() },
{ $0.publish().refCount() },
{ $0.shareReplayLatestWhileConnected() }
] as [(Observable<Int>) -> Observable<Int>] {
performSharingOperatorsTest(share: op)
}
}
}
| mit | 465fa5f65a9861e5f1c19491ad3e49f1 | 34.162602 | 136 | 0.463584 | 5.332922 | false | true | false | false |
digoreis/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0163.xcplaygroundpage/Contents.swift | 1 | 14727 | /*:
# String Revision: Collection Conformance, C Interop, Transcoding
* Proposal: [SE-0163](0163-string-revision-1.md)
* Authors: [Ben Cohen](https://github.com/airspeedswift), [Dave Abrahams](http://github.com/dabrahams/)
* Review Manager: [John McCall](https://github.com/rjmccall)
* Status: **Active review (April 5...11, 2017)**
## Introduction
This proposal is to implement a subset of the changes from the [Swift 4
String
Manifesto](https://github.com/apple/swift/blob/master/docs/StringManifesto.md).
Specifically:
* Make `String` conform to `BidirectionalCollection`
* Make `String` conform to `RangeReplaceableCollection`
* Create a `Substring` type for `String.SubSequence`
* Create a `Unicode` protocol to allow for generic operations over both types.
* Consolidate on a concise set of C interop methods.
* Revise the transcoding infrastructure.
Other existing aspects of `String` remain unchanged for the purposes of this
proposal.
## Motivation
This proposal follows up on a number of recommendations found in the manifesto:
`Collection` conformance was dropped from `String` in Swift 2. After
reevaluation, the feeling is that the minor semantic discrepancies (mainly with
`RangeReplaceableCollection`) are outweighed by the significant benefits of
restoring these conformances. For more detail on the reasoning, see
[here](https://github.com/apple/swift/blob/master/docs/StringManifesto.md#string-should-be-a-collection-of-characters-again)
While it is not a collection, the Swift 3 string does have slicing operations.
`String` is currently serving as its own subsequence, allowing substrings
to share storage with their "owner". This can lead to memory leaks when small substrings of larger
strings are stored long-term (see [here](https://github.com/apple/swift/blob/master/docs/StringManifesto.md#substrings)
for more detail on this problem). Introducing a separate type of `Substring` to
serve as `String.Subsequence` is recommended to resolve this issue, in a similar
fashion to `ArraySlice`.
As noted in the manifesto, support for interoperation with nul-terminated C
strings in Swift 3 is scattered and incoherent, with 6 ways to transform a C
string into a `String` and four ways to do the inverse. These APIs should be
replaced with a simpler set of methods on `String`.
## Proposed solution
A new type, `Substring`, will be introduced. Similar to `ArraySlice` it will
be documented as only for short- to medium-term storage:
> **Important**
>
> Long-term storage of `Substring` instances is discouraged. A substring holds a
> reference to the entire storage of a larger string, not just to the portion it
> presents, even after the original string’s lifetime ends. Long-term storage of
> a substring may therefore prolong the lifetime of elements that are no longer
> otherwise accessible, which can appear to be memory leakage.
Aside from minor differences, such as having a `SubSequence` of `Self` and a
larger size to describe the range of the subsequence, `Substring`
will be near-identical from a user perspective.
In order to be able to write extensions accross both `String` and `Substring`,
a new `Unicode` protocol to which the two types will conform will be
introduced. For the purposes of this proposal, `Unicode` will be defined as a
protocol to be used whenver you would previously extend `String`. It should be
possible to substitute `extension Unicode { ... }` in Swift 4 wherever
`extension String { ... }` was written in Swift 3, with one exception: any
passing of `self` into an API that takes a concrete `String` will need to be
rewritten as `String(self)`. If `Self` is a `String` then this should
effectively optimize to a no-op, whereas if `Self` is a `Substring` then this
will force a copy, helping to avoid the "memory leak" problems described above.
The exact nature of the protocol – such as which methods should be protocol
requirements vs which can be implemented as protocol extensions, are considered
implementation details and so not covered in this proposal.
`Unicode` will conform to `BidirectionalCollection`.
`RangeReplaceableCollection` conformance will be added directly onto the
`String` and `Substring` types, as it is possible future `Unicode`-conforming
types might not be range-replaceable (e.g. an immutable type that wraps
a `const char *`).
The C string interop methods will be updated to those described
[here](https://github.com/apple/swift/blob/master/docs/StringManifesto.md#c-string-interop):
a single `withCString` operation and two `init(cString:)` constructors, one for
UTF8 and one for arbitrary encodings. The primary change is to remove
"non-repairing" variants of construction from nul-terminated C strings. In both
of the construction APIs, any invalid encoding sequence detected will have its
longest valid prefix replaced by `U+FFFD`, the Unicode replacement character,
per the Unicode specification. This covers the common case. The replacement is
done physically in the underlying storage and the validity of the result is
recorded in the String's encoding such that future accesses need not be slowed
down by possible error repair separately. Construction that is aborted when
encoding errors are detected can be accomplished using APIs on the encoding.
The current transcoding support will be updated to improve usability and
performance. The primary changes will be:
- to allow transcoding directly from one encoding to another without having
to triangulate through an intermediate scalar value
- to add the ability to transcode an input collection in reverse, allowing the
different views on `String` to be made bi-directional
- to have decoding take a collection rather than an iterator, and return an
index of its progress into the source, allowing that method to be static
The standard library currently lacks a `Latin1` codec, so a
`enum Latin1: UnicodeEncoding` type will be added.
## Detailed design
The following additions will be made to the standard library:
```swift
protocol Unicode: BidirectionalCollection {
// Implementation detail as described above
}
extension String: Unicode, RangeReplaceableCollection {
typealias SubSequence = Substring
}
struct Substring: Unicode, RangeReplaceableCollection {
typealias SubSequence = Substring
// near-identical API surface area to String
}
```
The subscript operations on `String` will be amended to return `Substring`:
```swift
struct String {
subscript(bounds: Range<String.Index>) -> Substring { get }
subscript(bounds: ClosedRange<String.Index>) -> Substring { get }
}
```
Note that properties or methods that due to their nature create new `String`
storage (such as `lowercased()`) will _not_ change.
C string interop will be consolidated on the following methods:
```swift
extension String {
/// Constructs a `String` having the same contents as `nulTerminatedUTF8`.
///
/// - Parameter nulTerminatedUTF8: a sequence of contiguous UTF-8 encoded
/// bytes ending just before the first zero byte (NUL character).
init(cString nulTerminatedUTF8: UnsafePointer<CChar>)
/// Constructs a `String` having the same contents as `nulTerminatedCodeUnits`.
///
/// - Parameter nulTerminatedCodeUnits: a sequence of contiguous code units in
/// the given `encoding`, ending just before the first zero code unit.
/// - Parameter encoding: describes the encoding in which the code units
/// should be interpreted.
init<Encoding: UnicodeEncoding>(
cString nulTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
encoding: Encoding)
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result
}
```
Additionally, the current ability to pass a Swift `String` into C methods that
take a C string will remain as-is.
A new protocol, `UnicodeEncoding`, will be added to replace the current
`UnicodeCodec` protocol:
```swift
public enum UnicodeParseResult<T, Index> {
/// Indicates valid input was recognized.
///
/// `resumptionPoint` is the end of the parsed region
case valid(T, resumptionPoint: Index) // FIXME: should these be reordered?
/// Indicates invalid input was recognized.
///
/// `resumptionPoint` is the next position at which to continue parsing after
/// the invalid input is repaired.
case error(resumptionPoint: Index)
/// Indicates that there was no more input to consume.
case emptyInput
/// If any input was consumed, the point from which to continue parsing.
var resumptionPoint: Index? {
switch self {
case .valid(_,let r): return r
case .error(let r): return r
case .emptyInput: return nil
}
}
}
/// An encoding for text with UnicodeScalar as a common currency type
public protocol UnicodeEncoding {
/// The maximum number of code units in an encoded unicode scalar value
static var maxLengthOfEncodedScalar: Int { get }
/// A type that can represent a single UnicodeScalar as it is encoded in this
/// encoding.
associatedtype EncodedScalar : EncodedScalarProtocol
/// Produces a scalar of this encoding if possible; returns `nil` otherwise.
static func encode<Scalar: EncodedScalarProtocol>(
_:Scalar) -> Self.EncodedScalar?
/// Parse a single unicode scalar forward from `input`.
///
/// - Parameter knownCount: a number of code units known to exist in `input`.
/// **Note:** passing a known compile-time constant is strongly advised,
/// even if it's zero.
static func parseScalarForward<C: Collection>(
_ input: C, knownCount: Int /* = 0, via extension */
) -> ParseResult<EncodedScalar, C.Index>
where C.Iterator.Element == EncodedScalar.Iterator.Element
/// Parse a single unicode scalar in reverse from `input`.
///
/// - Parameter knownCount: a number of code units known to exist in `input`.
/// **Note:** passing a known compile-time constant is strongly advised,
/// even if it's zero.
static func parseScalarReverse<C: BidirectionalCollection>(
_ input: C, knownCount: Int /* = 0 , via extension */
) -> ParseResult<EncodedScalar, C.Index>
where C.Iterator.Element == EncodedScalar.Iterator.Element
}
/// Parsing multiple unicode scalar values
extension UnicodeEncoding {
@discardableResult
public static func parseForward<C: Collection>(
_ input: C,
repairingIllFormedSequences makeRepairs: Bool = true,
into output: (EncodedScalar) throws->Void
) rethrows -> (remainder: C.SubSequence, errorCount: Int)
@discardableResult
public static func parseReverse<C: BidirectionalCollection>(
_ input: C,
repairingIllFormedSequences makeRepairs: Bool = true,
into output: (EncodedScalar) throws->Void
) rethrows -> (remainder: C.SubSequence, errorCount: Int)
where C.SubSequence : BidirectionalCollection,
C.SubSequence.SubSequence == C.SubSequence,
C.SubSequence.Iterator.Element == EncodedScalar.Iterator.Element
}
```
`UnicodeCodec` will be updated to refine `UnicodeEncoding`, and all
existing codecs will conform to it.
Note, depending on whether this change lands before or after some of the
generics features, generic `where` clauses may need to be added temporarily.
## Source compatibility
Adding collection conformance to `String` should not materially impact source
stability as it is purely additive: Swift 3's `String` interface currently
fulfills all of the requirements for a bidirectional range replaceable
collection.
Altering `String`'s slicing operations to return a different type is source
breaking. The following mitigating steps are proposed:
- Add a deprecated subscript operator that will run in Swift 3 compatibility
mode and which will return a `String` not a `Substring`.
- Add deprecated versions of all current slicing methods to similarly return a
`String`.
i.e.:
```swift
extension String {
@available(swift, obsoleted: 4)
subscript(bounds: Range<Index>) -> String {
return String(characters[bounds])
}
@available(swift, obsoleted: 4)
subscript(bounds: ClosedRange<Index>) -> String {
return String(characters[bounds])
}
}
```
In a review of 77 popular Swift projects found on GitHub, these changes
resolved any build issues in the 12 projects that assumed an explicit `String`
type returned from slicing operations.
Due to the change in internal implementation, this means that these operations
will be _O(n)_ rather than _O(1)_. This is not expected to be a major concern,
based on experiences from a similar change made to Java, but projects will be
able to work around performance issues without upgrading to Swift 4 by
explicitly typing slices as `Substring`, which will call the Swift 4 variant,
and which will be available but not invoked by default in Swift 3 mode.
The C string interoperability methods outside the ones described in the
detailed design will remain in Swift 3 mode, be deprecated in Swift 4 mode, and
be removed in a subsequent release. `UnicodeCodec` will be similarly deprecated.
## Effect on ABI stability
As a fundamental currency type for Swift, it is essential that the `String`
type (and its associated subsequence) is in a good long-term state before being
locked down when Swift declares ABI stability. Shrinking the size of `String`
to be 64 bits is an important part of this.
## Effect on API resilience
Decisions about the API resilience of the `String` type are still to be
determined, but are not adversely affected by this proposal.
## Alternatives considered
For a more in-depth discussion of some of the trade-offs in string design, see
the manifesto and associated [evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170116/thread.html#30497).
This proposal does not yet introduce an implicit conversion from `Substring` to
`String`. The decision on whether to add this will be deferred pending feedback
on the initial implementation. The intention is to make a preview toolchain
available for feedback, including on whether this implicit conversion is
necessary, prior to the release of Swift 4.
Several of the types related to `String`, such as the encodings, would ideally
reside inside a namespace rather than live at the top level of the standard
library. The best namespace for this is probably `Unicode`, but this is also
the name of the protocol. At some point if we gain the ability to nest enums
and types inside protocols, they should be moved there. Putting them inside
`String` or some other enum namespace is probably not worthwhile in the
mean-time.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | 5a69d52fbb537e4cb397b6d7cda821a2 | 41.186246 | 138 | 0.763567 | 4.36237 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/DeDaoSwift/Home/View/DDHomeStorytellCell.swift | 1 | 4667 | //
// DDHomeStorytellCell.swift
// DeDaoSwift
//
// Created by niuting on 2017/3/15.
// Copyright © 2017年 niuNaruto. All rights reserved.
//
import UIKit
class DDHomeStorytellCell: DDBaseTableViewCell {
override func setCellsViewModel(_ model: Any?) {
if let modelT = model as? DDHomeStorytellDataModel {
leftImage.kf.setImage(with: URL(string: modelT.m_img))
timerLabel.text = timeFormatted(modelT.m_duration)
moneyLabel.text = "¥\(modelT.m_price)"
if let name = modelT.m_info?.name{
subDescLabel.text = "\(name) 陈述"
}
titleLabel.text = modelT.m_title
infoLable.text = modelT.m_description
}
}
lazy var leftImage : UIImageView = {
let leftImage = UIImageView()
return leftImage
}()
lazy var subDescLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.init("#999999")
titleLabel.font = UIFont.systemFont(ofSize: 10)
return titleLabel
}()
lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.init("#333333")
titleLabel.font = UIFont.systemFont(ofSize: 15)
return titleLabel
}()
lazy var timerLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.init("#999999")
titleLabel.font = UIFont.systemFont(ofSize: 10)
return titleLabel
}()
lazy var infoLable : UILabel = {
let titleLabel = UILabel()
titleLabel.numberOfLines = 2
titleLabel.textColor = UIColor.init("#999999")
titleLabel.font = UIFont.systemFont(ofSize: 10)
return titleLabel
}()
lazy var moneyLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.orange
titleLabel.font = UIFont.systemFont(ofSize: 10)
return titleLabel
}()
lazy var buyButton : UIButton = {
let buyButton = UIButton()
buyButton.layer.borderColor = UIColor.orange.cgColor
buyButton.layer.borderWidth = 0.8
buyButton.layer.cornerRadius = 12.0
buyButton.layer.masksToBounds = true
buyButton.setTitle("购买", for: .normal)
buyButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
buyButton.setTitleColor(UIColor.orange, for: .normal)
return buyButton
}()
override func setUI() {
contentView.addSubview(leftImage)
contentView.addSubview(timerLabel)
contentView.addSubview(moneyLabel)
contentView.addSubview(infoLable)
contentView.addSubview(titleLabel)
contentView.addSubview(subDescLabel)
contentView.addSubview(buyButton)
}
override func setLayout() {
leftImage.snp.makeConstraints { (make) in
make.top.left.equalToSuperview().offset(10)
make.bottom.equalToSuperview().offset(-10)
make.height.equalTo(120)
make.width.equalTo(90)
}
subDescLabel.snp.makeConstraints { (make) in
make.left.equalTo(leftImage.snp.right).offset(10)
make.bottom.equalTo(contentView.snp.centerY).offset(-6)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(subDescLabel.snp.left)
make.bottom.equalTo(subDescLabel.snp.top).offset(-6)
}
infoLable.snp.makeConstraints { (make) in
make.top.equalTo(leftImage.snp.centerY).offset(0)
make.right.equalToSuperview().offset(-10)
make.left.equalTo(subDescLabel.snp.left)
}
moneyLabel.snp.makeConstraints { (make) in
make.left.equalTo(subDescLabel.snp.left)
make.bottom.equalTo(leftImage.snp.bottom).offset(-10)
}
timerLabel.snp.makeConstraints { (make) in
make.left.equalTo(moneyLabel.snp.right).offset(15)
make.centerY.equalTo(moneyLabel.snp.centerY)
}
buyButton.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-10)
make.centerY.equalTo(moneyLabel.snp.centerY)
make.width.equalTo(60)
}
}
func timeFormatted(_ seconds : CGFloat ) -> String {
let s : Int = Int(seconds) / 60
let minutes : Int = (Int(seconds) / 60) % 60;
return "时长:\(minutes)分\(s)秒"
}
}
| mit | ee9e1d4497937db03ba45b32d7fead90 | 29.768212 | 67 | 0.586096 | 4.6 | false | false | false | false |
san2ride/NavColonialStock | ColonialStockTransfer/ColonialStockTransfer/DashBoardViewController.swift | 1 | 1410 | //
// DashBoardViewController.swift
// ColonialStockTransfer
//
// Created by don't touch me on 10/13/16.
// Copyright © 2016 trvl, LLC. All rights reserved.
//
import UIKit
import Firebase
class DashBoardViewController: UIViewController {
@IBOutlet weak var bearBullImage: UIImageView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var nav = self.navigationController?.navigationItem
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "colonialnewlogo16")
imageView.image = image
navigationItem.titleView = imageView
}
override func viewDidLoad() {
super.viewDidLoad()
var imagesArray = [UIImage]()
for i in 1...4 {
if let image = UIImage(named: "\(i)bb") {
imagesArray.append(image)
print("bb_\(i)")
}
}
bearBullImage.animationImages = imagesArray
bearBullImage.animationDuration = 1.5
bearBullImage.animationRepeatCount = 0
bearBullImage.startAnimating()
}
}
| mit | 7bd838ce1b98531d3c0842fde57d5a55 | 19.720588 | 86 | 0.540809 | 5.068345 | false | false | false | false |
shu223/Pulsator | Pulsator.playground/Pages/MapAnnotation.xcplaygroundpage/Contents.swift | 1 | 2188 | //: [Previous](@previous)
import UIKit
import XCPlayground
import Pulsator
import MapKit
class AnnotationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
addHalo()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addHalo() {
let pulsator = Pulsator()
pulsator.position = center
pulsator.numPulse = 5
pulsator.radius = 40
pulsator.animationDuration = 3
pulsator.backgroundColor = UIColor(red: 0, green: 0.455, blue: 0.756, alpha: 1).cgColor
layer.addSublayer(pulsator)
pulsator.start()
}
}
class MapViewController: UIViewController, MKMapViewDelegate {
let mapView = MKMapView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
mapView.frame = view.bounds
mapView.delegate = self
let delta = 5.0
var region = MKCoordinateRegion()
region.center.latitude = 50.0
region.center.longitude = -100.0
region.span.latitudeDelta = delta
region.span.longitudeDelta = delta
mapView.setRegion(region, animated: true)
view.addSubview(mapView)
view.backgroundColor = UIColor.yellow
addAnnotations()
}
private func addAnnotations() {
let point = MKPointAnnotation()
point.coordinate = CLLocationCoordinate2DMake(50, -100)
point.title = "TITLE"
point.subtitle = "Subtitle"
mapView.addAnnotation(point)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !annotation.isKind(of: MKUserLocation.classForCoder()) else { return nil }
return AnnotationView(annotation: annotation, reuseIdentifier: "PulsatorDemoAnnotation")
}
}
let controller = MapViewController()
XCPlaygroundPage.currentPage.liveView = controller.view
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [Next](@next)
| mit | f5bdf1be3ece4b0b562ebe7c40a9ddfb | 28.567568 | 96 | 0.658592 | 4.851441 | false | false | false | false |
swift-tweets/tweetup-kit | Sources/TweetupKit/OAuthCredential.swift | 1 | 832 | import Foundation
public struct OAuthCredential {
public let consumerKey: String
public let consumerSecret: String
public let oauthToken: String
public let oauthTokenSecret: String
public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.oauthToken = oauthToken
self.oauthTokenSecret = oauthTokenSecret
}
}
extension OAuthCredential: Equatable {
public static func ==(lhs: OAuthCredential, rhs: OAuthCredential) -> Bool {
return lhs.consumerKey == rhs.consumerKey
&& lhs.consumerSecret == rhs.consumerSecret
&& lhs.oauthToken == rhs.oauthToken
&& lhs.oauthTokenSecret == rhs.oauthTokenSecret
}
}
| mit | 54573623dd66875af43c2112a0601969 | 33.666667 | 108 | 0.694712 | 5.583893 | false | false | false | false |
srxboys/RXSwiftExtention | RXSwiftExtention/BaseController/ViewModel/RXTabBarDownloadImage.swift | 1 | 1896 | //
// RXTabBarDownloadImage.swift
// RXSwiftExtention
//
// Created by srx on 2017/3/29.
// Copyright © 2017年 https://github.com/srxboys. All rights reserved.
//
/*
* tabBar 网络下载 (后期维护)
*/
import UIKit
class RXTabBarDownloadImage: NSObject {
fileprivate var queue : OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.waitUntilAllOperationsAreFinished()
return queue
}()
//接口值
fileprivate var dataArray = [[String:String]]()
//下载后转换的模型 的数组
fileprivate var downFinallArray : [RXTabBarModel] = [RXTabBarModel]()
}
// MARK: - 下载操作
extension RXTabBarDownloadImage {
//开始下载
fileprivate func recoveryDownload() {
downFinallArray = [RXTabBarModel]()
var nomalOperation : BlockOperation?
var operationsArray = [BlockOperation]()
for i in 0..<dataArray.count {
guard dataArray[i].isEmpty != false else {
//并告诉下载者 下载失败
return
}
let dict = dataArray[i] as [String: String]
let tabBarModel = RXTabBarModel()
//这里我没有写string的key,下面是做个样式
guard (tabBarModel.noamlImgData?.length)! > 0 || (tabBarModel.selectedImgData?.length)! > 0 else {
//并告诉下载者 下载失败
return
}
}
let activtyOp = BlockOperation{() -> Void in
//这里code
}
}
}
// MARK: - 外部调用
extension RXTabBarDownloadImage {
func downloadTabBar(array : NSArray) {
guard array.count > 0 else {
return
}
}
}
| mit | 1222bbb4231d084dc3e9f4ba20904ae3 | 21.74026 | 110 | 0.541405 | 4.291667 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCWalletTransactionsPageViewController.swift | 2 | 2503 | //
// NCWalletTransactionsPageViewController.swift
// Neocom
//
// Created by Artem Shimanski on 19.03.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import CloudData
class NCWalletTransactionsPageViewController: NCPageViewController {
private var accountChangeObserver: NotificationObserver?
override func viewDidLoad() {
super.viewDidLoad()
let label = NCNavigationItemTitleLabel(frame: CGRect(origin: .zero, size: .zero))
label.set(title: NSLocalizedString("Wallet Transactions", comment: ""), subtitle: nil)
navigationItem.titleView = label
accountChangeObserver = NotificationCenter.default.addNotificationObserver(forName: .NCCurrentAccountChanged, object: nil, queue: nil) { [weak self] _ in
self?.reload()
}
reload()
}
private var errorLabel: UILabel? {
didSet {
oldValue?.removeFromSuperview()
if let label = errorLabel {
view.addSubview(label)
label.frame = view.bounds.insetBy(UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0))
}
}
}
private func reload() {
guard let account = NCAccount.current else {return}
let dataManager = NCDataManager(account: account)
let progress = NCProgressHandler(viewController: self, totalUnitCount: 2)
progress.progress.perform {
dataManager.corpWalletBalance().then(on: .main) { result -> Void in
guard let balance = result.value?.reduce(0, { $0 + $1.balance }) else {return}
let label = self.navigationItem.titleView as? NCNavigationItemTitleLabel
label?.set(title: NSLocalizedString("Wallet Journal", comment: ""), subtitle: NCUnitFormatter.localizedString(from: balance, unit: .isk, style: .full))
}
}.then {
return progress.progress.perform {
dataManager.divisions().then { result in
return result.value?.wallet?.filter {$0.division != nil}
}
}
}.then(on: .main) { result in
guard let result = result, !result.isEmpty else {throw NCDataManagerError.noResult}
self.viewControllers = result.map { division in
let controller = self.storyboard!.instantiateViewController(withIdentifier: "NCWalletTransactionsViewController") as! NCWalletTransactionsViewController
controller.wallet = .corporation(division)
return controller
}
self.errorLabel = nil
}.catch(on: .main) { error in
self.errorLabel = NCTableViewBackgroundLabel(text: error.localizedDescription)
}.finally(on: .main) {
progress.finish()
}
}
}
| lgpl-2.1 | e1a9f387d7fd1d5508a8cbba60e45dd8 | 32.810811 | 157 | 0.727018 | 4.074919 | false | false | false | false |
simonnarang/Fandom-IOS | Fandomm/SearchTableViewController.swift | 1 | 1413 | //
// SearchTableViewController.swift
// Fandomm
//
// Created by Simon Narang on 11/23/15.
// Copyright © 2015 Simon Narang. All rights reserved.
//
import UIKit
class SearchTableViewController: UITableViewController {
var usernameTwoTextTwo = String()
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
self.navigationController?.navigationBar.tintColor = UIColor.purpleColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.purpleColor()]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
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 {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
}
| unlicense | 9c87077b48aeee2e551583734737077b | 35.205128 | 126 | 0.716006 | 5.834711 | false | false | false | false |
ello/ello-ios | Sources/Model/UserFlag.swift | 1 | 787 | ////
/// UserFlag.swift
//
enum UserFlag: String {
case spam = "Spam"
case violence = "Violence"
case copyright = "Copyright infringement"
case threatening = "Threatening"
case hate = "Hate Speech"
case adult = "NSFW Content"
case dontLike = "I don't like it"
var name: String {
return self.rawValue
}
var kind: String {
switch self {
case .spam: return "spam"
case .violence: return "violence"
case .copyright: return "copyright"
case .threatening: return "threatening"
case .hate: return "hate_speech"
case .adult: return "adult"
case .dontLike: return "offensive"
}
}
static let all = [spam, violence, copyright, threatening, hate, adult, dontLike]
}
| mit | 19b62f80b991fa1d6251247923337397 | 24.387097 | 84 | 0.602287 | 3.820388 | false | false | false | false |
ProcedureKit/ProcedureKit | Sources/ProcedureKit/PendingEvent.swift | 2 | 4906 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import Dispatch
/// `PendingEvent` encapsulates a reference to a future `Procedure` event, and can be used
/// to ensure that asynchronous tasks are executed to completion *before* the future event.
///
/// While a reference to the `PendingEvent` exists, the event will not occur.
///
/// You cannot instantiate your own `PendingEvent` instances - only the framework
/// itself creates and provides (in certain circumstances) PendingEvents.
///
/// A common use-case is when handling a WillExecute or WillFinish observer callback.
/// ProcedureKit will provide your observer with a `PendingExecuteEvent` or a `PendingFinishEvent`.
///
/// If you must dispatch an asynchronous task from within your observer, but want to
/// ensure that the observed `Procedure` does not execute / finish until your asynchronous task
/// completes, you can use the Pending(Execute/Finish)Event like so:
///
/// ```swift
/// procedure.addWillFinishObserver { procedure, errors, pendingFinish in
/// DispatchQueue.global().async {
/// pendingFinish.doBeforeEvent {
/// // do something asynchronous
/// // this block is guaranteed to complete before the procedure finishes
/// }
// }
/// }
/// ```
///
/// Some of the built-in `Procedure` functions take an optional "before:" parameter,
/// to which a `PendingEvent` can be directly passed. For example:
///
/// ```swift
/// procedure.addWillFinishObserver { procedure, errors, pendingFinish in
/// // produce a new operation before the procedure finishes
/// procedure.produce(BlockOperation { /* do something */ }, before: pendingFinish)
/// }
/// ```
///
final public class PendingEvent: CustomStringConvertible {
public enum Kind: CustomStringConvertible {
case postDidAttach
case addOperation
case postDidAddOperation
case execute
case postDidExecute
case postDidCancel
case finish
case postDidFinish
public var description: String {
switch self {
case .postDidAttach: return "PostDidAttach"
case .addOperation: return "AddOperation"
case .postDidAddOperation: return "PostAddOperation"
case .execute: return "Execute"
case .postDidExecute: return "PostExecute"
case .postDidCancel: return "PostDidCancel"
case .finish: return "Finish"
case .postDidFinish: return "PostFinish"
}
}
}
internal let event: Kind
internal let group: DispatchGroup
fileprivate let procedure: ProcedureProtocol
private let isDerivedEvent: Bool
internal init(forProcedure procedure: ProcedureProtocol, withGroup group: DispatchGroup = DispatchGroup(), withEvent event: Kind) {
self.group = group
self.procedure = procedure
self.event = event
self.isDerivedEvent = false
group.enter()
}
// Ensures that a block is executed prior to the event described by the `PendingEvent`
public func doBeforeEvent(block: () -> Void) {
group.enter()
block()
group.leave()
}
// Ensures that the call to this function will occur prior to the event described by the `PendingEvent`
public func doThisBeforeEvent() {
group.enter()
group.leave()
}
deinit {
debugProceed()
group.leave()
}
private func debugProceed() {
(procedure as? Procedure)?.log.verbose.message("(\(self)) is ready to proceed")
}
public var description: String {
return "Pending\(event.description) for: \(procedure.procedureName)"
}
}
internal extension PendingEvent {
static let postDidAttach: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAttach) }
static let addOperation: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .addOperation) }
static let postDidAdd: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAddOperation) }
static let execute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .execute) }
static let postDidExecute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidExecute) }
static let postDidCancel: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidCancel) }
static let finish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .finish) }
static let postFinish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidFinish) }
}
public typealias PendingExecuteEvent = PendingEvent
public typealias PendingFinishEvent = PendingEvent
public typealias PendingAddOperationEvent = PendingEvent
| mit | 788489c5acfa8c69b49ed6fc67c7ad52 | 38.556452 | 135 | 0.685423 | 4.649289 | false | false | false | false |
usharif/GrapeVyne | GrapeVyne/GameViewController.swift | 1 | 11575 | //
// GameViewController.swift
// StoryApp
//
// Created by Umair Sharif on 12/28/16.
// Copyright © 2016 usharif. All rights reserved.
//
import UIKit
import Koloda
import TKSubmitTransitionSwift3
// MARK: Global properties
// Color Config
private let viewBackgroundColor = UIColor.black
private let cardViewTextColor = UIColor.white
private let timerLabelTextColor = UIColor.white
private let countDownLabelTextColor = UIColor.white
private let timeEndingWarningColor = CustomColor.red
// Card Config
let cardCornerRadius : CGFloat = 20
// Animation Times
private let instructionAnimationDuration = 0.8
private let countDownAnimationDuration = 0.4
private let gameTimerAnimationDuration = 0.2
private let revealAnimationDuration = 0.3
// Taptic Engine
private let cardSwipeTaptic = UISelectionFeedbackGenerator()
private let gameFinishTaptic = UINotificationFeedbackGenerator()
//Swipe Sensitivity
private let swipeSensitivityPercentage : CGFloat = 20/100
class GameViewController: UIViewController {
var dataSource : [CardView]?
var gameTime = 60
var gameTimer = Timer()
var countDownTime = 5
var countDownTimer = Timer()
var blurEffectView = UIVisualEffectView()
let instructionView = Bundle.main.loadNibNamed("Instruction", owner: nil, options: nil)?[0] as! UIView
var gameSetArray = [Story]()
// MARK: IBOutlets
@IBOutlet weak var kolodaView: KolodaView!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var countDownLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = viewBackgroundColor
modalTransitionStyle = appModalTransitionStyle
dataSource = getDataSource()
kolodaView.dataSource = self
kolodaView.delegate = self
configureViewUI()
instructionView.frame = view.bounds
view.insertSubview(instructionView, belowSubview: countDownLabel)
//game starts with this completion handler
countDownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {started in self.updateCountDownTimer()})
}
// MARK: IBActions
// MARK: Private functions
private func configureViewUI() {
kolodaView.layer.cornerRadius = cardCornerRadius
configureCardBlurEffectView()
countDownLabel.textColor = countDownLabelTextColor
countDownLabel.text = String(countDownTime)
timerLabel.textColor = timerLabelTextColor
updateTimerLabel()
}
private func configureCardBlurEffectView() {
let blurEffect = UIBlurEffect(style: .light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.layer.cornerRadius = kolodaView.layer.cornerRadius
blurEffectView.layer.masksToBounds = true
blurEffectView.frame = kolodaView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
kolodaView.addSubview(blurEffectView)
}
private func getDataSource() -> [CardView] {
var tempArray = gameSetArray
var arrayOfCardViews : [CardView] = []
while tempArray.count > 0 {
let randomIndex = Int(arc4random_uniform(UInt32(tempArray.count)))
let cardView = configureCardUI(story: tempArray[randomIndex], arrayCount: tempArray.count)
arrayOfCardViews.append(cardView)
tempArray.remove(at: randomIndex)
}
return arrayOfCardViews
}
private func configureCardUI(story: Story, arrayCount: Int) -> CardView {
let cardView = Bundle.main.loadNibNamed("CardView", owner: nil, options: nil)?[0] as! CardView
cardView.story = story
cardView.titleLabel.text = story.title
cardView.layer.cornerRadius = cardCornerRadius
cardView.titleLabel.textColor = cardViewTextColor
return cardView
}
private func updateCountDownTimer() {
if countDownTime > 1 {
countDownTime -= 1
if countDownTime <= 2 {
//remove instructions
UIView.animate(withDuration: instructionAnimationDuration, animations: {self.instructionView.alpha = 0}, completion: {finished in self.instructionView.removeFromSuperview()})
}
countDownLabel.pushTransitionFromBottomWith(duration: countDownAnimationDuration)
countDownLabel.text = String(countDownTime)
} else {
//end timer
//start game
startGame()
}
}
private func updateGameTimer() {
countDownLabel.isHidden = true
UIView.animate(withDuration: revealAnimationDuration, animations: {self.blurEffectView.effect = nil}, completion: {finished in self.blurEffectView.removeFromSuperview()})
if gameTime > 0 {
gameTime -= 1
updateTimerLabel()
} else {
//end game
endGame()
}
}
private func updateTimerLabel() {
if gameTime < 11 {
timerLabel.textColor = timeEndingWarningColor
}
var concatStr = ""
if gameTime % 60 < 10 {
concatStr = "0"
}
let minutes = String(gameTime / 60)
let seconds = String(gameTime % 60)
//timerLabel.pushTransitionFromBottomWith(duration: gameTimerAnimationDuration)
timerLabel.text = "\(minutes):\(concatStr)\(seconds)"
}
// MARK: Class functions
func startGame() {
countDownLabel.pushTransitionFromBottomWith(duration: countDownAnimationDuration)
countDownLabel.text = "GO!"
countDownTimer.invalidate()
gameTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {started in self.updateGameTimer()})
}
func endGame() {
gameTimer.invalidate()
gameFinishTaptic.notificationOccurred(.success)
let resultTableVC = storyboard?.instantiateViewController(withIdentifier: "ResultTableViewController") as! ResultTableViewController
resultTableVC.modalTransitionStyle = self.modalTransitionStyle
present(resultTableVC, animated: true, completion: nil)
}
}
// MARK: Animations
extension UIView: CAAnimationDelegate {
func pushTransitionFromTopWith(duration: CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionPush
animation.subtype = kCATransitionFromTop
animation.duration = duration
self.layer.add(animation, forKey: kCATransitionPush)
}
func pushTransitionFromBottomWith(duration: CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionPush
animation.subtype = kCATransitionFromBottom
animation.duration = duration
self.layer.add(animation, forKey: kCATransitionPush)
}
}
// MARK: KolodaViewDelegate
extension GameViewController: KolodaViewDelegate {
func kolodaDidRunOutOfCards(_ koloda: KolodaView) {
endGame()
}
func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
}
func koloda(_ koloda: KolodaView, allowedDirectionsForIndex index: Int) -> [SwipeResultDirection] {
//add .up to pass card
return [.left, .right]
}
func koloda(_ koloda: KolodaView, didSwipeCardAt index: Int, in direction: SwipeResultDirection) {
if let cardAtIndex = dataSource?[index], let story = cardAtIndex.story, let storyID = story.id {
let userAnswer = isUserCorrectFor(factValue: story.fact, swipeDirection: direction)
performSwipeResultAnimationFor(userAns: userAnswer)
storyRepo.arrayOfSwipedStories.append(story)
updateResultArrayFor(userAns: userAnswer, story: story)
CoreDataManager.deleteObjectBy(id: storyID)
}
}
func kolodaShouldTransparentizeNextCard(_ koloda: KolodaView) -> Bool {
return false
}
func koloda(_ koloda: KolodaView, shouldDragCardAt index: Int) -> Bool {
cardSwipeTaptic.selectionChanged()
return true
}
func kolodaSwipeThresholdRatioMargin(_ koloda: KolodaView) -> CGFloat? {
return swipeSensitivityPercentage
}
// MARK: KolodaViewDelegate private functions
private func isUserCorrectFor(factValue: Bool, swipeDirection: SwipeResultDirection) -> Bool {
var isUserCorrect = false
switch swipeDirection {
case .right:
if factValue {
//User action correct
isUserCorrect = true
} else {
//User action incorrect
isUserCorrect = false
}
case .left:
if factValue {
//User action incorrect
isUserCorrect = false
} else {
//User action correct
isUserCorrect = true
}
default:
break
}
return isUserCorrect
}
private func performSwipeResultAnimationFor(userAns: Bool) {
let resultView = Bundle.main.loadNibNamed("SwipeOverlayResultView", owner: nil, options: nil)?[0] as! SwipeOverlayResultView
resultView.setupAccordingTo(userAnswer: userAns)
resultView.alpha = 0
resultView.center = kolodaView.center
self.view.addSubview(resultView)
UIView.animate(withDuration: revealAnimationDuration, delay: 0, options: .curveEaseOut,
animations: {
resultView.alpha = 1},
completion: { finished in
UIView.animate(withDuration: revealAnimationDuration * 2, delay: 0,
animations: {
resultView.alpha = 0},
completion: { finished in
resultView.removeFromSuperview()
})
})
}
private func updateResultArrayFor(userAns: Bool, story: Story) {
if (userAns) {
storyRepo.arrayOfCorrectStories.append(story)
} else {
storyRepo.arrayOfIncorrectStories.append(story)
}
}
}
// MARK: KolodaViewDataSource
extension GameViewController: KolodaViewDataSource {
func kolodaSpeedThatCardShouldDrag(_ koloda: KolodaView) -> DragSpeed {
return .default
}
func kolodaNumberOfCards(_ koloda:KolodaView) -> Int {
return dataSource!.count
}
func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
return dataSource![index]
}
}
// MARK: UIViewControllerTransitioningDelegate
extension GameViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let fadeInAnimator = TKFadeInAnimator()
return fadeInAnimator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let fadeInAnimator = TKFadeInAnimator()
return fadeInAnimator
}
}
| mit | cf1d98d6c6a7a898e2dc6ad999aa59cb | 34.612308 | 190 | 0.653707 | 5.413471 | false | false | false | false |
tkausch/swiftalgorithms | CodePuzzles/LongestPalindromSubstring.playground/Contents.swift | 1 | 3808 | //: # Longest Palindromic Substring
//: **Question:** Given a string S, find the longest palindromic substring in S. You may assume there exists one unique longest palindromic substring.
//: **Hint:** First, make sure you understand what a palindrome means. A palindrome is a string which reads the same in both directions. For example, “aba” is a palindome, “abc” is not.
//: **Brute force - O(n3) runtime, O(n) space:** The obvious brute force solution is to pick all possible starting and ending positions for a substring, and verify if it is a palindrome. There are a total of `𝑛 * (n-1)` such substrings (excluding the trivial solution where a character itself is a palindrome).
import Foundation
func longestPalindromeSubString(_ s: String) -> String {
guard s.count > 2 else {
return s
}
var maxLen = 0
var longestPalindrome = ""
for start in s.indices {
var end = s.index(after: start)
while end != s.endIndex {
let p = s[start ..< end]
if p == String(p.reversed()) {
if p.count > maxLen {
maxLen = p.count
longestPalindrome = String(p)
}
}
end = s.index(after: end)
}
}
return longestPalindrome
}
longestPalindromeSubString("aabbab") == "abba"
longestPalindromeSubString("aabab") == "aba"
longestPalindromeSubString("babababcd") == "bababab"
longestPalindromeSubString("abc") == "a"
longestPalindromeSubString("a") == "a"
longestPalindromeSubString("") == ""
//: **Simpler solution - O(n2) runtime, O(1) space**
//: In fact, we could solve it in O(n2) time using only constant space.
//: We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n – 1 such centers.
//: You might be asking why there are 2n – 1 but not n centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as “abba”) and its center are between the two ‘b’s.
//: Since expanding a palindrome around its center could take O(n) time, the overall complexity is O(n2).
func longestPalindromeSubStr(_ s: String) -> String {
var maxLen = 0
var maxStart: String.Index = s.startIndex
func expand(left: String.Index, right: String.Index) -> (start: String.Index,len: Int) {
var len = 0
var l = left, r = right
while r != s.endIndex && s[l] == s[r] {
if l != r {
len += 2
} else {
len += 1
}
if (l == s.startIndex) {
return (l,len)
} else {
l = s.index(before: l)
}
r = s.index(after: r)
}
return (s.index(after: l),len)
}
func updateMax(_ t:(start: String.Index, len: Int)) {
if t.len > maxLen {
maxLen = t.len
maxStart = t.start
}
}
for pos in s.indices {
updateMax(expand(left: pos, right: pos))
updateMax(expand(left: pos, right: s.index(after: pos)))
}
return String(s[maxStart..<s.index(maxStart, offsetBy: maxLen)])
}
longestPalindromeSubStr("aabbab") == "abba"
longestPalindromeSubStr("aabab") == "aba"
longestPalindromeSubStr("babababcd") == "bababab"
longestPalindromeSubStr("abc") == "a"
longestPalindromeSubStr("a") == "a"
longestPalindromeSubStr("") == ""
//: **Manacher's algorithm: O(n) runtime, O(n) space**
//: There is even an O(n) algorithm called Manacher's algorithm, explained [here in detail](http://articles.leetcode.com/longest-palindromic-substring-part-ii). However, it is a non-trivial algorithm. please go ahead and understand it.
| gpl-3.0 | 03f5e6184b294f4e0849eea7ba1a8257 | 38.020619 | 310 | 0.619287 | 3.902062 | false | false | false | false |
austinzheng/swift | test/stdlib/Reflection.swift | 12 | 5220 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %{python} %S/timeout.py 360 %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// FIXME: timeout wrapper is necessary because the ASan test runs for hours
//
// DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift.
//
import Swift
// A more interesting struct type.
struct Complex<T> {
let real, imag: T
}
// CHECK-LABEL: Complex:
print("Complex:")
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: 1.5
// CHECK-NEXT: imag: 0.75
dump(Complex<Double>(real: 1.5, imag: 0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: -1.5
// CHECK-NEXT: imag: -0.75
dump(Complex<Double>(real: -1.5, imag: -0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Int>
// CHECK-NEXT: real: 22
// CHECK-NEXT: imag: 44
dump(Complex<Int>(real: 22, imag: 44))
// CHECK-NEXT: Reflection.Complex<Swift.String>
// CHECK-NEXT: real: "is this the real life?"
// CHECK-NEXT: imag: "is it just fantasy?"
dump(Complex<String>(real: "is this the real life?",
imag: "is it just fantasy?"))
// Test destructuring of a pure Swift class hierarchy.
class Good {
let x: UInt = 11
let y: String = "222"
}
class Better : Good {
let z: Double = 333.5
}
class Best : Better {
let w: String = "4444"
}
// CHECK-LABEL: Root class:
// CHECK-NEXT: Reflection.Good #0
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
print("Root class:")
dump(Good())
// CHECK-LABEL: Subclass:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Subclass:")
dump(Best())
// Test protocol types, which reflect as their dynamic types.
// CHECK-LABEL: Any int:
// CHECK-NEXT: 1
print("Any int:")
var any: Any = 1
dump(any)
// CHECK-LABEL: Any class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Any class:")
any = Best()
dump(any)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
print("second verse same as the first:")
dump(any)
// CHECK-LABEL: Any double:
// CHECK-NEXT: 2.5
print("Any double:")
any = 2.5
dump(any)
// CHECK-LABEL: Character:
// CHECK-NEXT: "a"
print("Character:")
dump(Character("a"))
protocol Fooable {}
extension Int : Fooable {}
extension Double : Fooable {}
// CHECK-LABEL: Fooable int:
// CHECK-NEXT: 1
print("Fooable int:")
var fooable: Fooable = 1
dump(fooable)
// CHECK-LABEL: Fooable double:
// CHECK-NEXT: 2.5
print("Fooable double:")
fooable = 2.5
dump(fooable)
protocol Barrable : class {}
extension Best: Barrable {}
// CHECK-LABEL: Barrable class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Barrable class:")
var barrable: Barrable = Best()
dump(barrable)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("second verse same as the first:")
dump(barrable)
// CHECK-NEXT: Logical: true
switch true.customPlaygroundQuickLook {
case .bool(let x): print("Logical: \(x)")
default: print("wrong quicklook type")
}
let intArray = [1,2,3,4,5]
// CHECK-NEXT: 5 elements
// CHECK-NEXT: 1
// CHECK-NEXT: 2
// CHECK-NEXT: 3
// CHECK-NEXT: 4
// CHECK-NEXT: 5
dump(intArray)
var justSomeFunction = { (x:Int) -> Int in return x + 1 }
// CHECK-NEXT: (Function)
dump(justSomeFunction as Any)
// CHECK-NEXT: Swift.String
dump(String.self)
// CHECK-NEXT: ▿
// CHECK-NEXT: from: 1.0
// CHECK-NEXT: through: 12.15
// CHECK-NEXT: by: 3.14
dump(stride(from: 1.0, through: 12.15, by: 3.14))
// CHECK-NEXT: nil
var nilUnsafeMutablePointerString: UnsafeMutablePointer<String>?
dump(nilUnsafeMutablePointerString)
// CHECK-NEXT: 123456
// CHECK-NEXT: - pointerValue: 1193046
var randomUnsafeMutablePointerString = UnsafeMutablePointer<String>(
bitPattern: 0x123456)!
dump(randomUnsafeMutablePointerString)
// CHECK-NEXT: Hello panda
var sanePointerString = UnsafeMutablePointer<String>.allocate(capacity: 1)
sanePointerString.initialize(to: "Hello panda")
dump(sanePointerString.pointee)
sanePointerString.deinitialize(count: 1)
sanePointerString.deallocate()
// Don't crash on types with opaque metadata. rdar://problem/19791252
// CHECK-NEXT: (Opaque Value)
var rawPointer = unsafeBitCast(0 as Int, to: Builtin.RawPointer.self)
dump(rawPointer)
// CHECK-LABEL: and now our song is done
print("and now our song is done")
| apache-2.0 | 51a2dc3fcffc0c309e7c096f5e173d6d | 25.48731 | 80 | 0.654657 | 3.124551 | false | false | false | false |
brentdax/swift | validation-test/Sema/type_checker_perf/fast/rdar19836070.swift | 2 | 341 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types
// REQUIRES: tools-release,no_asserts
let _: (Character) -> Bool = { c in
("a" <= c && c <= "z") || ("A" <= c && c <= "Z") || c == "_"
}
| apache-2.0 | aa4e4586e4a9535263acdf964bb28edc | 55.833333 | 200 | 0.651026 | 3.157407 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-ios | Source/Cards/Client/Models/RawSignedModel.swift | 1 | 6139 | //
// Copyright (C) 2015-2020 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
/// Declares error types and codes
///
/// - invalidBase64String: Passed string is not correct base64 encoded string
/// - duplicateSignature: Signature with same signer already exists
@objc(VSSRawSignedModelError) public enum RawSignedModelError: Int, LocalizedError {
case invalidBase64String = 1
case duplicateSignature = 2
/// Human-readable localized description
public var errorDescription: String? {
switch self {
case .invalidBase64String:
return "Passed string is not correct base64 encoded string"
case .duplicateSignature:
return "Signature with same signer already exists"
}
}
}
/// Represents some model in binary form that can have signatures and corresponds to Virgil Cards Service model
@objc(VSSRawSignedModel) public final class RawSignedModel: NSObject, Codable {
/// Snapshot of `RawCardContent`
@objc public let contentSnapshot: Data
/// Array with RawSignatures of card
@objc public private(set) var signatures: [RawSignature]
/// Defines coding keys for encoding and decoding
private enum CodingKeys: String, CodingKey {
case contentSnapshot = "content_snapshot"
case signatures = "signatures"
}
/// Initializes a new `RawSignedModel` with the provided contentSnapshot
///
/// - Parameter contentSnapshot: data with snapshot of content
@objc public init(contentSnapshot: Data) {
self.contentSnapshot = contentSnapshot
self.signatures = []
super.init()
}
/// Initializes `RawSignedModel` from json dictionary
///
/// - Parameter json: Json-compatible dictionary
/// - Returns: RawSignedModel instance
/// - Throws: Rethrows from `JSONDecoder` and `NSJSONSerialization`
@objc public static func `import`(fromJson json: Any) throws -> RawSignedModel {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
return try JSONDecoder().decode(RawSignedModel.self, from: data)
}
/// Initializes `RawSignedModel` from base64 encoded string
///
/// - Parameter base64EncodedString: Base64 encoded string with `RawSignedModel`
/// - Returns: RawSignedModel instance
/// - Throws:
/// - `RawSignedModelError.invalidBase64String` if passed string is not base64 encoded data.
/// - Rethrows from JSONDecoder
@objc public static func `import`(fromBase64Encoded base64EncodedString: String) throws -> RawSignedModel {
guard let data = Data(base64Encoded: base64EncodedString) else {
throw RawSignedModelError.invalidBase64String
}
return try self.import(fromData: data)
}
/// Initializes `RawSignedModel` from Data
///
/// - Parameter data: Data with `RawSignedModel`
/// - Returns: RawSignedModel instance
/// - Throws:
/// - Rethrows from JSONDecoder
@objc public static func `import`(fromData data: Data) throws -> RawSignedModel {
return try JSONDecoder().decode(RawSignedModel.self, from: data)
}
/// Exports `RawSignedModel` as base64 encoded string
///
/// - Returns: Base64 encoded string with `RawSignedModel`
/// - Throws: Rethrows from `JSONEncoder`
@objc public func exportAsBase64EncodedString() throws -> String {
return try self.exportAsData().base64EncodedString()
}
/// Exports `RawSignedModel` as Data
///
/// - Returns: Data with `RawSignedModel`
/// - Throws: Rethrows from `JSONEncoder`
@objc public func exportAsData() throws -> Data {
return try JSONEncoder().encode(self)
}
/// Exports `RawSignedModel` as json dictionary
///
/// - Returns: Json-compatible dictionary with `RawSignedModel`
/// - Throws: Rethrows from `JSONEncoder` and `JSONSerialization`
@objc public func exportAsJson() throws -> Any {
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data, options: [])
}
/// Adds new signature
///
/// - Parameter signature: signature to add
/// - Throws: RawSignedModelError.duplicateSignature if signature with same signer already exists
@objc public func addSignature(_ signature: RawSignature) throws {
guard !self.signatures.contains(where: { $0.signer == signature.signer }) else {
throw RawSignedModelError.duplicateSignature
}
self.signatures.append(signature)
}
}
| bsd-3-clause | fbe55d81e419051dcc10612c783ff15c | 38.863636 | 111 | 0.698322 | 4.654284 | false | false | false | false |
BeamNG/remotecontrol | iOS/BeamNG.SteeringDevice/BeamNG.SteeringDevice/PSSession.swift | 1 | 8605 | //
// PSSession.swift
// BeamNG.SteeringDevice
//
// Created by Pawel Sulik on 10.10.14.
// Copyright (c) 2014 28Apps. All rights reserved.
//
import Foundation
import UIKit
class PSSteerData : NSObject
{
var acceleration : Float = 0.0;
var brake : Float = 0.0;
var steer : Float = 0.0;
var id : Float = 1;
var lagDelay : Double = 0;
override init()
{
super.init();
}
}
class PSCarData : NSObject
{
var speed : Float = 0.0;
var rpm : Float = 0.0;
var fuel : Float = 0.0;
var temperature : Float = 0.0;
var gear : Int = 0;
var distance : Int = 0;
var lights : UInt32 = 0;
override init()
{
super.init();
}
}
class PSReceivedData
{
func fromData(_ data: Data)
{
// var s : NSInputStream = NSInputStream(data: data);
// var buffer : [UInt8] = [UInt8](count: 64, repeatedValue: 0);
//fix for accidentally grabbing hello message and trying to parse it, resulting in a crash
if (data.count > 50) {
(data as NSData).getBytes(&timer, range: NSMakeRange(0, 4));
(data as NSData).getBytes(&carName, range: NSMakeRange(4, 4));
(data as NSData).getBytes(&flags, range: NSMakeRange(8, 2));
(data as NSData).getBytes(&gear, range: NSMakeRange(10, 1));
(data as NSData).getBytes(&playerId, range: NSMakeRange(11, 1));
(data as NSData).getBytes(&speed, range: NSMakeRange(12, 4));
(data as NSData).getBytes(&rpm, range: NSMakeRange(16, 4));
(data as NSData).getBytes(&turbo, range: NSMakeRange(20, 4));
(data as NSData).getBytes(&engineTemperature, range: NSMakeRange(24, 4));
(data as NSData).getBytes(&fuel, range: NSMakeRange(28, 4));
(data as NSData).getBytes(&oilPressure, range: NSMakeRange(32, 4));
(data as NSData).getBytes(&oilTemperature, range: NSMakeRange(36, 4));
(data as NSData).getBytes(&dashLights, range: NSMakeRange(40, 4));
(data as NSData).getBytes(&showLights, range: NSMakeRange(44, 4));
(data as NSData).getBytes(&throttle, range: NSMakeRange(48, 4));
(data as NSData).getBytes(&brake, range: NSMakeRange(52, 4));
(data as NSData).getBytes(&clutch, range: NSMakeRange(56, 4));
(data as NSData).getBytes(&display1, range: NSMakeRange(60, 16));
(data as NSData).getBytes(&display2, range: NSMakeRange(76, 16));
(data as NSData).getBytes(&rid, range: NSMakeRange(92, 4));
}
}
var timer : UInt32 = 0;
var carName = [UInt8](repeating: 0, count: 4);
var flags : UInt16 = 0;
var gear : UInt8 = 0;
var playerId : UInt8 = 0;
var speed : Float = 0.0;
var rpm : Float = 0.0;
var turbo : Float = 0.0;
var engineTemperature : Float = 0.0;
var fuel : Float = 0.0;
var oilPressure : Float = 0.0;
var oilTemperature : Float = 0.0;
var dashLights : UInt32 = 0;
var showLights : UInt32 = 0;
var throttle : Float = 0.0;
var brake : Float = 0.0;
var clutch : Float = 0.0;
var display1 = [UInt8](repeating: 0, count: 16);
var display2 = [UInt8](repeating: 0, count: 16);
var rid : Int = 0;
}
class PSSession : NSObject, AsyncUdpSocketDelegate
{
var sendSocket : AsyncUdpSocket!;
var listenSocket : AsyncUdpSocket!;
var currentData : PSSteerData!;
var carData : PSCarData!;
var onSessionBroken : ((NSError)->(Void))! = nil;
var receiveTimeout : CFTimeInterval = 10.0;
var finalHost : String = "";
var finalPort: UInt16 = 4445;
var lastID : Int = 0;
var lpTime : Double = 0;
var oldDiff : Double = 0;
init(host: String, port: UInt16, sessionBrokenHandler: ((NSError)->(Void))!)
{
super.init();
currentData = PSSteerData();
carData = PSCarData();
self.onSessionBroken = sessionBrokenHandler;
self.sendSocket = AsyncUdpSocket(delegate: self);
do {
print("Connecting Send Socket: "+host+" : \(port)");
try self.sendSocket.bind(toAddress: host, port: 4445)
//try self.sendSocket.connect(toHost: host, onPort: 4445)
//try sendSocket.bind(toPort: 4445)
} catch _ {
};
let error : NSError? = nil;
self.listenSocket = AsyncUdpSocket(delegate: self);
do {
print("Connecting Listen Socket: "+PSNetUtil.localIPAddress()+" : 4445");
try self.listenSocket.bind(toAddress: PSNetUtil.localIPAddress(), port: 4445)
//try self.listenSocket.connect(toHost: PSNetUtil.localIPAddress(), onPort: 4445)
} catch _ {
};
if(error != nil)
{
print(error);
}
finalHost = host;
finalPort = port;
listenSocket.receive(withTimeout: -1, tag: 0);
}
deinit
{
print("close!!!!");
listenSocket.close();
sendSocket.close();
}
func sendCurrentData()
{
let toBytes : [UInt32] = [UInt32(bigEndian: UInt32(currentData.steer.bitPattern)), UInt32(bigEndian: UInt32(currentData.brake.bitPattern)), UInt32(bigEndian: UInt32(currentData.acceleration.bitPattern)), UInt32(bigEndian: UInt32(currentData.id.bitPattern))];
let dataBytes = Data(bytes: UnsafeRawPointer(toBytes), count: 16);
/*var test = [UInt32](count: 4, repeatedValue: 0);
dataBytes.getBytes(&test, length: 16);
test[0] = UInt32(bigEndian: test[0]);
test[1] = UInt32(bigEndian: test[1]);
test[2] = UInt32(bigEndian: test[2]);
test[3] = UInt32(bigEndian: test[3]);
let dataBytes2 = NSData(bytes: test, length: 16);*/
sendSocket.send(dataBytes, toHost: finalHost, port: 4444, withTimeout: -1, tag: 0);
if (lastID != Int(currentData.id)) {
lastID = Int(currentData.id);
lpTime = CACurrentMediaTime();
}
}
@objc func onUdpSocket(_ sock: AsyncUdpSocket!, didNotReceiveDataWithTag tag: Int, dueToError error: NSError!)
{
print("Did not receive!");
print(error);
//If receive timeout has been reached OR the connection has been actually broken, send a notification to given callback
if(self.onSessionBroken != nil)
{
self.listenSocket.setDelegate(nil);
self.sendSocket.setDelegate(nil);
self.onSessionBroken(error);
}
}
@objc func onUdpSocket(_ sock: AsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!)
{
print("Data not sent!\n\(error)");
//Something went wrong! It is better to raise an error than trying to send again!
if(self.onSessionBroken != nil)
{
self.listenSocket.setDelegate(nil);
self.sendSocket.setDelegate(nil);
self.onSessionBroken(error);
}
}
@objc func onUdpSocket(_ sock: AsyncUdpSocket!, didReceive data: Data!, withTag tag: Int, fromHost host: String!, port: UInt16) -> Bool
{
//print("PSSession: Received data!\n\t\(data)\nfrom: \(host):\(port)");
let recData : PSReceivedData = PSReceivedData();
recData.fromData(data);
//print(recData.speed);
carData.speed = recData.speed;
carData.rpm = recData.rpm;
carData.gear = Int(recData.gear);
carData.fuel = recData.fuel;
carData.temperature = recData.engineTemperature;
//print(recData.showLights);
carData.lights = recData.showLights;
//print(carData.lights);
if (recData.rid == Int(currentData.id)) {
let diff : Double = (CACurrentMediaTime() - lpTime)*1000/2;
currentData.lagDelay = (oldDiff + diff+currentData.lagDelay)/3;
currentData.lagDelay = round(currentData.lagDelay*100)/100;
//print(currentData.lagDelay);
currentData.id += 1;
if (currentData.id == 128) {
currentData.id = 0;
}
oldDiff = diff;
}
//print(recData.showLights);
listenSocket.receive(withTimeout: -1, tag: 0);
return true;
}
@objc func onUdpSocket(_ sock: AsyncUdpSocket!, didSendDataWithTag tag: Int)
{
}
@objc func onUdpSocketDidClose(_ sock: AsyncUdpSocket!)
{
}
}
| isc | 346db1f108254a56a8de985fe0a00fec | 31.969349 | 266 | 0.577687 | 3.978271 | false | false | false | false |
proxpero/Placeholder | Placeholder/Resource.swift | 1 | 992 | //
// Resource.swift
// Placeholder
//
// Created by Todd Olsen on 4/6/17.
// Copyright © 2017 proxpero. All rights reserved.
//
import Foundation
public struct Resource<A> {
public let url: URL
public let method: HttpMethod<Data>
public let parse: (Data) -> A?
}
extension Resource {
/// Initialize a `Resource` specifically expecting JSON
init(url: URL, method: HttpMethod<Any> = .get, parseJSON: @escaping (Any) -> A?) {
self.url = url
self.method = method.map { json in
// If `json` cannot be transformed into `Data` then it is a programmer
// error and the app will crash. Check that the json was formed correctly.
let result = try! JSONSerialization.data(withJSONObject: json, options: [])
return result
}
self.parse = { data in
let json = try? JSONSerialization.jsonObject(with: data, options: [])
return json.flatMap(parseJSON)
}
}
}
| mit | 58ad27b2cc1888dac327964edcbdaf23 | 28.147059 | 87 | 0.612513 | 4.095041 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/28090-bool.swift | 11 | 2811 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct X<T:T.a
func b:d
}
extension String{}
class A
class b<T where h:S{
( "
}
func b
}typealias e = object {
{class A
class var f = compose()init(n: At c {struct S<T B {{{class A{
extension NSFileManager {
var e = Dictionary<f:a
var b<f
class A {
}
struct B<{{func b{}}
}
var d {
class P{class D {
}}print{var "
in
typealias d
class var a{
func < {
func a {
conary<T where T. : a {{
protocol A {
class A : a{
class A{
import Foundation
class A{
class u{var e = object {
{func b:T:A
}
in
}
( "
struct E{
}}
struct B<T == object {
func<T where T{
[ {
{
protocol A : Any, A : a {func b:{
class A : a {
class A
}
func a {
import Foundation
typealias e = Dictionary<T where T: a {
}typealias e {
protocol a
protocol A : a{
struct B{class A{
}
class d
}
let h:d:A
"
}
"
class A : a {{
protocol a{
}
enum S<{
}print{
func < {
col A {
}
protocol A : e
}}
protocol A {{
}
}
class A : A{class a{
{}
class A {func a {
}}
class P{
extension NSFileMa}
}
class A : Any, A : T:T:A{
class A {
"
var "
struct c {
struct S<I
( "
protocol C{
col A : a {
class P{
protocol A : a {a
struct B {
class A {{
( "
class a<T where f{class A {
protocol C{
protocol c {
protocol C{
}}
struct B{a
let:a
{
func b:A{
}struct E {enum C {
class c{enum S<I
class a {class u{
( "
class a{
struct c {
var b
class var "
class T{enum C {
struct B
}
typealias f
}print{
typealias f:
typealias etatic var f
typealias etatic var f:T{
( "
class A {
let h:S<T == B
var f{
struct B {
typealias e = a{}}struct B<{
}typealias d:{
class A {
class D {a{var d {class A{
struct B {
}enum b
}}
struct B{
}
"
}
init()
let:S{
var d {
protocol a {
}
struct B {}
if true{
}
extension NSFileMa}
func<T where T. : A {
}
func a {
class A {func b
class A {}protocol a<{{
struct S<T where T{
enum a{class A
struct B : a {var f:{
typealias f = compose()
typealias f = object {
var f
import Foundation
typealias e = object {
typealias e {}
}
protocol A {
class A : A{
protocol a
class A : A : e = object {
let h: a {a
class D {
class A {
protocol a {
}
let:d
class A
class var f:{
var d {{}
func a {
protocol a {
struct B
}
var a
struct S<T where T{
struct S{}}
extension String{
protocol A {
}
struct X<T:T.a
protocol a{
struct S{
func f:a
}
typealias f
struct S<T B {
}
var b}
protocol a : a
typealias etatic var a
}print{
class var a{
S<I
func b{}
struct S{
class A : A {struct X<T:T.a
}}
func<T where T{
typealias e = B
var d {
}
let:A{
extension NSFileMa}
extension NSFileMa
| apache-2.0 | 6210fc601c752b0b5906068089100c41 | 11.894495 | 78 | 0.647812 | 2.597967 | false | false | false | false |
NitWitStudios/NWSExtensions | Example/NWSExtensionsExample/Controllers/View Controllers/NWSTableViewController.swift | 1 | 2990 | //
// NWSTableViewController.swift
// NWSExtensions
//
// Created by James Hickman on 3/19/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
let NWSModalViewControllerIdentifier = "NWSModalViewControllerIdentifier"
let NWSTableViewControllerTableViewCellIdentifier = "NWSModalViewControllerTableViewCellIdentifier"
enum NWSTableViewControllerRow: Int {
case modalAnimatorBlurred
case modalAnimatorTransparent
case rowCount
}
class NWSTableViewController: UITableViewController {
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NWSTableViewControllerTableViewCellIdentifier)
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NWSTableViewControllerRow.rowCount.rawValue
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NWSTableViewControllerTableViewCellIdentifier, for: indexPath)
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = 0.5
cell.textLabel?.text = stringForRow(NWSTableViewControllerRow(rawValue: indexPath.row)!)
cell.accessoryType = .disclosureIndicator
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.isSelected = false
switch indexPath.row {
case NWSTableViewControllerRow.modalAnimatorBlurred.rawValue:
let modalViewController = NWSModalViewController.viewControllerFromStoryboardInstance()
modalViewController.animator.type = .blurred
self.navigationController?.present(modalViewController, animated: true, completion: nil)
break
case NWSTableViewControllerRow.modalAnimatorTransparent.rawValue:
let modalViewController = NWSModalViewController.viewControllerFromStoryboardInstance()
modalViewController.animator.type = .transparent
self.navigationController?.present(modalViewController, animated: true, completion: nil)
break
default:
break
}
}
// MARK: - Helpers
func stringForRow(_ row: NWSTableViewControllerRow) -> String {
switch row {
case .modalAnimatorBlurred:
return "Modal Animator w/ Blurred Background"
case .modalAnimatorTransparent:
return "Modal Animator w/ Transparent Background"
default:
return ""
}
}
}
| mit | 5192389156502c857591b5dab4227cfe | 35.012048 | 127 | 0.700903 | 5.715105 | false | false | false | false |
yichizhang/YZKeyboardInputAccessoryView | NumberKeyboardViewDemo/NumberKeyboardViewDemo/ViewController.swift | 1 | 1314 | //
// ViewController.swift
// NumberKeyboardViewDemo
//
// Created by Yichi on 10/03/2015.
// Copyright (c) 2015 Yichi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
@IBOutlet weak var textField3: UITextField!
var numberKeyboardView = YZNumberKeyboardInputAccessoryView()
var emojiKeyboardView = YZKeyboardInputAccessoryView(keys: "😀 😁 😂 😃 😄 😅 😆 😇".componentsSeparatedByString(" "))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.darkGrayColor()
textField1.delegate = self
textField2.delegate = self
textField3.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == textField1 {
textField.autocorrectionType = .No
numberKeyboardView.attachTo(textInput: textField)
}
if textField == textField3 {
textField.autocorrectionType = .No
emojiKeyboardView.attachTo(textInput: textField)
}
return true
}
}
| mit | 3bb7a8c4e93f4122c78c5f4ab758c84b | 25.326531 | 111 | 0.745736 | 4.174757 | false | false | false | false |
Brightify/DataMapper | Source/Core/ObjectMapper.swift | 1 | 4398 | //
// ObjectMapper.swift
// DataMapper
//
// Created by Filip Dolnik on 28.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public final class ObjectMapper {
private let polymorph: Polymorph?
public init(polymorph: Polymorph? = nil) {
self.polymorph = polymorph
}
public func serialize<T: Serializable>(_ value: T?) -> SupportedType {
if let value = value {
var serializableData = SerializableData(objectMapper: self)
value.serialize(to: &serializableData)
var data = serializableData.raw
polymorph?.writeTypeInfo(to: &data, of: type(of: value))
return data
} else {
return .null
}
}
public func serialize<T: Serializable>(_ array: [T?]?) -> SupportedType {
if let array = array {
return .array(array.map(serialize))
} else {
return .null
}
}
public func serialize<T: Serializable>(_ dictionary: [String: T?]?) -> SupportedType {
if let dictionary = dictionary {
return .dictionary(dictionary.mapValues(serialize))
} else {
return .null
}
}
public func serialize<T, R: SerializableTransformation>(_ value: T?, using transformation: R) -> SupportedType where R.Object == T {
return transformation.transform(object: value)
}
public func serialize<T, R: SerializableTransformation>(_ array: [T?]?, using transformation: R) -> SupportedType where R.Object == T {
if let array = array {
return .array(array.map(transformation.transform(object:)))
} else {
return .null
}
}
public func serialize<T, R: SerializableTransformation>(_ dictionary: [String: T?]?, using transformation: R) -> SupportedType where R.Object == T {
if let dictionary = dictionary {
return .dictionary(dictionary.mapValues(transformation.transform(object:)))
} else {
return .null
}
}
public func deserialize<T: Deserializable>(_ type: SupportedType) -> T? {
let data = DeserializableData(data: type, objectMapper: self)
let type = polymorph?.polymorphType(for: T.self, in: type) ?? T.self
return try? type.init(data)
}
public func deserialize<T: Deserializable>(_ type: SupportedType) -> [T]? {
guard let array = type.array else {
return nil
}
return array.mapOrNil(deserialize)
}
public func deserialize<T: Deserializable>(_ type: SupportedType) -> [T?]? {
return type.array?.map(deserialize)
}
public func deserialize<T: Deserializable>(_ type: SupportedType) -> [String: T]? {
guard let dictionary = type.dictionary else {
return nil
}
return dictionary.mapValueOrNil(deserialize)
}
public func deserialize<T: Deserializable>(_ type: SupportedType) -> [String: T?]? {
return type.dictionary?.mapValues(deserialize)
}
public func deserialize<T, R: DeserializableTransformation>(_ type: SupportedType, using transformation: R) -> T? where R.Object == T {
return transformation.transform(from: type)
}
public func deserialize<T, R: DeserializableTransformation>(_ type: SupportedType, using transformation: R) -> [T]? where R.Object == T {
guard let array = type.array else {
return nil
}
return array.mapOrNil(transformation.transform(from:))
}
public func deserialize<T, R: DeserializableTransformation>(_ type: SupportedType, using transformation: R) -> [T?]? where R.Object == T {
return type.array?.map(transformation.transform(from:))
}
public func deserialize<T, R: DeserializableTransformation>(_ type: SupportedType, using transformation: R) -> [String: T]? where R.Object == T {
guard let dictionary = type.dictionary else {
return nil
}
return dictionary.mapValueOrNil(transformation.transform(from:))
}
public func deserialize<T, R: DeserializableTransformation>(_ type: SupportedType, using transformation: R) -> [String: T?]? where R.Object == T {
return type.dictionary?.mapValues(transformation.transform(from:))
}
}
| mit | 8ae0660068fa0145ac471a19d594b75f | 35.040984 | 152 | 0.610644 | 4.692636 | false | false | false | false |
wangyuanou/Coastline | Coastline/Structure/String+Draw.swift | 1 | 1158 | //
// String+Draw.swift
// Coastline
//
// Created by 王渊鸥 on 2016/9/25.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import UIKit
public extension String {
// 获取字符串的尺寸(单行)
public func textSize(_ font:UIFont) -> CGSize {
return (self as NSString).size(attributes: [NSFontAttributeName:font])
}
// 获取字符串的尺寸(多行)
public func textRectInSize(_ size:CGSize, font:UIFont, wordwarp:NSLineBreakMode, kern:CGFloat = 0) -> CGRect {
let maxSize = CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude)
let pStyle = NSMutableParagraphStyle()
pStyle.lineBreakMode = wordwarp
let rect = (self as NSString).boundingRect(with: maxSize, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSFontAttributeName:font, NSParagraphStyleAttributeName:pStyle, NSKernAttributeName:NSNumber(value: Float(kern))], context: nil)
return CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height+1).integral
}
// 绘制字符串
public func drawInRect(_ rect:CGRect, attr:[String:AnyObject]) {
(self as NSString).draw(in: rect, withAttributes: attr)
}
}
| mit | 7bddb6c8cd02d95cbe5ba719cb6970cf | 35.433333 | 255 | 0.73559 | 3.607261 | false | false | false | false |
marcusellison/lil-twitter | lil-twitter/Tweet.swift | 1 | 2064 | //
// Tweet.swift
// lil-twitter
//
// Created by Marcus J. Ellison on 5/19/15.
// Copyright (c) 2015 Marcus J. Ellison. All rights reserved.
//
import UIKit
class Tweet: NSObject {
var user: User?
var text: String?
var createdAtString: String?
var createdAt: NSDate?
var imageURL: NSURL?
var retweetedBy: String?
var retweeted: Bool?
var favorited: Bool?
var retweetsCount: Int?
var favoritesCount: Int?
var tweetID: Double?
var tweetIDString: String?
init(dictionary: NSDictionary) {
user = User(dictionary: (dictionary["user"] as! NSDictionary))
text = dictionary["text"] as? String
createdAtString = dictionary["created_at"] as? String
// N.B. NSDateFormatter is really expensive
// would be better to use a lazy load or a 'static NSDateFormatter'
var formatter = NSDateFormatter()
// date format must match exactly
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
// formatter.dateStyle = NSDateFormatterStyle.ShortStyle
createdAt = formatter.dateFromString(createdAtString!)
var imageURLString = user?.profileImageURL
if imageURLString != nil {
imageURL = NSURL(string: imageURLString!)!
} else {
imageURL = nil
}
tweetID = dictionary["id"] as? Double
tweetIDString = dictionary["id_str"] as? String
favoritesCount = dictionary["favorite_count"] as? Int
retweetsCount = dictionary["retweet_count"] as? Int
retweeted = dictionary["retweeted"] as? Bool
favorited = dictionary["favorited"] as? Bool
}
// convenience method that parses an array of tweets
class func tweetsWithArray( array: [NSDictionary]) -> [Tweet] {
var tweets = [Tweet]()
for (dictionary) in array{
tweets.append(Tweet(dictionary: dictionary))
}
return tweets
}
}
| mit | 406e62089ef1efd7278c6b24071ed6bf | 27.666667 | 75 | 0.595446 | 4.84507 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/ViewModels/RegisterViewModel.swift | 1 | 4152 | //
// RegisterViewModel.swift
// travelMapMvvm
//
// Created by green on 15/9/7.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import ReactiveCocoa
import ReactiveViewModel
class RegisterViewModel: RVMViewModel,SecondViewControllerDelegate {
let smsDataSourceProtocol = SMSDataSource.shareInstance()
dynamic var countryAndAreaCode:CountryAndAreaCode! // 国家名称、国家码
dynamic var zonesArray = NSMutableArray() // 支持的区号数组
dynamic var errorMsg = "" // 错误提示信息
dynamic var telephone = "" // 手机号
dynamic var isValidTelephone = false // 手机号是否有效
var searchZonesArrayCommand:RACCommand! // 查询支持的区号数组命令
var sendVerityCodeCommand:RACCommand! // 发送验证码命令
override init() {
super.init()
// 查询国家名称、国家码
self.countryAndAreaCode = self.smsDataSourceProtocol.queryCountryAndAreaCode()
setupSearchZonesArrayCommand() // 初始化查询支持的区号数组命令
setupSendVerityCodeCommand() // 初始化发送验证码命令
// 手机号是否有效
RACSignalEx.combineLatestAs([RACObserve(self, "telephone"),RACObserve(self, "countryAndAreaCode")], reduce: { (telephone:NSString, cac:CountryAndAreaCode) -> NSNumber in
let zoneCode = cac.areaCode.stringByReplacingOccurrencesOfString("+", withString: "")
return self.smsDataSourceProtocol.isValidTelephone(telephone as String, zoneCode: zoneCode, zonesArray: self.zonesArray)
}) ~> RAC(self,"isValidTelephone")
// 激活后开始更新数据
didBecomeActiveSignal.subscribeNext { (any:AnyObject!) -> Void in
let tempSignal = self.smsDataSourceProtocol.queryZone()
// 查询支持的区号数组
self.searchZonesArrayCommand.execute(nil)
}
}
// MARK: - setup
/**
* 初始化查询支持的区号数组命令
*/
private func setupSearchZonesArrayCommand() {
// 初始化查询命令
searchZonesArrayCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
return self.smsDataSourceProtocol.queryZone()
})
// 处理错误
searchZonesArrayCommand.errors.subscribeNextAs { (error:NSError!) -> () in
self.errorMsg = error.localizedDescription
}
// 更新支持的区号数组
searchZonesArrayCommand.executionSignals.switchToLatest().subscribeNextAs { (zonesArray:NSMutableArray) -> () in
self.zonesArray = zonesArray
}
// 重置错误
searchZonesArrayCommand.executionSignals.subscribeNext { (any:AnyObject!) -> Void in
self.errorMsg = ""
}
}
/**
* 初始化发送验证码命令
*/
private func setupSendVerityCodeCommand() {
// 是否可以执行
let enabledSignal = RACObserve(self, "isValidTelephone")
// 初始化发送验证码命令
sendVerityCodeCommand = RACCommand(enabled: enabledSignal,signalBlock: { (any:AnyObject!) -> RACSignal! in
let zoneCode = self.countryAndAreaCode.areaCode.stringByReplacingOccurrencesOfString("+", withString: "")
return self.smsDataSourceProtocol.getVerificationCodeBySMS(self.telephone, zone: zoneCode).materialize()
})
// 重置错误
sendVerityCodeCommand.executionSignals.subscribeNext { (any:AnyObject!) -> Void in
self.errorMsg = ""
}
}
// MARK: - SecondViewControllerDelegate
func setSecondData(data: CountryAndAreaCode!) {
data.areaCode = data.areaCode != nil ? ("+"+data.areaCode) : ""
self.countryAndAreaCode = data
}
}
| apache-2.0 | 3a74df0325683de2f67f11fcffdf7df9 | 32.610619 | 177 | 0.59742 | 4.718012 | false | false | false | false |
guoc/spi | SPiKeyboard/InputHistory.swift | 1 | 8652 |
import Foundation
class InputHistory {
var candidatesRecord = [Candidate]()
var history = [String: Int]()
var databaseQueue: FMDatabaseQueue?
var recentCandidate: (text: String, querycode: String)? {
set {
UserDefaults.standard.set(newValue?.text, forKey: "InputHistory.recentCandidate.text")
UserDefaults.standard.set(newValue?.querycode, forKey: "InputHistory.recentCandidate.querycode")
}
get {
if let text = UserDefaults.standard.object(forKey: "InputHistory.recentCandidate.text") as? String, let querycode = UserDefaults.standard.object(forKey: "InputHistory.recentCandidate.querycode") as? String {
return (text: text, querycode: querycode)
} else {
return nil
}
}
}
init() {
let documentsFolder = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let databasePath = URL(string: documentsFolder)!.appendingPathComponent("history.sqlite")
print(databasePath)
databaseQueue = FMDatabaseQueue(path: databasePath.absoluteString)
if databaseQueue == nil {
print("Unable to open database")
return
}
databaseQueue?.inDatabase() {
db in
if !(db?.executeUpdate("create table if not exists history(candidate text, shuangpin text, shengmu text, length integer, frequency integer, candidate_type integer, primary key (candidate, shuangpin))", withArgumentsIn: nil))! {
print("create table failed: \(db?.lastErrorMessage())")
}
if !(db?.executeUpdate("CREATE INDEX IF NOT EXISTS idx_shengmu on history(shengmu)", withArgumentsIn: nil))! {
print("create index failed: \(db?.lastErrorMessage())")
}
}
}
deinit {
databaseQueue!.close()
}
func getFrequencyOf(_ candidate: Candidate) -> Int {
return getFrequencyOf(candidateText: candidate.text, queryCode: candidate.queryCode)
}
func getFrequencyOf(candidateText: String, queryCode: String) -> Int {
var frequency: Int? = nil
let whereStatement = "candidate = ? and shuangpin = ?"
let queryStatement = "select frequency from history where " + whereStatement + " order by length desc, frequency desc"
databaseQueue?.inDatabase() {
db in
if let rs = db?.executeQuery(queryStatement, withArgumentsIn: [candidateText, queryCode]) {
while rs.next() {
frequency = Int(rs.int(forColumn: "frequency"))
break
}
} else {
print("select failed: \(db?.lastErrorMessage())")
}
}
return frequency ?? 0
}
func updateDatabase(candidatesString: String) {
let candidatesArray = candidatesString.components(separatedBy: "\n")
for candidateStr in candidatesArray {
if candidateStr != "" {
let arr = candidateStr.components(separatedBy: "\t")
updateDatabase(candidateText: arr[0], customCandidateQueryString: arr[1])
}
}
}
func updateDatabase(candidateText: String, queryString: String, candidateType: String) -> Bool {
switch candidateType {
case "1":
updateDatabase(candidateText: candidateText, shuangpinString: queryString)
return true
case "2":
updateDatabase(candidateText: candidateText, englishString: queryString)
return true
case "3":
updateDatabase(candidateText: candidateText, specialString: queryString)
return true
case "4":
updateDatabase(candidateText: candidateText, customCandidateQueryString: queryString)
return true
default:
return false
}
}
func updateDatabase(candidateText: String, customCandidateQueryString: String) {
updateDatabase(with: Candidate(text: candidateText, withCustomString: customCandidateQueryString))
}
func updateDatabase(candidateText: String, shuangpinString: String) {
updateDatabase(with: Candidate(text: candidateText, withShuangpinString: shuangpinString))
}
func updateDatabase(candidateText: String, englishString: String) {
updateDatabase(with: Candidate(text: candidateText, withEnglishString: englishString))
}
func updateDatabase(candidateText: String, specialString: String) {
updateDatabase(with: Candidate(text: candidateText, withSpecialString: specialString))
}
func updateDatabase(with candidate: Candidate) {
func canInsertIntoInputHistory(_ candidate: Candidate) -> Bool {
func candidateIsTooSimple(_ candidate: Candidate) -> Bool {
if candidate.queryCode.getReadingLength() == 2 && candidate.text == candidate.queryCode || candidate.queryCode.getReadingLength() == 1 {
return true
} else {
return false
}
}
if candidateIsTooSimple(candidate) {
return false
} else {
return true
}
}
self.recentCandidate = (text: candidate.text, querycode: candidate.shuangpinAttributeString)
if canInsertIntoInputHistory(candidate) == false {
return
}
updateDatabase(candidateText: candidate.text, shuangpin: candidate.shuangpinAttributeString, shengmu: candidate.shengmuAttributeString, length: candidate.lengthAttribute as NSNumber, frequency: 1 as NSNumber, candidateType: candidate.typeAttributeString)
}
func updateDatabase(candidateText: String, shuangpin: String, shengmu: String, length: NSNumber, frequency: NSNumber, candidateType: String) {
let previousFrequency = getFrequencyOf(candidateText: candidateText, queryCode: shuangpin)
databaseQueue?.inDatabase() {
db in
if previousFrequency == 0 {
if !(db?.executeUpdate("insert into history (candidate, shuangpin, shengmu, length, frequency, candidate_type) values (?, ?, ?, ?, ?, ?)", withArgumentsIn: [candidateText, shuangpin, shengmu, length, frequency, candidateType]))! {
print("insert 1 table failed: \(db?.lastErrorMessage()) \(candidateText) \(shuangpin)")
}
} else {
if !(db?.executeUpdate("update history set frequency = ? where shuangpin = ? and candidate = ?", withArgumentsIn: [NSNumber(value: previousFrequency + frequency.intValue as Int), shuangpin, candidateText]))! {
print("update 1 table failed: \(db?.lastErrorMessage()) \(candidateText) \(shuangpin)")
}
}
}
}
func updateHistoryWith(_ candidate: Candidate) {
if candidate.type == .onlyText {
return
}
updateDatabase(with: candidate)
}
func deleteRecentCandidate() {
databaseQueue?.inDatabase() {
db in
if let candidate = self.recentCandidate {
if !(db?.executeUpdate("delete from history where candidate == ? and shuangpin == ?", withArgumentsIn: [candidate.text, candidate.querycode]))! {
print("delete 1 table failed: \(db?.lastErrorMessage()) \(candidate.text) \(candidate.querycode)")
}
self.recentCandidate = nil
}
}
}
func cleanAllCandidates() { // Drop table in database.
databaseQueue?.inDatabase() {
db in
if !(db?.executeUpdate("drop table history", withArgumentsIn: []))! {
print("drop table history failed: \(db?.lastErrorMessage())")
}
}
}
func getCandidatesByQueryArguments(_ queryArguments: [String], andWhereStatement whereStatement: String, withQueryCode queryCode: String) -> [Candidate] {
let queryStatement = "select candidate, shuangpin, candidate_type from history where " + whereStatement + " order by length desc, frequency desc"
print(queryStatement)
print(queryArguments)
let candidates = databaseQueue!.getCandidates(byQueryStatement: queryStatement, byQueryArguments: queryArguments, withQueryCode: queryCode, needTruncateCandidates: false)
return candidates
}
}
| bsd-3-clause | 39dce4af58d8cc0f39a49e01faf77b77 | 41.62069 | 262 | 0.613962 | 5.068541 | false | false | false | false |
theMatys/myWatch | myWatch/Source/UI/Core/MWTabBarOld.swift | 1 | 28961 | //
// MWTabBar.swift
// myWatch
//
// Created by Máté on 2017. 06. 16.
// Copyright © 2017. theMatys. All rights reserved.
//
import UIKit
/// A custom-designed tab bar for the application.
class MWTabBar: UITabBar
{
//MARK: Inspectables
/// The style of the tab bar in an Interface Builder-supported format.
///
/// We use the number this variable holds to make an `MWTabBarStyle` instance out of it.
///
/// Before we can use the variable, we have to clamp it, so that it does not get out of range of the `MWTabBarStyle` enumeration.
/// - See: `count` in `MWTabBarStyle`
/// - Also, see `_style` below for more details on the styles.
@IBInspectable var style: Int = 1
{
didSet
{
_style = MWTabBarStyle(rawValue: MWUtil.clamp(style - 1, min: 0, max: MWTabBarStyle.count - 1))!
}
}
/// Indicates whether the tab bar sould hide the titles of the items and center their icons.
@IBInspectable var hidesTitles: Bool = false
{
didSet
{
_setItems(animated: animated)
}
}
//MARK: Overriden variables
/// Holds the items of the tab bar.
///
/// This property has a custom setter, because whenever we set the ites of the tab bar, they have to be rearranged.
///
/// The setter of this variable invokes function `setItems(_:animated:)`, which does all the rearranging work.
///
/// Because of the setter, we need to specify a variable which holds the actual value of this property - in this case, that is `_items`.
///
/// We return `_items` when getting this property's value.
override var items: [UITabBarItem]?
{
get { return _items }
set { setItems(newValue, animated: animated) }
}
//MARK: Instance variables
/// Indicates whether any changes to the tab bar should be animated.
var animated: Bool = false
/// Holds the actual style of the tab bar which later will be used to determine which style should we draw.
///
/// - See: `MWTabBarStyle` for more details on the styles.
var _style: MWTabBarStyle = .system
{
didSet
{
_init()
}
}
/// Holds the shadow layer for a custom tab bar style.
private var shadowLayer: CALayer = CALayer()
/// Holds the layer which the shadow should be clipped to for a custom tab bar style.
private var clippingLayer: CALayer = CALayer()
/// Holds the value of `items`.
///
/// Because `items` has a custom setter which calls `setItems(_:animated)`, we need to create a property which stores its value, and prevents the application from being stuck in an infinite setter-loop - this is the purpose of this property.
///
/// We return this variable when getting `items` (that is the reason why this property is never being read from in this file).
///
/// - See: overriden property `items` for more details.
private var _items: [UITabBarItem]?
/// Holds the buttons for each item of the tab bar.
///
/// Its layout is exactly like the `_items` array.
private var buttons: [MWTabBarButton] = [MWTabBarButton]()
/// Holds the corresponding button for the currently selected item of the tab bar.
///
/// It is `nil` when no items are selected.
private var selectedButtton: MWTabBarButton?
/// A boolean which indicates whether the separator line (default shadow image) of the tab bar has already been removed.
///
/// Only used if the style of the tab bar is set to custom.
private var removedSeparatorLine: Bool = false
//MARK: - Inherited initializers from: UITabBar
override init(frame: CGRect)
{
super.init(frame: frame)
//Initialize using our custom function
_init()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
//Initialize using our custom function
_init()
}
//MARK: Inherited functions from: UITabBar
override func layoutSubviews()
{
super.layoutSubviews()
//Lay out subviews
self.layoutIfNeeded()
}
override func layoutIfNeeded()
{
//Update/redraw the custom tab bar if the style is custom
if(_style == .custom)
{
//Remove the separator line if we have not removed it already
if(!removedSeparatorLine)
{
if let separatorLine = getSeparatorLine(for: self)
{
separatorLine.isHidden = true
removedSeparatorLine = true
}
}
//Update/redraw
clippingLayer.frame = self.bounds.offsetBy(dx: 0.0, dy: -(self.bounds.height -- 30.0)).withSize(width: self.bounds.width, height: 30.0)
let shadowPath = UIBezierPath(rect: self.bounds.scaleBy(width: -10.0, height: 0.0))
shadowLayer.frame = clippingLayer.bounds.offsetBy(dx: 0.0, dy: clippingLayer.bounds.height)
shadowLayer.shadowOffset = CGSize(width: 5.0, height: -4.0)
shadowLayer.shadowPath = shadowPath.cgPath
}
//Lay out the items
_setItems(animated: true)
//Set the selected button if there none of them is selected
self.selectedButtton ?= {
self.buttons[0].isSelected = true
self.selectedButtton = self.buttons[0]
}
}
override func setItems(_ items: [UITabBarItem]?, animated: Bool)
{
//Check what should the function do
MWUtil.nilcheck(items, not: {
MWUtil.nilcheck(self.items, nil: {
//Set intitial items of the tab bar / show the items of the tab bar
self._setItems(items!, animated: animated)
}, not: {
if(self.items!.count > items!.count)
{
//Add a new tab bar item
self.addItems(new: items!, animated: animated)
}
else if(self.items!.count < items!.count)
{
//Remove a tab bar item
self.removeItems(new: items!, animated: animated)
}
})
}) {
MWUtil.nilcheck(self.items, not: {
//Remove all items of the tab bar
self.removeAllItems(animated)
})
}
}
//MARK: Instance functions
/// Custom initializer for drawing specific tab bar styles.
private func _init()
{
switch _style
{
case .system:
break
case .custom:
self.layer.masksToBounds = false
clippingLayer.frame = self.bounds.offsetBy(dx: 0.0, dy: -(self.bounds.height -- 30.0)).withSize(width: self.bounds.width, height: 30.0)
clippingLayer.masksToBounds = true
let shadowPath = UIBezierPath(rect: self.bounds.scaleByCentered(width: -10.0, height: 0.0))
shadowLayer.frame = clippingLayer.bounds.offsetBy(dx: 0.0, dy: clippingLayer.bounds.height)
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowRadius = 7.0
shadowLayer.shadowOpacity = 0.5
shadowLayer.shadowOffset = CGSize(width: 5.0, height: -4.0)
shadowLayer.shadowPath = shadowPath.cgPath
shadowLayer.masksToBounds = false
clippingLayer.addSublayer(shadowLayer)
self.layer.addSublayer(clippingLayer)
break
}
}
/// Sets/rearranges the items of the tab bar.
///
/// - Parameters:
/// - items: The items that should initially be added to the tab bar. It is unnecccessary to provide, if using the function to rearrange.
/// - animated: A boolean which indicates that the process of adding the buttons initially or rearranging the existing ones should be animated.
private func _setItems(_ items: [UITabBarItem]? = nil, animated: Bool, function: String = #function)
{
//Check if we are setting the item initially
//If we are, an array of the new items must be provided, meaning it cannot be nil
//If we are not, the items array is nil, because we already have the items set
MWUtil.nilcheck(items, not: {
//Initialize the "_items" array
_items = [UITabBarItem]()
//If we are, calculate one item's width based on the tab bar's width
let width: CGFloat = self.frame.width / CGFloat(items!.count)
//Iterate through the new items and add them
for (i, item) in items!.enumerated()
{
//Create the button for the current item
let button: MWTabBarButton = MWTabBarButton(tabBar: self, tabBarItem: item)
//Create the frame for the button
let frame: CGRect = CGRect(x: CGFloat(i) * width, y: 0.0, width: width, height: self.frame.height)
//Check if we have to animate
if(animated)
{
//If we have to, prepare the button's alpha value
button.alpha = 0.0
//Do the fade in animation
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseOut, animations: {
button.alpha = 1.0
}, completion: nil)
}
//Set the button's frame
button.frame = frame
//Set the button's target for selecting
button.addTarget(self, action: #selector(releaseSelect(sender:)), for: .touchUpInside)
//Add the button to the tab bar
self.addSubview(button)
//Add the item to the tab bar items
buttons.append(button)
_items!.append(item)
}
}) {
//If we are not, calculate one item's width based on the tab bar's width
let width: CGFloat = self.frame.width / CGFloat(self.items!.count)
//Iterate through the existing items and rearrange them
for (i, _) in self.items!.enumerated()
{
//Get the button for the current item
let button: MWTabBarButton = self.buttons[i]
//Update the "hidesTitle" property of the buttons
button.hidesTitle = self.hidesTitles
//Create the frame for the button
let frame: CGRect = CGRect(x: CGFloat(i) * width, y: 0.0, width: width, height: self.frame.height)
//Check if we have to animate
if(animated)
{
//If we have to, do the animation where all items fly to their positions
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseInOut, animations: {
button.frame = frame
}, completion: nil)
}
else
{
//If we do no have to, simply set the button's frame
button.frame = frame
}
}
}
}
/// Adds one or more items to the tab bar.
///
/// - Parameters:
/// - items: The array which contains the item(s) that should be added to the tab bar.
/// - animated: A boolean which indicates that the process of adding the new button(s) and resizing the existing ones should be animated.
private func addItems(new items: [UITabBarItem], animated: Bool)
{
//Calculate one item's width based on the tab bar's width
let width: CGFloat = self.frame.width / CGFloat(items.count)
for (i, item) in items.enumerated()
{
//Calculate the new frame of the button no matter what
let frame: CGRect = CGRect(x: CGFloat(i) * width, y: 0.0, width: width, height: self.frame.height)
//Check if the item exists in the current items of the tab bar
guard let _ = self.items!.index(of: item) else
{
//If it does not, the current item is the new item, or one of the new items
//This means that we have to create a new button for it.
//Create a new button
let button: MWTabBarButton = MWTabBarButton(tabBar: self, tabBarItem: item)
//Check if we have to animate
if(animated)
{
//If we do, prepare the button for the animation
button.alpha = 0.0
//Do the animation
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseOut, animations: {
button.frame = frame
button.alpha = 1.0
}, completion: nil)
}
else
{
//If we do not, simply set the button's frame
button.frame = frame
}
//Set the button's target for selecting
button.addTarget(self, action: #selector(releaseSelect(sender:)), for: .touchUpInside)
//Add this new item to the final array
buttons.insert(button, at: i)
_items!.insert(item, at: i)
continue
}
//If the operation above succeeds, the item is among the current items of the tab bar, meaning we have to resize its button
//Get the button for the current item
let button: MWTabBarButton = buttons[i]
//Check if we have to animate
if(animated)
{
//If we do, do the animation
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseOut, animations: {
button.frame = frame
}, completion: nil)
}
else
{
//If we do not, simply set the button's frame
button.frame = frame
}
}
}
/// Removes one or more items from the tab bar.
///
/// - Parameters:
/// - items: An array without the item(s) that has/have to be removed.
/// - animated: A boolean which indicates that the process of removing the button(s) and resizing the existing ones should be animated.
private func removeItems(new items: [UITabBarItem], animated: Bool)
{
let width: CGFloat = self.frame.width / CGFloat(items.count)
//An iterator for buttons that are not going to get removed
//Required for frame calculation
var _i: Int = 0
for (i, item) in self.items!.enumerated()
{
//Get the button for the item
let button: MWTabBarButton = buttons[i]
//Try to get the index of the current item in the array which does not contain the item which should be removed
//If the operation succeeds, the else block will not be executed, and we can assume that the current item is not the item which should be removed
guard let _ = items.index(of: item) else
{
//If this block gets executed, we assume that the current item can not be found in the new array, which means the current item is the button which should be removed
//Check if we have to animate
if(animated)
{
//If we do, do the animation
//As a completion after the animation has finished, we remove the button finally
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseIn, animations: {
button.frame = CGRect.zero
button.alpha = 0.0
}, completion: { (finished: Bool) in
button.removeFromSuperview()
self.buttons.remove(at: i)
self._items!.remove(at: i)
})
}
else
{
//If we do not, simply remove the button
button.removeFromSuperview()
buttons.remove(at: i)
_items!.remove(at: i)
}
continue
}
//This segment should only be executed if the current item is not going to be removed
//Check if we have to animate
if(animated)
{
//If we do, do the animation
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseIn, animations: {
button.frame = CGRect(x: CGFloat(_i) * width, y: 0.0, width: width, height: self.frame.height)
}, completion: nil)
}
else
{
//If we do not, simply set the button's frame
button.frame = CGRect(x: CGFloat(_i) * width, y: 0.0, width: width, height: self.frame.height)
}
//Increment the iterator for buttons that are not going to get removed
_i += 1
}
}
/// Removes all the items from the tab bar.
///
/// - Parameter animated: A boolean which indicates that the process of removing all the buttons should be animated.
private func removeAllItems(_ animated: Bool)
{
//Iterate through all the items
for (i, _) in self.items!.enumerated()
{
//Get the button for the current item
let button: MWTabBarButton = buttons[i]
//Check if we have to animate
if(animated)
{
//If we do, do the fade out animation and, as a completion, remove the item
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseIn, animations: {
button.alpha = 0.0
}, completion: { (finished: Bool) in
button.removeFromSuperview()
self.buttons.remove(at: i)
self._items!.remove(at: i)
})
}
else
{
//If we do not, simply remove the item
button.removeFromSuperview()
buttons.remove(at: i)
_items!.remove(at: i)
}
}
}
/// Called whenever a button is selected.
///
/// - Parameter sender: The button which has just been selected.
@objc private func releaseSelect(sender: MWTabBarButton)
{
//Deselect the currently selected button if there was one before
selectedButtton?.isSelected = false
//Select the new button
sender.isSelected = true
selectedButtton = sender
//Inform the delegate that an item has been selected
self.delegate?.tabBar?(self, didSelect: sender.tabBarItem)
}
/// Searches for a separator line in subviews of the given view
///
/// - Parameter view: The view whose subviews the function should search for the separator line in.
/// - Returns: The separator line (default shadow image) of the tab bar.
private func getSeparatorLine(for view: UIView) -> UIImageView?
{
//Check if the current view is the separator line
if(view is UIImageView && view.frame.height <= 1)
{
//If it is, return it as a "UIImageView"
return view as? UIImageView
}
//If it is not, search for it in its subviews
for subview in view.subviews
{
//For optimization puposes, we exclude the buttons from the search
//(We are looking for a view with type "_UIBarBackground", but that is not a public view type available in UIKit.)
if(!(subview is MWTabBarButton))
{
if let shadowImage = getSeparatorLine(for: subview)
{
return shadowImage
}
}
}
return nil
}
}
/// A custom button for a tab bar item on a tab bar.
class MWTabBarButton: UIControl
{
/// A boolean indicating whether the button is selected.
///
/// Whenever we set this value, based on the new value, the button either displays itself selected or unselected.
override var isSelected: Bool
{
didSet
{
//Check if the button is currently selected
if(isSelected)
{
//If it is, display the selected look
//Set the image view
imageView.silently().tintingColor = selectedColor
UIView.transition(with: imageView, duration: 0.1, options: .transitionCrossDissolve, animations: {
self.imageView.image = self.selectedImage
}, completion: nil)
//Optionally, set the label
MWUtil.nilcheck(label, not: {
UIView.transition(with: label!, duration: 0.1, options: .transitionCrossDissolve, animations: {
self.label!.textColor = self.selectedColor
}, completion: nil)
})
}
else
{
//If it is not, display the unselected look
//Set the image view
imageView.silently().tintingColor = unselectedColor
UIView.transition(with: imageView, duration: 0.1, options: .transitionCrossDissolve, animations: {
self.imageView.image = self.image
}, completion: nil)
//Optionally, set the label
MWUtil.nilcheck(label, not: {
UIView.transition(with: label!, duration: 0.1, options: .transitionCrossDissolve, animations: {
self.label!.textColor = self.unselectedColor
}, completion: nil)
})
}
}
}
/// The frame of the button.
///
/// Whenever we set its value, the button updates its layout, but only if the button has already been initialized.
override var frame: CGRect
{
didSet
{
//Check if the button has already been initialized
if(initilaized)
{
//If it has, layout immediately
layoutIfNeeded()
}
}
}
/// The tab bar item corresponding to this button.
var tabBarItem: UITabBarItem!
/// A boolean which indicates whether the button should hide the item's title.
var hidesTitle: Bool = false
/// A boolean which indicates whether the button has already been initialized.
///
/// If set to `true`, the button will lay out itself automatically whenever the frame changes.
private var initilaized: Bool = false
/// The image that sould show the image provided in the corresponding tab bar item.
private var imageView: MWImageView!
/// The image provided in the corresponding tab bar item for the unselected state.
private var image: UIImage!
/// The image provided in the corresponding tab bar item for the selected state.
private var selectedImage: UIImage!
/// The label showing the title of the tab bar item if the tab bar does not hide titles.
private var label: UILabel?
/// The color that the button should be tinted with if it is selected.
private var selectedColor: UIColor!
/// The color that the button should be tinted with if it is not selected.
private var unselectedColor: UIColor!
/// Makes an `MWTabBarItem` instance out of the given parameters.
///
/// - Parameters:
/// - tabBar: The tab bar that this button belongs to.
/// - tabBarItem: The tab bar item which corresponds to this button.
///
/// In the supercall, we provide a zero rectangle as the frame of the control.
///
/// Laying out the actual frame of the button is done explicitly in `MWTabBar`.
///
/// - See: `_setItems(_:animated:)` in `MWTabBar` for more details on the frame.
init(tabBar: MWTabBar, tabBarItem: UITabBarItem)
{
super.init(frame: CGRect.zero)
//Set the colors
self.selectedColor = tabBar.tintColor
self.unselectedColor = tabBar.unselectedItemTintColor ?? UIColor.lightGray
//Create the image view
self.imageView = MWImageView(frame: CGRect.zero)
self.image = tabBarItem.image ?? MWAssets.Images.imageNoImage.getImage(in: Bundle(for: type(of: self)), traits: self.traitCollection)
self.selectedImage = tabBarItem.selectedImage ?? tabBarItem.image
imageView.silently().tintingColor = unselectedColor
imageView.image = image
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//Add the image view
self.addSubview(imageView)
//Check if we are not hiding the title
if(!tabBar.hidesTitles)
{
//If we are not, create the label
self.label = UILabel()
label!.font = tabBarItem.titleTextAttributes(for: .normal)?[NSFontAttributeName] as? UIFont ?? UIFont.systemFont(ofSize: 10.0)
label!.text = tabBarItem.title
label!.textColor = self.unselectedColor
label!.textAlignment = .center
label!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//Add the label
self.addSubview(label!)
}
//Set other variables
self.tabBarItem = tabBarItem
self.hidesTitle = tabBar.hidesTitles
//Allow the button to lay out itself whenever its frame is changed
initilaized = true
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
MWLError("MWTabBarButton has been initialized with initializer: \"required init?(coder:)\" Nothing will happen, creating an empty view...", module: nil)
self.frame = CGRect.zero
}
/// Lays out the subviews of the button based on the button's frame.
override func layoutIfNeeded()
{
//Set the frame for the image view based on whether we hide the title
if(hidesTitle)
{
//Hide the title label
label?.isHidden = true
//If do hide the title, the image view's frame is centered both horizontally and vertically
imageView.frame = CGRect(x: (self.frame.width - image.size.width) / 2, y: (self.frame.height - image.size.height) / 2, width: image.size.width, height: image.size.height)
}
else
{
//Show the title label
label?.isHidden = false
//If do not hide the title, the image view's frame is slightly offsetted from the top of the button
imageView.frame = CGRect(x: (self.frame.width - image.size.width) / 2, y: 7, width: image.size.width, height: image.size.height)
//Also, if we do not hide the title, set the label
label!.sizeToFit()
label!.frame = label!.frame.withPosition(x: (self.frame.width - label!.frame.width) / 2, y: self.frame.height - label!.frame.height - 1.0)
self.clipsToBounds = false
}
}
}
/// The enumeration which holds all tab bar styles that currently exist in myWatch.
enum MWTabBarStyle: Int
{
/// Case __system__ involves having a tab bar which looks like the system default
case system
/// Case __custom__ involves having a tab bar with a custom shadow and with the 1px separator line removed.
case custom
///Holds the total amount of styles in this enumeration.
///
///This is required to make clamping the value given in `style` in `MWTabBar` possible.
static var count: Int
{
return self.custom.hashValue + 1
}
}
| gpl-3.0 | 3830de80fcbb6a91fe48b50dea51c0d4 | 38.238482 | 245 | 0.555598 | 4.984165 | false | false | false | false |
jubinjacob19/ExpandableTableView | ExpandableTableView/ExpandableTableViewController.swift | 1 | 4660 | //
// ExpandableTableViewController.swift
// CollapsibleTableView
//
// Created by Jubin Jacob on 10/08/16.
// Copyright © 2016 J. All rights reserved.
//
import UIKit
open class ExpandableTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
fileprivate lazy var sizingCell : ExpandableTableViewCell = {
guard let cell = self.tableView.dequeueReusableCell(withIdentifier:"CellID") as? ExpandableTableViewCell else{
preconditionFailure("reusable cell not found")
}
return cell
} ()
fileprivate lazy var tableView : UITableView = {
let tbl = UITableView(frame: CGRect.zero)
tbl.separatorColor = UIColor.lightGray
tbl.translatesAutoresizingMaskIntoConstraints = false
tbl.dataSource = self
tbl.delegate = self
tbl.register(ExpandableTableViewCell.self, forCellReuseIdentifier: "CellID")
return tbl
} ()
open var dataSourceArray = [ItemModel]()
var expandedIndexPaths : [IndexPath] = [IndexPath]()
public convenience init(faqs: [ItemModel]) {
self.init(nibName: nil, bundle: nil)
self.dataSourceArray = faqs
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
self.title = "FAQ"
self.addSubviews()
}
fileprivate func addSubviews() {
self.view.addSubview(self.tableView)
let views = ["view":self.tableView]
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
//MARK: table view datasource
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell : ExpandableTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CellID") as? ExpandableTableViewCell else {
preconditionFailure("reusable cell not found")
}
let item = self.dataSourceArray[(indexPath as NSIndexPath).row]
cell.setCellContent(item, isExpanded: self.expandedIndexPaths.contains(indexPath))
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSourceArray.count
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
return UITableViewAutomaticDimension
} else {
return self.dynamicCellHeight(indexPath)
}
}
open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return self.dynamicCellHeight(indexPath)
}
open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
}
//MARK: table view delegate
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(self.expandedIndexPaths.contains(indexPath)) {
let idx = self.expandedIndexPaths.index(of: indexPath)
self.expandedIndexPaths.remove(at: idx!)
} else {
self.expandedIndexPaths.append(indexPath)
}
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
//MARK: compute cell height
fileprivate func dynamicCellHeight(_ indexPath:IndexPath)->CGFloat {
let item = self.dataSourceArray[(indexPath as NSIndexPath).row]
sizingCell.setCellContent(item, isExpanded: self.expandedIndexPaths.contains(indexPath))
sizingCell.setNeedsUpdateConstraints()
sizingCell.updateConstraintsIfNeeded()
sizingCell.setNeedsLayout()
sizingCell.layoutIfNeeded()
return sizingCell.cellContentHeight()
}
}
| mit | bb5fff8dd7b1c48b5e9daa5a88152366 | 37.188525 | 169 | 0.681691 | 5.494104 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_017_Generics.playground/section-2.swift | 2 | 3201 | import UIKit
/*
// Memory Management
//
// Recommeded Reading:
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-ID179
/==============================*/
/*-----------------------------/
// Generic Function
/-----------------------------*/
func swapVals<T>(inout v1: T, inout v2: T) {
let temp = v1
v1 = v2
v2 = temp
}
var sA = "one"
var sB = "two"
swapVals(&sA, &sB)
sA
sB
var iA = 1
var iB = 2
swapVals(&iA, &iB)
iA
iB
/*-----------------------------/
// Generic Type
/-----------------------------*/
struct Stack<T> {
var q = [T]()
mutating func push(item: T) {
q.append(item)
}
mutating func pop() -> T {
return q.removeLast()
}
}
var ints = Stack<Int>()
ints.push(1)
ints.push(2)
ints.push(3)
ints.pop()
ints.pop()
ints.pop()
var strs = Stack<String>()
strs.push("un")
strs.push("deux")
strs.push("trois")
strs.pop()
strs.pop()
strs.pop()
/*----------------------------------/
// Constraining Types: Subclasses
/----------------------------------*/
class Dog {
func bark() -> String {
return "bark"
}
}
class Dachshund: Dog {
override func bark() -> String {
return "yap"
}
}
class Mastiff: Dog {
override func bark() -> String {
return "RAWR"
}
}
struct BarkStack<T: Dog> {
var q = [T]()
mutating func add(dog: T) {
q.append(dog)
}
func sing() -> String {
var s = ""
for dog in q {
s += dog.bark()
}
return s
}
}
var dachshunds = BarkStack<Dachshund>()
dachshunds.add(Dachshund())
dachshunds.add(Dachshund())
dachshunds.sing()
var mastiffs = BarkStack<Mastiff>()
mastiffs.add(Mastiff())
mastiffs.add(Mastiff())
mastiffs.sing()
var dogs = BarkStack<Dog>()
dogs.add(Mastiff())
dogs.add(Dachshund())
dogs.add(Mastiff())
dogs.add(Dachshund())
dogs.sing()
/*----------------------------------/
// Constraining Types: Protocols
/----------------------------------*/
struct OrderableStack<T: Comparable> {
var q = [T]()
mutating func push(item: T) {
q.append(item)
}
mutating func pop() -> T {
return q.removeLast()
}
// New Stuff
mutating func sorted() -> [T] {
return q.sorted { $0 < $1 }
}
}
var orderable = OrderableStack<Double>()
orderable.push(3.14)
orderable.push(22.0/7.0)
orderable.push(1.0)
orderable.push(42.0)
orderable.sorted()
/*------------------------------------------/
// Generic Protocols and Associated Types
/------------------------------------------*/
protocol Stackable {
typealias ItemType
mutating func push(item: ItemType)
mutating func pop() -> ItemType
}
// Explicit implementation of Stackable protocol with `Int`s
struct ExplicitStack<Int>: Stackable {
typealias ItemType = Int
var q = [ItemType]()
mutating func push(item: ItemType) {
q.append(item)
}
mutating func pop() -> ItemType {
return q.removeLast()
}
}
// No need to explicity give ItemType's type
// and can use a generic type for the items.
struct ImplicitStack<T>: Stackable {
var q = [T]()
mutating func push(item: T) {
q.append(item)
}
mutating func pop() -> T {
return q.removeLast()
}
}
| gpl-3.0 | efd2ac01f1f82321ed83f8032e052587 | 16.396739 | 157 | 0.556701 | 3.166172 | false | false | false | false |
drewcrawford/DCAKit | DCAKit/Swiftastic/PowerOptionals.swift | 1 | 7724 | //
// PowerOptionals.swift
// DCAKit
//
// Created by Drew Crawford on 1/14/15.
// Copyright (c) 2015 DrewCrawfordApps.
// This file is part of DCAKit. It is subject to the license terms in the LICENSE
// file found in the top level of this distribution and at
// https://github.com/drewcrawford/DCAKit/blob/master/LICENSE.
// No part of DCAKit, including this file, may be copied, modified,
// propagated, or distributed except according to the terms contained
// in the LICENSE file.
/**This library provides some high-power tools for Swift optionals that have proven themselves useful for real-world applications.
Many functions have the property that ideally they return some value (like a String) but in rare cases they may produce an error. PowerOptionals supplies an ErrorOr<T> that you can use as a return type to encapsulate this behavior.
There are many advantages to using PowerOptionals instead of rolling your own:
1. Convenient ways (.error? .value?) to get and check if errors occurred
2. Debugging support built-in, with things like line and file numbers inside the error userInfo
3. Convenient "pass-through" syntax for chaining error types between functions
func foo(ErrorOr<Int> inValue) -> ErrorOr<String> {
if (inValue.error?) {
return ErrorOrCast(inValue) //automatically produce an ErrorOr<String> with the right value
}
return ErrorOr("String")
}
4. Lots of out-of-the-box support. For example, casting:
var i : Int? = nil
let j : ErrorOr<String> = PowerOptionalsCast(2)
//instead of
if let j = i as? String {
}
else {
//error
}
Note that PowerOptionals produces distinct errors for `ValueWasNil` vs `ValueCantBeCast`, and also includes file, line numbers, and optionally a programmer-specified `label` indicating the conversion that failed.
*/
import Foundation
//rdar://19479575
public let PowerOptionalsErrorDomain = "PowerOptionalsErrorDomain"
public class PowerOptionalsErrors {
public enum Codes: Int {
case ValueWasNil
case ValueCantBeCast
}
public class func error(code: Codes, userInfo:[NSObject : AnyObject]?) -> NSError {
return NSError(domain: PowerOptionalsErrorDomain, code: code.rawValue, userInfo: userInfo)
}
}
/** due to
rdar://19480424
and
rdar://19479187
*/
public final class SillyCompiler<A> {
let value: A
public init(_ value: A) {
self.value = value
}
}
/**A value that holds either an error, or the specified type. */
public enum ErrorOr<T> : Printable {
case Error(NSError)
case Value(SillyCompiler<T>)
/**Simpler syntax for creating values */
public init (value: T) {
self = .Value(SillyCompiler(value))
}
public init (error: NSError) {
self = .Error(error)
}
public var debugDescription: String {
switch(self) {
case Error(let err):
return "\(err)"
case Value(let sillycompiler):
return "\(sillycompiler.value)"
}
}
public var isError : Bool {
switch(self) {
case Error:
return true
default:
return false
}
}
public var isValue : Bool {
switch(self) {
case Value:
return true
default:
return false
}
}
public var error : NSError? {
switch(self) {
case Error(let err):
return err
default:
return nil
}
}
public var value: T? {
switch(self) {
case Value (let val):
return val.value
case Error:
return nil
}
}
public func handlers(valueHandler: (T)->(), errorHandler: (NSError)->()) {
if let v = value {
valueHandler(v)
}
else {
errorHandler(error!)
}
}
public var description : String {
get {
var rest = ""
switch (self) {
case .Error(let err):
rest = err.description
case .Value(let sc):
rest = "\(sc.value)"
}
return "ErrorOr<\(T.self)> \(rest)"
}
}
}
/**
This function attempts to cast an ErrorOr<A> into an ErrorOr<B>
In the error case, the error is preserved
In the value case, a cast is attempted, if successful you get a value, or otherwise you get a cast error
:param: t value to be converted
:param: label Optional label to be displayed in error messages
:param: file Optional filename to be displayed in error messages. The default value is the caller's.
:param: line Optional linenumber to be displayed in error messages. The default value is the caller's.
:returns: Declare the return type explicitly so we know what to convert to.
:warning: This must be AnyObject because of rdar://19480736 and/or rdar://19479752, but we'd rather it be `Any?` For the same reason, we can't fit it inside the enum itself, see also https://twitter.com/drewcrawford/status/555618897341067264
*/
public func ErrorOrCast<A, T: AnyObject> (t: ErrorOr<T>, label: String = "", file:String = __FILE__, line: UInt = __LINE__) -> ErrorOr<A> {
switch(t) {
case .Error(let err) :
return .Error(err)
case .Value(let sc):
return Cast(sc.value, label: label, file:file, line:line)
}
}
/**
Performs a cast between the first parameter and a ErrorOr<Whatever>.
:param: t value to be converted
:param: label Optional label to be displayed in error messages
:param: file Optional filename to be displayed in error messages. The default value is the caller's.
:param: line Optional linenumber to be displayed in error messages. The default value is the caller's.
:returns: Declare the return type explicitly so we know what to convert to.
:warning: I think a can't be Any? because of rdar://19480736 and/or rdar://19479752, so instead we declare it AnyObject? */
public func Cast<A>(a: AnyObject?, label: String = "", file: String = __FILE__, line: UInt = __LINE__, function : String = __FUNCTION__, column : Int = __COLUMN__) ->ErrorOr<A> {
let resultOrNil = Let(a, label: label, file: file, line: line)
switch(resultOrNil) {
case .Error (let err):
return ErrorOr<A>.Error(err)
case .Value(let sillyCompiler):
if let a = a as? A {
return ErrorOr<A>.Value(SillyCompiler(a))
}
else {
return ErrorOr<A>.Error(PowerOptionalsErrors.error(.ValueCantBeCast, userInfo: ["label":label, "file":file,"line":line, "function":function, "column":column, "from":"\(a)"]))
}
}
}
/**
Type casts between the parameter and ErrorOr<Whatever>, such that we attempt to convert the parameter to Whatever
:param: a value to be converted
:param: label Optional label to be displayed in error messages
:param: file Optional filename to be displayed in error messages. The default value is the caller's.
:param: line Optional linenumber to be displayed in error messages. The default value is the caller's.
:returns: Declare the return type explicitly so we know what to convert to.
*/
public func Let<A> (a: A?, label: String = "", file: String = __FILE__, function: String = __FUNCTION__, line: UInt = __LINE__, column: Int = __COLUMN__) -> ErrorOr<A> {
if let a = a {
return ErrorOr.Value(SillyCompiler(a))
}
return ErrorOr.Error(PowerOptionalsErrors.error(.ValueWasNil, userInfo: ["label":label,"file":file,"line":line]))
}
/**Conditional assignment */
infix operator =? { associativity right precedence 90 assignment }
public func =?<T> (inout left: T, right: T?) {
if let r = right {
left = r
}
}
| mit | 32faccad5bdb8c1578af99e434651f8c | 32.582609 | 242 | 0.648628 | 3.979392 | false | false | false | false |
jackxie1988/Swift-Study | Sources/SimpleNetwork.swift | 1 | 5654 | //
// SimpleNetwork.swift
// SimpleNetwork
//
// Created by 谢聪捷 on 3/3/15.
// Copyright (c) 2015 谢聪捷. All rights reserved.
//
import Foundation
/// 常用的网络访问方法 -> 枚举类型的定义
///
/// - GET: GET 请求
/// - POST: POST 请求
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
public class SimpleNetwork {
/// 请求 JSON 方法一
///
/// :param: Method HTTP 访问方法
/// :param: urlString urlString
/// :param: params 可选参数字典
/// :param: completion 完成回调
// 取别名:定义闭包类型,类型别名 -> 首字母一定要大写
public typealias Completion = (result: AnyObject?, error: NSError?) -> ()
public func requestJSON(method: HTTPMethod, _ urlString: String, _ params: [String: String]?,completion: Completion) {
// 实例化网络请求
if let request = request(method, urlString, params) {
// 访问网络 - 本身的回调方法是异步的
session!.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in
// 如果有错误,直接回调,将网络访问的错误传回
if error != nil {
completion(result: nil, error: error)
return
}
// 反序列化 -> 字典或者数组
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
// 判断是否反序列化成功
if json == nil {
let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "反序列化失败"])
completion(result: json, error: error)
} else {
// 反序列化成功,有结果
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(result: json, error: nil)
})
}
}).resume()
return
}
// 如果网络请求没有创建成功,应该生成一个错误,提供给其他的开发者
/**
domain: 错误所属领域字符串,com.itheima.error
code: 如果是复杂的系统,可以自己定义错误编号
userInfo: 错误信息字典
*/
let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "请求建立失败"])
completion(result: nil, error: error)
}
// 类属性,跟对象无关,调用时需使用类名调用
static let errorDomain = "com.itheima.error"
/// 全局网络会话, 提示,可以利用构造函数,设置不同的网络会话配置
lazy var session: NSURLSession? = {
return NSURLSession.sharedSession()
}()
/// 返回网络访问的请求
///
/// :param: method HTTP 访问方法
/// :param: urlString urlString
/// :param: params 可选参数字典
///
/// :returns: 可选网络请求
func request(method: HTTPMethod, _ urlString: String, _ params: [String: String]?) -> NSURLRequest? {
// isEmpty 是 "" & nil
if urlString.isEmpty {
return nil
}
// 记录 urlString,因为传入的参数是不可变的
var urlStr = urlString
var r: NSMutableURLRequest?
if method == .GET {
// URL 的参数是拼接在URL字符串中的
// 1.生成查询字符串
let query = queryString(params)
// 2.如果有拼接参数
if query != nil {
urlStr += "?" + query!
}
// 3.实例化请求
r = NSMutableURLRequest(URL: NSURL(string: urlStr)!)
} else {
// 设置请求体,提问:POST访问,能没有请求体码? -> 必需要提交数据给服务器
if let query = queryString(params) {
r = NSMutableURLRequest(URL: NSURL(string: urlString)!)
// 设置请求方法
// swift 语言中,枚举类型,如果要取返回值,需要使用一个 rawValue
r!.HTTPMethod = method.rawValue
// 设置数据体
r!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
}
}
return r
}
/// 生成查询字符串
///
/// :param: params 可选字典
///
/// :returns: 拼接完成的字符串
func queryString(params: [String: String]?) -> String? {
// 1. 判断参数
if params == nil {
return nil
}
// 2.涉及到数组的使用技巧
// 2.1 定义一个数组
var array = [String]()
// 2.2 遍历字典
for (k, v) in params! {
// 字典中的值要进行百分号转义 以防止特殊符号的拼接
let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
array.append(str)
}
return join("&", array)
}
// 公共的初始化函数,外部就能够调用了
public init() {}
}
| mit | f14b51dbc38969494cef1ad2ba7e759d | 20.56682 | 135 | 0.479487 | 4.325323 | false | false | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/AccessControl.swift | 1 | 12047 | //
// AccessControl.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/9/13.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
/*
访问控制 限制来自其他资源文件和模块的代码对你代码部分的访问。
这个特性可以让你隐藏代码的实现细节,并且可以让你指定一个更喜欢的接口。代码可以通过这个接口被访问和使用。
模块和资源文件
Swift 的访问控制模型是基于模块和资源文件的概念。
模块 是代码分发的独立单元——可以作为一个独立单元被构建和发布的 Framework 或 Application。
模块可以被另一个模块用 Swift 的 import 关键字引用。
在 Swift 中,Xcode 的每个构建目标(比如 app bundle 或 framework )都被当作一个独立模块。
如果你的团队把应用中部分代码放在一起作为一个独立的 framework ——可能用来在多个应用中包含和复用代码——然后,
当它被一个应用引用和使用,或被另一个 framework 使用的时候,在这个 framework 中定义的每个东西都将作为独立模块的一部分。
资源文件 是模块中单独的 Swift 源代码文件(实际上是应用或 framework 中的单独文件)。
虽然在不同的源文件中定义格子的类型是常见的,但一个单独的源文件可以包含不同类型、函数等的定义。
Swift 为代码中的实体提供了五种不同的 访问级别 。这些访问级别与定义实体的源文件相关联 ,也与源文件所属的模块相关联。
Open 访问 和 public 访问 使实体可以在定义所在的模块的任何源文件中使用,
也可以在引用了定义所在的模块的另一个模块中的源文件中使用。当为 framework 声明公用接口时常常使用 open 访问 或 public 访问 。
Internal 访问 使实体可以在定义所在的模块的任何源文件中使用 ,但是不能在这个模块之外的任何源文件中使用。
当定义一个应用或 framework 的内部结构时,常常使用Internal 访问 。
File-private 访问 限制实体只能在它定义所在的源文件中使用。当一个特定功能片段在整个文件中使用时,
用 file-private 访问 来隐藏它的实现细节。
Private 访问 限制实体用于在同一个文件中附加声明、扩展声明。当一个特定功能片段仅仅被用在单个声明中时,
用 Private 访问 隐藏它的实现细节。
Open 访问是最高的(限制性更弱的)访问级别,而 private 访问是最低的(限制性更强的)访问级别。
Open 访问仅仅应用于类和类的成员。它在几个方面区别于 public 访问:
public 访问或其他更多限制访问级别修饰的类,仅可以被其定义所在模块中的类继承。
public 访问或其他更多限制访问级别修饰的类成员,仅可以被其定义所在模块中的子类重载。
Open 修饰的类可以被其定义所在模块或任何引用其定义所在模块的模块中的类继承。
Open 修饰的类成员可以被其定义所在模块或任何引用该模块的模块中的子类重载。
public class SomePublicClass {}
internal class SomeInternalClass {}
fileprivate class SomeFilePrivateClass {}
private class SomePrivateClass {}
public var somePublicVariable = 0
internal let someInternalConstant = 0
fileprivate func someFilePrivateFunction() {}
private func somePrivateFunction() {}
除非另有规定,默认访问级别为 internal。 这意味着 SomeInternalClass 和 someInternalConstant
可以不用写显式访问级别修饰符,并且依然有访问级别 internal :
class SomeInternalClass {} // 隐式 internal
let someInternalConstant = 0 // 隐式 internal
public class SomePublicClass { // 显式 public 类
public var somePublicProperty = 0 // 显式 public 类成员
var someInternalProperty = 0 // 隐式 internal 类成员
fileprivate func someFilePrivateMethod() {} // 显式 file-private 类成员
private func somePrivateMethod() {} // 显式 private 类成员
}
class SomeInternalClass { // 隐式 internal 类
var someInternalProperty = 0 // 隐式 internal 类成员
fileprivate func someFilePrivateMethod() {} // 显式 file-private 类成员
private func somePrivateMethod() {} // 显式 private 类成员
}
fileprivate class SomeFilePrivateClass { // 显式 file-private 类
func someFilePrivateMethod() {} // 隐式 file-private 类成员
private func somePrivateMethod() {} // 显式 private 类成员
}
private class SomePrivateClass { // 显式 private class
func somePrivateMethod() {} // 隐式 private 类成员
}
*/
/*
元组类型
元组类型的访问权限是元组中使用的全部类型的访问级别中限制性最强的。
如果你组合两种不同类型的元组,一个带有 internal 访问,另一个带有 private 访问,合成的元组类型的访问级别将是 private.
元组类型没有像类、结构体、枚举、和函数那样的单独的定义。元组类型的访问级别是在使用元组时自动推导出来的,它不能被显式地指定。
*/
/*
函数类型
函数类型的访问级别被计算为函数参数类型和返回值类型的限制性最强的访问级别。
如果函数的计算访问级别和上下文默认的不匹配,你必须显式地指定访问级别作为函数定义的一部分。
函数的返回值是由两个定义在自定义类型中的自定义类型组成的元组。其中一个定义为 internal,另一个定义为 private。
因此,合成的元组的整体访问级别为 private(元组的组成类型的最小访问级别)。
因为函数的返回值类型是 private,为了函数声明有效,你必须用 private 修饰符标记函数的整体访问级别:
private func someFunction() -> (SomeInternalClass, SomePrivateClass) {
// 函数实现在这
}
*/
/*
枚举类型
枚举中的独立成员自动使用该枚举类型的访问级别。你不能给独立的成员指明一个不同的访问级别。
嵌套类型
定义在 private 类型中的嵌套类型自动访问级别为 private 。
定义在 file-private 类型中的嵌套类型自动访问级别为 file-private 。
定义在 public 类型中的嵌套类型自动访问级别为 public 。
如果你想要在 public 类型中的嵌套类型能够被外部访问,你必须要显示的声明这个嵌套类型为 public。
*/
/*
子类化
你可以在符合当前访问上下文中子类化任何类。子类不能拥有高于其父类的访问等级——举个例子,
你不能写父类为 internal 类型而其子类为 public 类型的代码。
在确定可见的访问权限上下文中,你可以重写任何类成员(方法,属性,初始化器或者下标)
重写类成员可以使其比父类版本更加开放。
常量,变量,属性和下标
一个常量,变量或者属性的访问级别不能比其所代表的类型更高。
举个例子,写一个代表了 private 类型的 public 属性是无效的。
private var privateInstance = SomePrivateClass()
赋值方法和取值方法
常量,变量,属性和下标的赋值和取值方法能够自动的接收和它们访问级别一致的常量,变量,属性和下标。
你可以设置一个比取值方法更 低 访问级别的赋值方法来进行约束属性或下标的读-写范围。
你可以在 var 或 subscript 前加入修饰符 fileprivate(set), private(set), 或 internal(set) 来给其分配一个较低的访问级别
注意
该规则适用于存储和计算属性。尽管你并没有显式的对存储属性写出赋值或取值方法,
但 Swift 仍然会为你的存储属性所存储的值隐式合成赋值和取值方法。使用 fileprivate(set), private(set),
或 internal(set) 修饰符去改变这个合成赋值方法的访问级别与显式的写出计算属性的赋值方法取得的效果是完全一致的。
struct TrackedString {
private(set) var numberOfEdits = 0
var value: String = "" {
didSet {
numberOfEdits += 1
}
}
}
通过结合 pulic 和 private(set) 访问级别修饰符,
你可以让该结构体的 numberOfEdits 属性取值方法为公开的,而它的赋值方法是私有的。
public private(set) var numberOfEdits = 0
初始化器的参数访问级别类型不能比该初始化器本身拥有的访问级别更低。
默认初始化器拥有和初始化对象类型相同的访问级别,除非该类型为 public 。
当初始化对象类型被定义为 public 时,它的默认初始化器被认为是 internal 级别。
如果你想要在另外一个模块中使用无参初始化器去初始化 public 类型参数,
你必须显式的提供一个 public 类型的无参初始化器作为类型定义的一部分
如果结构体类型中的任何一个存储属性为 private 类型,则该结构体类型的默认成员初始化器被认为是 private 类型
当在另外一个模块中,如果你想要成员初始化器初始化 public 的结构体类型时,
你必须要提供一个 public 类型的成员初始化器作为该结构体类型定义的一部分。
协议
如果要为协议类型分配显式访问级别,请在定义协议时执行此操作。这可以使你创建的协议只能在特定的上下文中访问。
协议定义中每个要求的访问级别自动设置为与协议相同的访问级别。你不能将协议要求设置为与协议不同的访问级别。
这可确保在采用该协议的任何类型上都可以看到所有协议的要求。
协议继承
如果你定义一个新的协议是从现有协议中继承而来,那么新协议的访问级别最多可以与其继承的协议相同。
例如,你无法编写一个从 internal 协议继承过来的 public 协议。
扩展
在扩展中添加的任何类型成员都与原始类型声明中的成员具有相同的默认访问级别。
你可以使用显示访问级别修饰符(例如 private extension )标记扩展,
用来给扩展中定义的成员重新设置默认的访问级别。这个新的默认值仍然可以在单个类型成员的扩展中被覆盖。
如果你使用扩展来添加协议一致性,则无法为扩展提供显式访问级别修饰符。
相反,协议本身的访问级别为扩展中的每个协议要求的实现提供默认的访问级别。
扩展中的私有成员
与类、结构体或枚举值写在同一个文件中的扩展的行为和原始类型声明的部分一样。因此,你可以:
在原始声明中声明一个私有成员,并在同一个文件的扩展中访问它。
在一个扩展中声明一个私有成员,并在同一个文件中的另一个扩展中访问它。
在一个扩展中声明一个私有成员,并在同一个文件中的原始声明里访问它。
protocol SomeProtocol { func doSomething() }
struct SomeStruct { private var privateVariable = 12 }
extension SomeStruct: SomeProtocol {
func doSomething() {
print(privateVariable)
}
}
泛型类型
任何泛型参数或泛型函数的访问级别是该泛型参数或函数自身访问级别的最小值,以及对其类型参数的任何类型约束的访问级别。
类型别名
为了达到访问控制的目的,你定义的任何类型别名会被看作是不同类型。
类型别名可以拥有小于或等于其所代表类型的访问级别。
举个例子,一个 private 的类型别名可以代表 private , file-private , internal , public 或 open 类型。
但是 public 级别的类型别名不能代表 internal , file-private , 或 private 类型。
*/
| apache-2.0 | a8a3c501e692342d80591b4d7332effe | 22.899614 | 91 | 0.766559 | 2.440852 | false | false | false | false |
Donny8028/Swift-TinyFeatures | LimitCharacter/LimitCharacter/ViewController.swift | 1 | 2495 | //
// ViewController.swift
// LimitCharacter
//
// Created by 賢瑭 何 on 2016/5/24.
// Copyright © 2016年 Donny. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var messageView: UITextView!
@IBOutlet weak var charactersLeft: UILabel!
@IBOutlet weak var bottomView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
messageView.delegate = self
messageView.becomeFirstResponder()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let counts = textView.text.characters.count
if range.location >= 140 {
return false
}
return counts <= 140
}
func textViewDidChange(textView: UITextView) {
let counts = textView.text.characters.count
charactersLeft.text = "\(140 - counts)"
}
func keyboardWillShow(notification: NSNotification) {
let userInfo = notification.userInfo
let keyboardFrame = (userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
let height = keyboardFrame?.size.height
bottomView.transform = CGAffineTransformMakeTranslation(0.0, -height!)
}
func keyboardWillHide(notifcation: NSNotification) {
bottomView.transform = CGAffineTransformIdentity
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
}
| mit | c690ea73c4748362c25503ba9f0054e4 | 33.054795 | 161 | 0.686645 | 5.573991 | false | false | false | false |
alisidd/iOS-WeJ | Pods/M13Checkbox/Sources/M13CheckboxAnimationGenerator.swift | 3 | 8127 | //
// M13CheckboxAnimationGenerator.swift
// M13Checkbox
//
// Created by McQuilkin, Brandon on 3/27/16.
// Copyright © 2016 Brandon McQuilkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class M13CheckboxAnimationGenerator {
//----------------------------
// MARK: - Properties
//----------------------------
// The duration of animations that are generated by the animation manager.
var animationDuration: TimeInterval = 0.3
// The frame rate for certian keyframe animations.
fileprivate var frameRate: CGFloat = 60.0
//----------------------------
// MARK: - Quick Animations
//----------------------------
final func quickAnimation(_ key: String, reverse: Bool) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: key)
// Set the start and end.
if !reverse {
animation.fromValue = 0.0
animation.toValue = 1.0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
} else {
animation.fromValue = 1.0
animation.toValue = 0.0
animation.beginTime = CACurrentMediaTime() + (animationDuration * 0.9)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
}
// Set animation properties.
animation.duration = animationDuration / 10.0
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
return animation
}
/**
Creates an animation that either quickly fades a layer in or out.
- note: Mainly used to smooth out the start and end of various animations.
- parameter reverse: The direction of the animation.
- returns: A `CABasicAnimation` that animates the opacity property.
*/
final func quickOpacityAnimation(_ reverse: Bool) -> CABasicAnimation {
return quickAnimation("opacity", reverse: reverse)
}
/**
Creates an animation that either quickly changes the line width of a layer from 0% to 100%.
- note: Mainly used to smooth out the start and end of various animations.
- parameter reverse: The direction of the animation.
- returns: A `CABasicAnimation` that animates the opacity property.
*/
final func quickLineWidthAnimation(_ width: CGFloat, reverse: Bool) -> CABasicAnimation {
let animation = quickAnimation("lineWidth", reverse: reverse)
// Set the start and end.
if !reverse {
animation.toValue = width
} else {
animation.fromValue = width
}
return animation
}
//----------------------------
// MARK: - Animation Component Generation
//----------------------------
final func animation(_ key: String, reverse: Bool) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: key)
// Set the start and end.
if !reverse {
animation.fromValue = 0.0
animation.toValue = 1.0
} else {
animation.fromValue = 1.0
animation.toValue = 0.0
}
// Set animation properties.
animation.duration = animationDuration
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animation
}
/**
Creates an animation that animates the stroke property.
- parameter reverse: The direction of the animation.
- returns: A `CABasicAnimation` that animates the stroke property.
*/
final func strokeAnimation(_ reverse: Bool) -> CABasicAnimation {
return animation("strokeEnd", reverse: reverse)
}
/**
Creates an animation that animates the opacity property.
- parameter reverse: The direction of the animation.
- returns: A `CABasicAnimation` that animates the opacity property.
*/
final func opacityAnimation(_ reverse: Bool) -> CABasicAnimation {
return animation("opacity", reverse: reverse)
}
/**
Creates an animation that animates between two `UIBezierPath`s.
- parameter fromPath: The start path.
- parameter toPath: The end path.
- returns: A `CABasicAnimation` that animates a path between the `fromPath` and `toPath`.
*/
final func morphAnimation(_ fromPath: UIBezierPath?, toPath: UIBezierPath?) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "path")
// Set the start and end.
animation.fromValue = fromPath?.cgPath
animation.toValue = toPath?.cgPath
// Set animation properties.
animation.duration = animationDuration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
return animation
}
/**
Creates an animation that animates between a filled an unfilled box.
- parameter numberOfBounces: The number of bounces in the animation.
- parameter amplitude: The distance of the bounce.
- parameter reverse: The direction of the animation.
- returns: A `CAKeyframeAnimation` that animates a change in fill.
*/
final func fillAnimation(_ numberOfBounces: Int, amplitude: CGFloat, reverse: Bool) -> CAKeyframeAnimation {
var values = [CATransform3D]()
var keyTimes = [Float]()
// Add the start scale
if !reverse {
values.append(CATransform3DMakeScale(0.0, 0.0, 0.0))
} else {
values.append(CATransform3DMakeScale(1.0, 1.0, 1.0))
}
keyTimes.append(0.0)
// Add the bounces.
if numberOfBounces > 0 {
for i in 1...numberOfBounces {
let scale = i % 2 == 1 ? (1.0 + (amplitude / CGFloat(i))) : (1.0 - (amplitude / CGFloat(i)))
let time = (Float(i) * 1.0) / Float(numberOfBounces + 1)
values.append(CATransform3DMakeScale(scale, scale, scale))
keyTimes.append(time)
}
}
// Add the end scale.
if !reverse {
values.append(CATransform3DMakeScale(1.0, 1.0, 1.0))
} else {
values.append(CATransform3DMakeScale(0.0001, 0.0001, 0.0001))
}
keyTimes.append(1.0)
// Create the animation.
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.values = values.map({ NSValue(caTransform3D: $0) })
animation.keyTimes = keyTimes.map({ NSNumber(value: $0 as Float) })
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.duration = animationDuration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animation
}
}
| gpl-3.0 | 5b35ca5d87ac9bb73e20ab71d5af4fe7 | 41.544503 | 464 | 0.640413 | 5.185705 | false | false | false | false |
superk589/DereGuide | DereGuide/Toolbox/Gacha/View/GachaCardWithOddsListView.swift | 2 | 2978 | //
// GachaCardWithOddsListView.swift
// DereGuide
//
// Created by zzk on 2017/7/17.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import TTGTagCollectionView
class GachaCardWithOddsListView: UIView {
var collectionView: TTGTagCollectionView!
var tagViews = NSCache<NSNumber, GachaCardView>()
weak var delegate: CGSSIconViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
collectionView = TTGTagCollectionView()
collectionView.contentInset = .zero
collectionView.verticalSpacing = 5
collectionView.horizontalSpacing = 5
addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
collectionView.scrollView.isScrollEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupWith(cards: [CGSSCard], odds: [Int?]) {
self.cards = cards
self.odds = odds
collectionView.reload()
self.isHidden = cards.count == 0
}
var cards = [CGSSCard]()
var odds = [Int?]()
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
layoutIfNeeded()
collectionView.invalidateIntrinsicContentSize()
return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
}
}
extension GachaCardWithOddsListView: TTGTagCollectionViewDelegate, TTGTagCollectionViewDataSource {
func numberOfTags(in tagCollectionView: TTGTagCollectionView!) -> UInt {
return UInt(cards.count)
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, tagViewFor index: UInt) -> UIView! {
let gachaCardView: GachaCardView
if let view = tagViews.object(forKey: NSNumber.init(value: index)) {
gachaCardView = view
} else {
gachaCardView = GachaCardView()
gachaCardView.icon.isUserInteractionEnabled = false
tagViews.setObject(gachaCardView, forKey: NSNumber.init(value: index))
}
gachaCardView.setupWith(card: cards[Int(index)], odds: odds[Int(index)])
return gachaCardView
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, sizeForTagAt index: UInt) -> CGSize {
return CGSize(width: 48, height: 62.5)
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, didSelectTag tagView: UIView!, at index: UInt) {
let cardView = tagView as! GachaCardView
delegate?.iconClick(cardView.icon)
}
}
| mit | cb20d0fe4f81064ee6c3083e9417b757 | 33.218391 | 193 | 0.680551 | 4.961667 | false | false | false | false |
yazhenggit/wbtest | 微博项目练习/微博项目练习/Classes/Module/Main/visitorLogView.swift | 1 | 7877 | //
// visitorLogView.swift
// 微博项目练习
//
// Created by 王亚征 on 15/10/8.
// Copyright © 2015年 yazheng. All rights reserved.
//
import UIKit
protocol visitorLogViewDelegate:NSObjectProtocol{
func visitorLoginViewWillLogin()
func visitorLoginViewWillRegister()
}
class visitorLogView: UIView {
weak var delegate:visitorLogViewDelegate?
func clickLogin(){
print("登录")
delegate?.visitorLoginViewWillLogin()
}
func clickRegister(){
print("注册")
delegate?.visitorLoginViewWillRegister()
}
// 设置视图信息
func setupViewInfo(isHome:Bool,imageName:String,
message:String){
messageLabel.text = message
iconView.image = UIImage(named: imageName)
homeiconView.hidden = !isHome
isHome ? startAnimation():sendSubviewToBack(maskiconView)
}
private func startAnimation(){
let anim = CABasicAnimation(keyPath:"transform.rotation")
anim.toValue = 2 * M_PI
anim.repeatCount = MAXFLOAT
anim.duration = 20.0
anim.removedOnCompletion = false
iconView.layer.addAnimation(anim, forKey: nil)
}
// 界面初始化
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder:aDecoder)
setupUI()
}
// 设置界面
private func setupUI(){
// 1.添加控件
addSubview(iconView)
addSubview(maskiconView)
addSubview(homeiconView)
addSubview(messageLabel)
addSubview(registerButton)
addSubview(loginButton)
// 2.自动布局
iconView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: -60))
homeiconView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: homeiconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: homeiconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
messageLabel.translatesAutoresizingMaskIntoConstraints
= false
addConstraint(NSLayoutConstraint(item:messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 88))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 224))
registerButton.translatesAutoresizingMaskIntoConstraints
= false
addConstraint(NSLayoutConstraint(item:registerButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35))
loginButton.translatesAutoresizingMaskIntoConstraints
= false
addConstraint(NSLayoutConstraint(item:loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35))
maskiconView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview" :maskiconView]))
addConstraints (NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-(-35)-[regButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview" :maskiconView,"regButton":registerButton]))
backgroundColor = UIColor(white: 237.0/255.0, alpha: 1.0)
}
// 懒加载控件
lazy private var iconView:UIImageView = {
let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
return iv
}()
lazy private var maskiconView:UIImageView = {
let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
return iv
}()
lazy private var homeiconView:UIImageView = {
let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
return iv
}()
lazy private var messageLabel:UILabel = {
let label = UILabel()
label.text = "关注一些人,回这里看看有什么惊喜"
label.textColor = UIColor.darkGrayColor()
label.font = UIFont.systemFontOfSize(14)
label.numberOfLines = 0
label.sizeToFit()
return label
}()
lazy private var registerButton:UIButton = {
let btn = UIButton()
btn.setTitle("注册", forState:UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
btn.addTarget(self, action: "clickRegister", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
lazy private var loginButton:UIButton = {
let btn = UIButton()
btn.setTitle("登录", forState:UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
btn.addTarget(self, action: "clickLogin", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
}
| mit | a6e9cfc38d1f1e60c0a764a0da96f0ef | 51.734694 | 228 | 0.723168 | 5.161119 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Main/Model/AnchorModel.swift | 1 | 857 | //
// AnchorModel.swift
// DYZB
//
// Created by xiudou on 16/9/20.
// Copyright © 2016年 xiudo. All rights reserved.
// 主播模型
import UIKit
class AnchorModel: BaseModel {
/// 房间ID
var room_id : Int64 = 0
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
// 0 : 电脑直播 1 : 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
// MARK:- 重写description属性(方便打印看到信息)
override var description:String{
return dictionaryWithValues(forKeys: ["isVertical", "room_name", "nickname"]).description
}
}
| mit | 3311a57c9da44c3c7195840b618794b2 | 19.857143 | 97 | 0.575342 | 3.631841 | false | false | false | false |
asp2insp/CodePathFinalProject | Pretto/EventDetailViewController.swift | 1 | 5152 | //
// EventDetailViewController.swift
// Pretto
//
// Created by Josiah Gaskin on 6/14/15.
// Copyright (c) 2015 Pretto. All rights reserved.
//
import Foundation
class EventDetailViewController : ZoomableCollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var invitation : Invitation?
@IBOutlet weak var requestButton: UIButton!
@IBOutlet weak var headerImage: PFImageView!
var photos : [Photo] = []
var refreshControl : UIRefreshControl!
var selectedIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
self.requestButton.backgroundColor = UIColor.prettoBlue()
self.title = invitation?.event.title
self.headerImage.file = invitation?.event.coverPhoto
self.headerImage.loadInBackground()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refreshData", forControlEvents: UIControlEvents.ValueChanged)
collectionView.addSubview(refreshControl)
collectionView.alwaysBounceVertical = true
self.onSelectionChange()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
cameraView.hidden = true
// Scale up to maximum
flowLayout.itemSize = aspectScaleWithConstraints(flowLayout.itemSize, scale: 10, max: maxSize, min: minSize)
self.refreshControl.beginRefreshing()
self.clearSelections()
self.refreshData()
}
func refreshData() {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.activityIndicatorColor = UIColor.whiteColor()
hud.color = UIColor.prettoBlue().colorWithAlphaComponent(0.75)
dispatch_async(GlobalMainQueue) {
self.invitation?.event.getAllPhotosInEvent(kOrderedByNewestFirst) {photos in
self.photos = photos
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
self.clearSelections()
self.refreshControl.endRefreshing()
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
}
}
// Clear all selections
func clearSelections() {
for path in selectedPaths {
if let path = path as? NSIndexPath {
deselectItemAtIndexPathIfNecessary(path)
}
}
}
@IBAction func didTapRequestPhotos(sender: UIButton) {
requestButton.setTitle("Requesting photos...", forState: UIControlState.Normal)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
for path in self.selectedPaths {
Request.makeRequestForPhoto(self.photos[path.row]).save()
}
dispatch_async(dispatch_get_main_queue()) {
self.requestButton.setTitle("Request Sent!", forState: UIControlState.Normal)
self.clearSelections()
}
}
}
override func onSelectionChange() {
let selectionCount = selectedPaths.count
if selectionCount == 0 {
requestButton.setTitle("Select Photos", forState: UIControlState.Normal)
requestButton.enabled = false
} else {
requestButton.setTitle("Create Album with \(selectionCount) Photos", forState: UIControlState.Normal)
requestButton.enabled = true
}
}
}
// MARK: AUX Methods
extension EventDetailViewController {
func doubleTapReconized(sender: UITapGestureRecognizer) {
selectedIndex = collectionView.indexPathForCell(sender.view as! SelectableImageCell)?.row
self.performSegueWithIdentifier("SingleImageViewSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
println("Preparing for Segue with image index \(selectedIndex)")
let singlePhotoVC = segue.destinationViewController as! SinglePhotoViewController
singlePhotoVC.photos = self.photos
singlePhotoVC.initialIndex = self.selectedIndex ?? 0
}
}
// UICollectionViewDataSource Extension
extension EventDetailViewController : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! SelectableImageCell
let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "doubleTapReconized:")
doubleTapRecognizer.numberOfTapsRequired = 2
cell.addGestureRecognizer(doubleTapRecognizer)
cell.image.file = self.photos[indexPath.row].thumbnailFile
cell.image.loadInBackground()
cell.backgroundColor = UIColor.clearColor()
cell.updateCheckState()
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count
}
} | mit | b8893580b794b91b96c08fc0aedc5ec5 | 38.037879 | 134 | 0.671778 | 5.486688 | false | false | false | false |
dzenbot/Iconic | Vendor/SwiftGen/UnitTests/TestSuites/ColorsTests.swift | 1 | 6487 | //
// SwiftGen
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import XCTest
import GenumKit
import PathKit
// MARK: - Tests for TXT files
class ColorsTextFileTests: XCTestCase {
func testEmpty() {
let parser = ColorsTextFileParser()
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-Empty.swift.out")
XCTDiffStrings(result, expected)
}
func testListWithDefaults() {
let parser = ColorsTextFileParser()
parser.addColorWithName("Text&Body Color", value: "0x999999")
parser.addColorWithName("ArticleTitle", value: "#996600")
parser.addColorWithName("ArticleBackground", value: "#ffcc0099")
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-List-Defaults.swift.out")
XCTDiffStrings(result, expected)
}
func testListWithRawValueTemplate() {
let parser = ColorsTextFileParser()
parser.addColorWithName("Text&Body Color", value: "0x999999")
parser.addColorWithName("ArticleTitle", value: "#996600")
parser.addColorWithName("ArticleBackground", value: "#ffcc0099")
let template = GenumTemplate(templateString: fixtureString("colors-rawValue.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-List-RawValue.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithDefaults() {
let parser = ColorsTextFileParser()
try! parser.parseFile(fixturePath("colors.txt"))
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-File-Defaults.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithCustomName() {
let parser = ColorsTextFileParser()
try! parser.parseFile(fixturePath("colors.txt"))
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext(enumName: "XCTColors"))
let expected = self.fixtureString("Colors-File-CustomName.swift.out")
XCTDiffStrings(result, expected)
}
}
// MARK: - Tests for CLR Palette files
class ColorsCLRFileTests: XCTestCase {
func testEmpty() {
let parser = ColorsCLRFileParser()
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-Empty.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithDefaults() {
let parser = ColorsCLRFileParser()
parser.parseFile(fixturePath("colors.clr"))
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-File-Defaults.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithCustomName() {
let parser = ColorsCLRFileParser()
parser.parseFile(fixturePath("colors.clr"))
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext(enumName: "XCTColors"))
let expected = self.fixtureString("Colors-File-CustomName.swift.out")
XCTDiffStrings(result, expected)
}
}
// MARK: - Tests for XML Android color files
class ColorsXMLFileTests: XCTestCase {
func testEmpty() {
let parser = ColorsXMLFileParser()
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-Empty.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithDefaults() {
let parser = ColorsXMLFileParser()
do {
try parser.parseFile(fixturePath("colors.xml"))
} catch {
XCTFail("Exception while parsing file: \(error)")
}
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-File-Defaults.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithCustomName() {
let parser = ColorsXMLFileParser()
do {
try parser.parseFile(fixturePath("colors.xml"))
} catch {
XCTFail("Exception while parsing file: \(error)")
}
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext(enumName: "XCTColors"))
let expected = self.fixtureString("Colors-File-CustomName.swift.out")
XCTDiffStrings(result, expected)
}
}
class ColorsJSONFileTests: XCTestCase {
func testEmpty() {
let parser = ColorsJSONFileParser()
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-Empty.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithDefaults() {
let parser = ColorsJSONFileParser()
do {
try parser.parseFile(fixturePath("colors.json"))
} catch {
XCTFail("Exception while parsing file: \(error)")
}
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext())
let expected = self.fixtureString("Colors-File-Defaults.swift.out")
XCTDiffStrings(result, expected)
}
func testFileWithCustomName() {
let parser = ColorsJSONFileParser()
do {
try parser.parseFile(fixturePath("colors.json"))
} catch {
XCTFail("Exception while parsing file: \(error)")
}
let template = GenumTemplate(templateString: fixtureString("colors-default.stencil"))
let result = try! template.render(parser.stencilContext(enumName: "XCTColors"))
let expected = self.fixtureString("Colors-File-CustomName.swift.out")
XCTDiffStrings(result, expected)
}
}
| mit | e31cd12aa989b971febc7ed6aca0f2b8 | 32.266667 | 93 | 0.710344 | 4.581215 | false | true | false | false |
darren90/Gankoo_Swift | Gankoo/Gankoo/Classes/Main/Base/BaseViewController2.swift | 1 | 6453 | //
// BaseViewController.swift
// iTVshows
//
// Created by Fengtf on 2016/11/21.
// Copyright © 2016年 tengfei. All rights reserved.
//
import UIKit
enum ErrorNetType:Int {
case None //没有错误 --- 移除loadingView
case Default //默认错误
case NoNet // 无网络
case ServerError// 服务器错误
}
class BaseViewController2: UIViewController,UIGestureRecognizerDelegate {
var errorView:ErrorView = Bundle.main.loadNibNamed("ErrorView", owner: nil, options: nil)?.first as! ErrorView
let loadingView : LoadingView = LoadingView()
var timer:Timer?
var errorType:ErrorNetType = .Default {
didSet{
self.destoryTimer()
errorView.isHidden = false
loadingView.isHidden = true
switch errorType {
case .None:
loadingView.removeFromSuperview()
errorView.removeFromSuperview()
case .Default:
errorView.msgLabel.text = "网络错误"
errorView.msgDetailLabel.text = "请检查网络连接"
case .NoNet:
errorView.msgLabel.text = "网络错误"
errorView.msgDetailLabel.text = "请检查网络连接"
case .ServerError:
errorView.msgLabel.text = "出现错误"
errorView.msgDetailLabel.text = "服务器出错,请稍后重试"
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
view.bringSubview(toFront: navBarView);
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
//启用滑动返回手势
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
request()
navigationController?.interactivePopGestureRecognizer?.isEnabled = true
automaticallyAdjustsScrollViewInsets = false
navigationController?.isNavigationBarHidden = true
navBarView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64)
navBarView.leftButton.addTarget(self, action: #selector(self.leftBtnClick), for: .touchUpInside)
navBarView.rightButton.addTarget(self, action: #selector(self.rightBtnClick), for: .touchUpInside)
view.addSubview(navBarView)
addLoadingView()
}
func request(){
}
// MARK:-- 加载loadingView
func addLoadingView() {
view.addSubview(errorView)
errorView.frame = view.frame;
errorView.retryBtn.addTarget(self, action: #selector(self.retryBtnClick), for: .touchUpInside)
view.addSubview(loadingView)
loadingView.frame = view.bounds
addTimer()
}
func retryBtnClick() {
self.addTimer()
errorView.isHidden = true
loadingView.isHidden = false
request()
}
func timerAction() {
loadingView.progress = loadingView.progress + 1
}
func addTimer() {
if timer == nil {
timer = Timer(timeInterval: 0.15, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
}
func destoryTimer() {
if timer != nil {
timer!.invalidate()
timer = nil
}
}
deinit {
destoryTimer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: --- 启用手势
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
return (self.navigationController?.viewControllers.count)! > 1
}
return true
}
//MARK: -- NavBar
var navBarView:BaseNaviBar = BaseNaviBar()
var leftImg:String? {
didSet {
self.navBarView.leftButton.contentHorizontalAlignment = .left
self.navBarView.leftButton.setImage(UIImage(named: leftImg ?? ""), for: .normal)
self.navBarView.leftButton.setTitle(nil, for: .normal)
self.navBarView.leftButton.setImage(UIImage(named: leftImg ?? "")?.imageWithTintColor(color: UIColor.lightGray), for: .highlighted)
}
}
var leftTitle:String? {
didSet {
self.navBarView.leftButton.contentHorizontalAlignment = .center
self.navBarView.leftButton.setTitle(leftTitle, for: .normal)
self.navBarView.leftButton.setImage(nil, for: .normal)
self.navBarView.leftButton.setImage(nil, for: .highlighted)
}
}
var rightImg:String? {
didSet {
// self.navBarView.rightButton.contentHorizontalAlignment = .left
self.navBarView.rightButton.isHidden = false
self.navBarView.rightButton.setImage(UIImage(named: rightImg ?? ""), for: .normal)
self.navBarView.rightButton.setTitle(nil, for: .normal)
self.navBarView.rightButton.setImage(UIImage(named: rightImg ?? "")?.imageWithTintColor(color: UIColor.lightGray), for: .highlighted)
}
}
var rightTitle:String? {
didSet {
self.navBarView.rightButton.isHidden = false
self.navBarView.rightButton.setTitle(rightTitle, for: .normal)
self.navBarView.rightButton.setImage(nil, for: .normal)
self.navBarView.rightButton.setImage(nil, for: .highlighted)
}
}
var navTitleStr:String? {
didSet {
self.navBarView.navTitle.text = navTitleStr
}
}
//MARK: -- 控制转屏
func leftBtnClick() {
self.navigationController?.popViewController(animated: true)
// navigationController?.popViewController(animated: true)
print("---leftBtnClick---")
}
func rightBtnClick() {
print("---leftBtnClick---")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return .portrait
}
override var shouldAutorotate: Bool {
return false
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
}
| apache-2.0 | 732b4300c9ef7cf4fcc67604a4e2c8a6 | 28.32093 | 145 | 0.615958 | 4.909657 | false | false | false | false |
firebase/quickstart-ios | analytics/LegacyAnalyticsQuickstart/AnalyticsExampleSwift/PatternTabBarController.swift | 1 | 2235 | //
// 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 FirebaseAnalytics
/**
* PatternTabBarController exists as a subclass of UITabBarConttroller that
* supports a 'share' action. This will trigger a custom event to Analytics and
* display a dialog.
*/
@objc(PatternTabBarController) // match the ObjC symbol name inside Storyboard
class PatternTabBarController: UITabBarController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if getUserFavoriteFood() == nil {
askForFavoriteFood()
}
}
@IBAction func didTapShare(_ sender: AnyObject) {
let name = "Pattern~\(selectedViewController!.title!)",
text = "I'd love you to hear about\(name)"
// [START custom_event_swift]
Analytics.logEvent("share_image", parameters: [
"name": name as NSObject,
"full_text": text as NSObject,
])
// [END custom_event_swift]
let title = "Share: \(selectedViewController!.title!)",
message = "Share event sent to Analytics; actual share not implemented in this quickstart",
alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
@IBAction func unwindToHome(_ segue: UIStoryboardSegue?) {
if let nc = navigationController {
nc.dismiss(animated: true, completion: nil)
}
}
func getUserFavoriteFood() -> String? {
return UserDefaults.standard.string(forKey: "favorite_food")
}
func askForFavoriteFood() {
performSegue(withIdentifier: "pickFavoriteFood", sender: self)
}
}
| apache-2.0 | b8a4a6dd0cb4695102cd6264a0f111af | 33.384615 | 97 | 0.708725 | 4.249049 | false | false | false | false |
exponent/exponent | ios/vendored/unversioned/@stripe/stripe-react-native/ios/Errors.swift | 6 | 4097 | import Stripe
enum ConfirmPaymentErrorType: String {
case Failed, Canceled, Unknown
}
enum ApplePayErrorType: String {
case Failed, Canceled, Unknown
}
enum NextPaymentActionErrorType: String {
case Failed, Canceled, Unknown
}
enum ConfirmSetupIntentErrorType: String {
case Failed, Canceled, Unknown
}
enum RetrievePaymentIntentErrorType: String {
case Unknown
}
enum RetrieveSetupIntentErrorType: String {
case Unknown
}
enum PaymentSheetErrorType: String {
case Failed, Canceled
}
enum CreateTokenErrorType: String {
case Failed
}
class Errors {
static internal let isPIClientSecretValidRegex: NSRegularExpression? = try? NSRegularExpression(
pattern: "^pi_[^_]+_secret_[^_]+$", options: [])
static internal let isSetiClientSecretValidRegex: NSRegularExpression? = try? NSRegularExpression(
pattern: "^seti_[^_]+_secret_[^_]+$", options: [])
static internal let isEKClientSecretValidRegex: NSRegularExpression? = try? NSRegularExpression(
pattern: "^ek_[^_](.)+$", options: [])
class func isPIClientSecretValid(clientSecret: String) -> Bool {
return (Errors.isPIClientSecretValidRegex?.numberOfMatches(
in: clientSecret,
options: .anchored,
range: NSRange(location: 0, length: clientSecret.count))) == 1
}
class func isSetiClientSecretValid(clientSecret: String) -> Bool {
return (Errors.isSetiClientSecretValidRegex?.numberOfMatches(
in: clientSecret,
options: .anchored,
range: NSRange(location: 0, length: clientSecret.count))) == 1
}
class func isEKClientSecretValid(clientSecret: String) -> Bool {
return (Errors.isEKClientSecretValidRegex?.numberOfMatches(
in: clientSecret,
options: .anchored,
range: NSRange(location: 0, length: clientSecret.count))) == 1
}
class func createError (_ code: String, _ message: String?) -> NSDictionary {
let value: NSDictionary = [
"code": code,
"message": message ?? NSNull(),
"localizedMessage": message ?? NSNull(),
"declineCode": NSNull(),
"stripeErrorCode": NSNull(),
"type": NSNull()
]
return ["error": value]
}
class func createError (_ code: String, _ error: NSError?) -> NSDictionary {
let value: NSDictionary = [
"code": code,
"message": error?.userInfo["com.stripe.lib:ErrorMessageKey"] ?? error?.userInfo["NSLocalizedDescription"] ?? NSNull(),
"localizedMessage": error?.userInfo["NSLocalizedDescription"] ?? NSNull(),
"declineCode": error?.userInfo["com.stripe.lib:DeclineCodeKey"] ?? NSNull(),
"stripeErrorCode": error?.userInfo["com.stripe.lib:StripeErrorCodeKey"] ?? NSNull(),
"type": error?.userInfo["com.stripe.lib:StripeErrorTypeKey"] ?? NSNull(),
]
return ["error": value]
}
class func createError (_ code: String, _ error: STPSetupIntentLastSetupError?) -> NSDictionary {
let value: NSDictionary = [
"code": code,
"message": error?.message ?? NSNull(),
"localizedMessage": error?.message ?? NSNull(),
"declineCode": error?.declineCode ?? NSNull(),
"stripeErrorCode": error?.code ?? NSNull(),
"type": Mappers.mapFromSetupIntentLastPaymentErrorType(error?.type) ?? NSNull()
]
return ["error": value]
}
class func createError (_ code: String, _ error: STPPaymentIntentLastPaymentError?) -> NSDictionary {
let value: NSDictionary = [
"code": code,
"message": error?.message ?? NSNull(),
"localizedMessage": error?.message ?? NSNull(),
"declineCode": error?.declineCode ?? NSNull(),
"stripeErrorCode": error?.code ?? NSNull(),
"type": Mappers.mapFromPaymentIntentLastPaymentErrorType(error?.type) ?? NSNull()
]
return ["error": value]
}
}
| bsd-3-clause | 0081a92111106c667b4ccbe7bb8ec1de | 34.938596 | 130 | 0.617525 | 4.763953 | false | false | false | false |
gugutech/gugutech_else_ios | ELSE/ELSE/AppDelegate.swift | 1 | 6447 | //
// AppDelegate.swift
// ELSE
//
// Created by Luliang on 15/7/20.
// Copyright © 2015年 gugutech. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let login = false
if !login {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC = mainStoryboard.instantiateViewControllerWithIdentifier("LoginVC")
let loginNC = UINavigationController(rootViewController: loginVC)
self.window?.rootViewController = loginNC
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Lu.l.ELSE" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("ELSE", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 3005a5b73fa4fd30a394667925b1790b | 52.256198 | 290 | 0.711515 | 5.906508 | false | false | false | false |
keitaoouchi/RxAudioVisual | RxAudioVisualTests/AVPlayer+RxSpec.swift | 1 | 3590 | import Quick
import Nimble
import RxSwift
import AVFoundation
@testable import RxAudioVisual
class AVPlayerSpec: QuickSpec {
override func spec() {
describe("KVO through rx") {
var player: AVPlayer!
var disposeBag: DisposeBag!
beforeEach {
player = AVPlayer(url: TestHelper.sampleURL)
disposeBag = DisposeBag()
}
it("should load status") {
var e: AVPlayerStatus?
player.rx.status.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerStatus.readyToPlay))
}
it("should load timeControlStatus") {
player.pause()
var e: AVPlayerTimeControlStatus?
player.rx.timeControlStatus.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerTimeControlStatus.paused))
player.play()
expect(e).toEventually(equal(AVPlayerTimeControlStatus.playing))
}
it("should load rate") {
var e: Float?
player.rx.rate.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(0.0))
player.rate = 1.0
expect(e).toEventually(equal(1.0))
}
it("should load currentItem") {
var e: AVPlayerItem?
player.rx.currentItem.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
it("should load actionAtItemEnd") {
var e: AVPlayerActionAtItemEnd?
player.rx.actionAtItemEnd.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerActionAtItemEnd.pause))
}
it("should load volume") {
var e: Float?
player.rx.volume.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(1.0))
player.volume = 0.0
expect(e).toEventually(equal(0.0))
}
it("should load muted") {
var e: Bool?
player.rx.muted.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
player.isMuted = true
expect(e).toEventually(beTrue())
}
it("should load closedCaptionDisplayEnabled") {
var e: Bool?
player.rx.closedCaptionDisplayEnabled.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load allowsExternalPlayback") {
var e: Bool?
player.rx.allowsExternalPlayback.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beTrue())
}
it("should load externalPlaybackActive") {
var e: Bool?
player.rx.externalPlaybackActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load usesExternalPlaybackWhileExternalScreenIsActive") {
var e: Bool?
player.rx.usesExternalPlaybackWhileExternalScreenIsActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
}
}
}
| mit | 0ac0c051f04e8c8e47f5762762c059dc | 32.240741 | 124 | 0.627298 | 4.203747 | false | false | false | false |
google/promises | Sources/PromisesTestHelpers/PromisesTestHelpers.swift | 1 | 2202 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Namespace for test helpers.
public struct Test {
/// Executes `work` after a time `interval` on the main queue.
public static func delay(_ interval: TimeInterval, work: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
work()
}
}
// Phony errors.
public enum Error: Int, CustomNSError {
case code13 = 13
case code42 = 42
public static var errorDomain: String {
return "com.google.Promises.Test.Error"
}
public var errorCode: Int { return rawValue }
public var errorUserInfo: [String: Any] { return [:] }
}
}
/// Convenience `NSError` accessors for `Error` protocol.
public extension Error {
var domain: String { return (self as NSError).domain }
var code: Int { return (self as NSError).code }
var userInfo: [String: Any] { return (self as NSError).userInfo }
}
/// Compare two `Error?`.
public func == (lhs: Error?, rhs: Error?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case (nil, _?), (_?, nil):
return false
case let (lhs?, rhs?):
return (lhs as NSError).isEqual(rhs as NSError)
}
}
public func != (lhs: Error?, rhs: Error?) -> Bool {
return !(lhs == rhs)
}
/// Compare two arrays of the same generic type conforming to `Equatable` protocol.
public func == <T: Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
if lhs.count != rhs.count { return false }
for (lhs, rhs) in zip(lhs, rhs) where lhs != rhs { return false }
return true
}
public func != <T: Equatable>(lhs: [T?], rhs: [T?]) -> Bool {
return !(lhs == rhs)
}
| apache-2.0 | 5639dfb22c0bc7ff83b741af65cb5bc5 | 28.756757 | 83 | 0.662125 | 3.783505 | false | false | false | false |
practicalswift/Pythonic.swift | src/Pythonic.file.swift | 1 | 2337 | // Python docs: https://docs.python.org/2/library/stdtypes.html
//
// Most frequently used:
// 15 file.close
// 9 file.name
// 8 file.readline
// 7 file.write
// 2 file.read
// 1 file.writelines
// 1 file.readlines
// 1 file.fileno
//
// >>> filter(lambda s: not s.startswith("_"), dir(open("/tmp/foo")))
// close: TODO.
// closed
// encoding
// errors
// fileno
// flush: TODO.
// isatty
// mode
// name
// newlines
// next
// read
// readinto
// readline
// readlines
// seek
// softspace
// tell
// truncate
// write: TODO.
// writelines
// xreadlines
import Foundation
public typealias file = NSFileHandle
public extension NSFileHandle {
public func read() -> String {
let data: NSData = self.readDataToEndOfFile()
return NSString(data: data, encoding: NSUTF8StringEncoding)! as String
}
public func readLines() -> [String] {
return self.read().strip().split("\n")
}
public func readlines() -> [String] {
return self.readLines()
}
public func close() {
self.closeFile()
}
public func write(s: String) {
if let data = s.dataUsingEncoding(NSUTF8StringEncoding) {
self.writeData(data)
}
}
}
extension NSFileHandle: SequenceType {
public func availableText () -> String? {
let data: NSData = self.availableData
if data.length == 0 {
return nil
} else {
return String(data: data, encoding: NSUTF8StringEncoding)
}
}
public func generate() -> _FileHandle_Generator {
return _FileHandle_Generator(fileHandle: self)
}
}
public class _FileHandle_Generator: GeneratorType {
private let fileHandle: NSFileHandle
private var cache = ""
private init(fileHandle: NSFileHandle) {
self.fileHandle = fileHandle
}
public func next() -> String? {
let (nextLine, returnedSeparator, remainder) = cache.partition("\n")
cache = remainder
let newLineWasFound = returnedSeparator != ""
if newLineWasFound {
return nextLine
}
if let newCache = fileHandle.availableText() {
cache = nextLine + newCache
return next()
}
return nextLine == "" ? nil : nextLine
}
}
| mit | 20397df43b5a11f058dfdd3e6e0708a7 | 21.911765 | 78 | 0.590501 | 3.981261 | false | false | false | false |
nixzhu/SuperPreview | SuperPreview/PhotoTransitionAnimator.swift | 1 | 10969 | //
// PhotoTransitionAnimator.swift
// SuperPreview
//
// Created by NIX on 2016/11/28.
// Copyright © 2016年 nixWork. All rights reserved.
//
import UIKit
class PhotoTransitionAnimator: NSObject {
var startingReference: Reference?
var endingReference: Reference?
var startingViewForAnimation: UIView?
var endingViewForAnimation: UIView?
var isDismissing: Bool = false
let animationDurationWithZooming: TimeInterval = Config.animationDurationWithZooming ?? 0.4
let animationDurationWithoutZooming: TimeInterval = Config.animationDurationWithoutZooming ?? 0.3
let animationDurationFadeRatio: TimeInterval = 4.0 / 9.0
let animationDurationEndingViewFadeInRatio: TimeInterval = 0.1
let animationDurationStartingViewFadeOutRatio: TimeInterval = 0.05
let zoomingAnimationSpringDamping: CGFloat = 0.9
var shouldPerformZoomingAnimation: Bool {
return (startingReference != nil) && (endingReference != nil)
}
private class func newView(from view: UIView) -> UIView {
let newView: UIView
if view.layer.contents != nil {
if let image = (view as? UIImageView)?.image {
newView = UIImageView(image: image)
newView.bounds = view.bounds
} else {
newView = UIView()
newView.layer.contents = view.layer.contents
newView.layer.bounds = view.layer.bounds
}
newView.layer.cornerRadius = view.layer.cornerRadius
newView.layer.masksToBounds = view.layer.masksToBounds
newView.contentMode = view.contentMode
newView.transform = view.transform
} else {
newView = view.snapshotView(afterScreenUpdates: true)!
}
return newView
}
class func newAnimationView(from view: UIView) -> UIView {
return newView(from: view)
}
class func centerPointForView(_ view: UIView, translatedToContainerView containerView: UIView) -> CGPoint {
guard let superview = view.superview else {
fatalError("No superview")
}
var centerPoint = view.center
if let scrollView = superview as? UIScrollView {
if scrollView.zoomScale != 1.0 {
centerPoint.x += (scrollView.bounds.width - scrollView.contentSize.width) / 2 + scrollView.contentOffset.x
centerPoint.y += (scrollView.bounds.height - scrollView.contentSize.height) / 2 + scrollView.contentOffset.y
}
}
return superview.convert(centerPoint, to: containerView)
}
}
extension PhotoTransitionAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if shouldPerformZoomingAnimation {
return animationDurationWithZooming
} else {
return animationDurationWithoutZooming
}
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
setupTransitionContainerHierarchyWithTransitionContext(transitionContext)
performFadeAnimationWithTransitionContext(transitionContext)
if shouldPerformZoomingAnimation {
performZoomingAnimationWithTransitionContext(transitionContext)
}
}
private func setupTransitionContainerHierarchyWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
if let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
toView.frame = transitionContext.finalFrame(for: toViewController)
let containerView = transitionContext.containerView
if !toView.isDescendant(of: containerView) {
containerView.addSubview(toView)
}
}
if isDismissing {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let containerView = transitionContext.containerView
containerView.bringSubview(toFront: fromView)
}
}
private func performFadeAnimationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
let viewToFade: UIView?
let beginningAlpha: CGFloat
let endingAlpha: CGFloat
if isDismissing {
viewToFade = fromView
beginningAlpha = 1
endingAlpha = 0
} else {
viewToFade = toView
beginningAlpha = 0
endingAlpha = 1
}
viewToFade?.alpha = beginningAlpha
let duration = fadeDurationForTransitionContext(transitionContext)
UIView.animate(withDuration: duration, animations: {
viewToFade?.alpha = endingAlpha
}, completion: { [unowned self] finished in
if !self.shouldPerformZoomingAnimation {
self.completeTransitionWithTransitionContext(transitionContext)
}
})
}
private func performZoomingAnimationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
var _startingViewForAnimation: UIView? = self.startingViewForAnimation
var _endingViewForAnimation: UIView? = self.startingViewForAnimation
if _startingViewForAnimation == nil {
if let startingReference = startingReference {
let view = isDismissing ? startingReference.view : startingReference.imageView
_startingViewForAnimation = PhotoTransitionAnimator.newAnimationView(from: view)
}
}
if _endingViewForAnimation == nil {
if let endingReference = endingReference {
let view = isDismissing ? endingReference.imageView : endingReference.view
_endingViewForAnimation = PhotoTransitionAnimator.newAnimationView(from: view)
}
}
guard let startingViewForAnimation = _startingViewForAnimation else {
return
}
guard let endingViewForAnimation = _endingViewForAnimation else {
return
}
guard let originalStartingViewForAnimation = startingReference?.view else {
return
}
guard let originalEndingViewForAnimation = endingReference?.view else {
return
}
startingViewForAnimation.clipsToBounds = true
endingViewForAnimation.clipsToBounds = true
let endingViewForAnimationFinalFrame = originalEndingViewForAnimation.frame
endingViewForAnimation.frame = originalStartingViewForAnimation.frame
var startingMaskView: UIView?
if let _startingMaskView = startingReference?.view.mask {
startingMaskView = PhotoTransitionAnimator.newAnimationView(from: _startingMaskView)
startingMaskView?.frame = startingViewForAnimation.bounds
}
var endingMaskView: UIView?
if let _endingMaskView = endingReference?.view.mask {
endingMaskView = PhotoTransitionAnimator.newAnimationView(from: _endingMaskView)
endingMaskView?.frame = endingViewForAnimation.bounds
}
startingViewForAnimation.mask = startingMaskView
endingViewForAnimation.mask = endingMaskView
if let startingView = startingReference?.view {
let translatedStartingViewCenter = PhotoTransitionAnimator.centerPointForView(startingView, translatedToContainerView: containerView)
startingViewForAnimation.center = translatedStartingViewCenter
endingViewForAnimation.center = translatedStartingViewCenter
}
if isDismissing {
startingViewForAnimation.alpha = 1
endingViewForAnimation.alpha = 1
} else {
startingViewForAnimation.alpha = 1
endingViewForAnimation.alpha = 0
}
containerView.addSubview(startingViewForAnimation)
containerView.addSubview(endingViewForAnimation)
startingReference?.view.alpha = 0
endingReference?.view.alpha = 0
var translatedEndingViewFinalCenter: CGPoint?
if let endingView = endingReference?.view {
translatedEndingViewFinalCenter = PhotoTransitionAnimator.centerPointForView(endingView, translatedToContainerView: containerView)
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: zoomingAnimationSpringDamping, initialSpringVelocity: 0, options: [.allowAnimatedContent, .beginFromCurrentState], animations: { [unowned self] in
endingViewForAnimation.frame = endingViewForAnimationFinalFrame
endingMaskView?.frame = endingViewForAnimation.bounds
if let translatedEndingViewFinalCenter = translatedEndingViewFinalCenter {
endingViewForAnimation.center = translatedEndingViewFinalCenter
}
startingViewForAnimation.frame = endingViewForAnimationFinalFrame
startingMaskView?.frame = startingViewForAnimation.bounds
if let translatedEndingViewFinalCenter = translatedEndingViewFinalCenter {
startingViewForAnimation.center = translatedEndingViewFinalCenter
}
if self.isDismissing {
startingViewForAnimation.alpha = 0
} else {
endingViewForAnimation.alpha = 1
}
}, completion: { [unowned self] finished in
self.endingReference?.view.alpha = 1
self.startingReference?.view.alpha = 1
startingViewForAnimation.removeFromSuperview()
endingViewForAnimation.removeFromSuperview()
self.completeTransitionWithTransitionContext(transitionContext)
})
}
private func fadeDurationForTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) -> TimeInterval {
if shouldPerformZoomingAnimation {
return transitionDuration(using: transitionContext) * animationDurationFadeRatio
} else {
return transitionDuration(using: transitionContext)
}
}
private func completeTransitionWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
if transitionContext.isInteractive {
if transitionContext.transitionWasCancelled {
transitionContext.cancelInteractiveTransition()
} else {
transitionContext.finishInteractiveTransition()
}
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
| mit | 1cff3f4c1643c209331cdbf65e364f9e | 44.502075 | 263 | 0.688765 | 6.098999 | false | false | false | false |
bnickel/StackedDrafts | StackedDrafts/StackedDrafts/OpenDraftsManager.swift | 1 | 5260 | //
// OpenDraftsManager.swift
// StackedDrafts
//
// Created by Brian Nickel on 4/21/16.
// Copyright © 2016 Stack Exchange. All rights reserved.
//
import UIKit
extension Notification.Name {
static let openDraftsManagerDidUpdateOpenDraftingControllers = NSNotification.Name(rawValue: "OpenDraftsManager.notifications.didUpdateOpenDraftingControllers")
}
/**
This singleton class keeps track of all view controllers conforming to `DraftViewControllerProtocol` that are either presented or minimized. When a change is observed in automatically updates the appearance of all instances of `OpenDraftsIndicatorViews`.
- Note: This singleton is eligible for state restoration. Because it can contain multiple detached view controllers, it is important that each draft view controller have a unique restoration identifier such as a UUID.
*/
@objc(SEUIOpenDraftsManager) open class OpenDraftsManager : NSObject {
@objc(sharedInstance) open static let shared: OpenDraftsManager = {
let manager = OpenDraftsManager()
UIApplication.registerObject(forStateRestoration: manager, restorationIdentifier: "OpenDraftsManager.sharedInstance")
return manager
}()
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(didPresent(_:)), name: .draftPresentationControllerDidPresentDraftViewController, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willDismissNonInteractive(_:)), name: .draftPresentationControllerWillDismissNonInteractiveDraftViewController, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// All instances of `DraftViewControllerProtocol` either presented or minimized.
private(set) open var openDraftingViewControllers: [UIViewController & DraftViewControllerProtocol] = [] { didSet { notify() } }
private func notify() {
NotificationCenter.default.post(name: .openDraftsManagerDidUpdateOpenDraftingControllers, object: self, userInfo: nil)
}
@objc private func didPresent(_ notification: Notification) {
guard let viewController = notification.presentedDraftViewController else { return }
add(viewController)
}
@objc private func willDismissNonInteractive(_ notification: Notification) {
guard let viewController = notification.presentedDraftViewController else { return }
remove(viewController)
}
/**
Presents the open draft view controller or controllers from a source view controller.
If a single draft view controller is open and minimized, it will be presented directly. If multiple draft view controllers are minimized, a draft picker view controller will be presented, allowing the user to select any draft or dismiss and return to the presenting view controller. If there are no view controllers to present, the fuction fails without error.
- Parameters:
- from: The presenting view controller.
- animated: Whether to animate the transition.
- completion: An optional callback notifying when the presentation has completed.
*/
open func presentDraft(from presentingViewController: UIViewController, openDraftsIndicatorSource: OpenDraftsIndicatorSource, animated: Bool, completion: (() -> Void)? = nil) {
if self.openDraftingViewControllers.count > 1 {
let viewController = OpenDraftSelectorViewController(openDraftsIndicatorSource: openDraftsIndicatorSource)
viewController.setRestorationIdentifier("open-drafts", contingentOnViewController: presentingViewController)
presentingViewController.present(viewController, animated: animated, completion: completion)
} else if let viewController = openDraftingViewControllers.last {
presentingViewController.present(viewController, animated: animated, completion: completion)
viewController.draftPresentationController?.hasBeenPresented = true
}
}
open func add(_ viewController: UIViewController & DraftViewControllerProtocol) {
openDraftingViewControllers = openDraftingViewControllers.filter({ $0 !== viewController }) + [viewController]
}
open func remove(_ viewController: UIViewController & DraftViewControllerProtocol) {
openDraftingViewControllers = openDraftingViewControllers.filter({ $0 !== viewController })
}
}
extension OpenDraftsManager : UIStateRestoring, UIObjectRestoration {
public var objectRestorationClass: UIObjectRestoration.Type? {
return OpenDraftsManager.self
}
public static func object(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIStateRestoring? {
return shared
}
public func encodeRestorableState(with coder: NSCoder) {
coder.encodeSafeArray(openDraftingViewControllers, forKey: "openDraftingViewControllers")
}
public func decodeRestorableState(with coder: NSCoder) {
openDraftingViewControllers = coder.decodeSafeArrayForKey("openDraftingViewControllers")
}
public func applicationFinishedRestoringState() {
notify()
}
}
| mit | 2eaaffc29aa4c3ebb2cf4c3214f5d36d | 48.149533 | 367 | 0.745959 | 5.393846 | false | false | false | false |
colinta/Moya | Source/Plugins/NetworkLoggerPlugin.swift | 11 | 3906 | import Foundation
import Result
/// Logs network activity (outgoing requests and incoming responses).
public final class NetworkLoggerPlugin: PluginType {
private let loggerId = "Moya_Logger"
private let dateFormatString = "dd/MM/yyyy HH:mm:ss"
private let dateFormatter = NSDateFormatter()
private let separator = ", "
private let terminator = "\n"
private let output: (items: Any..., separator: String, terminator: String) -> Void
private let responseDataFormatter: ((NSData) -> (NSData))?
/// If true, also logs response body data.
public let verbose: Bool
public init(verbose: Bool = false, output: (items: Any..., separator: String, terminator: String) -> Void = print, responseDataFormatter: ((NSData) -> (NSData))? = nil) {
self.verbose = verbose
self.output = output
self.responseDataFormatter = responseDataFormatter
}
public func willSendRequest(request: RequestType, target: TargetType) {
outputItems(logNetworkRequest(request.request))
}
public func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) {
if case .Success(let response) = result {
outputItems(logNetworkResponse(response.response, data: response.data, target: target))
} else {
outputItems(logNetworkResponse(nil, data: nil, target: target))
}
}
private func outputItems(items: [String]) {
if verbose {
items.forEach { output(items: $0, separator: separator, terminator: terminator) }
} else {
output(items: items, separator: separator, terminator: terminator)
}
}
}
private extension NetworkLoggerPlugin {
private var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter.stringFromDate(NSDate())
}
private func format(loggerId: String, date: String, identifier: String, message: String) -> String {
return "\(loggerId): [\(date)] \(identifier): \(message)"
}
func logNetworkRequest(request: NSURLRequest?) -> [String] {
var output = [String]()
output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")]
if let headers = request?.allHTTPHeaderFields {
output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)]
}
if let bodyStream = request?.HTTPBodyStream {
output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)]
}
if let httpMethod = request?.HTTPMethod {
output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)]
}
if let body = request?.HTTPBody where verbose == true {
if let stringOutput = NSString(data: body, encoding: NSUTF8StringEncoding) as? String {
output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)]
}
}
return output
}
func logNetworkResponse(response: NSURLResponse?, data: NSData?, target: TargetType) -> [String] {
guard let response = response else {
return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")]
}
var output = [String]()
output += [format(loggerId, date: date, identifier: "Response", message: response.description)]
if let data = data where verbose == true {
if let stringData = String(data: responseDataFormatter?(data) ?? data , encoding: NSUTF8StringEncoding) {
output += [stringData]
}
}
return output
}
}
| mit | e1a24b477065448df9cbee1ef3a8c439 | 38.06 | 174 | 0.641833 | 4.822222 | false | false | false | false |
calgaryscientific/pureweb-ios-samples | Swift-Asteroids/Asteroids/Asteroids/LoginViewController.swift | 1 | 2518 | //
// LoginViewController.swift
// Asteroids
//
// Created by Jonathan Neitz on 2016-02-10.
// Copyright © 2016 Calgary Scientific Inc. All rights reserved.
//
import UIKit
import PureWeb
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var connectButton: UIButton!
var processLoginCredentials : ((String,String)->())? = nil
override func viewDidLoad() {
super.viewDidLoad()
usernameField.delegate = self
passwordField.delegate = self
loadCredentials()
}
func loadCredentials() {
usernameField.text = UserDefaults.standard.string(forKey: "pureweb_username")
passwordField.text = UserDefaults.standard.string(forKey: "pureweb_password")
if let username = usernameField.text, let password = passwordField.text, username.characters.count > 0 && password.characters.count > 0 {
connectButton.isEnabled = true
} else {
connectButton.isEnabled = false
}
loadCollaborationCredentials()
}
func loadCollaborationCredentials() {
if let name = UserDefaults.standard.string(forKey: "pureweb_collab_name") {
PWFramework.sharedInstance().collaborationManager().updateUserInfo("Name", value: name)
}
if let email = UserDefaults.standard.string(forKey: "pureweb_collab_email") {
PWFramework.sharedInstance().collaborationManager().updateUserInfo("Email", value: email)
}
}
// MARK: - Button actions
@IBAction func connectButtonPressed(_ sender: AnyObject) {
if let username = usernameField.text, let password = passwordField.text, username.characters.count > 0 && password.characters.count > 0 {
processLoginCredentials!(username,password);
}
}
// MARK: - TextField delegate methods
@IBAction func editingDidChange(_ sender: AnyObject) {
if let username = usernameField.text, let password = passwordField.text, username.characters.count > 0 && password.characters.count > 0 {
connectButton.isEnabled = true
} else {
connectButton.isEnabled = false
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 96062b9d2db3e5c4681b105c99575061 | 30.4625 | 145 | 0.644418 | 5.095142 | false | false | false | false |
pedrovgs/KataStringCalculatorSwift | KataStringCalculatorSwift/extensions.swift | 1 | 1208 | //
// Extensions.swift
// KataStringCalculatorSwift
//
// Created by Pedro Vicente on 17/10/15.
// Copyright © 2015 Pedro Vicente Gómez Sánchez. All rights reserved.
//
import Foundation
extension String {
subscript(integerIndex: Int) -> Character {
let index = self.startIndex.advancedBy(integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = self.startIndex.advancedBy(integerRange.startIndex)
let end = self.startIndex.advancedBy(min(self.characters.count, integerRange.endIndex))
let range = start..<end
return self[range]
}
func countChars() -> Int {
return characters.count
}
}
extension Character {
func isDigit() -> Bool {
let string = String(self).unicodeScalars
let uni = string[string.startIndex]
let digits = NSCharacterSet.decimalDigitCharacterSet()
return digits.longCharacterIsMember(uni.value)
}
}
extension Int {
func countChars() -> Int {
var sum = self < 0 ? 1 : 0
var n = abs(self)
while n > 0 {
sum++
n /= 10
}
return sum
}
} | apache-2.0 | 8a22b4085f4da5467050402ed7281c41 | 21.754717 | 95 | 0.608299 | 4.318996 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/core-data-basics/core-data-basics/AppDelegate.swift | 1 | 6119 | //
// AppDelegate.swift
// core-data-basics
//
// Created by Mark Hamilton on 2/29/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.dryverless.core_data_basics" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("core_data_basics", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | e9a81bb3b3d84e2cbcf533f1765704e7 | 54.117117 | 291 | 0.719843 | 5.843362 | false | false | false | false |
shunabcd/FirebaseSocialLoginSample-swift | FirebaseSocialLoginSample/AppDelegate.swift | 1 | 5548 | //
// AppDelegate.swift
// FirebaseSocialLoginSample
//
// Created by S-SAKU on 2016/11/26.
// Copyright © 2016年 S-SAKU. All rights reserved.
//
import UIKit
import CoreData
import Firebase
import GoogleSignIn
@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "FirebaseSocialLoginSample")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
return self.application(application,
open: url,
sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: [:])
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if GIDSignIn.sharedInstance().handle(url,
sourceApplication: sourceApplication,
annotation: annotation) {
return true
}
return false
}
}
| mit | bc46d532297dd9e50d2aa0cbb832a88e | 47.217391 | 285 | 0.662038 | 5.924145 | false | false | false | false |
Linganna/XMPPChat | XMPPChat/XMPPConnection.swift | 1 | 8438 | //
// XMPPConnection.swift
// XMPPChat
//
// Created by LInganna on 18/07/17.
// Copyright © 2017 LInganna. All rights reserved.
//
import Foundation
import XMPPFramework
open class XMPPConnection:NSObject {
var xmppStream: XMPPStream
let hostName: String
let userJID: XMPPJID
let hostPort: UInt16
let password: String
var xmppDelegate:XMPPDelegate?
let completionBlockQueue = DispatchQueue(label: "xmppCompletionBlock")
var reConnect:XMPPReconnect?
public init(hostName: String, userJIDString: String, hostPort: UInt16 = 5222, password: String, delegate:XMPPDelegate) {
self.hostName = hostName
self.hostPort = hostPort
self.password = password
let userJID = XMPPJID(string: userJIDString)
self.xmppStream = XMPPStream()
self.xmppStream.hostName = hostName
self.xmppStream.hostPort = hostPort
self.userJID = userJID!
self.xmppDelegate = delegate
self.xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicy.allowed
self.xmppStream.myJID = self.userJID
super.init()
self.xmppStream.addDelegate(self, delegateQueue: completionBlockQueue)
DDLog.add(DDTTYLogger.sharedInstance)
}
fileprivate func initializeReconnectXMPP() {
self.reConnect = XMPPReconnect()
self.reConnect?.activate(self.xmppStream)
self.reConnect?.addDelegate(self, delegateQueue: completionBlockQueue)
}
public func connect() {
if !self.xmppStream.isDisconnected() {
return
}
try! self.xmppStream.connect(withTimeout: XMPPStreamTimeoutNone)
}
public func setManualReconnection(){
self.reConnect = XMPPReconnect()
self.reConnect?.activate(self.xmppStream)
self.reConnect?.manualStart()
self.reConnect?.addDelegate(self, delegateQueue: completionBlockQueue)
}
public func disconnect(){
goOffline()
self.xmppStream.disconnect()
self.reConnect?.stop()
}
public func logOut() {
self.disconnect()
CoreDataManger.shared.clearData()
}
public func goOnline() {
let presence = XMPPPresence()
self.xmppStream.send(presence)
}
public func goOffline() {
let presence = XMPPPresence(type: "unavailable")
self.xmppStream.send(presence)
}
public func sendMessage(message:String, to:String) {
DispatchQueue.global().async {
let senderJID = XMPPJID(string: to)
let msg = XMPPMessage(type: "chat", to: senderJID)
msg?.addBody(message)
msg?.addAttribute(withName: "id", stringValue: self.xmppStream.generateUUID())
Messages.saveMessage(serverMsg: msg!, isOutGoing: true)
self.xmppStream.send(msg)
}
}
public func sendAttachment(image:UIImage, to jId:String ) {
let data = UIImageJPEGRepresentation(image, 0.1)
let imageStr = data?.base64EncodedString()
let body = DDXMLElement.element(withName: "body") as! DDXMLElement
let messageID = self.xmppStream.generateUUID()
let imageAttachement = DDXMLElement.element(withName: "attachment", stringValue: imageStr!) as! DDXMLElement
let message = DDXMLElement.element(withName: "message") as! DDXMLElement
message.addAttribute(withName: "type", stringValue: "chat")
message.addAttribute(withName: "id", stringValue: messageID!)
message.addAttribute(withName: "to", stringValue: jId)
message.addChild(body)
message.addChild(imageAttachement)
let msg = XMPPMessage(from: message)
Messages.saveMessage(serverMsg:msg!, isOutGoing: true)
self.xmppStream.send(message)
}
public func forwardMessage(forwardingMessage:String, to:String, originalMsgTofeild:String?, originalMssgFromFeild:String?) {
DispatchQueue.global().async {
let senderJID = XMPPJID(string: to)
let msg = XMPPMessage(type: "chat", to: senderJID)
msg?.addBody(forwardingMessage)
msg?.addAttribute(withName: "id", stringValue: self.xmppStream.generateUUID())
let forwarded = XMLElement(name: "forwarded")
forwarded.setXmlns("urn:xmpp:forward:0")
let delay = XMLElement(name:"delay" , xmlns: "urn:xmpp:delay")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
delay?.addAttribute(withName: "stamp", stringValue:formatter.string(from: NSDate() as Date) )
forwarded.addChild(delay!)
let senderJID2 = XMPPJID(string: originalMsgTofeild)
let msg2 = XMPPMessage(type: "chat", to: senderJID2)
msg2?.addAttribute(withName: "from", stringValue: originalMssgFromFeild!)
msg2?.addBody(forwardingMessage)
msg2?.addAttribute(withName: "id", stringValue: self.xmppStream.generateUUID())
forwarded.addChild(msg2!)
msg?.addChild(forwarded)
Messages.saveMessage(serverMsg: msg!, isOutGoing: true)
self.xmppStream.send(msg)
}
}
func sendPendingMessage() {
if let moc = CoreDataManger.shared.backgroundMoc{
moc.performAndWait {
let msgs = Messages.fetchOutGoingPendingMessages(inMoc: moc)
if msgs.count > 0 {
for msg in msgs {
let senderJID = XMPPJID(string: msg.to)
let xmppMsg = XMPPMessage(type: "chat", to: senderJID)
xmppMsg?.addBody(msg.body)
xmppMsg?.addAttribute(withName: "id", stringValue: msg.id!)
self.xmppStream.send(xmppMsg)
}
}
}
}
}
public func xmppConnectionStatus() -> XMPPStreamState {
return self.xmppStream.state
}
public func isConnected() -> Bool {
return self.xmppStream.isConnected()
}
public func isConnecting() -> Bool {
return self.xmppStream.isConnecting()
}
}
extension XMPPConnection: XMPPStreamDelegate,XMPPReconnectDelegate {
public func xmppStreamDidConnect(_ stream: XMPPStream!) {
NSLog("XMPP: Connected")
self.xmppDelegate?.xmppConnectionState(xmppConnectionStatue: .connecting)
try! stream.authenticate(withPassword: self.password)
guard let _ = self.reConnect else {
self.initializeReconnectXMPP()
return
}
}
public func xmppStreamDidDisconnect(_ sender: XMPPStream!, withError error: Error!) {
NSLog("XMPP: DisConnected error:\(error)")
goOffline()
self.xmppDelegate?.xmppConnectionState(xmppConnectionStatue: .disConnected)
}
public func xmppStreamDidAuthenticate(_ sender: XMPPStream!) {
print("XMPP: Authenticated")
goOnline()
self.xmppDelegate?.xmppConnectionState(xmppConnectionStatue: .connected)
self.sendPendingMessage()
}
func xmppStream(sender: XMPPStream!, didReceiveIQ iq: XMPPIQ!) -> Bool {
print("XMPP receive IQ - Query")
return false
}
public func xmppStream(_ sender: XMPPStream!, didSend message: XMPPMessage!) {
print("XMPP send message \(message)")
Messages.updateMessage(satue: .Sent, for: message.elementID())
}
public func xmppStream(_ sender: XMPPStream!, didReceive message: XMPPMessage!) {
print("XMPP receive message \(message)")
Messages.saveMessage(serverMsg: message, isOutGoing: false)
self.xmppDelegate?.xmppDidReceiveMessage(message: message.body(), to: message.toStr())
}
public func xmppReconnect(_ sender: XMPPReconnect!, shouldAttemptAutoReconnect connectionFlags: SCNetworkConnectionFlags) -> Bool {
return true
}
public func xmppReconnect(_ sender: XMPPReconnect!, didDetectAccidentalDisconnect connectionFlags: SCNetworkConnectionFlags) {
NSLog("didDetectAccidentalDisconnect: \(connectionFlags)")
}
}
| mit | 0874610551a43a7bae407fd01f64e7a9 | 33.577869 | 135 | 0.622259 | 4.832188 | false | false | false | false |
CassiusPacheco/sweettrex | Sources/App/External Files/Mailgun.swift | 1 | 3802 | import HTTP
import SMTP
import URI
import FormData
import Multipart
import Vapor
// Courtesy of https://github.com/vapor-community/mailgun-provider
// MARK: Mailgun
final class Mailgun: MailProtocol {
public let clientFactory: ClientFactoryProtocol
public let apiURI: URI
public let apiKey: String
public let domain: String
public init( domain: String, apiKey: String, _ clientFactory: ClientFactoryProtocol) throws {
self.apiURI = try URI("https://api.mailgun.net/v3/")
self.clientFactory = clientFactory
self.apiKey = apiKey
self.domain = domain
}
}
// MARK: Sending Emails
extension Mailgun {
public func send(_ emails: [Email]) throws {
try emails.forEach(_send)
}
private func _send(_ mail: Email) throws {
let uri = apiURI.appendingPathComponent(domain).appendingPathComponent("messages")
let req = Request(method: .post, uri: uri)
let basic = "api:\(apiKey)".makeBytes().base64Encoded.makeString()
req.headers["Authorization"] = "Basic \(basic)"
var json = JSON()
try json.set("subject", mail.subject)
switch mail.body.type {
case .html:
try json.set("html", mail.body.content)
case .plain:
try json.set("text", mail.body.content)
}
let fromName = mail.from.name ?? "Vapor Mailgun"
let fromPart = Part(headers: [:], body: "\(fromName) <\(mail.from.address)>".makeBytes())
let from = FormData.Field(name: "from", filename: nil, part: fromPart)
let toPart = Part(headers: [:], body: mail.to.map({ $0.address }).joined(separator: ", ").makeBytes() )
let to = FormData.Field(name: "to", filename: nil, part: toPart)
let subjectPart = Part(headers: [:], body: mail.subject.makeBytes())
let subject = FormData.Field(name: "subject", filename: nil, part: subjectPart)
let bodyKey: String
switch mail.body.type {
case .html:
bodyKey = "html"
case .plain:
bodyKey = "text"
}
let bodyPart = Part(headers: [:], body: mail.body.content.makeBytes())
let body = FormData.Field(name: bodyKey, filename: nil, part: bodyPart)
req.formData = [
"from": from,
"to": to,
"subject": subject,
bodyKey: body
]
let client = try clientFactory.makeClient(
hostname: apiURI.hostname,
port: apiURI.port ?? 443,
securityLayer: .tls(EngineClient.defaultTLSContext())
)
let res = try client.respond(to: req)
guard res.status.statusCode < 400 else {
guard let json = res.json else { throw Abort.badRequest }
throw Abort(.badRequest, metadata: json.makeNode(in: nil))
}
}
}
// MARK: Config
extension Mailgun: ConfigInitializable {
public convenience init(config: Config) throws {
guard let mailgun = config["mailgun"] else { throw ConfigError.missingFile("mailgun") }
guard let domain = mailgun["domain"]?.string else { throw ConfigError.missing(key: ["domain"], file: "mailgun", desiredType: String.self) }
guard let apiKey = mailgun["key"]?.string else { throw ConfigError.missing(key: ["key"], file: "mailgun", desiredType: String.self) }
let client = try config.resolveClient()
try self.init(domain: domain, apiKey: apiKey, client)
}
}
| mit | 46f462661673e10f1de2e95ddd2870b4 | 29.910569 | 147 | 0.561547 | 4.558753 | false | true | false | false |
eKasztany/4ania | ios/Queue/Pods/Alamofire/Source/SessionManager.swift | 23 | 33489 | //
// SessionManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
open static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
open let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
open let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return request(encodedURLRequest)
} catch {
return request(failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
do {
let originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(failedWith error: Error) -> DataRequest {
let request = DataRequest(session: session, requestTask: .data(nil, nil), error: error)
if startRequestsImmediately { request.resume() }
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest
{
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let request = DownloadRequest(session: session, requestTask: .download(downloadable, task))
request.downloadDelegate.destination = destination
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return download(failedWith: error)
}
}
private func download(failedWith error: Error) -> DownloadRequest {
let download = DownloadRequest(session: session, requestTask: .download(nil, nil), error: error)
if startRequestsImmediately { download.resume() }
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(fileURL, with: urlRequestWithContentType),
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(failedWith: error)
}
}
private func upload(failedWith error: Error) -> UploadRequest {
let upload = UploadRequest(session: session, requestTask: .upload(nil, nil), error: error)
if startRequestsImmediately { upload.resume() }
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
request.delegate.task = task // resets all task delegate data
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error
return false
}
}
}
| apache-2.0 | 3e1bf4b68b5397541699c2a8313624b7 | 42.155928 | 129 | 0.631043 | 5.389282 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/AboutMeModifyTextViewController.swift | 1 | 4341 | //
// AboutMeModifyTextViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/23.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
enum aboutMeModityTextType: String {
case nickName = "姓名"
case sign = "签名"
case qq = "QQ"
case wechat = "微信"
case weibo = "新浪微博"
case address = "固定电话"
case telephone = "详细地址"
func keyValue() -> String {
switch self {
case .nickName:
return "nick_name"
case .sign:
return "tip"
case .qq:
return "qq"
case .wechat:
return "wechat"
case .weibo:
return "weibo"
case .address:
return "address"
case .telephone:
return "telephone"
}
}
}
class AboutMeModifyTextViewController: UITableViewController {
var icyType: aboutMeModityTextType!
weak var delegate: ModifyTextDelegate?
private weak var icyTextField: UITextField!
var defaultText: String?
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()
addRightButton("确定", action: "rightButtonPressed:")
navigationItem.title = icyType.rawValue
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
private var _parameters: [String: String!]!
func rightButtonPressed(sender: AnyObject) {
let parameter = [
"user_name" : LCYCommon.sharedInstance.userName!,
"key" : icyType.keyValue(),
"value" : icyTextField.text
]
_parameters = parameter
showHUDWithTips("正在提交修改")
LCYNetworking.sharedInstance.POST(LCYApi.UserModifySingle,
parameters: parameter,
success: { [weak self](object) -> Void in
self?.hideHUD()
if let result = object["result"]?.boolValue {
if result {
self?.alertWithDelegate("修改成功", tag: 9001, delegate: self)
self?.delegate?.didModifyText(self?.icyType, text: self?._parameters["value"])
} else {
self?.alert("修改失败")
}
} else {
self?.alert("修改失败")
}
return
}) { [weak self] (error) -> Void in
self?.hideHUD()
self?.alert("修改失败,请检查网络状态")
return
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(AboutMeModifyTextCell.identifier(), forIndexPath: indexPath) as! AboutMeModifyTextCell
icyTextField = cell.icyTextField
cell.icyTextField.text = defaultText
cell.icyTextField.becomeFirstResponder()
return cell
}
}
extension AboutMeModifyTextViewController: UIAlertViewDelegate {
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.tag == 9001 {
navigationController?.popViewControllerAnimated(true)
}
}
}
protocol ModifyTextDelegate: class {
func didModifyText(type: aboutMeModityTextType?, text: String?)
}
| apache-2.0 | 43c2dbc7db15b48df5eb86f9e619ae3d | 30.110294 | 149 | 0.597967 | 5.024941 | false | false | false | false |
daniel-barros/ExtendedUIKit | Sources/iOS/Extensions/UIScrollView.swift | 2 | 1613 | //
// UIScrollView.swift
// ExtendedUIKit
//
// Created by Daniel Barros López on 11/5/16.
//
// Copyright (c) 2016 - 2017 Daniel Barros López
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public extension UIScrollView {
/// Makes the scroll view stop the scrolling immediately.
func killScroll() {
var offset = contentOffset
offset.x -= 1
offset.y -= 1
setContentOffset(offset, animated: false)
offset.x += 1
offset.y += 1
setContentOffset(offset, animated: false)
}
}
| mit | f2204fda3289a9eab21fc722b234cf4f | 37.357143 | 81 | 0.710739 | 4.389646 | false | false | false | false |
douban/rexxar-ios | RexxarDemo/FullRXRViewController.swift | 2 | 1440 | //
// FullRXRViewController.swift
// RexxarDemo
//
// Created by GUO Lin on 8/19/16.
// Copyright © 2016 Douban.Inc. All rights reserved.
//
import UIKit
class FullRXRViewController: RXRViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// Widgets
let pullRefreshWidget = RXRPullRefreshWidget()
let titleWidget = RXRNavTitleWidget()
let alertDialogWidget = RXRAlertDialogWidget()
let toastWidget = RXRToastWidget()
let navMenuWidget = RXRNavMenuWidget()
widgets = [titleWidget, alertDialogWidget, pullRefreshWidget, toastWidget, navMenuWidget]
// Decorators
let headers = ["Customer-Authorization": "Bearer token"]
let parameters = ["apikey": "apikey value"]
let requestDecorator = RXRRequestDecorator(headers: headers, parameters: parameters)
RXRRequestInterceptor.decorators = [requestDecorator]
RXRNSURLProtocol.registerRXRProtocolClass(RXRRequestInterceptor.self)
// ContainerAPIs
let geoContainerAPI = RXRGeoContainerAPI()
let logContainerAPI = RXRLogContainerAPI()
RXRContainerInterceptor.containerAPIs = [geoContainerAPI, logContainerAPI]
RXRNSURLProtocol.registerRXRProtocolClass(RXRContainerInterceptor.self)
}
deinit {
RXRNSURLProtocol.unregisterRXRProtocolClass(RXRContainerInterceptor.self)
RXRNSURLProtocol.unregisterRXRProtocolClass(RXRRequestInterceptor.self)
}
}
| mit | 1f5778684e54f90e2d90b7ad85f85123 | 32.465116 | 93 | 0.765115 | 4.146974 | false | false | false | false |
argon/WordPress-iOS | WordPress/Classes/Extensions/UIView+Helpers.swift | 8 | 3382 | import Foundation
extension UIView
{
// MARK: - Public Methods
public func pinSubview(subview: UIView, aboveSubview: UIView) {
let constraint = NSLayoutConstraint(item: subview, attribute: .Bottom, relatedBy: .Equal, toItem: aboveSubview, attribute: .Top, multiplier: 1, constant: 0)
addConstraint(constraint)
}
public func pinSubviewAtBottom(subview: UIView) {
let newConstraints = [
NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: subview, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: subview, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: subview, attribute: .Bottom, multiplier: 1, constant: 0),
]
addConstraints(newConstraints)
}
public func pinSubviewToAllEdges(subview: UIView) {
let newConstraints = [
NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: subview, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: subview, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: subview, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: subview, attribute: .Top, multiplier: 1, constant: 0)
]
addConstraints(newConstraints)
}
public func constraintForAttribute(attribute: NSLayoutAttribute) -> CGFloat? {
for constraint in constraints() as! [NSLayoutConstraint] {
if constraint.firstItem as! NSObject == self {
if constraint.firstAttribute == attribute || constraint.secondAttribute == attribute {
return constraint.constant
}
}
}
return nil
}
public func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) {
updateConstraintWithFirstItem(self, attribute: attribute, constant: constant)
}
public func updateConstraintWithFirstItem(firstItem: NSObject!, attribute: NSLayoutAttribute, constant: CGFloat) {
for constraint in constraints() as! [NSLayoutConstraint] {
if constraint.firstItem as! NSObject == firstItem {
if constraint.firstAttribute == attribute || constraint.secondAttribute == attribute {
constraint.constant = constant
}
}
}
}
public func updateConstraintWithFirstItem(firstItem: NSObject!, secondItem: NSObject!, firstItemAttribute: NSLayoutAttribute, secondItemAttribute: NSLayoutAttribute, constant: CGFloat) {
for constraint in constraints() as! [NSLayoutConstraint] {
if (constraint.firstItem as! NSObject == firstItem) && (constraint.secondItem as? NSObject == secondItem) {
if constraint.firstAttribute == firstItemAttribute && constraint.secondAttribute == secondItemAttribute {
constraint.constant = constant
}
}
}
}
}
| gpl-2.0 | 6a5b2cc884965356f16360596a2a1495 | 49.477612 | 190 | 0.651685 | 5.267913 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/animation/layer_animation/FuncBounds.swift | 1 | 420 |
func boundsForFunc(_ func2d: func2D) -> Rect {
var p = func2d(0.0)
var minX = p.x
var minY = p.y
var maxX = minX
var maxY = minY
for t in stride(from: 0.0, to: 1.0, by: 0.01) {
p = func2d(t)
if minX > p.x {
minX = p.x
}
if minY > p.y {
minY = p.y
}
if maxX < p.x {
maxX = p.x
}
if maxY < p.y {
maxY = p.y
}
}
return Rect(x: minX, y: minY, w: maxX - minX, h: maxY - minY)
}
| mit | 5d814d359b1e2302e3171e8a226d5988 | 12.125 | 62 | 0.509524 | 2.079208 | false | false | false | false |
zhxnlai/wwdc | Zhixuan Lai/Zhixuan Lai/ZLCollectionReusableView.swift | 1 | 846 | //
// ZLCollectionReusableView.swift
// ZLBalancedFlowLayoutDemo
//
// Created by Zhixuan Lai on 12/24/14.
// Copyright (c) 2014 Zhixuan Lai. All rights reserved.
//
import UIKit
class ZLCollectionReusableView: UICollectionReusableView {
// var headerView = ZLSectionHeaderView()
override init(frame: CGRect) {
super.init(frame: frame)
// setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// setup()
}
// func setup() {
//// backgroundColor = UIColor.lightGrayColor()
//// headerView.textColor = UIColor.blackColor()
//// headerView.textAlignment = .Center
// addSubview(headerView)
// }
//
// override func layoutSubviews() {
// super.layoutSubviews()
// headerView.frame = self.bounds
// }
}
| mit | 5333afa035c3b3f861265e124c73783d | 23.882353 | 58 | 0.618203 | 4.167488 | false | false | false | false |
MadAppGang/refresher | PullToRefreshDemo/ChooseModeViewController.swift | 1 | 1985 | //
// ChooseModeViewController.swift
// PullToRefresh
//
// Created by Josip Cavar on 01/08/15.
// Copyright (c) 2015 Josip Cavar. All rights reserved.
//
import UIKit
class ChooseModeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func defaultAction(sender: AnyObject) {
showControllerWithMode(.Default)
}
@IBAction func beatAction(sender: AnyObject) {
showControllerWithMode(.Beat)
}
@IBAction func pacmanAction(sender: AnyObject) {
showControllerWithMode(.Pacman)
}
@IBAction func customAction(sender: AnyObject) {
showControllerWithMode(.Custom)
}
@IBAction func loadMoreDefaultAction(sender: AnyObject) {
showControllerWithMode(.LoadMoreDefault)
}
@IBAction func loadMoreCustomAction(sender: AnyObject) {
showControllerWithMode(.LoadMoreCustom)
}
@IBAction func reachabilityAction(sender: AnyObject) {
showControllerWithMode(.InternetConnectionLost)
}
func showControllerWithMode(mode: ExampleMode) {
if let pullToRefreshViewControler = self.storyboard?.instantiateViewControllerWithIdentifier("PullToRefreshViewController") as? PullToRefreshViewController {
pullToRefreshViewControler.exampleMode = mode
navigationController?.pushViewController(pullToRefreshViewControler, animated: true)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "reachabilityCustom" {
if let vc = segue.destinationViewController as? ConnectionLostViewController {
vc.showCustomView = true
}
}
}
}
| mit | f65f4c1e983992684d30ce9dc5fd9e64 | 28.626866 | 165 | 0.681612 | 5.307487 | false | false | false | false |
kickstarter/ios-oss | Library/SharedFunctions.swift | 1 | 23069 | import KsApi
import Prelude
import ReactiveSwift
import UIKit
import UserNotifications
/**
Determines if the personalization data in the project implies that the current user is backing the
reward passed in. Because of the many ways in which we can get this data we have multiple ways of
determining this.
- parameter reward: A reward.
- parameter project: A project.
- returns: A boolean.
*/
internal func userIsBacking(reward: Reward, inProject project: Project) -> Bool {
guard let backing = project.personalization.backing else { return false }
return backing.reward?.id == reward.id
|| backing.rewardId == reward.id
|| (backing.reward == nil && backing.rewardId == nil && reward == Reward.noReward)
}
/**
Determines if the personalization data in the project implies that the current user is backing the
project passed in.
- parameter project: A project.
- returns: A boolean.
*/
internal func userIsBackingProject(_ project: Project) -> Bool {
return project.personalization.backing != nil || project.personalization.isBacking == .some(true)
}
/**
Determines if the current user is the creator for a given project.
- parameter project: A project.
- returns: A boolean.
*/
public func currentUserIsCreator(of project: Project) -> Bool {
guard let user = AppEnvironment.current.currentUser else { return false }
return project.creator.id == user.id
}
/**
Returns a reward from a backing in a given project
- parameter backing: A backing
- parameter project: A project
- returns: A reward
*/
internal func reward(from backing: Backing, inProject project: Project) -> Reward {
if let backingReward = backing.reward {
return backingReward
}
guard let rewardId = backing.rewardId else { return Reward.noReward }
return reward(withId: rewardId, inProject: project)
}
/**
Returns a reward for a backing ID in a given project
- parameter backing: A backing ID
- parameter project: A project
- returns: A reward
*/
internal func reward(withId rewardId: Int, inProject project: Project) -> Reward {
let noRewardFromProject = project.rewards.first { $0.id == Reward.noReward.id }
return project.rewards.first { $0.id == rewardId }
?? noRewardFromProject
?? Reward.noReward
}
/**
Computes the minimum and maximum amounts that can be pledge to a reward. For the "no reward" reward,
this looks up values in the table of launched countries, since the values depend on the currency.
- parameter project: A project.
- parameter reward: A reward.
- returns: A pair of the minimum and maximum amount that can be pledged to a reward.
*/
internal func minAndMaxPledgeAmount(forProject project: Project, reward: Reward?)
-> (min: Double, max: Double) {
// The country on the project cannot be trusted to have the min/max values, so first try looking
// up the country in our launched countries array that we get back from the server config.
// project currency is more accurate to find the country to base the min/max values off of.
let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country
let country = AppEnvironment.current.launchedCountries.countries
.first { $0 == projectCurrencyCountry }
.coalesceWith(projectCurrencyCountry)
switch reward {
case .none, .some(Reward.noReward):
return (Double(country.minPledge ?? 1), Double(country.maxPledge ?? 10_000))
case let .some(reward):
return (reward.minimum, Double(country.maxPledge ?? 10_000))
}
}
/**
Computes the minimum amount needed to pledge to a reward. For the "no reward" reward,
this looks up values in the table of launched countries, since the values depend on the currency.
- parameter project: A project.
- parameter reward: A reward.
- returns: The minimum amount needed to pledge to the reward.
*/
internal func minPledgeAmount(forProject project: Project, reward: Reward?) -> Double {
return minAndMaxPledgeAmount(forProject: project, reward: reward).min
}
/**
Returns the full currency symbol for a country. Special logic is added around prefixing currency symbols
with country/currency codes based on a variety of factors.
- parameter country: The country.
- parameter omitCurrencyCode: Safe to omit the US currencyCode
- parameter env: Current Environment.
- returns: The currency symbol that can be used for currency display.
*/
public func currencySymbol(
forCountry country: Project.Country,
omitCurrencyCode: Bool = true,
env: Environment = AppEnvironment.current
) -> String {
guard env.launchedCountries.currencyNeedsCode(country.currencySymbol) else {
// Currencies that dont have ambigious currencies can just use their symbol.
return country.currencySymbol
}
if country == .us && env.countryCode == Project.Country.us.countryCode && omitCurrencyCode {
// US people looking at US projects just get the currency symbol
return country.currencySymbol
} else if country == .sg {
// Singapore projects get a special currency prefix
return "\(String.nbsp)S\(country.currencySymbol)\(String.nbsp)"
} else if country.currencySymbol == "kr" || country.currencySymbol == "Fr" {
// Kroner projects use the currency code prefix
return "\(String.nbsp)\(country.currencyCode)\(String.nbsp)"
} else {
// Everything else uses the country code prefix.
return "\(String.nbsp)\(country.countryCode)\(country.currencySymbol)\(String.nbsp)"
}
}
/**
Returns the full country for a currency code.
- parameter code: The currency code.
- parameter env: Current Environment.
- returns: The first matching country for currency symbol
*/
public func projectCountry(
forCurrency code: String?,
env: Environment = AppEnvironment.current
) -> Project.Country? {
guard let currencyCode = code,
let country = env.launchedCountries.countries.filter({ $0.currencyCode == currencyCode }).first else {
return nil
}
// return a hardcoded Country if it matches the country code
return country
}
public func updatedUserWithClearedActivityCountProducer() -> SignalProducer<User, Never> {
return AppEnvironment.current.apiService.clearUserUnseenActivity(input: .init())
.filter { _ in AppEnvironment.current.currentUser != nil }
.map { $0.activityIndicatorCount }
.map { count in AppEnvironment.current.currentUser ?|> User.lens.unseenActivityCount .~ count }
.skipNil()
.demoteErrors()
}
public func defaultShippingRule(fromShippingRules shippingRules: [ShippingRule]) -> ShippingRule? {
let shippingRuleFromCurrentLocation = shippingRules
.first { shippingRule in shippingRule.location.country == AppEnvironment.current.config?.countryCode }
if let shippingRuleFromCurrentLocation = shippingRuleFromCurrentLocation {
return shippingRuleFromCurrentLocation
}
let shippingRuleInUSA = shippingRules
.first { shippingRule in shippingRule.location.country == "US" }
return shippingRuleInUSA ?? shippingRules.first
}
public func formattedAmountForRewardOrBacking(
project: Project,
rewardOrBacking: Either<Reward, Backing>
) -> String {
let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country
switch rewardOrBacking {
case let .left(reward):
let min = minPledgeAmount(forProject: project, reward: reward)
return Format.currency(
min,
country: projectCurrencyCountry,
omitCurrencyCode: project.stats.omitUSCurrencyCode
)
case let .right(backing):
return Format.formattedCurrency(
backing.amount,
country: projectCurrencyCountry,
omitCurrencyCode: project.stats.omitUSCurrencyCode
)
}
}
internal func classNameWithoutModule(_ class: AnyClass) -> String {
return `class`
.description()
.components(separatedBy: ".")
.dropFirst()
.joined(separator: ".")
}
public func deviceIdentifier(uuid: UUIDType, env: Environment = AppEnvironment.current) -> String {
guard let identifier = env.device.identifierForVendor else {
return uuid.uuidString
}
return identifier.uuidString
}
typealias SanitizedPledgeParams = (pledgeTotal: String, rewardIds: [String], locationId: String?)
internal func sanitizedPledgeParameters(
from rewards: [Reward],
selectedQuantities: SelectedRewardQuantities,
pledgeTotal: Double,
shippingRule: ShippingRule?
) -> SanitizedPledgeParams {
let shippingLocationId = (shippingRule?.location.id).flatMap(String.init)
let formattedPledgeTotal = Format.decimalCurrency(for: pledgeTotal)
let rewardIds = rewards.map { reward -> [String] in
guard let selectedRewardQuantity = selectedQuantities[reward.id] else { return [] }
return Array(0..<selectedRewardQuantity).map { _ in reward.graphID }
}
.flatMap { $0 }
return (formattedPledgeTotal, rewardIds, shippingLocationId)
}
public func ksr_pledgeAmount(
_ pledgeAmount: Double,
subtractingShippingAmount shippingAmount: Double?
) -> Double {
guard let shippingAmount = shippingAmount, shippingAmount > 0 else { return pledgeAmount }
let pledgeAmount = Decimal(pledgeAmount) - Decimal(shippingAmount)
return (pledgeAmount as NSDecimalNumber).doubleValue
}
public func discoveryPageBackgroundColor() -> UIColor {
let variant = OptimizelyExperiment.nativeProjectCardsExperimentVariant()
switch variant {
case .variant1:
return UIColor.ksr_support_100
case .variant2, .control:
return UIColor.ksr_white
}
}
public func isNativeRiskMessagingControlEnabled() -> Bool {
guard let variant = AppEnvironment.current.optimizelyClient?
.variant(for: .nativeRiskMessaging)
else { return true }
switch variant {
case .control, .variant2:
return true
case .variant1:
return false
}
}
public func rewardIsAvailable(project: Project, reward: Reward) -> Bool {
let isLimited = reward.isLimitedQuantity
let isTimebased = reward.isLimitedTime
guard isLimited || isTimebased else { return true }
let remainingQty = rewardLimitRemainingForBacker(project: project, reward: reward)
let isRemaining = remainingQty == nil || (remainingQty ?? 0) > 0
let now = AppEnvironment.current.dateType.init().timeIntervalSince1970
let endsAt = reward.endsAt.coalesceWith(now)
let timeLimitNotReached = endsAt > now
// Limited availability is valid if the reward is limited and remaining > 0 OR this reward is not limited.
let limitedAvailabilityValid = (isLimited && isRemaining) || !isLimited
// Timebased availability is valid if the reward is timebased and the time limit has not been reached
// OR the reward is not timebased.
let timebasedAvailabilityValid = (isTimebased && timeLimitNotReached) || !isTimebased
// Both types of availability must be valid in order for this reward to be considered available.
return limitedAvailabilityValid && timebasedAvailabilityValid
}
public func rewardLimitRemainingForBacker(project: Project, reward: Reward) -> Int? {
guard let remaining = reward.remaining else {
return nil
}
// If the reward is limited, determine the currently backed quantity.
var backedQuantity: Int = 0
if let backing = project.personalization.backing {
let rewardQuantities = selectedRewardQuantities(in: backing)
backedQuantity = rewardQuantities[reward.id] ?? 0
}
/**
Remaining limit for the backer is the minimum of the total remaining quantity
(including what has been backed).
For example, let `remaining` be 1 and `backedQuantity` be 3:
`remainingForBacker` will be 4 as the backer as already backed 3, 1 is available.
*/
return remaining + backedQuantity
}
public func rewardLimitPerBackerRemainingForBacker(project: Project, reward: Reward) -> Int? {
/// Be sure that there is a `limitPerBacker` set
guard let limitPerBacker = reward.limitPerBacker else { return nil }
/**
If this is not a limited reward, the `limitPerBacker` is remaining when creating/editing a pledge.
This amount will include any backed quantity as the user is able to edit their pledge.
*/
guard let remaining = reward.remaining else {
return limitPerBacker
}
// If the reward is limited, determine the currently backed quantity.
var backedQuantity: Int = 0
if let backing = project.personalization.backing {
let rewardQuantities = selectedRewardQuantities(in: backing)
backedQuantity = rewardQuantities[reward.id] ?? 0
}
/**
Remaining for the backer is the minimum of the total remaining quantity
(including what has been backed) or `limitPerBacker`.
For example, let `remaining` be 1, `limitPerBacker` be 5 and `backedQuantity` be 3:
`remainingForBacker` will be 4 as the backer as already backed 3, 1 is available and this amount is less
than `limitPerBacker`.
*/
let remainingPlusBacked = remaining + backedQuantity
return min(remainingPlusBacked, limitPerBacker)
}
public func selectedRewardQuantities(in backing: Backing) -> SelectedRewardQuantities {
var quantities: [SelectedRewardId: SelectedRewardQuantity] = [:]
let rewards = [backing.reward].compact() + (backing.addOns ?? [])
rewards.forEach { reward in
quantities[reward.id] = (quantities[reward.id] ?? 0) + 1
}
return quantities
}
public func rewardsCarouselCanNavigateToReward(_ reward: Reward, in project: Project) -> Bool {
guard !currentUserIsCreator(of: project) else { return false }
let isBacking = userIsBacking(reward: reward, inProject: project)
let isAvailableForNewBacker = rewardIsAvailable(project: project, reward: reward) && !isBacking
let isAvailableForExistingBackerToEdit = (isBacking && reward.hasAddOns)
return [
project.state == .live,
isAvailableForNewBacker || isAvailableForExistingBackerToEdit
]
.allSatisfy(isTrue)
}
/**
Determines if a start date from a given reward/add on predates the current date.
- parameter reward: The reward being evaluated
- returns: A Bool representing whether the reward has a start date prior to the current date/time.
*/
public func isStartDateBeforeToday(for reward: Reward) -> Bool {
return (reward.startsAt == nil || (reward.startsAt ?? 0) <= AppEnvironment.current.dateType.init()
.timeIntervalSince1970)
}
/**
Determines if an end date from a given reward/add on is after the current date.
- parameter reward: The reward being evaluated
- returns: A Bool representing whether the reward has an end date after to the current date/time.
*/
public func isEndDateAfterToday(for reward: Reward) -> Bool {
return (reward.endsAt == nil || (reward.endsAt ?? 0) >= AppEnvironment.current.dateType.init()
.timeIntervalSince1970)
}
/*
A helper that assists in rounding a Double to a given number of decimal places
*/
public func rounded(_ value: Double, places: Int16) -> Decimal {
let roundingBehavior = NSDecimalNumberHandler(
roundingMode: .bankers,
scale: places,
raiseOnExactness: true,
raiseOnOverflow: true,
raiseOnUnderflow: true,
raiseOnDivideByZero: true
)
return NSDecimalNumber(value: value).rounding(accordingToBehavior: roundingBehavior) as Decimal
}
/*
A helper that assists in rounding a Float to a given number of decimal places
*/
public func rounded(_ value: Float, places: Int16) -> Decimal {
let roundingBehavior = NSDecimalNumberHandler(
roundingMode: .bankers,
scale: places,
raiseOnExactness: true,
raiseOnOverflow: true,
raiseOnUnderflow: true,
raiseOnDivideByZero: true
)
return NSDecimalNumber(value: value).rounding(accordingToBehavior: roundingBehavior) as Decimal
}
/**
An helper func that calculates shipping total for base reward
- parameter project: The `Project` associated with a group of Rewards.
- parameter baseReward: The reward being evaluated
- parameter shippingRule: `ShippingRule` information about shipping details of selected rewards.
- returns: A `Double` of the shipping value. If the `Project` `Backing` object is nil,
and `baseReward` shipping is not enabled, the value is `0.0`
*/
public func getBaseRewardShippingTotal(
project: Project,
baseReward: Reward,
shippingRule: ShippingRule?
) -> Double {
// If digital or local pickup there is no shipping
guard !isRewardDigital(baseReward),
!isRewardLocalPickup(baseReward),
baseReward != .noReward else { return 0.0 }
let backing = project.personalization.backing
// If there is no `Backing` (new pledge), return the rewards shipping rule
return backing.isNil ?
baseReward.shippingRule(matching: shippingRule)?.cost ?? 0.0 :
backing?.shippingAmount.flatMap(Double.init) ?? 0.0
}
/**
An helper func that calculates shipping total for base reward
- parameter shippingRule: `ShippingRule` information about shipping details of selected rewards.
- parameter addOnRewards: An array of `Reward` objects representing the available add-ons.
- parameter quantities: A dictionary that aggregates the quantity of selected add-ons.
- returns: A `Double` of the shipping value.
*/
func calculateShippingTotal(
shippingRule: ShippingRule,
addOnRewards: [Reward],
quantities: SelectedRewardQuantities
) -> Double {
let calculatedShippingTotal = addOnRewards.reduce(0.0) { total, reward in
guard !isRewardDigital(reward), !isRewardLocalPickup(reward), reward != .noReward else { return total }
let shippingCostForReward = reward.shippingRule(matching: shippingRule)?.cost ?? 0
let totalShippingForReward = shippingCostForReward
.multiplyingCurrency(Double(quantities[reward.id] ?? 0))
return total.addingCurrency(totalShippingForReward)
}
return calculatedShippingTotal
}
/**
An helper func that calculates pledge total for all rewards
- parameter pledgeAmount: The amount pledged for a project.
- parameter shippingCost: The shipping cost for the pledge.
- parameter addOnRewardsTotal: The total amount of all addOn rewards.
- returns: A `Double` of the pledge value.
*/
func calculatePledgeTotal(
pledgeAmount: Double,
shippingCost: Double,
addOnRewardsTotal: Double
) -> Double {
let r = [pledgeAmount, shippingCost, addOnRewardsTotal].reduce(0) { accum, amount in
accum.addingCurrency(amount)
}
return r
}
/**
An helper func that calculates pledge total for all rewards
- parameter addOnRewards: The `Project` associated with a group of Rewards.
- parameter selectedQuantities: A dictionary that aggregates the quantity of selected add-ons.
- returns: A `Double` of all rewards add-ons total.
*/
func calculateAllRewardsTotal(addOnRewards: [Reward],
selectedQuantities: SelectedRewardQuantities) -> Double {
addOnRewards.filter { !$0.isNoReward }
.reduce(0.0) { total, reward -> Double in
let totalForReward = reward.minimum
.multiplyingCurrency(Double(selectedQuantities[reward.id] ?? 0))
return total.addingCurrency(totalForReward)
}
}
/**
Creates `CheckoutPropertiesData` to send with our event properties.
- parameter from: The `Project` associated with the checkout.
- parameter baseReward: The reward being evaluated
- parameter addOnRewards: An array of `Reward` objects representing the available add-ons.
- parameter selectedQuantities: A dictionary of reward id to quantitiy.
- parameter additionalPledgeAmount: The bonus amount included in the pledge.
- parameter pledgeTotal: The total amount of the pledge.
- parameter shippingTotal: The shipping cost for the pledge.
- parameter checkoutId: The unique ID associated with the checkout.
- parameter isApplePay: A `Bool` indicating if the pledge was done with Apple pay.
- returns: A `CheckoutPropertiesData` object required for checkoutProperties.
*/
public func checkoutProperties(
from project: Project,
baseReward: Reward,
addOnRewards: [Reward],
selectedQuantities: SelectedRewardQuantities,
additionalPledgeAmount: Double,
pledgeTotal: Double,
shippingTotal: Double,
checkoutId: String? = nil,
isApplePay: Bool?
) -> KSRAnalytics.CheckoutPropertiesData {
let staticUsdRate = Double(project.stats.staticUsdRate)
// Two decimal places to represent cent values
let pledgeTotalUsd = rounded(pledgeTotal.multiplyingCurrency(staticUsdRate), places: 2)
let bonusAmountUsd = rounded(additionalPledgeAmount.multiplyingCurrency(staticUsdRate), places: 2)
let addOnRewards = addOnRewards
.filter { reward in reward.id != baseReward.id }
.map { reward -> [Reward] in
guard let selectedRewardQuantity = selectedQuantities[reward.id] else { return [] }
return Array(0..<selectedRewardQuantity).map { _ in reward }
}
.flatMap { $0 }
let addOnsCountTotal = addOnRewards.map(\.id).count
let addOnsCountUnique = Set(addOnRewards.map(\.id)).count
let addOnsMinimumUsd = addOnRewards
.reduce(0.0) { accum, addOn in accum.addingCurrency(addOn.minimum) }
.multiplyingCurrency(staticUsdRate)
let shippingAmount: Double? = baseReward.shipping.enabled ? shippingTotal : nil
let rewardId = String(baseReward.id)
let estimatedDelivery = baseReward.estimatedDeliveryOn
var paymentType: String?
if let isApplePay = isApplePay {
paymentType = isApplePay
? PaymentType.applePay.trackingString
: PaymentType.creditCard.trackingString
}
let rewardTitle = baseReward.title
let rewardMinimumUsd = rounded(baseReward.minimum.multiplyingCurrency(staticUsdRate), places: 2)
let shippingEnabled = baseReward.shipping.enabled
let shippingAmountUsd = shippingAmount?.multiplyingCurrency(staticUsdRate)
let userHasEligibleStoredApplePayCard = AppEnvironment.current
.applePayCapabilities
.applePayCapable(for: project)
return KSRAnalytics.CheckoutPropertiesData(
addOnsCountTotal: addOnsCountTotal,
addOnsCountUnique: addOnsCountUnique,
addOnsMinimumUsd: addOnsMinimumUsd,
bonusAmountInUsd: bonusAmountUsd,
checkoutId: checkoutId,
estimatedDelivery: estimatedDelivery,
paymentType: paymentType,
revenueInUsd: pledgeTotalUsd,
rewardId: rewardId,
rewardMinimumUsd: rewardMinimumUsd,
rewardTitle: rewardTitle,
shippingEnabled: shippingEnabled,
shippingAmountUsd: shippingAmountUsd,
userHasStoredApplePayCard: userHasEligibleStoredApplePayCard
)
}
/**
Indicates `Reward` is locally picked up/not.
- parameter reward: A `Reward` object
- returns: A `Bool` for if a reward is locally picked up/not
*/
public func isRewardLocalPickup(_ reward: Reward?) -> Bool {
guard let existingReward = reward else {
return false
}
return !existingReward.shipping.enabled &&
existingReward.localPickup != nil &&
existingReward.shipping
.preference.isAny(of: Reward.Shipping.Preference.local)
}
/**
Indicates `Reward` is digital or not.
- parameter reward: A `Reward` object
- returns: A `Bool` for if a reward is digital or not
*/
public func isRewardDigital(_ reward: Reward?) -> Bool {
guard let existingReward = reward else {
return false
}
return !existingReward.shipping.enabled &&
existingReward.shipping.preference
.isAny(of: Reward.Shipping.Preference.none)
}
| apache-2.0 | 60ddb54f7bf303ea1dc1892fd5785fd3 | 32.974963 | 108 | 0.744982 | 4.272037 | false | false | false | false |
mentalfaculty/impeller | Sources/CloudKitRepository.swift | 1 | 14796 | //
// CloudKitRepository.swift
// Impeller
//
// Created by Drew McCormack on 29/12/2016.
// Copyright © 2016 Drew McCormack. All rights reserved.
//
import Foundation
import CloudKit
public struct CloudKitCursor: Cursor {
var serverToken: CKServerChangeToken
init(serverToken: CKServerChangeToken) {
self.serverToken = serverToken
}
init?(data: Data) {
if let newToken = NSKeyedUnarchiver.unarchiveObject(with: data) as? CKServerChangeToken {
serverToken = newToken
}
else {
return nil
}
}
public var data: Data {
return NSKeyedArchiver.archivedData(withRootObject: serverToken)
}
}
@available (macOS 10.12, iOS 10, *)
public class CloudKitRepository: Exchangable {
public let uniqueIdentifier: UniqueIdentifier
private let database: CKDatabase
private let zone: CKRecordZone
private let prepareZoneOperation: CKDatabaseOperation
public init(withUniqueIdentifier identifier: UniqueIdentifier, cloudDatabase: CKDatabase) {
self.uniqueIdentifier = identifier
self.database = cloudDatabase
self.zone = CKRecordZone(zoneName: uniqueIdentifier)
self.prepareZoneOperation = CKModifyRecordZonesOperation(recordZonesToSave: [self.zone], recordZoneIDsToDelete: nil)
self.database.add(self.prepareZoneOperation)
}
public func removeZone(completionHandler completion:@escaping CompletionHandler) {
database.delete(withRecordZoneID: zone.zoneID) { zoneID, error in
completion(error)
}
}
public func push(changesSince cursor: Cursor?, completionHandler completion: @escaping (Error?, [ValueTree], Cursor?)->Void) {
var newCursor: CloudKitCursor?
var valueTrees = [ValueTree]()
let token = (cursor as? CloudKitCursor)?.serverToken
let options = CKFetchRecordZoneChangesOptions()
options.previousServerChangeToken = token
let operation = CKFetchRecordZoneChangesOperation(recordZoneIDs: [zone.zoneID], optionsByRecordZoneID: [zone.zoneID : options])
operation.addDependency(prepareZoneOperation)
operation.fetchAllChanges = true
operation.recordChangedBlock = { record in
if let valueTree = record.asValueTree {
valueTrees.append(valueTree)
}
}
operation.recordWithIDWasDeletedBlock = { recordID in
// TODO: Finish implementing deletions
}
operation.recordZoneFetchCompletionBlock = { zoneID, token, clientData, moreComing, error in
if let token = token, error == nil {
newCursor = CloudKitCursor(serverToken: token)
}
}
operation.fetchRecordZoneChangesCompletionBlock = { error in
if let error = error as? CKError {
if error.code == .changeTokenExpired {
completion(nil, [], nil)
}
else {
completion(error, [], nil)
}
}
else {
completion(nil, valueTrees, newCursor)
}
}
database.add(operation)
}
public func pull(_ valueTrees: [ValueTree], completionHandler completion: @escaping CompletionHandler) {
let valueTreesByRecordID = valueTrees.elementsByKey { $0.recordID(inZoneWithID: zone.zoneID) }
let recordIDs = Array(valueTreesByRecordID.keys)
let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDs)
fetchOperation.addDependency(prepareZoneOperation)
fetchOperation.fetchRecordsCompletionBlock = { recordsByRecordID, error in
// Only acceptable errors are partial errors where code is .unknownItem
let ckError = error as! CKError?
guard ckError == nil || ckError!.code == .partialFailure else {
completion(error)
return
}
for (_, partialError) in ckError?.partialErrorsByItemID ?? [:] {
guard (partialError as! CKError).code == .unknownItem else {
completion(error)
return
}
}
// Process updates
var recordsToUpload = [CKRecord]()
for pulledValueTree in valueTrees {
let recordID = pulledValueTree.recordID(inZoneWithID: self.zone.zoneID)
let record = recordsByRecordID![recordID]
let cloudValueTree = record?.asValueTree
let mergedTree = pulledValueTree.merged(with: cloudValueTree)
if mergedTree != cloudValueTree {
let recordToUpdate = record ?? CKRecord(recordType: pulledValueTree.repositedType, recordID: recordID)
mergedTree.updateRecord(recordToUpdate)
recordsToUpload.append(recordToUpdate)
}
}
// Upload
let modifyOperation = CKModifyRecordsOperation(recordsToSave: recordsToUpload, recordIDsToDelete: nil)
modifyOperation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
completion(error)
}
self.database.add(modifyOperation)
}
database.add(fetchOperation)
}
public func makeCursor(fromData data: Data) -> Cursor? {
return CloudKitCursor(data: data)
}
}
extension ValueTree {
var recordName: String {
return "\(repositedType)__\(metadata.uniqueIdentifier)"
}
func recordID(inZoneWithID zoneID: CKRecordZoneID) -> CKRecordID {
return CKRecordID(recordName: recordName, zoneID: zoneID)
}
func makeRecord(inZoneWithID zoneID:CKRecordZoneID) -> CKRecord {
let recordID = self.recordID(inZoneWithID: zoneID)
let newRecord = CKRecord(recordType: repositedType, recordID: recordID)
updateRecord(newRecord)
return newRecord
}
func updateRecord(_ record: CKRecord) {
record["metadata__timestamp"] = metadata.timestamp as CKRecordValue
record["metadata__version"] = metadata.version as CKRecordValue
record["metadata__isDeleted"] = metadata.isDeleted as CKRecordValue
for name in propertyNames {
let property = get(name)!
let propertyTypeKey = name + "__metadata__propertyType"
record[propertyTypeKey] = property.propertyType.rawValue as CKRecordValue
switch property {
case .primitive(let primitive):
let typeKey = name + "__metadata__primitiveType"
record[typeKey] = primitive.type.rawValue as CKRecordValue
record[name] = primitive.value as? CKRecordValue
case .optionalPrimitive(let primitive):
let typeKey = name + "__metadata__primitiveType"
if let primitive = primitive {
record[typeKey] = primitive.type.rawValue as CKRecordValue
record[name] = primitive.value as? CKRecordValue
}
else {
record[typeKey] = 0 as CKRecordValue
record[name] = nil
}
case .primitives(let primitives):
let typeKey = name + "__metadata__primitiveType"
if primitives.count > 0 {
record[typeKey] = primitives.first!.type.rawValue as CKRecordValue
record[name] = primitives.map { $0.value } as CKRecordValue
}
else {
record[typeKey] = 0 as CKRecordValue
record[name] = [] as CKRecordValue
}
case .valueTreeReference(let ref):
record[name] = [ref.repositedType, ref.uniqueIdentifier] as CKRecordValue
case .optionalValueTreeReference(let ref):
if let ref = ref {
record[name] = [ref.repositedType, ref.uniqueIdentifier] as CKRecordValue
}
else {
record[name] = ["nil", ""] as CKRecordValue
}
case .valueTreeReferences(let refs):
record[name] = refs.map { $0.recordName } as CKRecordValue
}
}
}
}
extension ValueTreeReference {
var recordName: String {
// Record name is repositedType + "__" + unique id. This is because in Impeller,
// the uniqueId only has to be unique for a single stored type
return "\(repositedType)__\(uniqueIdentifier)"
}
}
extension String {
var valueTreeReference: ValueTreeReference {
let recordName = self
let components = recordName.components(separatedBy: "__")
return ValueTreeReference(uniqueIdentifier: components[1], repositedType: components[0])
}
}
extension CKRecord {
var valueTreeReference: ValueTreeReference {
return recordID.recordName.valueTreeReference
}
var asValueTree: ValueTree? {
guard let timestamp = self["metadata__timestamp"] as? TimeInterval,
let version = self["metadata__version"] as? RepositedVersion,
let isDeleted = self["metadata__isDeleted"] as? Bool else {
return nil
}
let ref = valueTreeReference
var metadata = Metadata(uniqueIdentifier: ref.uniqueIdentifier)
metadata.version = version
metadata.timestamp = timestamp
metadata.isDeleted = isDeleted
var valueTree = ValueTree(repositedType: recordType, metadata: metadata)
for key in allKeys() {
if key.contains("__metadata__") { continue }
let propertyTypeKey = key + "__metadata__propertyType"
guard
let value = self[key],
let propertyTypeInt = self[propertyTypeKey] as? Int,
let propertyType = PropertyType(rawValue: propertyTypeInt) else {
continue
}
let primitiveTypeKey = key + "__metadata__primitiveType"
let primitiveTypeInt = self[primitiveTypeKey] as? Int
let primitiveType = primitiveTypeInt != nil ? PrimitiveType(rawValue: primitiveTypeInt!) : nil
var property: Property?
switch propertyType {
case .primitive:
switch primitiveType! {
case .string:
guard let v = value as? String else { continue }
property = .primitive(.string(v))
case .int:
guard let v = value as? Int else { continue }
property = .primitive(.int(v))
case .float:
guard let v = value as? Float else { continue }
property = .primitive(.float(v))
case .bool:
guard let s = value as? Bool else { continue }
property = .primitive(.bool(s))
case .data:
guard let s = value as? Data else { continue }
property = .primitive(.data(s))
}
case .optionalPrimitive:
let isNull = primitiveTypeInt == 0
if isNull {
property = .optionalPrimitive(nil)
}
else {
switch primitiveType! {
case .string:
guard let v = value as? String else { continue }
property = .optionalPrimitive(.string(v))
case .int:
guard let v = value as? Int else { continue }
property = .optionalPrimitive(.int(v))
case .float:
guard let v = value as? Float else { continue }
property = .optionalPrimitive(.float(v))
case .bool:
guard let v = value as? Bool else { continue }
property = .optionalPrimitive(.bool(v))
case .data:
guard let v = value as? Data else { continue }
property = .optionalPrimitive(.data(v))
}
}
case .primitives:
let isEmpty = primitiveTypeInt == 0
if isEmpty {
property = .primitives([])
}
else {
switch primitiveType! {
case .string:
guard let v = value as? [String] else { continue }
property = .primitives(v.map { .string($0) })
case .int:
guard let v = value as? [Int] else { continue }
property = .primitives(v.map { .int($0) })
case .float:
guard let v = value as? [Float] else { continue }
property = .primitives(v.map { .float($0) })
case .bool:
guard let v = value as? [Bool] else { continue }
property = .primitives(v.map { .bool($0) })
case .data:
guard let v = value as? [Data] else { continue }
property = .primitives(v.map { .data($0) })
}
}
case .valueTreeReference:
guard let v = value as? [String], v.count == 2 else { continue }
let ref = ValueTreeReference(uniqueIdentifier: v[1], repositedType: v[0])
property = .valueTreeReference(ref)
case .optionalValueTreeReference:
guard let v = value as? [String], v.count == 2 else { continue }
if v[0] == "nil" {
property = .optionalValueTreeReference(nil)
}
else {
let ref = ValueTreeReference(uniqueIdentifier: v[1], repositedType: v[0])
property = .optionalValueTreeReference(ref)
}
case .valueTreeReferences:
guard let v = value as? [String] else { continue }
let refs = v.map { $0.valueTreeReference }
property = .valueTreeReferences(refs)
}
guard let p = property else {
continue
}
valueTree.set(key, to: p)
}
return valueTree
}
}
| mit | 0caa08783fab599473c1f70ff70b9da5 | 38.664879 | 135 | 0.549307 | 5.356626 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Lint/LowerACLThanParentRule.swift | 1 | 9988 | import SwiftSyntax
struct LowerACLThanParentRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxCorrectableRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "lower_acl_than_parent",
name: "Lower ACL than parent",
description: "Ensure declarations have a lower access control level than their enclosing parent",
kind: .lint,
nonTriggeringExamples: [
Example("public struct Foo { public func bar() {} }"),
Example("internal struct Foo { func bar() {} }"),
Example("struct Foo { func bar() {} }"),
Example("struct Foo { internal func bar() {} }"),
Example("open class Foo { public func bar() {} }"),
Example("open class Foo { open func bar() {} }"),
Example("fileprivate struct Foo { private func bar() {} }"),
Example("private struct Foo { private func bar(id: String) }"),
Example("extension Foo { public func bar() {} }"),
Example("private struct Foo { fileprivate func bar() {} }"),
Example("private func foo(id: String) {}"),
Example("private class Foo { func bar() {} }"),
Example("public extension Foo { struct Bar { public func baz() {} }}"),
Example("public extension Foo { struct Bar { internal func baz() {} }}"),
Example("internal extension Foo { struct Bar { internal func baz() {} }}"),
Example("extension Foo { struct Bar { internal func baz() {} }}")
],
triggeringExamples: [
Example("struct Foo { ↓public func bar() {} }"),
Example("enum Foo { ↓public func bar() {} }"),
Example("public class Foo { ↓open func bar() }"),
Example("class Foo { ↓public private(set) var bar: String? }"),
Example("private struct Foo { ↓public func bar() {} }"),
Example("private class Foo { ↓public func bar() {} }"),
Example("private actor Foo { ↓public func bar() {} }"),
Example("fileprivate struct Foo { ↓public func bar() {} }"),
Example("class Foo { ↓public func bar() {} }"),
Example("actor Foo { ↓public func bar() {} }"),
Example("private struct Foo { ↓internal func bar() {} }"),
Example("fileprivate struct Foo { ↓internal func bar() {} }"),
Example("extension Foo { struct Bar { ↓public func baz() {} }}"),
Example("internal extension Foo { struct Bar { ↓public func baz() {} }}"),
Example("private extension Foo { struct Bar { ↓public func baz() {} }}"),
Example("fileprivate extension Foo { struct Bar { ↓public func baz() {} }}"),
Example("private extension Foo { struct Bar { ↓internal func baz() {} }}"),
Example("fileprivate extension Foo { struct Bar { ↓internal func baz() {} }}"),
Example("public extension Foo { struct Bar { struct Baz { ↓public func qux() {} }}}"),
Example("final class Foo { ↓public func bar() {} }")
],
corrections: [
Example("struct Foo { ↓public func bar() {} }"):
Example("struct Foo { func bar() {} }"),
Example("enum Foo { ↓public func bar() {} }"):
Example("enum Foo { func bar() {} }"),
Example("public class Foo { ↓open func bar() }"):
Example("public class Foo { func bar() }"),
Example("class Foo { ↓public private(set) var bar: String? }"):
Example("class Foo { private(set) var bar: String? }"),
Example("private struct Foo { ↓public func bar() {} }"):
Example("private struct Foo { func bar() {} }"),
Example("private class Foo { ↓public func bar() {} }"):
Example("private class Foo { func bar() {} }"),
Example("private actor Foo { ↓public func bar() {} }"):
Example("private actor Foo { func bar() {} }"),
Example("class Foo { ↓public func bar() {} }"):
Example("class Foo { func bar() {} }"),
Example("actor Foo { ↓public func bar() {} }"):
Example("actor Foo { func bar() {} }")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
Rewriter(
locationConverter: file.locationConverter,
disabledRegions: disabledRegions(file: file)
)
}
}
private extension LowerACLThanParentRule {
private final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: DeclModifierSyntax) {
if node.isHigherACLThanParent {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
private(set) var correctionPositions: [AbsolutePosition] = []
let locationConverter: SourceLocationConverter
let disabledRegions: [SourceRange]
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
self.locationConverter = locationConverter
self.disabledRegions = disabledRegions
}
override func visit(_ node: DeclModifierSyntax) -> DeclModifierSyntax {
guard
node.isHigherACLThanParent,
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
let newNode = node.withName(
.contextualKeyword("", leadingTrivia: node.leadingTrivia ?? .zero)
)
return super.visit(newNode)
}
}
}
private extension DeclModifierSyntax {
var isHigherACLThanParent: Bool {
guard let nearestNominalParent = parent?.nearestNominalParent() else {
return false
}
switch name.tokenKind {
case .internalKeyword
where nearestNominalParent.modifiers.isPrivate ||
nearestNominalParent.modifiers.isFileprivate:
return true
case .internalKeyword
where !nearestNominalParent.modifiers.containsACLModifier:
guard let nominalExtension = nearestNominalParent.nearestNominalExtensionDeclParent() else {
return false
}
return nominalExtension.modifiers.isPrivate ||
nominalExtension.modifiers.isFileprivate
case .publicKeyword
where nearestNominalParent.modifiers.isPrivate ||
nearestNominalParent.modifiers.isFileprivate ||
nearestNominalParent.modifiers.isInternal:
return true
case .publicKeyword
where !nearestNominalParent.modifiers.containsACLModifier:
guard let nominalExtension = nearestNominalParent.nearestNominalExtensionDeclParent() else {
return true
}
return !nominalExtension.modifiers.isPublic
case .contextualKeyword("open") where !nearestNominalParent.modifiers.isOpen:
return true
default:
return false
}
}
}
private extension SyntaxProtocol {
func nearestNominalParent() -> Syntax? {
guard let parent = parent else {
return nil
}
return parent.isNominalTypeDecl ? parent : parent.nearestNominalParent()
}
func nearestNominalExtensionDeclParent() -> Syntax? {
guard let parent = parent, !parent.isNominalTypeDecl else {
return nil
}
return parent.isExtensionDecl ? parent : parent.nearestNominalExtensionDeclParent()
}
}
private extension Syntax {
var isNominalTypeDecl: Bool {
self.is(StructDeclSyntax.self) ||
self.is(ClassDeclSyntax.self) ||
self.is(ActorDeclSyntax.self) ||
self.is(EnumDeclSyntax.self)
}
var isExtensionDecl: Bool {
self.is(ExtensionDeclSyntax.self)
}
var modifiers: ModifierListSyntax? {
if let node = self.as(StructDeclSyntax.self) {
return node.modifiers
} else if let node = self.as(ClassDeclSyntax.self) {
return node.modifiers
} else if let node = self.as(ActorDeclSyntax.self) {
return node.modifiers
} else if let node = self.as(EnumDeclSyntax.self) {
return node.modifiers
} else if let node = self.as(ExtensionDeclSyntax.self) {
return node.modifiers
} else {
return nil
}
}
}
private extension ModifierListSyntax? {
var isFileprivate: Bool {
self?.contains(where: { $0.name.tokenKind == .fileprivateKeyword }) == true
}
var isPrivate: Bool {
self?.contains(where: { $0.name.tokenKind == .privateKeyword }) == true
}
var isInternal: Bool {
self?.contains(where: { $0.name.tokenKind == .internalKeyword }) == true
}
var isPublic: Bool {
self?.contains(where: { $0.name.tokenKind == .publicKeyword }) == true
}
var isOpen: Bool {
self?.contains(where: { $0.name.tokenKind == .contextualKeyword("open") }) == true
}
var containsACLModifier: Bool {
guard self?.isEmpty == false else {
return false
}
let aclTokens: [TokenKind] = [
.fileprivateKeyword,
.privateKeyword,
.internalKeyword,
.publicKeyword,
.contextualKeyword("open")
]
return self?.contains(where: {
aclTokens.contains($0.name.tokenKind)
}) == true
}
}
| mit | 91b5eebb2bab67e7306b2953ddb0cb35 | 39.864198 | 105 | 0.582477 | 5.076687 | false | false | false | false |
entaq/Cliq | Cliq/Cliq/AppDelegate.swift | 1 | 2500 | import UIKit
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GMSServices.provideAPIKey("AIzaSyARWlypKPlMgxJDCgTJZUEGRVUxAtAm1qo")
Parse.setApplicationId("a1PPRqrWNi69aExmxnkCNmRabf13nMoWeduYY3SB", clientKey: "dKEPhkmMHpkQWy2Fo3M7d0tdvNirhzbU5StL3Adu")
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// if "content_available" was used to trigger a background push we skip tracking avoid double counting
if let options = launchOptions {
if options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
}
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackgroundWithBlock(nil)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(userInfo, block: nil)
}
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
}
| mit | 7a902a971835c3f06492d241aa2d0dca | 45.296296 | 157 | 0.7316 | 5.555556 | false | false | false | false |
wanghdnku/Whisper | Whisper/VerticalScrollViewController.swift | 1 | 4810 | //
// MiddleScrollViewController.swift
// SnapchatSwipeView
//
// Created by Jake Spracher on 12/14/15.
// Copyright © 2015 Jake Spracher. All rights reserved.
//
import UIKit
class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {
var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!
class func verticalScrollVcWith(_ middleVc: UIViewController,
topVc: UIViewController?=nil,
bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
let middleScrollVc = VerticalScrollViewController()
middleScrollVc.topVc = topVc
middleScrollVc.middleVc = middleVc
middleScrollVc.bottomVc = bottomVc
return middleScrollVc
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view:
setupScrollView()
}
func setupScrollView() {
scrollView = UIScrollView()
scrollView.isPagingEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.bounces = false
let view = (
x: self.view.bounds.origin.x,
y: self.view.bounds.origin.y,
width: self.view.bounds.width,
height: self.view.bounds.height
)
scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
self.view.addSubview(scrollView)
let scrollWidth: CGFloat = view.width
var scrollHeight: CGFloat
if topVc != nil && bottomVc != nil {
scrollHeight = 3 * view.height
topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)
addChildViewController(topVc)
addChildViewController(middleVc)
addChildViewController(bottomVc)
scrollView.addSubview(topVc.view)
scrollView.addSubview(middleVc.view)
scrollView.addSubview(bottomVc.view)
topVc.didMove(toParentViewController: self)
middleVc.didMove(toParentViewController: self)
bottomVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = middleVc.view.frame.origin.y
} else if topVc == nil {
scrollHeight = 2 * view.height
middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
bottomVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
addChildViewController(middleVc)
addChildViewController(bottomVc)
scrollView.addSubview(middleVc.view)
scrollView.addSubview(bottomVc.view)
middleVc.didMove(toParentViewController: self)
bottomVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = 0
} else if bottomVc == nil {
scrollHeight = 2 * view.height
topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
addChildViewController(topVc)
addChildViewController(middleVc)
scrollView.addSubview(topVc.view)
scrollView.addSubview(middleVc.view)
topVc.didMove(toParentViewController: self)
middleVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = middleVc.view.frame.origin.y
} else {
scrollHeight = view.height
middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
addChildViewController(middleVc)
scrollView.addSubview(middleVc.view)
middleVc.didMove(toParentViewController: self)
}
scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
}
// MARK: - SnapContainerViewControllerDelegate Methods
func outerScrollViewShouldScroll() -> Bool {
if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > 2*middleVc.view.frame.origin.y {
return false
} else {
return true
}
}
}
| mit | b726bf3c2eb1e1e85796b078964e384a | 36.570313 | 133 | 0.602412 | 4.785075 | false | false | false | false |
zyhndesign/SDX_DG | sdxdg/sdxdg/MyMatchViewController.swift | 1 | 11081 | //
// MyMatchViewController.swift
// sdxdg
//
// Created by lotusprize on 17/1/3.
// Copyright © 2017年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import AlamofireObjectMapper
import SwiftyJSON
class MyMatchViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var pushBtn: UIButton!
@IBOutlet var backBtn: UIButton!
@IBOutlet var draftBtn: UIButton!
@IBOutlet var tableView: UITableView!
let screenWidth = UIScreen.main.bounds.width
let fbIconArray:[String] = ["fb1","fb2","fb3","fb4","fb5","fb6","fb7","fb8","fb9","fb10"]
var btnInitTag:Int = 0
var shareList:[Match] = []
var feedbackList:[Match] = []
var draftList:[Match] = []
let pageLimit:Int = 10
var sharePageNum:Int = 0
var feedbackPageNum:Int = 0
var draftPageNum = 0
let refresh = UIRefreshControl()
let userId = LocalDataStorageUtil.getUserIdFromUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pushBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
backBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
draftBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
pushBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.selected)
backBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.selected)
draftBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.selected)
pushBtn.setTitle("已推送", for: UIControlState.normal)
pushBtn.setTitle("已推送", for: UIControlState.selected)
backBtn.setTitle("已反馈", for: UIControlState.normal)
backBtn.setTitle("已反馈", for: UIControlState.selected)
draftBtn.setTitle("草稿箱", for: UIControlState.normal)
draftBtn.setTitle("草稿箱", for: UIControlState.selected)
let titleColor:UIColor = UIColor.init(red: 59/255.0, green: 59/255.0, blue: 59/255.0, alpha: 1.0)
pushBtn.setTitleColor(titleColor, for: UIControlState.normal)
pushBtn.setTitleColor(titleColor, for: UIControlState.selected)
backBtn.setTitleColor(titleColor, for: UIControlState.normal)
backBtn.setTitleColor(titleColor, for: UIControlState.selected)
draftBtn.setTitleColor(titleColor, for: UIControlState.normal)
draftBtn.setTitleColor(titleColor, for: UIControlState.selected)
tableView.delegate = self
tableView.dataSource = self
tableView.register(MyMatchTableViewCell.self, forCellReuseIdentifier: "MatchCell")
refresh.backgroundColor = UIColor.white
refresh.tintColor = UIColor.lightGray
refresh.attributedTitle = NSAttributedString(string:"下拉刷新")
refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged)
tableView.addSubview(refresh)
if btnInitTag == 0{
pushBtn.isSelected = true
self.loadDataByCondition(category: 1, userId: userId, limit: pageLimit, offset: sharePageNum * pageLimit)
}
else if btnInitTag == 1{
pushBtn.isSelected = true
self.loadDataByCondition(category: 1, userId: userId, limit: pageLimit, offset: sharePageNum * pageLimit)
}
else if btnInitTag == 2{
backBtn.isSelected = true
self.loadDataByCondition(category: 2, userId: userId, limit: pageLimit, offset: feedbackPageNum * pageLimit)
}
else if btnInitTag == 3{
draftBtn.isSelected = true
self.loadDataByCondition(category: 3, userId: userId, limit: pageLimit, offset: draftPageNum * pageLimit)
}
self.tableView.tableFooterView = UIView.init(frame: CGRect.init())
}
func refreshLoadingData(){
if btnInitTag == 1{
self.loadDataByCondition(category: 1, userId: userId, limit: pageLimit, offset: sharePageNum * pageLimit)
}
else if btnInitTag == 2{
self.loadDataByCondition(category: 2, userId: userId, limit: pageLimit, offset: feedbackPageNum * pageLimit)
}
else if btnInitTag == 3{
self.loadDataByCondition(category: 3, userId: userId, limit: pageLimit, offset: draftPageNum * pageLimit)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let indexCellName:String = "MatchCell"
let matchCell:MyMatchTableViewCell = tableView.dequeueReusableCell(withIdentifier: indexCellName, for: indexPath) as! MyMatchTableViewCell
matchCell.selectionStyle = UITableViewCellSelectionStyle.none
var match:Match?
if (btnInitTag == 1){
match = self.shareList[indexPath.row]
}
else if (btnInitTag == 2){
match = self.feedbackList[indexPath.row]
}
else if (btnInitTag == 3){
match = self.draftList[indexPath.row]
}
matchCell.initCellData(titleLable: match?.seriesname, timeLabel: match?.createtime, modelLists:match?.matchlists)
return matchCell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int = 0
if (btnInitTag == 1){
count = self.shareList.count
}
else if (btnInitTag == 2){
count = self.feedbackList.count
}
else if (btnInitTag == 3){
count = self.draftList.count
}
return count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (screenWidth - 50)/4 + 40
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if btnInitTag == 0 || btnInitTag == 1{
let view:PushDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "PushDetailView") as! PushDetailViewController
view.match = shareList[indexPath.row]
self.navigationController?.pushViewController(view, animated: true)
}
else if btnInitTag == 2{
let view:MyFeedbackDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyFeedbackDetailView") as! MyFeedbackDetailViewController
view.match = feedbackList[indexPath.row]
self.navigationController?.pushViewController(view, animated: true)
}
else if btnInitTag == 3{
let view:DraftDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "DraftDetailView") as! DraftDetailViewController
print(draftList.count)
print(indexPath.row)
print(draftList[indexPath.row])
view.match = draftList[indexPath.row]
self.navigationController?.pushViewController(view, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadDataByCondition(category:Int,userId:Int,limit:Int,offset:Int){
var parameters:Parameters = [:]
var url:String = ""
if (category == 1){ //已经分享数据
url = ConstantsUtil.APP_MATCH_LIST_BY_SHARESTATUS_URL
parameters = ["userId":userId, "shareStatus":1,"limit":limit,"offset":offset]
}
else if (category == 2){ //已经反馈数据
url = ConstantsUtil.APP_MATCH_LIST_BY_BACK_URL
parameters = ["userId":userId, "backStatus":1,"limit":limit,"offset":offset]
}
else if (category == 3){ //草稿箱
url = ConstantsUtil.APP_MATCH_LIST_BY_DRAFT_URL
parameters = ["userId":userId, "draftStatus":1,"limit":limit,"offset":offset]
}
Alamofire.request(url,method:.post,parameters:parameters).responseObject { (response: DataResponse<MatchServerModel>) in
let matchServerModel = response.result.value
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "加载中..."
if(matchServerModel?.success)!{
if let matchlist = matchServerModel?.object{
if matchlist.count > 0{
for match in matchlist{
if (category == 1){
self.shareList.insert(match, at: 0)
self.sharePageNum = self.sharePageNum + 1
}
else if (category == 2){
self.feedbackList.insert(match, at: 0)
self.feedbackPageNum = self.feedbackPageNum + 1
}
else if (category == 3){
self.draftList.insert(match, at: 0)
self.draftPageNum = self.draftPageNum + 1
}
}
hud.hide(animated: true, afterDelay: 1.0)
}
else{
hud.label.text = "无更多数据"
hud.hide(animated: true, afterDelay: 1.0)
}
self.tableView.reloadData()
}
else{
hud.label.text = "数据加载失败"
hud.hide(animated: true, afterDelay: 1.0)
}
}
else{
hud.label.text = "数据加载失败"
hud.hide(animated: true, afterDelay: 1.0)
}
self.refresh.endRefreshing()
}
}
@IBAction func pushBtnClick(_ sender: Any) {
pushBtn.isSelected = true
backBtn.isSelected = false
draftBtn.isSelected = false
btnInitTag = 1
self.loadDataByCondition(category: 1, userId: userId, limit: pageLimit, offset: sharePageNum * pageLimit)
}
@IBAction func backBtnClick(_ sender: Any) {
pushBtn.isSelected = false
backBtn.isSelected = true
draftBtn.isSelected = false
btnInitTag = 2
self.loadDataByCondition(category: 2, userId: userId, limit: pageLimit, offset: feedbackPageNum * pageLimit)
}
@IBAction func draftBtnClick(_ sender: Any) {
pushBtn.isSelected = false
backBtn.isSelected = false
draftBtn.isSelected = true
btnInitTag = 3
self.loadDataByCondition(category: 3, userId: userId, limit: pageLimit, offset: draftPageNum * pageLimit)
}
}
| apache-2.0 | fe41802d3a955ee04b10d6dd5d08e336 | 41.496124 | 171 | 0.609996 | 4.691485 | false | false | false | false |
stulevine/firefox-ios | Sync/KeyBundle.swift | 1 | 8065 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import FxA
import Account
private let KeyLength = 32
public class KeyBundle: Equatable {
let encKey: NSData
let hmacKey: NSData
public class func fromKB(kB: NSData) -> KeyBundle {
let salt = NSData()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
let derived = kB.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: len)
return KeyBundle(encKey: derived.subdataWithRange(NSRange(location: 0, length: KeyLength)),
hmacKey: derived.subdataWithRange(NSRange(location: KeyLength, length: KeyLength)))
}
public class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
public class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")
}
public init(encKeyB64: String, hmacKeyB64: String) {
self.encKey = Bytes.decodeBase64(encKeyB64)
self.hmacKey = Bytes.decodeBase64(hmacKeyB64)
}
public init(encKey: NSData, hmacKey: NSData) {
self.encKey = encKey
self.hmacKey = hmacKey
}
private func _hmac(ciphertext: NSData) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(hmacAlgorithm, hmacKey.bytes, hmacKey.length, ciphertext.bytes, ciphertext.length, result)
return (result, digestLen)
}
public func hmac(ciphertext: NSData) -> NSData {
let (result, digestLen) = _hmac(ciphertext)
var data = NSMutableData(bytes: result, length: digestLen)
result.destroy()
return data
}
/**
* Returns a hex string for the HMAC.
*/
public func hmacString(ciphertext: NSData) -> String {
let (result, digestLen) = _hmac(ciphertext)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(hash)
}
public func encrypt(cleartext: NSData, iv: NSData?=nil) -> (ciphertext: NSData, iv: NSData)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytes: b, length: Int(copied))
b.destroy()
return (d, iv)
}
b.destroy()
return nil
}
// You *must* verify HMAC before calling this.
public func decrypt(ciphertext: NSData, iv: NSData) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytesNoCopy: b, length: Int(copied))
let s = NSString(data: d, encoding: NSUTF8StringEncoding)
b.destroy()
return s as String?
}
b.destroy()
return nil
}
private func crypt(input: NSData, iv: NSData, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutablePointer<Void>, count: Int) {
let resultSize = input.length + kCCBlockSizeAES128
let result = UnsafeMutablePointer<Void>.alloc(resultSize)
var copied: Int = 0
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.bytes,
kCCKeySizeAES256,
iv.bytes,
input.bytes,
input.length,
result,
resultSize,
&copied
);
return (success, result, copied)
}
public func verify(#hmac: NSData, ciphertextB64: NSData) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return expectedHMAC.isEqualToData(computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
public func factory<T : CleartextPayloadJSON>(f: (JSON) -> T) -> (String) -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !(potential.isValid()) {
return nil
}
let cleartext = potential.cleartext
if (cleartext == nil) {
return nil
}
return f(cleartext!)
}
}
public func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
}
public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return lhs.encKey.isEqualToData(rhs.encKey) &&
lhs.hmacKey.isEqualToData(rhs.hmacKey)
}
public class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload {
if payload.isValid() {
if let keys = payload.defaultKeys {
self.defaultBundle = keys
self.valid = true
return
}
self.collectionKeys = payload.collectionKeys
}
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
public func forCollection(collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
public func factory<T : CleartextPayloadJSON>(collection: String, f: (JSON) -> T) -> (String) -> T? {
let bundle = forCollection(collection)
return bundle.factory(f)
}
public func asPayload() -> KeysPayload {
let json: JSON = JSON([
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, { $0.asPair() })
])
return KeysPayload(json)
}
}
public func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
| mpl-2.0 | e31e86cdfe0566f9f6dce09922b5a740 | 33.762931 | 145 | 0.609175 | 4.62708 | false | false | false | false |
krzysztofzablocki/LifetimeTracker | Sources/iOS/UI/LifetimeTrackerListViewController.swift | 1 | 1659 | //
// LifetimeTrackerListViewController.swift
// LifetimeTracker-iOS
//
// Created by Hans Seiffert on 18.03.18.
// Copyright © 2018 LifetimeTracker. All rights reserved.
//
import UIKit
protocol PopoverViewControllerDelegate: AnyObject {
func dismissPopoverViewController()
func changeHideOption(for hideOption: HideOption)
}
class LifetimeTrackerListViewController: UIViewController {
weak var delegate: PopoverViewControllerDelegate?
weak var tableViewController: DashboardTableViewController?
var dashboardViewModel = BarDashboardViewModel()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func closeButtonPressed(_ sender: Any) {
delegate?.dismissPopoverViewController()
}
@IBAction func settingsButtonPressed(_ sender: Any) {
SettingsManager.showSettingsActionSheet(on: self, completionHandler: { [weak self] (selectedOption: HideOption) in
self?.delegate?.changeHideOption(for: selectedOption)
})
}
func update(dashboardViewModel: BarDashboardViewModel) {
self.dashboardViewModel = dashboardViewModel
title = "popover.dasboard.title".lt_localized
tableViewController?.update(dashboardViewModel: dashboardViewModel)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.Segue.embedDashboardTableView.identifier {
tableViewController = segue.destination as? DashboardTableViewController
tableViewController?.update(dashboardViewModel: dashboardViewModel)
}
}
}
| mit | e67f89b9122233045c71c8c600a03ca3 | 30.884615 | 122 | 0.712304 | 5.436066 | false | false | false | false |
mathewsheets/SwiftLearning | SwiftLearning.playground/Pages/HTTP | ReST.xcplaygroundpage/Contents.swift | 1 | 13689 | /*:
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
- - -
# HTTP & ReST
* callout(Session Overview): Programs need to communicate to each other. They communicate by retrieving data from other programs and send data to make the other programs perform actions on its behalf. There are many communication technologies, but the industry standard is to use **H**yper**t**ext **T**ransfer **P**rotocol along with an architectural style called **R**epresentational **S**tate **T**ransfer. HTTP with ReST allows programs implemented in different programming languages and on different operating systems the ability to communicate with each other without the need to create a specialized technology that only two programs would know about.
- important: This is only a brief overview of HTTP and ReST. Please take extra time outside of this session to learn all that HTTP and ReST have to offer.
- - -
*/
import Foundation
// NEEDED TO HANDLE RESPONSES
import PlaygroundSupport
PlaygroundSupport.PlaygroundPage.current.needsIndefiniteExecution = true
/*:
## **H**ypertext **T**ransfer **P**rotocol or HTTP
HTTP is an application protocol, meaning a set of rules that specifies the shared protocols and interface methods on how to send/receive and create/parse HTTP messages. There are two components to HTTP, the server and the client. The HTTP server is able to handle communicating to multiple HTTP clients simultaneously. The HTTP client, which is what we’ll focus on, will communicate with one HTTP server.
### The Client
The scope of HTTP that we will focus on is the HTTP Client. The HTTP Client communicates with the HTTP server for a specific purpose by sending/receiving HTTP messages that are tailored to functionality. Think of the HTTP message as an envelope that has to/from addresses with a letter representing the data. We will refer to sending and receiving HTTP messages as request and response.
This is a simple HTTP Request message
````
GET /person/ HTTP/1.1
Host: www.people.com
Accept: text/json
````
This is a simple HTTP Response message
````
HTTP/1.1 200 OK
Content-Length: 44
Connection: close
Content-Type: text/json
{
}
````
## **R**epresentational **S**tate **T**ransfer or ReST
ReST is not a standard, but more of an easily understandable agreement between the HTTP Client and HTTP Server on how and what should be sent and received as well as how the data should be handled. The industry standard data format that ReSTful Clients and Servers use is the JSON data format. With ReST, you want to narrow your scope of functionality and data to a concept called a Resource. A Person is a resource. The client needs a list of persons, the server knows how to retrieve a list of persons and responds with a JSON payload that the client knows how to handle. There are four main components to ReST: the HTTP Method, the URI, the data or payload, and the response code.
## Methods or Verbs
The HTTP Method, or HTTP verb, is used by the client in the request to tell the server what should happen. A client typically needs to **C**reate, **R**etrieve, **U**pdate or **D**elete data.
- `POST` = Tells the server to **create** data
- `GET` = Tells the server to **retrieve** data
- `PUT` = Tells the server to **update** data
- `DELETE` = Tells the server to **delete** data
## URI
The **U**niform **R**esource **I**dentifier or URI is used to identify the resource. Think of the URI as the path portion of a URL. Below is the URI for the person resource.
`/persons`
## Data
The data that is requested by the client or responded to by the server will be in the JSON data format but structured in a way that makes sense for the resource.
Client requests to create a Person:
````
{
"name": "Mathew Sheets",
"phone": "6141234567",
}
````
Server responds with a list of Persons:
````
[
{
"id": "52206853-2787-458d-a85b-b37c2daf73d9",
"name": "Mathew Sheets",
"phone": "6141234567",
},
...
]
````
## Response Codes
Along with a JSON payload, a server responds with a status code that can be interpreted by the client for the client to make a decision. Below are the most commonly used status codes when dealing with ReSTful services.
- `2xx` Success
- `200 OK` = The request was successfully handled by the server and will typically have a JSON payload in the response.
- `201 Created` = The request was successfully handled by the server and a resource was created with a JSON payload of a URI of the new resource.
- `204 No Content` = The request was successfully handled by the server but no JSON payload in the response.
- `3xx` Redirection
- `301 Moved Permanently` = The resource has been moved.
- `304 Not Modified` = The resource has not changed.
- `4xx` Client Error
- `400 Bad Request` = The request is invalid for a resource.
- `401 Unauthorized` = The request is unauthorized for a resource.
- `403 Forbidden` = The request is not allowed for a resource
- `404 Not Found` = The resource can not be found.
- `5xx` Server Error
- `501 Internal Server Error` = A generic error from the server.
- `500 Not Implemented` = An error from the server indicating to the client that the request has not been implemented.
## Person Resource and Routes
Consider that we want to communicate with a server that will produce a ReSTful service for a Person resource. Our program is the client what will consume the ReSTful service. The following is a brief example of what the HTTP method, URI, data and response code would look like. The HTTP method, URI, data and response code is considered a *route* for the resource and there are typically 5 routes per resource.
### `GET /persons`
Above is a *route* of a `GET` request for the *person* resource. Below is the response JSON payload of an array with each element in the array representing a person. This URI indicates all persons; here the absence of an `id`
````
[
{
"id": "52206853-2787-458d-a85b-b37c2daf73d9",
"name": "Mathew Sheets",
"phone": "6141234567",
},
...
]
````
### `GET /persons/52206853-2787-458d-a85b-b37c2daf73d9`
Above is a *route* of a `GET` request for a single *person* resource. Notice the `id:`, indicating the `id` of a specific person.
````
{
"id": "52206853-2787-458d-a85b-b37c2daf73d9",
"name": "Mathew Sheets",
"phone": "6141234567",
}
````
### `POST /persons`
Above is a *route* of a `POST` request to create a *person* resource. Below is the request JSON payload.
````
{
"name": "Mathew Sheets",
"phone": "6141234567",
}
````
### `PUT /persons/52206853-2787-458d-a85b-b37c2daf73d9`
Above is a *route* of a `PUT` request to update a *person* resource. Notice the `id:`, indicating the `id` of a specific person. Below is the request JSON payload.
````
{
"name": "Matt Sheets",
"phone": "6141234567",
}
````
### `DELETE /persons/52206853-2787-458d-a85b-b37c2daf73d9`
Above is a *route* of a `DELETE` request to delete a *person* resource. Notice the `id:`, indicating the `id` of a specific person.
*/
/*:
## URLRequest, URLResponse and URLSession
The Foundation Framework provides an API to interact with HTTP and ReSTful services. The three main classes involved in executing HTTP requests and handling responses are `URLRequest`, `URLResponse` and `URLSession`.
- [URLRequest](https://developer.apple.com/reference/foundation/nsurlrequest) = The class representing the request portion of the HTTP protocol
- [URLResponse](https://developer.apple.com/reference/foundation/urlresponse) = The class representing the response portion of the HTTP protocol
- [URLSession](https://developer.apple.com/reference/foundation/urlsession) = The class managing the collaboration between the request and response and also providing other capabilities such as caching
*/
var host = "http://cscc-persons.getsandbox.com"
var session = URLSession.shared
/*:
### `GET /persons`
- example: Below is an example implementation of the `GET /persons` route on the Person resource. This will get an array of person resources.
*/
//var request = URLRequest(url: URL(string: "\(host)/persons")!)
//request.httpMethod = "GET"
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//session.dataTask(with: request) { (data, response, error) in
//
// if error != nil {
// print(error!)
// } else {
// let statusCode = (response as? HTTPURLResponse)?.statusCode
// guard statusCode! >= 200 && statusCode! < 300, let json = data else {
// return
// }
//
// var result = String(data: json, encoding: .utf8)!
//
// print(result)
// }
//}.resume()
/*:
- experiment: Uncomment above and see what happends
*/
/*:
### `GET /persons/id:`
- example: Below is an example implementation of the `GET /persons/id:` route on the Person resource. This will get a single person resource.
*/
//var request = URLRequest(url: URL(string: "\(host)/persons/11956013-37ea-4daf-f62c-db204662b490")!)
//request.httpMethod = "GET"
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//session.dataTask(with: request) { (data, response, error) in
//
// if error != nil {
// print(error!)
// } else {
// let statusCode = (response as? HTTPURLResponse)?.statusCode
// guard statusCode! >= 200 && statusCode! < 300, let json = data else {
// return
// }
//
// var result = String(data: json, encoding: String.Encoding.utf8)!
//
// print(result)
// }
//}.resume()
/*:
- experiment: Uncomment above and see what happends
*/
/*:
### `POST /persons`
- example: Below is an example implementation of the `POST /persons` route on the Person resource. This will create a person resource.
*/
//let jsonPayload = "{\"first\":\"Mathew\", \"last\":\"Sheets\", \"phone\":\"16141234567\"}"
//
//var request = URLRequest(url: URL(string: "\(host)/persons")!)
//request.httpMethod = "POST"
//request.httpBody = jsonPayload.data(using: .utf8)
//
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//session.dataTask(with: request) { (data, response, error) in
//
// if error != nil {
// print(error!)
// } else {
// let statusCode = (response as? HTTPURLResponse)?.statusCode
// guard statusCode! >= 200 && statusCode! < 300, let json = data else {
// return
// }
//
// var result = String(data: json, encoding: String.Encoding.utf8)!
//
// print(result)
// }
//}.resume()
/*:
- experiment: Uncomment above and see what happends
*/
/*:
### `PUT /persons/id:`
- example: Below is an example implementation of the `PUT /persons/id:` route on the Person resource. This will update a person resource.
*/
//let jsonPayload = "{\"first\":\"Matt\", \"phone\":\"16147654321\"}"
//
//var request = URLRequest(url: URL(string: "\(host)/persons/11956013-37ea-4daf-f62c-db204662b490")!)
//request.httpMethod = "PUT"
//request.httpBody = jsonPayload.data(using: .utf8)
//
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//session.dataTask(with: request) { (data, response, error) in
//
// if error != nil {
// print(error!)
// } else {
// let statusCode = (response as? HTTPURLResponse)?.statusCode
// guard statusCode! >= 200 && statusCode! < 300 else {
// return
// }
//
// print("good response")
// }
//}.resume()
/*:
- experiment: Uncomment above and see what happends
*/
/*:
### `DELETE /persons/id:`
- example: Below is an example implementation of the `DELETE /persons/id:` route on the Person resource. This will delete a person resource.
*/
//var request = URLRequest(url: URL(string: "\(host)/persons/11956013-37ea-4daf-f62c-db204662b490")!)
//request.httpMethod = "DELETE"
//
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//session.dataTask(with: request) { (data, response, error) in
//
// if error != nil {
// print(error!)
// } else {
// let statusCode = (response as? HTTPURLResponse)?.statusCode
// guard statusCode! >= 200 && statusCode! < 300 else {
// return
// }
//
// print("good response")
// }
//}.resume()
/*:
- experiment: Uncomment above and see what happends
*/
/*:
- - -
* callout(Checkpoint): At this point, you should have basic knowledge of HTTP and ReSt outside the context of an operating system and programming language. We learned the five main routes for a ReSTful resource and the HTTP method, URI, data, and possible response codes for each. We also learned about the three main components that is provided from the Foundation Framework available in Swift programs enabling using to communicate with another program.
* callout(Supporting Materials): Additional Resources For Further Reading
- [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW1)
- [URL Loading System](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i)
- [ReST on Wikipedia](https://en.wikipedia.org/wiki/Representational_state_transfer)
- [ReST API Tutorial](http://www.restapitutorial.com/)
- [Response Status Codes](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
- [cURL as a HTTP Client](https://curl.haxx.se/docs/manpage.html)
- [ReSTful Service Sandboxing](https://getsandbox.com)
- - -
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
*/
| mit | 515826fc4340f9a6140beda86a413197 | 46.524306 | 684 | 0.701615 | 3.842504 | false | false | false | false |
USAssignmentWarehouse/EnglishNow | EnglishNow/Model/Profile/User.swift | 1 | 4239 | //
// User.swift
// EnglishNow
//
// Created by GeniusDoan on 6/28/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import Foundation
import UIKit
enum UserType: Int {
case learner
case speaker
}
class User: NSObject, NSCoding {
static var current: User = User()
var uid: String!
var type: UserType!
var name: String!
var email: String!
var password: String!
//var _photoUrl: URL?
var profilePhoto:String!
var conversations: Int!
var totalHours: Double!
var rating: Double!
var review:Review!
var reviews: [Review]!
var isSpeaker: Bool {
get{
return type == UserType.speaker
}
}
override init() {
super.init()
uid = ""
type = UserType.learner
name = ""
email = ""
password = ""
profilePhoto = ""
conversations = 0
totalHours = 0
rating = 0
review = Review()
reviews = [Review]()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(uid, forKey: "uid")
aCoder.encode(type?.hashValue, forKey: "type")
aCoder.encode(name, forKey: "name")
aCoder.encode(email, forKey: "email")
aCoder.encode(password, forKey: "password")
aCoder.encode(profilePhoto, forKey: "profilePhoto")
aCoder.encode(conversations, forKey: "conversations")
aCoder.encode(totalHours, forKey: "totalHours")
aCoder.encode(rating, forKey: "rating")
aCoder.encode(review, forKey: "review")
aCoder.encode(reviews, forKey: "reviews")
}
required init?(coder aDecoder: NSCoder) {
uid = aDecoder.decodeObject(forKey: "uid") as! String
type = UserType(rawValue: aDecoder.decodeObject(forKey: "type") as! Int)
name = aDecoder.decodeObject(forKey: "name") as! String
email = aDecoder.decodeObject(forKey: "email") as! String
password = aDecoder.decodeObject(forKey: "password") as! String
profilePhoto = aDecoder.decodeObject(forKey: "profilePhoto") as! String
conversations = aDecoder.decodeObject(forKey: "conversations") as! Int
totalHours = aDecoder.decodeObject(forKey: "totalHours") as! Double
rating = aDecoder.decodeObject(forKey: "rating") as! Double
review = aDecoder.decodeObject(forKey: "review") as! Review
reviews = aDecoder.decodeObject(forKey: "reviews") as! [Review]
}
// func initUser(){
// review = Review()
// }
func setUserPhotoView(view: UIImageView) {
if isSpeaker {
print(profilePhoto)
//view.setImageWith(URL(string: profilePhoto)!)
} else {
view.image = UIImage(named: profilePhoto)
}
}
func speakerAverageRatings() -> Double{
var rating:Double = 0
if reviews.count != 0{
for review in reviews{
print(review.rating)
rating += review.rating
}
rating /= Double(reviews.count > 0 ? reviews.count : 1)
}
return round(rating*10)/10
}
func learnerAverageRating() -> Double{
var rating:Double = 0
for review in reviews{
rating += (review.ratings?.listening)! + (review.ratings?.pronounciation)! + (review.ratings?.fluency)! + (review.ratings?.vocabulary)!
}
rating /= Double(reviews.count > 0 ? reviews.count : 1)
return round(rating*10)/10
}
func dictionary() -> [String: AnyObject] {
var dict = [String: AnyObject]()
dict["uid"] = uid as AnyObject
dict["type"] = type as AnyObject
dict["name"] = name as AnyObject
dict["email"] = email as AnyObject
dict["password"] = password as AnyObject
dict["profilePhoto"] = profilePhoto as AnyObject
dict["conversations"] = conversations as AnyObject
dict["totalHours"] = totalHours as AnyObject
dict["rating"] = rating as AnyObject
dict["review"] = review?.dictionary() as AnyObject
dict["reviews"] = Review.arrayDictionary(reviews: reviews) as AnyObject
return dict
}
}
| apache-2.0 | 45cea32b48cf39d239aa613eecadb4d8 | 30.864662 | 147 | 0.589665 | 4.461053 | false | false | false | false |
iwheelbuy/VK | VK/Method/Utils/VK+Method+Utils+ResolveScreenName.swift | 1 | 1376 | //import Foundation
//
//public extension Method.Utils {
// /// Тип объекта (пользователь, сообщество, приложение) и его идентификатор по короткому имени screen_name
// public struct ResolveScreenName {
// /// Ответ
// public typealias Response = Object.ResolvedScreenName?
// /// Короткое имя пользователя, группы или приложения
// public let screen_name: String
// /// Пользовательские данные
// public let user: App.User?
//
// public init(screen_name: String, user: App.User? = nil) {
// self.screen_name = screen_name
// self.user = user
// }
// }
//}
//
//extension Method.Utils.ResolveScreenName: ApiType {
//
// public var method_name: String {
// return "utils.resolveScreenName"
// }
//
// public var parameters: [String: String] {
// var dictionary = App.parameters
// dictionary["access_token"] = user?.token
// dictionary["screen_name"] = screen_name
// return dictionary
// }
//}
//
//extension Method.Utils.ResolveScreenName: StrategyType {
//
// public var api: AnyApi<Method.Utils.ResolveScreenName.Response> {
// return AnyApi(api: self)
// }
//}
| mit | 9bbd99e305a026ba3faf0f3c411d18a4 | 30.589744 | 111 | 0.604708 | 3.422222 | false | false | false | false |
mrdepth/CloudData | CloudData/CloudData/Reachability.swift | 1 | 2795 | //
// Reachability.swift
// CloudData
//
// Created by Artem Shimanski on 10.03.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import SystemConfiguration
import Darwin
enum NetworkStatus {
case notReachable
case reachableViaWiFi
case reachableViaWWAN
}
extension Notification.Name {
static let ReachabilityChanged = Notification.Name(rawValue: "ReachabilityChanged")
}
class Reachability {
private let reachability: SCNetworkReachability
convenience init?() {
var addr = sockaddr_in()
addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
addr.sin_family = sa_family_t(AF_INET)
let ptr = withUnsafePointer(to: &addr) {$0.withMemoryRebound(to: sockaddr.self, capacity: 1){$0}}
self.init(address: ptr)
}
init?(hostName: String) {
if let reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, hostName) {
self.reachability = reachability
}
else {
return nil
}
}
init?(address: UnsafePointer<sockaddr>) {
if let reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, address) {
self.reachability = reachability
}
else {
return nil
}
}
deinit {
stopNotifier()
}
func startNotifier() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: nil, release: nil, copyDescription: nil)
if (SCNetworkReachabilitySetCallback(reachability, {(reachability, flags, info) in
guard let info = info else {return}
let myself = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
NotificationCenter.default.post(name: .ReachabilityChanged, object: myself)
}, &context)) {
return SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
}
return false
}
func stopNotifier() {
SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
}
var reachabilityStatus: NetworkStatus {
var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
if !flags.contains(.reachable) {
return .notReachable
}
else {
var status: NetworkStatus = .notReachable
if !flags.contains(.connectionRequired) {
status = .reachableViaWiFi
}
if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
if !flags.contains(.interventionRequired) {
status = .reachableViaWiFi
}
}
if flags.contains(.isWWAN) {
status = .reachableViaWWAN
}
return status
}
}
var connectionRequired: Bool {
var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
return flags.contains(.connectionRequired)
}
}
| mit | 487f26582753d20f3124704c64dcf457 | 24.87037 | 154 | 0.736936 | 4.163934 | false | false | false | false |
material-motion/material-motion-swift | examples/apps/Catalog/ReactivePlayground.playground/Sources/Canvas.swift | 1 | 2642 | import Foundation
import UIKit
import PlaygroundSupport
import WebKit
public let canvas = createCanvas()
public func createCanvas() -> UIView {
let canvas = UIView(frame: .init(x: 0, y: 0, width: 600, height: 800))
canvas.backgroundColor = .white
PlaygroundPage.current.liveView = canvas
return canvas
}
public func visualize(graphviz: String, onCanvas canvas: UIView) {
let webView = VisualizingWebView(graphviz: graphviz, frame: .init(x: 0, y: canvas.bounds.height - canvas.bounds.width, width: canvas.bounds.width, height: canvas.bounds.width))
webView.load(.init(url: URL(string: "http://www.webgraphviz.com/")!))
canvas.addSubview(webView)
}
public func createExampleView() -> UIView {
let view = UIView(frame: .init(x: 0, y: 0, width: 128, height: 128))
view.backgroundColor = .primaryColor
view.layer.cornerRadius = view.bounds.width / 2
return view
}
public func createExampleSquareView() -> UIView {
let view = UIView(frame: .init(x: 0, y: 0, width: 128, height: 128))
view.backgroundColor = .primaryColor
return view
}
class VisualizingWebView: WKWebView, WKNavigationDelegate {
init(graphviz: String, frame: CGRect) {
self.graphviz = graphviz
super.init(frame: frame, configuration: .init())
self.navigationDelegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let javascript = "document.getElementById('graphviz_data').innerHTML = `\(graphviz.replacingOccurrences(of: "\\n", with: "\\\n"))`; document.getElementById('generate_btn').click(); var image = document.getElementById('graphviz_svg_div'); document.body.innerHTML = ''; document.body.appendChild(image);"
webView.evaluateJavaScript(javascript) { value, error in
}
}
let graphviz: String
}
extension UIColor {
private convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(hexColor: Int) {
self.init(red: (hexColor >> 16) & 0xff, green: (hexColor >> 8) & 0xff, blue: hexColor & 0xff)
}
static var primaryColor: UIColor {
return UIColor(hexColor: 0xFF80AB)
}
static var secondaryColor: UIColor {
return UIColor(hexColor: 0xC51162)
}
static var backgroundColor: UIColor {
return UIColor(hexColor: 0x212121)
}
}
| apache-2.0 | 46ce2d0e29915ba4fa4a1d3d3db5a079 | 32.871795 | 306 | 0.700227 | 3.664355 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/Speed.swift | 1 | 2269 | /*****************************************************************************************************
* Copyright 2013 appscape gmbh
* Copyright 2014-2016 SPECURE GmbH
*
* 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
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
let GAUGE_PARTS = 4.25
let LOG10_MAX = log10(250.0)
///
public func RMBTSpeedLogValue(_ kbps: Double) -> Double {
let bps = UInt64(kbps * 1_000)
var log: Double
if bps < 10_000 {
log = 0
} else {
log = ((GAUGE_PARTS - LOG10_MAX) + log10(Double(bps) / Double(1e6))) / GAUGE_PARTS
}
//if (log > 1.0) {
// log = 1.0
//}
return log
}
/// for nkom
public func RMBTSpeedLogValue(_ kbps: Double, gaugeParts: Double, log10Max: Double) -> Double {
let bps = kbps * 1_000
if bps < 10_000 {
return 0
}
return ((gaugeParts - log10Max) + log10(Double(bps) / 1e6)) / gaugeParts
}
///
public func RMBTSpeedMbpsString(_ kbps: Double, withMbps: Bool = true, maxDigits: Int = 2) -> String {
let speedValue = RMBTFormatNumber(NSNumber(value: kbps / 1000.0), maxDigits)
if withMbps {
let localizedMps = NSLocalizedString("test.speed.unit", value: "Mbps", comment: "Speed suffix")
return String(format: "%@ %@", speedValue, localizedMps)
}
return "\(speedValue)"
}
| apache-2.0 | 3c3275911d52a25b4ce48d4101a8a1ff | 28.855263 | 103 | 0.596298 | 3.865417 | false | false | false | false |
colemancda/Seam | Seam/Seam/CKRecord+NSManagedObject.swift | 1 | 8807 | // CKRecord+NSManagedObject.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nofel Mahmood ( https://twitter.com/NofelMahmood )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreData
import CloudKit
extension CKRecord
{
func allAttributeKeys(usingAttributesByNameFromEntity attributesByName: [String:NSAttributeDescription]) -> [String]
{
return self.allKeys().filter({ (key) -> Bool in
return attributesByName[key] != nil
})
}
func allReferencesKeys(usingRelationshipsByNameFromEntity relationshipsByName: [String:NSRelationshipDescription]) -> [String]
{
return self.allKeys().filter({ (key) -> Bool in
return relationshipsByName[key] != nil
})
}
class func recordWithEncodedFields(encodedFields: NSData) -> CKRecord
{
let coder = NSKeyedUnarchiver(forReadingWithData: encodedFields)
let record: CKRecord = CKRecord(coder: coder)!
coder.finishDecoding()
return record
}
func encodedSystemFields() -> NSData
{
let data = NSMutableData()
let coder = NSKeyedArchiver(forWritingWithMutableData: data)
self.encodeSystemFieldsWithCoder(coder)
coder.finishEncoding()
return data
}
private func allAttributeValuesAsManagedObjectAttributeValues(usingContext context: NSManagedObjectContext) -> [String:AnyObject]?
{
let entity = context.persistentStoreCoordinator?.managedObjectModel.entitiesByName[self.recordType]
return self.dictionaryWithValuesForKeys(self.allAttributeKeys(usingAttributesByNameFromEntity: entity!.attributesByName))
}
private func allCKReferencesAsManagedObjects(usingContext context: NSManagedObjectContext) -> [String:AnyObject]?
{
// Fix it : Need to fix relationships. No relationships are being saved at the moment
let entity = context.persistentStoreCoordinator?.managedObjectModel.entitiesByName[self.recordType]
if entity != nil
{
let referencesValuesDictionary = self.dictionaryWithValuesForKeys(self.allReferencesKeys(usingRelationshipsByNameFromEntity: entity!.relationshipsByName))
var managedObjectsDictionary: Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
for (key,value) in referencesValuesDictionary
{
if (value as? String) != nil && (value as! String) == SMCloudRecordNilValue
{
managedObjectsDictionary[key] = SMCloudRecordNilValue
continue
}
let relationshipDescription = entity!.relationshipsByName[key]
if relationshipDescription?.destinationEntity?.name != nil
{
let recordIDString = (value as! CKReference).recordID.recordName
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: relationshipDescription!.destinationEntity!.name!)
fetchRequest.predicate = NSPredicate(format: "%K == %@", SMLocalStoreRecordIDAttributeName,recordIDString)
fetchRequest.fetchLimit = 1
do
{
let results = try context.executeFetchRequest(fetchRequest)
if results.count > 0
{
let relationshipManagedObject: NSManagedObject = results.last as! NSManagedObject
managedObjectsDictionary[key] = relationshipManagedObject
}
}
catch
{
print("Failed to find relationship managed object for Key \(key) RecordID \(recordIDString)", terminator: "\n")
}
}
}
return managedObjectsDictionary
}
return nil
}
public func createOrUpdateManagedObjectFromRecord(usingContext context: NSManagedObjectContext) throws -> NSManagedObject?
{
let entity = context.persistentStoreCoordinator?.managedObjectModel.entitiesByName[self.recordType]
if entity?.name != nil
{
var managedObject: NSManagedObject?
let recordIDString = self.recordID.recordName
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: entity!.name!)
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "%K == %@", SMLocalStoreRecordIDAttributeName, recordIDString)
let results = try context.executeFetchRequest(fetchRequest)
if results.count > 0
{
managedObject = results.last as? NSManagedObject
if managedObject != nil
{
managedObject!.setValue(self.encodedSystemFields(), forKey: SMLocalStoreRecordEncodedValuesAttributeName)
let attributeValuesDictionary = self.allAttributeValuesAsManagedObjectAttributeValues(usingContext: context)
if attributeValuesDictionary != nil
{
managedObject!.setValuesForKeysWithDictionary(attributeValuesDictionary!)
}
let referencesValuesDictionary = self.allCKReferencesAsManagedObjects(usingContext: context)
if referencesValuesDictionary != nil
{
for (key,value) in referencesValuesDictionary!
{
if (value as? String) != nil && (value as! String) == SMCloudRecordNilValue
{
managedObject!.setValue(nil, forKey: key)
}
else
{
managedObject!.setValue(value, forKey: key)
}
}
}
}
}
else
{
managedObject = NSEntityDescription.insertNewObjectForEntityForName(entity!.name!, inManagedObjectContext: context)
if managedObject != nil
{
managedObject!.setValue(recordIDString, forKey: SMLocalStoreRecordIDAttributeName)
managedObject!.setValue(self.encodedSystemFields(), forKey: SMLocalStoreRecordEncodedValuesAttributeName)
let attributeValuesDictionary = self.allAttributeValuesAsManagedObjectAttributeValues(usingContext: context)
if attributeValuesDictionary != nil
{
managedObject!.setValuesForKeysWithDictionary(attributeValuesDictionary!)
}
let referencesValuesDictionary = self.allCKReferencesAsManagedObjects(usingContext: context)
if referencesValuesDictionary != nil
{
for (key,value) in referencesValuesDictionary!
{
if (value as? String) != nil && (value as! String) == SMCloudRecordNilValue
{
managedObject!.setValue(nil, forKey: key)
}
else
{
managedObject!.setValue(value, forKey: key)
}
}
}
}
}
return managedObject
}
return nil
}
}
| mit | 84797dd467717a7d651ea3e3b5a61a13 | 46.349462 | 166 | 0.593619 | 6.133008 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Player/PlayerAction.swift | 1 | 7016 | //
// File.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import RxSwift
import NotificationBannerSwift
import Action
import NSObject_Rx
protocol PlayerAction {
var store: PlayerStore { get }
func onPlayButtonPress() -> CocoaAction
func onBackwardPress() -> CocoaAction
func onForwardPress() -> CocoaAction
func onRepeatPress() -> CocoaAction
func onRefreshPress() -> CocoaAction
func onProgressBarDidEndDragging() -> Action<Int, Void>
var onPlay: CocoaAction { get }
var onPause: CocoaAction { get }
func onHeartButtonPress() -> CocoaAction
func onDownloadButtonPress() -> CocoaAction
func onShareButtonPress() -> CocoaAction
var onCalendarButtonPress: Action<TimerInfo, Int?> { get }
func onVolumeButtonPress() -> CocoaAction
var onTrackDidSelect: Action<Track, Void> { get }
var onDidPlay: CocoaAction { get }
var onDidPause: CocoaAction { get }
var onDidStop: CocoaAction { get }
var onDidGetMode: Action<MusicMode, Void> { get }
var onDidGetDuration: Action<Int, Void> { get }
var onDidGetCurrentTime: Action<Int, Void> { get }
var onDidGetNextTrack: Action<Track, Void> { get }
var onDidGetTracks: Action<[Track], Void> { get }
}
class MAPlayerAction : NSObject, PlayerAction {
let store: PlayerStore
let service: PlayerService
init(store: PlayerStore, service: PlayerService) {
self.store = store
self.service = service
super.init()
self.service.onDidPlay()
.subscribe(onDidPlay.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidPause()
.subscribe(onDidPause.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidStop()
.subscribe(onDidStop.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidGetMode()
.subscribe(onDidGetMode.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidGetDuration()
.subscribe(onDidGetDuration.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidGetCurrentTime()
.subscribe(onDidGetCurrentTime.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidGetNextTrack()
.subscribe(onDidGetNextTrack.inputs)
.addDisposableTo(rx_disposeBag)
self.service.onDidGetTracks()
.subscribe(onDidGetTracks.inputs)
.addDisposableTo(rx_disposeBag)
}
func onPlayButtonPress() -> CocoaAction {
return CocoaAction { [weak self] in
guard let this = self else { return .empty() }
switch this.store.playButtonState.value {
case .playing:
return this.service.pause()
case .paused:
return this.service.play()
}
}
}
func onBackwardPress() -> CocoaAction {
return CocoaAction { [weak self] in
self?.service.backward() ?? .empty()
}
}
func onForwardPress() -> CocoaAction {
return CocoaAction { [weak self] in
self?.service.forward() ?? .empty()
}
}
func onRepeatPress() -> CocoaAction {
return CocoaAction { [weak self] in
self?.service.nextRepeat() ?? .empty()
}
}
func onRefreshPress() -> CocoaAction {
return CocoaAction { [weak self] in
StatusBarNotificationBanner(title: "Khởi động lại danh sách bài hát", style: .info).show()
return self?.service.refresh() ?? .empty()
}
}
func onProgressBarDidEndDragging() -> Action<Int, Void> {
return Action { [weak self] currentTime in
return self?.service.seek(currentTime) ?? .empty()
}
}
lazy var onPlay: CocoaAction = {
return CocoaAction { [weak self] in
return self?.service.play() ?? .empty()
}
}()
lazy var onPause: CocoaAction = {
return CocoaAction { [weak self] in
return self?.service.pause() ?? .empty()
}
}()
func onHeartButtonPress() -> CocoaAction {
return CocoaAction {
return .empty()
}
}
func onDownloadButtonPress() -> CocoaAction {
return CocoaAction {
return .empty()
}
}
func onShareButtonPress() -> CocoaAction {
return CocoaAction {
return .empty()
}
}
lazy var onCalendarButtonPress: Action<TimerInfo, Int?> = {
return Action { [weak self] timerInfo in
return self?.service.presentTimer(in: timerInfo.controller, time: timerInfo.time) ?? .empty()
}
}()
func onVolumeButtonPress() -> CocoaAction {
return CocoaAction { [weak self] in
self?.store.volumeEnabled.value = !(self?.store.volumeEnabled.value ?? true)
return .empty()
}
}
lazy var onTrackDidSelect: Action<Track, Void> = {
return Action { [weak self] track in
self?.store.currentTime.value = 0
return self?.service.play(track: track) ?? .empty()
}
}()
lazy var onDidPlay: CocoaAction = {
return CocoaAction { [weak self] in
self?.store.playButtonState.value = .playing
return .empty()
}
}()
lazy var onDidPause: CocoaAction = {
return CocoaAction { [weak self] in
self?.store.playButtonState.value = .paused
return .empty()
}
}()
lazy var onDidStop: CocoaAction = {
return CocoaAction { [weak self] in
self?.store.playButtonState.value = .paused
return .empty()
}
}()
lazy var onDidGetMode: Action<MusicMode, Void> = {
return Action { [weak self] mode in
self?.store.repeatMode.value = mode
return .empty()
}
}()
lazy var onDidGetDuration: Action<Int, Void> = {
return Action { [weak self] duration in
self?.store.duration.value = duration
return .empty()
}
}()
lazy var onDidGetCurrentTime: Action<Int, Void> = {
return Action { [weak self] currentTime in
self?.store.currentTime.value = currentTime
return .empty()
}
}()
lazy var onDidGetNextTrack: Action<Track, Void> = {
return Action { [weak self] track in
self?.store.track.value = track
return .empty()
}
}()
lazy var onDidGetTracks: Action<[Track], Void> = {
return Action { [weak self] tracks in
self?.store.tracks.value = tracks
return .empty()
}
}()
}
| mit | b205ade322a406c79b40ecbf371e6dfa | 27.8107 | 105 | 0.568919 | 4.621122 | false | false | false | false |
shajrawi/swift | stdlib/public/core/VarArgs.swift | 1 | 22349 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type whose instances can be encoded, and appropriately passed, as
/// elements of a C `va_list`.
///
/// You use this protocol to present a native Swift interface to a C "varargs"
/// API. For example, a program can import a C API like the one defined here:
///
/// ~~~c
/// int c_api(int, va_list arguments)
/// ~~~
///
/// To create a wrapper for the `c_api` function, write a function that takes
/// `CVarArg` arguments, and then call the imported C function using the
/// `withVaList(_:_:)` function:
///
/// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int {
/// return withVaList(arguments) { c_api(x, $0) }
/// }
///
/// Swift only imports C variadic functions that use a `va_list` for their
/// arguments. C functions that use the `...` syntax for variadic arguments
/// are not imported, and therefore can't be called using `CVarArg` arguments.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Note: Declaring conformance to the `CVarArg` protocol for types defined
/// outside the standard library is not supported.
public protocol CVarArg {
// Note: the protocol is public, but its requirement is stdlib-private.
// That's because there are APIs operating on CVarArg instances, but
// defining conformances to CVarArg outside of the standard library is
// not supported.
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
var _cVarArgEncoding: [Int] { get }
}
/// Floating point types need to be passed differently on x86_64
/// systems. CoreGraphics uses this to make CGFloat work properly.
public // SPI(CoreGraphics)
protocol _CVarArgPassedAsDouble : CVarArg {}
/// Some types require alignment greater than Int on some architectures.
public // SPI(CoreGraphics)
protocol _CVarArgAligned : CVarArg {
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
var _cVarArgAlignment: Int { get }
}
#if arch(x86_64)
@usableFromInline
internal let _countGPRegisters = 6
// Note to future visitors concerning the following SSE register count.
//
// AMD64-ABI section 3.5.7 says -- as recently as v0.99.7, Nov 2014 -- to make
// room in the va_list register-save area for 16 SSE registers (XMM0..15). This
// may seem surprising, because the calling convention of that ABI only uses the
// first 8 SSE registers for argument-passing; why save the other 8?
//
// According to a comment in X86_64ABIInfo::EmitVAArg, in clang's TargetInfo,
// the AMD64-ABI spec is itself in error on this point ("NOTE: 304 is a typo").
// This comment (and calculation) in clang has been there since varargs support
// was added in 2009, in rev be9eb093; so if you're about to change this value
// from 8 to 16 based on reading the spec, probably the bug you're looking for
// is elsewhere.
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 2
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + _countFPRegisters * _fpRegisterWords
#elseif arch(s390x)
@usableFromInline
internal let _countGPRegisters = 16
@usableFromInline
internal let _registerSaveWords = _countGPRegisters
#elseif arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
// ARM Procedure Call Standard for aarch64. (IHI0055B)
// The va_list type may refer to any parameter in a parameter list may be in one
// of three memory locations depending on its type and position in the argument
// list :
// 1. GP register save area x0 - x7
// 2. 128-bit FP/SIMD register save area q0 - q7
// 3. Stack argument area
@usableFromInline
internal let _countGPRegisters = 8
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 16 / MemoryLayout<Int>.size
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + (_countFPRegisters * _fpRegisterWords)
#endif
#if arch(s390x)
@usableFromInline
internal typealias _VAUInt = CUnsignedLongLong
@usableFromInline
internal typealias _VAInt = Int64
#else
@usableFromInline
internal typealias _VAUInt = CUnsignedInt
@usableFromInline
internal typealias _VAInt = Int32
#endif
/// Invokes the given closure with a C `va_list` argument derived from the
/// given array of arguments.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withVaList(_:_:)`. Do not store or return the pointer for
/// later use.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameters:
/// - args: An array of arguments to convert to a C `va_list` pointer.
/// - body: A closure with a `CVaListPointer` parameter that references the
/// arguments passed as `args`. If `body` has a return value, that value
/// is also used as the return value for the `withVaList(_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // c-abi
public func withVaList<R>(_ args: [CVarArg],
_ body: (CVaListPointer) -> R) -> R {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
return _withVaList(builder, body)
}
/// Invoke `body` with a C `va_list` argument derived from `builder`.
@inlinable // c-abi
internal func _withVaList<R>(
_ builder: __VaListBuilder,
_ body: (CVaListPointer) -> R
) -> R {
let result = body(builder.va_list())
_fixLifetime(builder)
return result
}
#if _runtime(_ObjC)
// Excluded due to use of dynamic casting and Builtin.autorelease, neither
// of which correctly work without the ObjC Runtime right now.
// See rdar://problem/18801510
/// Returns a `CVaListPointer` that is backed by autoreleased storage, built
/// from the given array of arguments.
///
/// You should prefer `withVaList(_:_:)` instead of this function. In some
/// uses, such as in a `class` initializer, you may find that the language
/// rules do not allow you to use `withVaList(_:_:)` as intended.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameter args: An array of arguments to convert to a C `va_list`
/// pointer.
/// - Returns: A pointer that can be used with C functions that take a
/// `va_list` argument.
@inlinable // c-abi
public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
// FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one.
Builtin.retain(builder)
Builtin.autorelease(builder)
return builder.va_list()
}
#endif
@inlinable // c-abi
public func _encodeBitsAsWords<T>(_ x: T) -> [Int] {
let result = [Int](
repeating: 0,
count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size)
_internalInvariant(!result.isEmpty)
var tmp = x
// FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy.
_memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!),
src: UnsafeMutablePointer(Builtin.addressof(&tmp)),
size: UInt(MemoryLayout<T>.size))
return result
}
// CVarArg conformances for the integer types. Everything smaller
// than an Int32 must be promoted to Int32 or CUnsignedInt before
// encoding.
// Signed types
extension Int : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Bool : CVarArg {
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self ? 1:0))
}
}
extension Int64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension Int32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
// Unsigned types
extension UInt : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension UInt32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension OpaquePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#if _runtime(_ObjC)
extension AutoreleasingUnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#endif
extension Float : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Double(self))
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: Double(self))
}
}
extension Double : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#if !os(Windows) && (arch(i386) || arch(x86_64))
extension Float80 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#endif
#if (arch(x86_64) && !os(Windows)) || arch(s390x) || (arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows)))
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
#if arch(x86_64) || arch(s390x)
@_fixed_layout // c-abi
@usableFromInline
internal struct Header {
@inlinable // c-abi
internal init() {}
@usableFromInline // c-abi
internal var gp_offset = CUnsignedInt(0)
@usableFromInline // c-abi
internal var fp_offset =
CUnsignedInt(_countGPRegisters * MemoryLayout<Int>.stride)
@usableFromInline // c-abi
internal var overflow_arg_area: UnsafeMutablePointer<Int>?
@usableFromInline // c-abi
internal var reg_save_area: UnsafeMutablePointer<Int>?
}
#endif
@usableFromInline // c-abi
internal var gpRegistersUsed = 0
@usableFromInline // c-abi
internal var fpRegistersUsed = 0
#if arch(x86_64) || arch(s390x)
@usableFromInline // c-abi
final // Property must be final since it is used by Builtin.addressof.
internal var header = Header()
#endif
@usableFromInline // c-abi
internal var storage: ContiguousArray<Int>
@inlinable // c-abi
internal init() {
// prepare the register save area
storage = ContiguousArray(repeating: 0, count: _registerSaveWords)
}
@inlinable // c-abi
deinit {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
var encoded = arg._cVarArgEncoding
#if arch(x86_64) || arch(arm64)
let isDouble = arg is _CVarArgPassedAsDouble
if isDouble && fpRegistersUsed < _countFPRegisters {
#if arch(arm64)
var startIndex = fpRegistersUsed * _fpRegisterWords
#else
var startIndex = _countGPRegisters
+ (fpRegistersUsed * _fpRegisterWords)
#endif
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
fpRegistersUsed += 1
}
else if encoded.count == 1
&& !isDouble
&& gpRegistersUsed < _countGPRegisters {
#if arch(arm64)
let startIndex = ( _fpRegisterWords * _countFPRegisters) + gpRegistersUsed
#else
let startIndex = gpRegistersUsed
#endif
storage[startIndex] = encoded[0]
gpRegistersUsed += 1
}
else {
for w in encoded {
storage.append(w)
}
}
#elseif arch(s390x)
if gpRegistersUsed < _countGPRegisters {
for w in encoded {
storage[gpRegistersUsed] = w
gpRegistersUsed += 1
}
} else {
for w in encoded {
storage.append(w)
}
}
#endif
}
@inlinable // c-abi
internal func va_list() -> CVaListPointer {
#if arch(x86_64) || arch(s390x)
header.reg_save_area = storage._baseAddress
header.overflow_arg_area
= storage._baseAddress + _registerSaveWords
return CVaListPointer(
_fromUnsafeMutablePointer: UnsafeMutableRawPointer(
Builtin.addressof(&self.header)))
#elseif arch(arm64)
let vr_top = storage._baseAddress + (_fpRegisterWords * _countFPRegisters)
let gr_top = vr_top + _countGPRegisters
return CVaListPointer(__stack: gr_top,
__gr_top: gr_top,
__vr_top: vr_top,
__gr_off: -64,
__vr_off: -128)
#endif
}
}
#else
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
@inlinable // c-abi
internal init() {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
// Write alignment padding if necessary.
// This is needed on architectures where the ABI alignment of some
// supported vararg type is greater than the alignment of Int, such
// as non-iOS ARM. Note that we can't use alignof because it
// differs from ABI alignment on some architectures.
#if arch(arm) && !os(iOS)
if let arg = arg as? _CVarArgAligned {
let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size
let misalignmentInWords = count % alignmentInWords
if misalignmentInWords != 0 {
let paddingInWords = alignmentInWords - misalignmentInWords
appendWords([Int](repeating: -1, count: paddingInWords))
}
}
#endif
// Write the argument's value itself.
appendWords(arg._cVarArgEncoding)
}
// NB: This function *cannot* be @inlinable because it expects to project
// and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`.
// Marking it inlinable will cause it to resiliently use accessors to
// project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed
// property.
@usableFromInline // c-abi
internal func va_list() -> CVaListPointer {
// Use Builtin.addressof to emphasize that we are deliberately escaping this
// pointer and assuming it is safe to do so.
let emptyAddr = UnsafeMutablePointer<Int>(
Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists))
return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
}
// Manage storage that is accessed as Words
// but possibly more aligned than that.
// FIXME: this should be packaged into a better storage type
@inlinable // c-abi
internal func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// count is updated below
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
@inlinable // c-abi
internal func rawSizeAndAlignment(
_ wordCount: Int
) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
@inlinable // c-abi
internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
@usableFromInline // c-abi
internal func deallocStorage(
wordCount: Int,
storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
@inlinable // c-abi
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
// FIXME: alignof differs from the ABI alignment on some architectures
@usableFromInline // c-abi
internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
@usableFromInline // c-abi
internal var count = 0
@usableFromInline // c-abi
internal var allocated = 0
@usableFromInline // c-abi
internal var storage: UnsafeMutablePointer<Int>?
internal static var alignedStorageForEmptyVaLists: Double = 0
}
#endif
| apache-2.0 | f3dd50277ff426e0e9343ae583b3d99d | 32.307004 | 135 | 0.691396 | 4.113565 | false | false | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/ContextMenu/ContextMenuControllerAnimatedTransitioning.swift | 1 | 2517 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
@available(iOS 8, *)
internal class ContextMenuControllerAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
// MARK: - Properties
var presentation: Bool = false
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.4
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let animationViewKey: String
let animationViewControllerKey: String
if presentation {
animationViewKey = UITransitionContextToViewKey
animationViewControllerKey = UITransitionContextToViewControllerKey
} else {
animationViewKey = UITransitionContextFromViewKey
animationViewControllerKey = UITransitionContextFromViewControllerKey
}
guard let containerView = transitionContext.containerView(), animationView = transitionContext.viewForKey(animationViewKey), animationViewController = transitionContext.viewControllerForKey(animationViewControllerKey) else {
transitionContext.completeTransition(false)
return
}
if presentation {
animationView.alpha = 0
containerView.addSubview(animationView)
animationView.frame = transitionContext.finalFrameForViewController(animationViewController)
animationView.transform = CGAffineTransformMakeScale(1.1, 1.1)
}
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
if self.presentation {
animationView.alpha = 1
animationView.transform = CGAffineTransformIdentity
} else {
animationView.alpha = 0
}
}) { _ in
animationView.alpha = 1
transitionContext.completeTransition(true)
}
}
}
| mit | 8fe9adb0e902814b698dd72ca188c2b5 | 40.262295 | 232 | 0.70878 | 6.276808 | false | false | false | false |
ZeeQL/ZeeQL3 | Tests/ZeeQLTests/FakeAdaptor.swift | 1 | 2393 | //
// FakeAdaptor.swift
// ZeeQL3
//
// Created by Helge Hess on 06/06/17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import ZeeQL
class FakeAdaptor : Adaptor {
var expressionFactory = SQLExpressionFactory()
var model : Model?
var fakeFetchModel : Model?
var sqlCalls = [ String ]()
public init(model: Model? = nil) {
self.model = model
}
public func openChannel() throws -> AdaptorChannel {
return FakeAdaptorChannel(adaptor: self)
}
public func fetchModel() throws -> Model {
return fakeFetchModel ?? model ?? Model(entities: [])
}
func fetchModelTag() throws -> ModelTag {
return FakeModelTag()
}
struct FakeModelTag : ModelTag {
public func isEqual(to object: Any?) -> Bool {
return object is FakeModelTag
}
}
class FakeAdaptorChannel : AdaptorChannel {
let expressionFactory : SQLExpressionFactory
let model : Model
weak var adaptor : FakeAdaptor?
init(adaptor: Adaptor) {
self.adaptor = adaptor as? FakeAdaptor
self.expressionFactory = adaptor.expressionFactory
self.model = (adaptor as? FakeAdaptor)?.fakeFetchModel
?? adaptor.model ?? Model(entities:[])
}
public func querySQL(_ sql: String, _ optAttrs: [Attribute]?,
cb: (AdaptorRecord) throws -> Void) throws
{
adaptor?.sqlCalls.append(sql)
}
func performSQL(_ sql: String) throws -> Int {
adaptor?.sqlCalls.append(sql)
return 0
}
func evaluateQueryExpression(_ sqlexpr : SQLExpression,
_ optAttrs : [ Attribute ]?,
result: ( AdaptorRecord ) throws -> Void) throws
{
adaptor?.sqlCalls.append(sqlexpr.statement)
}
func evaluateUpdateExpression(_ sqlexpr : SQLExpression) throws -> Int {
adaptor?.sqlCalls.append(sqlexpr.statement)
return 0
}
func describeTableNames() throws -> [ String ] {
return model.entities.map { $0.externalName ?? $0.name }
}
func describeSequenceNames() throws -> [ String ] { return [] }
func describeDatabaseNames() throws -> [ String ] { return [ "fake" ] }
func describeEntityWithTableName(_ table: String) throws -> Entity? {
return model[entityGroup: table].first
}
}
}
| apache-2.0 | f0bf403993c5b4412cb405833afd4fc8 | 26.181818 | 81 | 0.608696 | 4.341198 | false | false | false | false |
JohnnyHao/ForeignChat | ForeignChat/TabVCs/Friends/SearchViewController.swift | 1 | 4697 | //
// SearchViewController.swift
// ForeignChat
//
// Created by Tonny Hao on 3/1/15.
// Copyright (c) 2015 Tonny Hao. All rights reserved.
//
import UIKit
class SearchViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
var users = [PFUser]()
@IBOutlet var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.loadUsers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
}
func loadUsers() {
var user = PFUser.currentUser()
var query = PFQuery(className: PF_USER_CLASS_NAME)
query.whereKey(PF_USER_OBJECTID, notEqualTo: user.objectId)
query.orderByAscending(PF_USER_FULLNAME)
query.limit = 1000
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.users.removeAll(keepCapacity: false)
self.users += objects as [PFUser]!
self.tableView.reloadData()
} else {
ProgressHUD.showError("Network error")
}
}
}
func searchUsers(searchString: String) {
let user = PFUser.currentUser()
var query = PFQuery(className: PF_USER_CLASS_NAME)
query.whereKey(PF_USER_OBJECTID, notEqualTo: user.objectId)
query.whereKey(PF_USER_FULLNAME_LOWER, containsString: searchString)
query.orderByAscending(PF_USER_FULLNAME)
query.limit = 1000
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.users.removeAll(keepCapacity: false)
self.users += objects as [PFUser]!
self.tableView.reloadData()
} else {
ProgressHUD.showError("Network error")
}
}
}
@IBAction func cancelButtonPressed(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let user = self.users[indexPath.row]
cell.textLabel?.text = user[PF_USER_FULLNAME] as? String
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let user1 = PFUser.currentUser()
let user2 = users[indexPath.row]
let groupId = Messages.startPrivateChat(user1, user2: user2)
self.performSegueWithIdentifier("searchChatSegue", sender: groupId)
}
// MARK: - Prepare for segue to private chatVC
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "searchChatSegue" {
let chatVC = segue.destinationViewController as ChatViewController
chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as String
chatVC.groupId = groupId
}
}
// MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if countElements(searchText) > 0 {
self.searchUsers(searchText.lowercaseString)
} else {
self.loadUsers()
}
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.searchBar.text = ""
self.searchBar.resignFirstResponder()
self.loadUsers()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
| apache-2.0 | f3ff0864d4778aedf7b483dcb1c89de9 | 31.846154 | 118 | 0.634022 | 5.319366 | false | false | false | false |
slxl/ReactKit | Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift | 2 | 30759 | //
// UploadTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
class UploadFileInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndFile() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, urlString, file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndFile() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndData() {
// Given
let urlString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, urlString, data: Data())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndData() {
// Given
let urlString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], data: Data())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadStreamInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(.POST, urlString, stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataTestCase: BaseTestCase {
func testUploadDataRequest() {
// Given
let urlString = "https://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "Upload request should succeed: \(urlString)")
var request: URLRequest?
var response: HTTPURLResponse?
var error: NSError?
// When
Alamofire.upload(.POST, urlString, data: data)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testUploadDataRequestWithProgress() {
// Given
let urlString = "https://httpbin.org/post"
let data: Data = {
var text = ""
for _ in 1...3_000 {
text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}
return text.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(withDescription: "Bytes upload progress should be reported: \(urlString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: URLRequest?
var responseResponse: HTTPURLResponse?
var responseData: Data?
var responseError: ErrorProtocol?
// When
let upload = Alamofire.upload(.POST, urlString, data: data)
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNotNil(responseData, "response data should not be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
// MARK: -
class UploadMultipartFormDataTestCase: BaseTestCase {
// MARK: Tests
func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload_data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
}
func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNil(streamFileURL, "stream file URL should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
if let
streamingFromDisk = streamingFromDisk,
streamFilePath = streamFileURL?.path
{
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
XCTAssertTrue(
FileManager.default().fileExists(atPath: streamFilePath),
"stream file path should exist"
)
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
}
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
// ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1
// func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
// // Given
// let manager: Manager = {
// let identifier = "com.alamofire.uploadtests.\(UUID().uuidString)"
// let configuration = URLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier)
//
// return Manager(configuration: configuration, serverTrustPolicyManager: nil)
// }()
//
// let urlString = "https://httpbin.org/post"
// let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
// let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
//
// let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
//
// var request: URLRequest?
// var response: HTTPURLResponse?
// var data: Data?
// var error: NSError?
// var streamingFromDisk: Bool?
//
// // When
// manager.upload(
// .POST,
// urlString,
// multipartFormData: { multipartFormData in
// multipartFormData.appendBodyPart(data: french, name: "french")
// multipartFormData.appendBodyPart(data: japanese, name: "japanese")
// },
// encodingCompletion: { result in
// switch result {
// case let .success(upload, uploadStreamingFromDisk, _):
// streamingFromDisk = uploadStreamingFromDisk
//
// upload.response { responseRequest, responseResponse, responseData, responseError in
// request = responseRequest
// response = responseResponse
// data = responseData
// error = responseError
//
// expectation.fulfill()
// }
// case .failure:
// expectation.fulfill()
// }
// }
// )
//
// waitForExpectations(withTimeout: timeout, handler: nil)
//
// // Then
// XCTAssertNotNil(request, "request should not be nil")
// XCTAssertNotNil(response, "response should not be nil")
// XCTAssertNotNil(data, "data should not be nil")
// XCTAssertNil(error, "error should be nil")
//
// if let streamingFromDisk = streamingFromDisk {
// XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
// } else {
// XCTFail("streaming from disk should not be nil")
// }
// }
// MARK: Combined Test Execution
private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
// Given
let urlString = "https://httpbin.org/post"
let loremData1: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
}
return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let loremData2: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
}
return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: loremData1, name: "lorem1")
multipartFormData.appendBodyPart(data: loremData2, name: "lorem2")
},
encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (
bytes: bytesWritten,
totalBytes: totalBytesWritten,
totalBytesExpected: totalBytesExpectedToWrite
)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
| mit | 14974fee540a544f739b26b02ade9e80 | 38.957087 | 129 | 0.607772 | 5.798641 | false | false | false | false |
nathawes/swift | test/SourceKit/ConformingMethods/basic.swift | 1 | 1311 | protocol Target1 {}
protocol Target2 {}
protocol Target3 {}
struct ConcreteTarget1 : Target1 {}
struct ConcreteTarget2 : Target2 {}
struct ConcreteTarget3 : Target3 {}
protocol P {
associatedtype Assoc
func protocolMethod(asc: Assoc) -> Self
}
extension P {
func protocolMethod(asc: Assoc) -> Self { return self }
}
class C : P {
typealias Assoc = String
static func staticMethod() -> Self {}
func instanceMethod(x: Int) -> C {}
func methodForTarget1() -> ConcreteTarget1 {}
func methodForTarget2() -> ConcreteTarget2 {}
}
func testing(obj: C) {
let _ = obj.
}
// RUN: %sourcekitd-test \
// RUN: -req=conformingmethods -pos=26:14 -repeat-request=2 %s -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' -- -module-name MyModule %s > %t.response
// RUN: %diff -u %s.response %t.response
// RUN: %sourcekitd-test \
// RUN: -req=global-config -req-opts=completion_max_astcontext_reuse_count=0 == \
// RUN: -req=conformingmethods -pos=26:14 -repeat-request=2 %s -req-opts=expectedtypes='$s8MyModule7Target2PD;$s8MyModule7Target1PD' -- -module-name MyModule %s | %FileCheck %s --check-prefix=DISABLED
// DISABLED-NOT: key.reuseastcontext
// DISABLED: key.members: [
// DISABLED-NOT: key.reuseastcontext
// DISABLED: key.members: [
// DISABLED-NOT: key.reuseastcontext
| apache-2.0 | e818d664033cec52050771910efe7157 | 31.775 | 202 | 0.710908 | 3.310606 | false | true | false | false |
evanhughes3/reddit-news-swift | reddit-news-swift/Domain/Models/ArticlesResponse.swift | 1 | 391 | import Foundation
enum ArticlesResponse: Equatable {
case Success([Article])
case Error(NetworkError)
}
func == (lhs: ArticlesResponse, rhs: ArticlesResponse) -> Bool {
switch (lhs, rhs) {
case (.Success(let val1), .Success(let val2)) where val1 == val2: return true
case (.Error(let error1), .Error(let error2)) where error1 == error2: return true
default: return false
}
}
| mit | 9297b2083c64c73ea1347e424ac65e37 | 26.928571 | 83 | 0.700767 | 3.554545 | false | false | false | false |
warrenm/slug-swift-metal | SwiftMetalDemo/SphereGenerator.swift | 1 | 2241 | //
// SphereGenerator.swift
// SwiftMetalDemo
//
// Created by Warren Moore on 11/4/14.
// Copyright (c) 2014 Warren Moore. All rights reserved.
//
import Metal
struct SphereGenerator
{
static func sphereWithRadius(_ radius: Float, stacks: Int, slices: Int, device: MTLDevice) -> (MTLBuffer, MTLBuffer)
{
let pi = Float.pi
let twoPi = pi * 2
let deltaPhi = pi / Float(stacks)
let deltaTheta = twoPi / Float(slices)
var vertices = [Vertex]()
var indices = [UInt16]()
var phi = Float.pi / 2
for _ in 0...stacks
{
var theta:Float = 0
for slice in 0...slices
{
let x = cos(theta) * cos(phi)
let y = sin(phi)
let z = sin(theta) * cos(phi)
let position = Vector4(x: radius * x, y: radius * y, z: radius * z, w: 1)
let normal = Vector4(x: x, y: y, z: z, w: 0)
let texCoords = TexCoords(u: 1 - Float(slice) / Float(slices), v: 1 - (sin(phi) + 1) * 0.5)
let vertex = Vertex(position: position, normal: normal, texCoords: texCoords)
vertices.append(vertex)
theta += deltaTheta
}
phi += deltaPhi
}
for stack in 0...stacks
{
for slice in 0..<slices
{
let i0 = UInt16(slice + stack * slices)
let i1 = i0 + 1
let i2 = i0 + UInt16(slices)
let i3 = i2 + 1
indices.append(i0)
indices.append(i2)
indices.append(i3)
indices.append(i0)
indices.append(i3)
indices.append(i1)
}
}
let vertexBuffer = device.makeBuffer(bytes: vertices, length:MemoryLayout<Vertex>.stride * vertices.count, options:[])
let indexBuffer = device.makeBuffer(bytes: indices, length:MemoryLayout<UInt16>.stride * indices.count, options:[])
return (vertexBuffer!, indexBuffer!)
}
}
| mit | 53dc2086819199465df9c245ac5650bb | 30.125 | 126 | 0.475234 | 4.293103 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Contacts/ContactCell.swift | 1 | 3304 | //
// SupportCell.swift
// PennMobile
//
// Created by Josh Doman on 8/12/17.
// Copyright © 2017 PennLabs. All rights reserved.
//
import UIKit
class ContactCell: UITableViewCell {
var contact: SupportItem! {
didSet {
contactNameLabel.text = contact.name
textLabel?.text = contact.name
setDetailTextLabel()
}
}
var isExpanded: Bool = false {
didSet {
setDetailTextLabel()
}
}
func setDetailTextLabel() {
if isExpanded, let phoneNumber = contact?.phone {
if let description = self.contact?.descriptionText {
self.detailTextLabel?.text = String(format: "%@\n%@", arguments: [phoneNumber, description])
} else {
self.detailTextLabel?.text = phoneNumber
}
} else {
detailTextLabel?.text = nil
}
}
private lazy var phoneButton: UIButton = {
let phoneImage = UIImage(named: "phone.png")
let phoneButton = UIButton(type: .custom)
phoneButton.translatesAutoresizingMaskIntoConstraints = false
phoneButton.setImage(phoneImage, for: .normal)
phoneButton.addTarget(self, action: #selector(handleCall(_:)), for: .touchUpInside)
phoneButton.isUserInteractionEnabled = true
return phoneButton
}()
private let contactNameLabel: UILabel = {
let contactLabel = UILabel()
contactLabel.font = UIFont(name: "HelveticaNeue", size: 18)
contactLabel.text = "Penn Walk"
contactLabel.translatesAutoresizingMaskIntoConstraints = false
return contactLabel
}()
weak var delegate: ContactCellDelegate?
override func layoutSubviews() {
super.layoutSubviews()
textLabel?.frame = CGRect(x: 64, y: textLabel!.frame.origin.y, width: textLabel!.frame.width, height: textLabel!.frame.height)
detailTextLabel?.frame = CGRect(x: 64, y: detailTextLabel!.frame.origin.y, width: contentView.bounds.width - 64 - 20, height: detailTextLabel!.frame.height)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
self.detailTextLabel?.numberOfLines = 5
let fakeButton = UIButton()
fakeButton.isUserInteractionEnabled = true
fakeButton.addTarget(self, action: #selector(handleCall(_:)), for: .touchUpInside)
addSubview(fakeButton)
addSubview(phoneButton)
_ = fakeButton.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 64, heightConstant: 0)
_ = phoneButton.anchor(nil, left: leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 16, bottomConstant: 0, rightConstant: 0, widthConstant: 30, heightConstant: 30)
phoneButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
@objc internal func handleCall(_ sender: UIButton) {
if let phoneNumber = contact.phoneFiltered {
delegate?.call(number: phoneNumber)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6de6795e77d73fc49f2d58fb808b3b71 | 34.516129 | 200 | 0.65274 | 4.793904 | false | false | false | false |
eofster/Telephone | Domain/UserAgentAudioDeviceNameToDeviceMap.swift | 1 | 1666 | //
// UserAgentAudioDeviceNameToDeviceMap.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
final class UserAgentAudioDeviceNameToDeviceMap {
private let devices: [UserAgentAudioDevice]
private var inputMap: [String: UserAgentAudioDevice] = [:]
private var outputMap: [String: UserAgentAudioDevice] = [:]
init(devices: [UserAgentAudioDevice]) {
self.devices = devices
devices.forEach(updateInputDeviceMap)
devices.forEach(updateOutputDeviceMap)
}
func inputDevice(named name: String) -> UserAgentAudioDevice {
return inputMap[name] ?? NullUserAgentAudioDevice()
}
func outputDevice(named name: String) -> UserAgentAudioDevice {
return outputMap[name] ?? NullUserAgentAudioDevice()
}
private func updateInputDeviceMap(with device: UserAgentAudioDevice) {
if device.hasInputs {
inputMap[device.name] = device
}
}
private func updateOutputDeviceMap(with device: UserAgentAudioDevice) {
if device.hasOutputs {
outputMap[device.name] = device
}
}
}
| gpl-3.0 | 5892c9eb811d0050ec2dbb04ad25f0f8 | 32.959184 | 75 | 0.703726 | 4.473118 | false | false | false | false |
ikemai/FullingSwiper | FullingSwiper/FullingSwiperTransition.swift | 1 | 8737 | //
// FullingSwiperTransition.swift
// FullingSwiper
//
// Created by Mai Ikeda on 2016/03/04.
// Copyright © 2016年 mai_ikeda. All rights reserved.
//
import UIKit
class FullingSwiperTransition: UIPercentDrivenInteractiveTransition {
// Closures
var popHandler: (() -> Void)?
var completed: (() -> Void)?
var shouldBeginGestureHandler: ((UIGestureRecognizer) -> Bool)?
// Can set paramators
// duration is the time when (pop or push) animation. Default is 0.3.
var animateDuration: NSTimeInterval = 0.3
// hideRatio is the value that less than hideRatio cancel pop. Default is 0.2.
var hideRatio: CGFloat = 0.2
// scale is under view scale when (pop or push) animation. Default is 1.
var scale: CGFloat = 1
// Animation
private var operation: UINavigationControllerOperation = .None
// Gesture
private var gestureBeginX: CGFloat = 0
private var beforeX = BeforeX(first: 0, last: 0)
private var poping = false
func removeHandlers() {
popHandler = nil
completed = nil
shouldBeginGestureHandler = nil
}
func createGesture() -> UIPanGestureRecognizer {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(FullingSwiperTransition.fullingSwiperPanGesture))
gesture.delegate = self
return gesture
}
}
// MARK: - Struct
extension FullingSwiperTransition {
struct BeforeX {
let first: CGFloat
let last: CGFloat
init(first: CGFloat, last: CGFloat) {
self.first = first
self.last = last
}
}
}
// MARK: - Gesture
extension FullingSwiperTransition: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
return shouldBeginGestureHandler?(gestureRecognizer) ?? true
}
func fullingSwiperPanGesture(gesture: UIPanGestureRecognizer) {
guard let view = gesture.view else { return }
switch gesture.state {
case .Began:
let rightDirection = gesture.translationInView(view).x >= 0
poping = rightDirection
guard rightDirection else { return }
gestureBeginX = gesture.locationInView(view).x
popHandler?()
case .Changed:
guard poping else { return }
let distanceX = gesture.locationInView(view).x - gestureBeginX
let ratio = distanceX / view.bounds.width
let percentComplete = max(0, min(1, ratio))
updateInteractiveTransition(percentComplete)
case .Ended, .Cancelled, .Failed:
guard poping else { return }
let hidableX = view.bounds.width * hideRatio
let x = gesture.locationInView(view).x
let distanceX = x - gestureBeginX
let reversed = beforeX.first > x
if distanceX > hidableX && reversed == false {
finishInteractiveTransition()
completed?()
} else {
cancelInteractiveTransition()
}
beforeX = BeforeX(first: 0, last: 0)
gestureBeginX = 0
poping = false
default:
break
}
if poping {
let first = beforeX.last
beforeX = BeforeX(first: first, last: gesture.locationInView(view).x)
}
}
}
// MARK: - UINavigationControllerDelegate
extension FullingSwiperTransition: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.operation = operation
return self
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return poping ? self : nil
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension FullingSwiperTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return animateDuration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey),
containerView = transitionContext.containerView() else { return }
let isPop = (operation == .Pop)
let toView = isPop ? fromViewController.view : toViewController.view
let fromView = isPop ? toViewController.view : fromViewController.view
// toView
let toViewMaxX: CGFloat = containerView.frame.width
toView.frame = containerView.bounds
toView.transform = isPop ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(toViewMaxX, 0)
let shadow = shadowView(containerView.bounds.height)
toView.addSubview(shadow)
// fromView
let scale = self.scale
fromView.frame = containerView.bounds
let framViewMinX = -(fromView.bounds.width / 4)
fromView.transform = isPop ? CGAffineTransformMakeTranslation(framViewMinX, 0) : CGAffineTransformIdentity
if scale != 1 {
fromView.transform = isPop ? CGAffineTransformMakeScale(scale, scale) : CGAffineTransformIdentity
}
// containerView
let overlayView = UIView(frame: containerView.bounds)
containerView.insertSubview(toViewController.view, aboveSubview: fromViewController.view)
if isPop {
containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)
overlayView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
fromView.addSubview(overlayView)
}
UIView.animateWithDuration(animateDuration,
delay: 0,
options: .CurveLinear,
animations: { [weak shadow, weak toView, weak fromView, weak overlayView] in
toView?.transform = isPop ? CGAffineTransformMakeTranslation(toViewMaxX, 0) : CGAffineTransformIdentity
fromView?.transform = isPop ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(framViewMinX, 0)
shadow?.alpha = isPop ? 0 : 1
if scale != 1 {
fromView?.transform = isPop ? CGAffineTransformIdentity : CGAffineTransformMakeScale(scale, scale)
}
if isPop {
overlayView?.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0)
}
}, completion: { [weak shadow, weak toView, weak fromView, weak overlayView, weak transitionContext] _ in
toView?.transform = CGAffineTransformIdentity
fromView?.transform = CGAffineTransformIdentity
let completed = transitionContext?.transitionWasCancelled() == false
transitionContext?.completeTransition(completed)
shadow?.removeFromSuperview()
overlayView?.removeFromSuperview()
})
}
}
// MARK: - Private method, for shadow view
private extension FullingSwiperTransition {
func shadowView(height: CGFloat) -> UIView {
let shadowWidth: CGFloat = 10
let shadow = UIView(frame: CGRect(x: -shadowWidth, y: 0, width: shadowWidth, height: height))
insertLayerVerticallyGradient(shadow)
return shadow
}
func insertLayerVerticallyGradient(view: UIView) {
let layer = CAGradientLayer()
layer.frame = view.bounds
let color = UIColor.blackColor()
layer.colors = [
color.colorWithAlphaComponent(0.3).CGColor,
color.colorWithAlphaComponent(0.2).CGColor,
color.colorWithAlphaComponent(0.05).CGColor,
color.colorWithAlphaComponent(0).CGColor
]
layer.locations = [0, 0.1, 0.5, 1]
layer.startPoint = CGPointMake(1, 0.5)
layer.endPoint = CGPointMake(0, 0.5)
view.layer.insertSublayer(layer, atIndex: 0)
}
}
| mit | 519d64a6ba6e16667c14d2592744fef8 | 37.991071 | 281 | 0.645523 | 5.623954 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.