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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jondwillis/Swinject | SwinjectTests/iOS/SwinjectStoryboardSpec.swift | 1 | 5580 | //
// SwinjectStoryboardSpec.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/31/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
@testable import Swinject
class SwinjectStoryboardSpec: QuickSpec {
override func spec() {
let bundle = NSBundle(forClass: SwinjectStoryboardSpec.self)
var container: Container!
beforeEach {
container = Container()
}
describe("Instantiation from storyboard") {
it("injects dependency definded by initCompleted handler.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateViewControllerWithIdentifier("AnimalAsCat") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
it("injects dependency to child view controllers.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat() }
.inObjectScope(.Container)
let storyboard = SwinjectStoryboard.create(name: "Tabs", bundle: bundle, container: container)
let tabBarController = storyboard.instantiateViewControllerWithIdentifier("TabBarController")
let animalViewController1 = tabBarController.childViewControllers[0] as! AnimalViewController
let animalViewController2 = tabBarController.childViewControllers[1] as! AnimalViewController
let cat1 = animalViewController1.animal as! Cat
let cat2 = animalViewController2.animal as! Cat
expect(cat1) === cat2
}
context("with a registration name set as a user defined runtime attribute on Interface Builder") {
it("injects dependency definded by initCompleted handler with the registration name.") {
// The registration name "hachi" is set in the storyboard.
container.registerForStoryboard(AnimalViewController.self, name: "hachi") { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Dog(name: "Hachi") }
// This registration should not be resolved.
container.registerForStoryboard(AnimalViewController.self) { _, c in
c.animal = Cat(name: "Mimi")
}
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateViewControllerWithIdentifier("AnimalAsDog") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Hachi")) == true
}
}
context("with container hierarchy") {
it("injects view controller dependency definded in the parent container.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let childContainer = Container(parent: container)
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: childContainer)
let animalViewController = storyboard.instantiateViewControllerWithIdentifier("AnimalAsCat") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
}
}
describe("Initial view controller") {
it("injects dependency definded by initCompleted handler.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateInitialViewController() as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
}
describe("Factory method") {
it("uses the default shared container if no container is passed.") {
Container.defaultContainer.registerForStoryboard(AnimalViewController.self) { _, _ in }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle)
let animalViewController = storyboard.instantiateViewControllerWithIdentifier("AnimalAsCat")
expect(animalViewController).notTo(beNil())
}
afterEach {
Container.defaultContainer.removeAll()
}
}
}
}
| mit | 310003747f7bbd20375b531e2e00e2d4 | 52.133333 | 137 | 0.595806 | 6.031351 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Timeout.swift | 8 | 5530 | //
// Timeout.swift
// RxSwift
//
// Created by Tomi Koskinen on 13/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a `RxError.timeout` in case of a timeout.
*/
public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
public func timeout<Source: ObservableConvertibleType>(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType)
-> Observable<Element> where Element == Source.Element {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler)
}
}
final private class TimeoutSink<Observer: ObserverType>: Sink<Observer>, LockOwnerType, ObserverType {
typealias Element = Observer.Element
typealias Parent = Timeout<Element>
private let parent: Parent
let lock = RecursiveLock()
private let timerD = SerialDisposable()
private let subscription = SerialDisposable()
private var id = 0
private var switched = false
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let original = SingleAssignmentDisposable()
self.subscription.disposable = original
self.createTimeoutTimer()
original.setDisposable(self.parent.source.subscribe(self))
return Disposables.create(subscription, timerD)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
var onNextWins = false
self.lock.performLocked {
onNextWins = !self.switched
if onNextWins {
self.id = self.id &+ 1
}
}
if onNextWins {
self.forwardOn(event)
self.createTimeoutTimer()
}
case .error, .completed:
var onEventWins = false
self.lock.performLocked {
onEventWins = !self.switched
if onEventWins {
self.id = self.id &+ 1
}
}
if onEventWins {
self.forwardOn(event)
self.dispose()
}
}
}
private func createTimeoutTimer() {
if self.timerD.isDisposed {
return
}
let nextTimer = SingleAssignmentDisposable()
self.timerD.disposable = nextTimer
let disposeSchedule = self.parent.scheduler.scheduleRelative(self.id, dueTime: self.parent.dueTime) { state in
var timerWins = false
self.lock.performLocked {
self.switched = (state == self.id)
timerWins = self.switched
}
if timerWins {
self.subscription.disposable = self.parent.other.subscribe(self.forwarder())
}
return Disposables.create()
}
nextTimer.setDisposable(disposeSchedule)
}
}
final private class Timeout<Element>: Producer<Element> {
fileprivate let source: Observable<Element>
fileprivate let dueTime: RxTimeInterval
fileprivate let other: Observable<Element>
fileprivate let scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, other: Observable<Element>, scheduler: SchedulerType) {
self.source = source
self.dueTime = dueTime
self.other = other
self.scheduler = scheduler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 681cdc1464c941e1a6cf5da8d219be99 | 35.615894 | 316 | 0.630675 | 5.342029 | false | false | false | false |
wangjianquan/wjKeyBoard | wjKeyBoard/PicPicker/PicPickerViewContro.swift | 1 | 3536 | //
// PicPickViewContro.swift
// wjKeyBoard
//
// Created by landixing on 2017/6/29.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
private let edgeMargin : CGFloat = 8
private let imageMargin : CGFloat = 8
class PicPickerViewContro: UICollectionViewController {
//图片数组
var images: [UIImage] = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
// self.collectionView?.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView?.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func imagePickerControll() {
if !UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
return
}
let pickerControll = UIImagePickerController()
pickerControll.sourceType = .savedPhotosAlbum
pickerControll.delegate = self
present(pickerControll, animated: true, completion: nil)
}
}
// MARK: UICollectionViewDelegate
class layout : UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
let imageHW = (UIScreen.main.bounds.width - 2 * edgeMargin - 2 * imageMargin) / 3
itemSize = CGSize(width: imageHW, height: imageHW)
minimumLineSpacing = imageMargin
minimumInteritemSpacing = imageMargin
collectionView?.contentInset = UIEdgeInsets(top: edgeMargin, left: edgeMargin, bottom: edgeMargin, right: edgeMargin)
collectionView?.backgroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1.0)
}
}
// MARK: UICollectionViewDataSource
extension PicPickerViewContro{
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count + 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicCollectionViewCell
cell.delegate = self
cell.image = indexPath.item < images.count ? images[indexPath.item] : nil
return cell
}
}
extension PicPickerViewContro: picCellDelegate {
func picPickerViewCellWithAddPhoto(_ cell: PicCollectionViewCell) {
imagePickerControll()
}
func picPickerViewCellWithRemovePhoto(_ cell: PicCollectionViewCell) {
let index = (collectionView?.indexPath(for: cell))!
images.remove(at: index.item)
collectionView?.reloadData()
}
}
extension PicPickerViewContro : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
images.append(image)
collectionView?.reloadData()
picker.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | cba599947e5018aee133084e5f37ad5e | 27.2 | 133 | 0.664965 | 5.533752 | false | false | false | false |
DarrenKong/firefox-ios | XCUITests/FxScreenGraph.swift | 1 | 37475 | /* 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 MappaMundi
import XCTest
let FirstRun = "OptionalFirstRun"
let TabTray = "TabTray"
let PrivateTabTray = "PrivateTabTray"
let NewTabScreen = "NewTabScreen"
let URLBarOpen = "URLBarOpen"
let URLBarLongPressMenu = "URLBarLongPressMenu"
let ReloadLongPressMenu = "ReloadLongPressMenu"
let PrivateURLBarOpen = "PrivateURLBarOpen"
let BrowserTab = "BrowserTab"
let PrivateBrowserTab = "PrivateBrowserTab"
let BrowserTabMenu = "BrowserTabMenu"
let PageOptionsMenu = "PageOptionsMenu"
let FindInPage = "FindInPage"
let SettingsScreen = "SettingsScreen"
let SyncSettings = "SyncSettings"
let HomePageSettings = "HomePageSettings"
let PasscodeSettings = "PasscodeSettings"
let PasscodeIntervalSettings = "PasscodeIntervalSettings"
let SearchSettings = "SearchSettings"
let NewTabSettings = "NewTabSettings"
let ClearPrivateDataSettings = "ClearPrivateDataSettings"
let LoginsSettings = "LoginsSettings"
let OpenWithSettings = "OpenWithSettings"
let ShowTourInSettings = "ShowTourInSettings"
let TrackingProtectionSettings = "TrackingProtectionSettings"
let Intro_FxASignin = "Intro_FxASignin"
let WebImageContextMenu = "WebImageContextMenu"
let WebLinkContextMenu = "WebLinkContextMenu"
let CloseTabMenu = "CloseTabMenu"
let AddCustomSearchSettings = "AddCustomSearchSettings"
let NewTabChoiceSettings = "NewTabChoiceSettings"
let DisablePasscodeSettings = "DisablePasscodeSettings"
let ChangePasscodeSettings = "ChangePasscodeSettings"
let LockedLoginsSettings = "LockedLoginsSettings"
let TabTrayLongPressMenu = "TabTrayLongPressMenu"
// These are in the exact order they appear in the settings
// screen. XCUIApplication loses them on small screens.
// This list should only be for settings screens that can be navigated to
// without changing userState. i.e. don't need conditional edges to be available
let allSettingsScreens = [
SearchSettings,
AddCustomSearchSettings,
NewTabSettings,
NewTabChoiceSettings,
HomePageSettings,
OpenWithSettings,
LoginsSettings,
PasscodeSettings,
ClearPrivateDataSettings,
TrackingProtectionSettings,
]
let HistoryPanelContextMenu = "HistoryPanelContextMenu"
let TopSitesPanelContextMenu = "TopSitesPanelContextMenu"
let BasicAuthDialog = "BasicAuthDialog"
let BookmarksPanelContextMenu = "BookmarksPanelContextMenu"
let SetPasscodeScreen = "SetPasscodeScreen"
let Intro_Welcome = "Intro.Welcome"
let Intro_Search = "Intro.Search"
let Intro_Private = "Intro.Private"
let Intro_Mail = "Intro.Mail"
let Intro_Sync = "Intro.Sync"
let allIntroPages = [
Intro_Welcome,
Intro_Search,
Intro_Private,
Intro_Mail,
Intro_Sync
]
let HomePanelsScreen = "HomePanels"
let PrivateHomePanelsScreen = "PrivateHomePanels"
let HomePanel_TopSites = "HomePanel.TopSites.0"
let HomePanel_Bookmarks = "HomePanel.Bookmarks.1"
let HomePanel_History = "HomePanel.History.2"
let HomePanel_ReadingList = "HomePanel.ReadingList.3"
let allHomePanels = [
HomePanel_Bookmarks,
HomePanel_TopSites,
HomePanel_History,
HomePanel_ReadingList
]
class Action {
static let LoadURL = "LoadURL"
static let LoadURLByTyping = "LoadURLByTyping"
static let LoadURLByPasting = "LoadURLByPasting"
static let SetURL = "SetURL"
static let SetURLByTyping = "SetURLByTyping"
static let SetURLByPasting = "SetURLByPasting"
static let ReloadURL = "ReloadURL"
static let OpenNewTabFromTabTray = "OpenNewTabFromTabTray"
static let TogglePrivateMode = "TogglePrivateBrowing"
static let TogglePrivateModeFromTabBarHomePanel = "TogglePrivateModeFromTabBarHomePanel"
static let TogglePrivateModeFromTabBarBrowserTab = "TogglePrivateModeFromTabBarBrowserTab"
static let TogglePrivateModeFromTabBarNewTab = "TogglePrivateModeFromTabBarNewTab"
static let ToggleRequestDesktopSite = "ToggleRequestDesktopSite"
static let ToggleNightMode = "ToggleNightMode"
static let ToggleNoImageMode = "ToggleNoImageMode"
static let Bookmark = "Bookmark"
static let BookmarkThreeDots = "BookmarkThreeDots"
static let OpenPrivateTabLongPressTabsButton = "OpenPrivateTabLongPressTabsButton"
static let OpenNewTabLongPressTabsButton = "OpenNewTabLongPressTabsButton"
static let SetPasscode = "SetPasscode"
static let SetPasscodeTypeOnce = "SetPasscodeTypeOnce"
static let DisablePasscode = "DisablePasscode"
static let LoginPasscodeTypeIncorrectOne = "LoginPasscodeTypeIncorrectOne"
static let ChangePasscode = "ChangePasscode"
static let ChangePasscodeTypeOnce = "ChangePasscodeTypeOnce"
static let ConfirmPasscodeToChangePasscode = "ConfirmPasscodeToChangePasscode"
static let UnlockLoginsSettings = "UnlockLoginsSettings"
static let DisablePasscodeTypeIncorrectPasscode = "DisablePasscodeTypeIncorrectPasscode"
static let TogglePocketInNewTab = "TogglePocketInNewTab"
static let ToggleBookmarksInNewTab = "ToggleBookmarksInNewTab"
static let ToggleHistoryInNewTab = "ToggleHistoryInNewTab"
static let SelectNewTabAsBlankPage = "SelectNewTabAsBlankPage"
static let SelectNewTabAsBookmarksPage = "SelectNewTabAsBookmarksPage"
static let SelectNewTabAsHistoryPage = "SelectNewTabAsHistoryPage"
static let AcceptClearPrivateData = "AcceptClearPrivateData"
static let ToggleTrackingProtectionPerTabEnabled = "ToggleTrackingProtectionPerTabEnabled"
static let ToggleTrackingProtectionSettingAlwaysOn = "ToggleTrackingProtectionSettingAlwaysOn"
static let ToggleTrackingProtectionSettingPrivateOnly = "ToggleTrackingProtectionSettingPrivateOnly"
static let ToggleTrackingProtectionSettingOff = "ToggleTrackingProtectionSettingOff"
static let CloseTab = "CloseTab"
static let CloseTabFromPageOptions = "CloseTabFromPageOptions"
static let CloseTabFromTabTrayLongPressMenu = "CloseTabFromTabTrayLongPressMenu"
}
private var isTablet: Bool {
// There is more value in a variable having the same name,
// so it can be used in both predicates and in code
// than avoiding the duplication of one line of code.
return UIDevice.current.userInterfaceIdiom == .pad
}
// Matches the available options in app settings for enabling Tracking Protection
enum TrackingProtectionSetting : Int { case alwaysOn; case privateOnly; case off }
class FxUserState: MMUserState {
required init() {
super.init()
initialScreenState = FirstRun
}
var isPrivate = false
var showIntro = false
var showWhatsNew = false
var waitForLoading = true
var url: String? = nil
var requestDesktopSite = false
var passcode: String? = nil
var newPasscode: String = "111111"
var wrongPasscode: String = "111112"
var noImageMode = false
var nightMode = false
var pocketInNewTab = false
var bookmarksInNewTab = true
var historyInNewTab = true
var fxaUsername: String? = nil
var fxaPassword: String? = nil
var numTabs: Int = 0
var trackingProtectionPerTabEnabled = true // TP can be shut off on a per-tab basis
var trackingProtectionSetting = TrackingProtectionSetting.privateOnly.rawValue // NSPredicate doesn't work with enum
// Construct an NSPredicate with this condition to use it.
static let trackingProtectionIsOnCondition = "trackingProtectionSetting == \(TrackingProtectionSetting.alwaysOn.rawValue) || (trackingProtectionSetting == \(TrackingProtectionSetting.privateOnly.rawValue) && isPrivate == YES)"
}
fileprivate let defaultURL = "https://www.mozilla.org/en-US/book/"
func createScreenGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<FxUserState> {
let map = MMScreenGraph(for: test, with: FxUserState.self)
let navigationControllerBackAction = {
app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
let cancelBackAction = {
if isTablet {
// There is no Cancel option in iPad.
app/*@START_MENU_TOKEN@*/.otherElements["PopoverDismissRegion"]/*[[".otherElements[\"dismiss popup\"]",".otherElements[\"PopoverDismissRegion\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
} else {
app.buttons["PhotonMenu.cancel"].tap()
}
}
let cancelTypePasscode = {
if isTablet {
if (app.buttons["Cancel"].exists){
app.buttons["Cancel"].tap()
} else {
app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
} else {
app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
}
let dismissContextMenuAction = {
app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.25)).tap()
}
let introScrollView = app.scrollViews["IntroViewController.scrollView"]
map.addScreenState(FirstRun) { screenState in
screenState.noop(to: BrowserTab, if: "showIntro == false && showWhatsNew == true")
screenState.noop(to: NewTabScreen, if: "showIntro == false && showWhatsNew == false")
screenState.noop(to: allIntroPages[0], if: "showIntro == true")
}
// Add the intro screens.
var i = 0
let introLast = allIntroPages.count - 1
let introPager = app.scrollViews["IntroViewController.scrollView"]
for intro in allIntroPages {
let prev = i == 0 ? nil : allIntroPages[i - 1]
let next = i == introLast ? nil : allIntroPages[i + 1]
map.addScreenState(intro) { screenState in
if let prev = prev {
screenState.swipeRight(introPager, to: prev)
}
if let next = next {
screenState.swipeLeft(introPager, to: next)
}
if i > 0 {
let startBrowsingButton = app.buttons["IntroViewController.startBrowsingButton"]
screenState.tap(startBrowsingButton, to: BrowserTab)
}
}
i += 1
}
let noopAction = {}
// Some internally useful screen states.
let WebPageLoading = "WebPageLoading"
map.addScreenState(NewTabScreen) { screenState in
screenState.noop(to: HomePanelsScreen)
if isTablet {
screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray)
} else {
screenState.gesture(to: TabTray) {
if (app.buttons["TabToolbar.tabsButton"].exists) {
app.buttons["TabToolbar.tabsButton"].tap()
} else {
app.buttons["URLBarView.tabsButton"].tap()
}
}
}
makeURLBarAvailable(screenState)
screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu)
screenState.tap(app.buttons["Private Mode"], forAction: Action.TogglePrivateModeFromTabBarNewTab, if: "tablet == true") { userState in
userState.isPrivate = !userState.isPrivate
}
}
map.addScreenState(URLBarLongPressMenu) { screenState in
let menu = app.sheets.element(boundBy: 0)
screenState.onEnterWaitFor(element: menu)
screenState.gesture(forAction: Action.LoadURLByPasting, Action.LoadURL) { userState in
UIPasteboard.general.string = userState.url ?? defaultURL
menu.buttons.element(boundBy: 0).tap()
}
screenState.gesture(forAction: Action.SetURLByPasting) { userState in
UIPasteboard.general.string = userState.url ?? defaultURL
menu.buttons.element(boundBy: 1).tap()
}
screenState.backAction = {
let buttons = menu.buttons
buttons.element(boundBy: buttons.count - 1).tap()
}
screenState.dismissOnUse = true
}
// URLBarOpen is dismissOnUse, which ScreenGraph interprets as "now we've done this action, then go back to the one before it"
// but SetURL is an action than keeps us in URLBarOpen. So let's put it here.
map.addScreenAction(Action.SetURL, transitionTo: URLBarOpen)
map.addScreenState(URLBarOpen) { screenState in
// This is used for opening BrowserTab with default mozilla URL
// For custom URL, should use Navigator.openNewURL or Navigator.openURL.
screenState.gesture(forAction: Action.LoadURLByTyping, Action.LoadURL) { userState in
let url = userState.url ?? defaultURL
app.textFields["address"].typeText("\(url)\r")
}
screenState.gesture(forAction: Action.SetURLByTyping, Action.SetURL) { userState in
let url = userState.url ?? defaultURL
app.textFields["address"].typeText("\(url)")
}
screenState.noop(to: HomePanelsScreen)
screenState.backAction = {
app.buttons["urlBar-cancel"].tap()
}
screenState.dismissOnUse = true
}
// LoadURL points to WebPageLoading, which allows us to add additional
// onEntryWaitFor requirements, which we don't need when we're returning to BrowserTab without
// loading a webpage.
// We do end up at WebPageLoading however, so should lead quickly back to BrowserTab.
map.addScreenAction(Action.LoadURL, transitionTo: WebPageLoading)
map.addScreenState(WebPageLoading) { screenState in
screenState.dismissOnUse = true
// Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element
// but this means exposing some of SnapshotHelper to another target.
if !(app.progressIndicators.element(boundBy: 0).exists) {
screenState.onEnterWaitFor("exists != true", element: app.progressIndicators.element(boundBy: 0), if: "waitForLoading == true")
} else {
screenState.onEnterWaitFor(element: app.progressIndicators.element(boundBy: 0), if: "waitForLoading == false")
}
screenState.noop(to: BrowserTab, if: "waitForLoading == true")
screenState.noop(to: BasicAuthDialog, if: "waitForLoading == false")
}
map.addScreenState(BasicAuthDialog) { screenState in
screenState.onEnterWaitFor(element: app.alerts.element(boundBy: 0))
screenState.backAction = {
app.alerts.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
screenState.dismissOnUse = true
}
map.addScreenState(HomePanelsScreen) { screenState in
screenState.tap(app.buttons["HomePanels.TopSites"], to: HomePanel_TopSites)
screenState.tap(app.buttons["HomePanels.Bookmarks"], to: HomePanel_Bookmarks)
screenState.tap(app.buttons["HomePanels.History"], to: HomePanel_History)
screenState.tap(app.buttons["HomePanels.ReadingList"], to: HomePanel_ReadingList)
screenState.tap(app.buttons["Private Mode"], forAction: Action.TogglePrivateModeFromTabBarHomePanel, if: "tablet == true") { userState in
userState.isPrivate = !userState.isPrivate
}
// Workaround to bug Bug 1417522
if isTablet {
screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray)
} else {
screenState.gesture(to: TabTray) {
if (app.buttons["TabToolbar.tabsButton"].exists) {
app.buttons["TabToolbar.tabsButton"].tap()
} else {
app.buttons["URLBarView.tabsButton"].tap()
}
}
}
}
map.addScreenState(HomePanel_Bookmarks) { screenState in
let bookmarkCell = app.tables["Bookmarks List"].cells.element(boundBy: 0)
screenState.press(bookmarkCell, to: BookmarksPanelContextMenu)
screenState.noop(to: HomePanelsScreen)
}
map.addScreenState(HomePanel_TopSites) { screenState in
let topSites = app.cells["TopSitesCell"]
screenState.press(topSites.cells.matching(identifier: "TopSite").element(boundBy: 0), to: TopSitesPanelContextMenu)
screenState.noop(to: HomePanelsScreen)
}
map.addScreenState(HomePanel_History) { screenState in
screenState.press(app.tables["History List"].cells.element(boundBy: 2), to: HistoryPanelContextMenu)
screenState.noop(to: HomePanelsScreen)
}
map.addScreenState(HomePanel_ReadingList) { screenState in
screenState.noop(to: HomePanelsScreen)
}
map.addScreenState(HistoryPanelContextMenu) { screenState in
screenState.dismissOnUse = true
screenState.backAction = dismissContextMenuAction
}
map.addScreenState(TopSitesPanelContextMenu) { screenState in
screenState.dismissOnUse = true
screenState.backAction = dismissContextMenuAction
}
map.addScreenState(BookmarksPanelContextMenu) { screenState in
screenState.dismissOnUse = true
screenState.backAction = dismissContextMenuAction
}
map.addScreenState(SettingsScreen) { screenState in
let table = app.tables.element(boundBy: 0)
screenState.tap(table.cells["Sync"], to: SyncSettings, if: "fxaUsername != nil")
screenState.tap(table.cells["Search"], to: SearchSettings)
screenState.tap(table.cells["NewTab"], to: NewTabSettings)
screenState.tap(table.cells["Homepage"], to: HomePageSettings)
screenState.tap(table.cells["OpenWith.Setting"], to: OpenWithSettings)
screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettings)
screenState.tap(table.cells["Logins"], to: LoginsSettings, if: "passcode == nil")
screenState.tap(table.cells["Logins"], to: LockedLoginsSettings, if: "passcode != nil")
screenState.tap(table.cells["ClearPrivateData"], to: ClearPrivateDataSettings)
screenState.tap(table.cells["TrackingProtection"], to: TrackingProtectionSettings)
screenState.tap(table.cells["ShowTour"], to: ShowTourInSettings)
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(SearchSettings) { screenState in
let table = app.tables.element(boundBy: 0)
screenState.tap(table.cells["customEngineViewButton"], to: AddCustomSearchSettings)
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(SyncSettings) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(AddCustomSearchSettings) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(NewTabSettings) { screenState in
let table = app.tables.element(boundBy: 0)
screenState.tap(table.cells["NewTabOption"], to: NewTabChoiceSettings)
screenState.gesture(forAction: Action.TogglePocketInNewTab) { userState in
userState.pocketInNewTab = !userState.pocketInNewTab
table.switches["ASPocketStoriesVisible"].tap()
}
screenState.gesture(forAction: Action.ToggleBookmarksInNewTab) { userState in
userState.bookmarksInNewTab = !userState.bookmarksInNewTab
table.switches["ASBookmarkHighlightsVisible"].tap()
}
screenState.gesture(forAction: Action.ToggleHistoryInNewTab) { userState in
userState.historyInNewTab = !userState.historyInNewTab
table.switches["ASRecentHighlightsVisible"].tap()
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(NewTabChoiceSettings) { screenState in
let table = app.tables["NewTabPage.Setting.Options"]
screenState.backAction = navigationControllerBackAction
screenState.gesture(forAction: Action.SelectNewTabAsBlankPage) { UserState in
table.cells["Blank"].tap()
}
screenState.gesture(forAction: Action.SelectNewTabAsBookmarksPage) { UserState in
table.cells["Bookmarks"].tap()
}
screenState.gesture(forAction: Action.SelectNewTabAsHistoryPage) { UserState in
table.cells["History"].tap()
}
}
map.addScreenState(HomePageSettings) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeSettings) { screenState in
screenState.backAction = navigationControllerBackAction
let table = app.tables.element(boundBy: 0)
screenState.tap(table.cells["TurnOnPasscode"], to: SetPasscodeScreen, if: "passcode == nil")
screenState.tap(table.cells["TurnOffPasscode"], to: DisablePasscodeSettings, if: "passcode != nil")
screenState.tap(table.cells["PasscodeInterval"], to: PasscodeIntervalSettings, if: "passcode != nil")
screenState.tap(table.cells["ChangePasscode"], to: ChangePasscodeSettings, if: "passcode != nil")
}
func typePasscode(_ passCode: String) {
passCode.forEach { char in
app.keys["\(char)"].tap()
}
}
map.addScreenState(SetPasscodeScreen) { screenState in
screenState.gesture(forAction: Action.SetPasscode, transitionTo: PasscodeSettings) { userState in
typePasscode(userState.newPasscode)
typePasscode(userState.newPasscode)
userState.passcode = userState.newPasscode
}
screenState.gesture(forAction: Action.SetPasscodeTypeOnce) { userState in
typePasscode(userState.newPasscode)
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(DisablePasscodeSettings) { screenState in
screenState.gesture(forAction: Action.DisablePasscode, transitionTo: PasscodeSettings) { userState in
if let passcode = userState.passcode {
typePasscode(passcode)
}
}
screenState.gesture(forAction: Action.DisablePasscodeTypeIncorrectPasscode) { userState in
typePasscode(userState.wrongPasscode)
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeIntervalSettings) { screenState in
screenState.onEnter { userState in
if let passcode = userState.passcode {
typePasscode(passcode)
}
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(ChangePasscodeSettings) { screenState in
screenState.gesture(forAction: Action.ChangePasscode, transitionTo: PasscodeSettings) { userState in
if let passcode = userState.passcode {
typePasscode(passcode)
typePasscode(userState.newPasscode)
typePasscode(userState.newPasscode)
userState.passcode = userState.newPasscode
}
}
screenState.gesture(forAction: Action.ConfirmPasscodeToChangePasscode) { userState in
if let passcode = userState.passcode {
typePasscode(passcode)
}
}
screenState.gesture(forAction: Action.ChangePasscodeTypeOnce) { userState in
typePasscode(userState.newPasscode)
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(LoginsSettings) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(LockedLoginsSettings) { screenState in
screenState.backAction = cancelTypePasscode
screenState.dismissOnUse = true
screenState.gesture(forAction: Action.LoginPasscodeTypeIncorrectOne) { userState in
typePasscode(userState.wrongPasscode)
}
// Gesture to get to the protected screen.
screenState.gesture(forAction: Action.UnlockLoginsSettings, transitionTo: LoginsSettings) { userState in
if let passcode = userState.passcode {
typePasscode(passcode)
}
}
}
map.addScreenState(ClearPrivateDataSettings) { screenState in
screenState.gesture(forAction: Action.AcceptClearPrivateData) { userState in
app.tables.cells["ClearPrivateData"].tap()
app.alerts.buttons["OK"].tap()
}
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(OpenWithSettings) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(ShowTourInSettings) { screenState in
screenState.gesture(to: Intro_FxASignin) {
let introScrollView = app.scrollViews["IntroViewController.scrollView"]
for _ in 1...4 {
introScrollView.swipeLeft()
}
app.buttons["Sign in to Firefox"].tap()
}
screenState.backAction = {
introScrollView.swipeLeft()
let startBrowsingButton = app.buttons["IntroViewController.startBrowsingButton"]
startBrowsingButton.tap()
}
}
map.addScreenState(TrackingProtectionSettings) { screenState in
screenState.backAction = navigationControllerBackAction
screenState.tap(app.cells["Settings.TrackingProtectionOption.OnLabel"], forAction: Action.ToggleTrackingProtectionSettingAlwaysOn) { userState in
userState.trackingProtectionSetting = TrackingProtectionSetting.alwaysOn.rawValue
}
screenState.tap(app.cells["Settings.TrackingProtectionOption.OnInPrivateBrowsingLabel"], forAction: Action.ToggleTrackingProtectionSettingPrivateOnly) { userState in
userState.trackingProtectionSetting = TrackingProtectionSetting.privateOnly.rawValue
}
screenState.tap(app.cells["Settings.TrackingProtectionOption.OffLabel"], forAction: Action.ToggleTrackingProtectionSettingOff) { userState in
userState.trackingProtectionSetting = TrackingProtectionSetting.off.rawValue
}
}
map.addScreenState(Intro_FxASignin) { screenState in
screenState.tap(app.navigationBars["Client.FxAContentView"].buttons.element(boundBy: 0), to: HomePanelsScreen)
}
map.addScreenState(TabTray) { screenState in
screenState.tap(app.buttons["TabTrayController.addTabButton"], forAction: Action.OpenNewTabFromTabTray, transitionTo: NewTabScreen)
screenState.tap(app.buttons["TabTrayController.maskButton"], forAction: Action.TogglePrivateMode) { userState in
userState.isPrivate = !userState.isPrivate
}
screenState.tap(app.buttons["TabTrayController.removeTabsButton"], to: CloseTabMenu)
screenState.onEnter { userState in
userState.numTabs = Int(app.collectionViews.cells.count)
}
}
// This menu is only available for iPhone, NOT for iPad, no menu when long tapping on tabs button
if !isTablet {
map.addScreenState(TabTrayLongPressMenu) { screenState in
screenState.dismissOnUse = true
screenState.tap(app.buttons["New Tab"], forAction: Action.OpenNewTabLongPressTabsButton, transitionTo: NewTabScreen)
screenState.tap(app.buttons["New Private Tab"], forAction: Action.OpenPrivateTabLongPressTabsButton, transitionTo: NewTabScreen) { userState in
userState.isPrivate = !userState.isPrivate
}
screenState.tap(app.buttons["Close Tab"], forAction: Action.CloseTabFromTabTrayLongPressMenu, Action.CloseTab, transitionTo: HomePanelsScreen)
}
}
map.addScreenState(CloseTabMenu) { screenState in
screenState.backAction = cancelBackAction
}
let lastButtonIsCancel = {
let lastIndex = app.sheets.element(boundBy: 0).buttons.count - 1
app.sheets.element(boundBy: 0).buttons.element(boundBy: lastIndex).tap()
}
func makeURLBarAvailable(_ screenState: MMScreenStateNode<FxUserState>) {
screenState.tap(app.textFields["url"], to: URLBarOpen)
screenState.gesture(to: URLBarLongPressMenu) {
app.textFields["url"].press(forDuration: 1.0)
}
}
func makeToolBarAvailable(_ screenState: MMScreenStateNode<FxUserState>) {
screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu)
if isTablet {
screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray)
} else {
screenState.gesture(to: TabTray) {
if (app.buttons["TabToolbar.tabsButton"].exists) {
app.buttons["TabToolbar.tabsButton"].tap()
} else {
app.buttons["URLBarView.tabsButton"].tap()
}
}
}
}
map.addScreenState(BrowserTab) { screenState in
makeURLBarAvailable(screenState)
screenState.tap(app.buttons["TabLocationView.pageOptionsButton"], to: PageOptionsMenu)
makeToolBarAvailable(screenState)
let link = app.webViews.element(boundBy: 0).links.element(boundBy: 0)
let image = app.webViews.element(boundBy: 0).images.element(boundBy: 0)
screenState.press(link, to: WebLinkContextMenu)
screenState.press(image, to: WebImageContextMenu)
let reloadButton = app.buttons["TabToolbar.stopReloadButton"]
screenState.press(reloadButton, to: ReloadLongPressMenu)
screenState.tap(reloadButton, forAction: Action.ReloadURL, transitionTo: WebPageLoading) { _ in }
// For iPad there is no long press on tabs button
if !isTablet {
let tabsButton = app.buttons["TabToolbar.tabsButton"]
screenState.press(tabsButton, to: TabTrayLongPressMenu)
}
screenState.tap(app.buttons["Private Mode"], forAction: Action.TogglePrivateModeFromTabBarBrowserTab) { userState in
userState.isPrivate = !userState.isPrivate
}
}
map.addScreenState(ReloadLongPressMenu) { screenState in
screenState.backAction = lastButtonIsCancel
screenState.dismissOnUse = true
let rdsButton = app.sheets.element(boundBy: 0).buttons.element(boundBy: 0)
screenState.tap(rdsButton, forAction: Action.ToggleRequestDesktopSite) { userState in
userState.requestDesktopSite = !userState.requestDesktopSite
}
let trackingProtectionButton = app.sheets.element(boundBy: 0).buttons.element(boundBy: 1)
screenState.tap(trackingProtectionButton, forAction: Action.ToggleTrackingProtectionPerTabEnabled, if: FxUserState.trackingProtectionIsOnCondition) { userState in
userState.trackingProtectionPerTabEnabled = !userState.trackingProtectionPerTabEnabled
}
}
map.addScreenState(WebImageContextMenu) { screenState in
screenState.dismissOnUse = true
screenState.backAction = lastButtonIsCancel
}
map.addScreenState(WebLinkContextMenu) { screenState in
screenState.dismissOnUse = true
screenState.backAction = lastButtonIsCancel
}
// make sure after the menu action, navigator.nowAt() is used to set the current state
map.addScreenState(PageOptionsMenu) {screenState in
screenState.tap(app.tables["Context Menu"].cells["menu-FindInPage"], to: FindInPage)
screenState.tap(app.tables["Context Menu"].cells["menu-Bookmark"], forAction: Action.BookmarkThreeDots, Action.Bookmark)
screenState.tap(app.tables["Context Menu"].cells["action_remove"], forAction: Action.CloseTabFromPageOptions, Action.CloseTab, transitionTo: HomePanelsScreen, if: "tablet != true")
screenState.backAction = cancelBackAction
screenState.dismissOnUse = true
}
map.addScreenState(FindInPage) { screenState in
screenState.tap(app.buttons["FindInPage.close"], to: BrowserTab)
}
map.addScreenState(BrowserTabMenu) { screenState in
screenState.tap(app.tables.cells["menu-Settings"], to: SettingsScreen)
screenState.tap(app.tables.cells["menu-panel-TopSites"], to: HomePanel_TopSites)
screenState.tap(app.tables.cells["menu-panel-Bookmarks"], to: HomePanel_Bookmarks)
screenState.tap(app.tables.cells["menu-panel-History"], to: HomePanel_History)
screenState.tap(app.tables.cells["menu-panel-ReadingList"], to: HomePanel_ReadingList)
screenState.tap(app.tables.cells["menu-NoImageMode"], forAction: Action.ToggleNoImageMode) { userState in
userState.noImageMode = !userState.noImageMode
}
screenState.tap(app.tables.cells["menu-NightMode"], forAction: Action.ToggleNightMode) { userState in
userState.nightMode = !userState.nightMode
}
screenState.dismissOnUse = true
screenState.backAction = cancelBackAction
}
return map
}
extension MMNavigator where T == FxUserState {
func openURL(_ urlString: String, waitForLoading: Bool = true) {
UIPasteboard.general.string = urlString
userState.url = urlString
userState.waitForLoading = waitForLoading
performAction(Action.LoadURL)
}
// Opens a URL in a new tab.
func openNewURL(urlString: String) {
self.goto(TabTray)
createNewTab()
self.openURL(urlString)
}
// Closes all Tabs from the option in TabTrayMenu
func closeAllTabs() {
let app = XCUIApplication()
app.buttons["TabTrayController.removeTabsButton"].tap()
app.sheets.buttons["Close All Tabs"].tap()
self.nowAt(HomePanelsScreen)
}
// Add a new Tab from the New Tab option in Browser Tab Menu
func createNewTab() {
let app = XCUIApplication()
self.goto(TabTray)
app.buttons["TabTrayController.addTabButton"].tap()
self.nowAt(NewTabScreen)
}
// Add Tab(s) from the Tab Tray
func createSeveralTabsFromTabTray(numberTabs: Int) {
for _ in 1...numberTabs {
self.goto(TabTray)
self.goto(HomePanelsScreen)
}
}
func browserPerformAction(_ view: BrowserPerformAction) {
let PageMenuOptions = [.toggleBookmarkOption, .addReadingListOption, .copyURLOption, .findInPageOption, .toggleDesktopOption, .pinToTopSitesOption, .sendToDeviceOption, BrowserPerformAction.shareOption]
let BrowserMenuOptions = [.openTopSitesOption, .openBookMarksOption, .openHistoryOption, .openReadingListOption, .toggleHideImages, .toggleNightMode, BrowserPerformAction.openSettingsOption]
let app = XCUIApplication()
if PageMenuOptions.contains(view) {
self.goto(PageOptionsMenu)
app.tables["Context Menu"].cells[view.rawValue].tap()
} else if BrowserMenuOptions.contains(view) {
self.goto(BrowserTabMenu)
app.tables["Context Menu"].cells[view.rawValue].tap()
}
}
}
enum BrowserPerformAction: String {
// Page Menu
case toggleBookmarkOption = "menu-Bookmark"
case addReadingListOption = "addToReadingList"
case copyURLOption = "menu-Copy-Link"
case findInPageOption = "menu-FindInPage"
case toggleDesktopOption = "menu-RequestDesktopSite"
case pinToTopSitesOption = "action_pin"
case sendToDeviceOption = "menu-Send-to-Device"
case shareOption = "action_share"
// Tab Menu
case openTopSitesOption = "menu-panel-TopSites"
case openBookMarksOption = "menu-panel-Bookmarks"
case openHistoryOption = "menu-panel-History"
case openReadingListOption = "menu-panel-ReadingList"
case toggleHideImages = "menu-NoImageMode"
case toggleNightMode = "menu-NightMode"
case openSettingsOption = "menu-Settings"
}
extension XCUIElement {
/// For tables only: scroll the table downwards until
/// the end is reached.
/// Each time a whole screen has scrolled, the passed closure is
/// executed with the index number of the screen.
/// Care is taken to make sure that every cell is completely on screen
/// at least once.
func forEachScreen(_ eachScreen: (Int) -> ()) {
guard self.elementType == .table else {
return
}
func firstInvisibleCell(_ start: UInt) -> UInt {
let cells = self.cells
for i in start ..< cells.count {
let cell = cells.element(boundBy: i)
// if the cell's bottom is beyond the table's bottom
// i.e. if the cell isn't completely visible.
if self.frame.maxY <= cell.frame.maxY {
return i
}
}
return UInt.min
}
var cellNum: UInt = 0
var screenNum = 0
while true {
eachScreen(screenNum)
let firstCell = self.cells.element(boundBy: cellNum)
cellNum = firstInvisibleCell(cellNum)
if cellNum == UInt.min {
return
}
let lastCell = self.cells.element(boundBy: cellNum)
let bottom: XCUICoordinate
// If the cell is a little bit on the table.
// We shouldn't drag from too close to the edge of the screen,
// because Control Center gets summoned.
if lastCell.frame.minY < self.frame.maxY * 0.95 {
bottom = lastCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.0))
} else {
bottom = self.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.95))
}
let top = firstCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.0))
bottom.press(forDuration: 0.1, thenDragTo: top)
screenNum += 1
}
}
}
| mpl-2.0 | 871d0bb1e26ab8a4e6d0855b88b2c76e | 40.31753 | 230 | 0.691901 | 4.917979 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Home/Model/Wenda.swift | 1 | 6694 | //
// File.swift
// News
//
// Created by 杨蒙 on 2018/1/9.
// Copyright © 2018年 hrscy. All rights reserved.
//
import UIKit
import HandyJSON
struct Wenda: HandyJSON {
var err_no = 0
var err_tips = ""
var offset = 0
var api_param = ""
var ans_list = [WendaAnswer]()
var has_more = false
var can_answer = false
var related_question_banner_type = 0
var related_question_reason_url = ""
var candidate_invite_user = CandidateInviteUser()
var module_list = [WendaModule]()
var module_count = 0
var question_header_content_fold_max_count = 0
var show_format = WendaShowFormat()
var repost_params = WendaRepostParam()
var question = WendaQuestion()
var has_profit: Bool = false
}
struct CandidateInviteUser: HandyJSON {
}
struct WendaAnswer: HandyJSON {
var cellHeight: CGFloat? {
// 60 + 5 + textH + 5 + imageH + 5 + 20 + 5
var height: CGFloat = 100 + content_abstract.textH!
if content_abstract.hasImage {
height += 166.0
}
return height
}
let emojiManager = EmojiManager()
var attributedString: NSMutableAttributedString {
return emojiManager.showEmoji(content: content_abstract.text, font: UIFont.systemFont(ofSize: 18))
}
var user = WendaUser()
var comment_count: Int = 0
var commentCount: String { return comment_count.convertString() }
var bury_count: Int = 0
var buryCount: String { return bury_count.convertString() }
var brow_count: Int = 0
var browCount: String { return brow_count.convertString() }
var ansid: String = ""
var comment_schema: String = ""
var schema: String = ""
var share_data: WendaShareData!
var is_show_bury: Bool = false
var title: String = ""
var forward_count: Int = 0
var content_abstract: WendaContentAbstract!
var is_digg: Bool = false
var is_buryed: Bool = false
var create_time: TimeInterval = 0
var createTime: String { return create_time.convertString() }
var digg_count: Int = 0
var diggCount: String { return digg_count.convertString() }
var ans_url: String = ""
}
struct WendaFoldReason: HandyJSON {
var open_url: String = ""
var title: String = ""
}
struct WendaConcernTag: HandyJSON {
var concern_id: String = ""
var name: String = ""
var schema: String = ""
}
struct WendaRepostParam: HandyJSON {
var repost_type: Int = 0
var opt_id: Int = 0
var schema: String = ""
var cover_url: String = ""
var title: String = ""
var fw_id_type: Int = 0
var opt_id_type: Int = 0
var fw_id: Int = 0
var fw_user_id: Int = 0
}
struct WendaModule: HandyJSON {
var text: String = ""
var day_icon_url: String = ""
var icon_type: Int = 0
var schema: String = ""
var night_icon_url: String = ""
}
struct WendaShowFormat: HandyJSON {
var font_size: String = ""
var answer_full_context_color: Int = 0
var show_module: Int = 0
}
struct WendaContentAbstract: HandyJSON {
var hasImage: Bool {
return thumb_image_list.count != 0
}
var thumb_image_list = [ThumbImage]()
var large_image_list = [LargeImage]()
var video_list: [WendaVideo]!
var text: String = ""
var textH: CGFloat? {
// 一行的高度
let lineHeight: CGFloat = 26.48046875
// 为富文本添加字体属性
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
let height = (text as NSString).boundingRect(with: CGSize(width: screenWidth - 30, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: UIFont.systemFont(ofSize: 18), .paragraphStyle: paragraphStyle], context: nil).height
if thumb_image_list.count == 0 { // 没有图片 26.5 * 6 = 160
let lineHeightX6 = lineHeight * 6
return height > lineHeightX6 ? lineHeightX6 : height
} else { // 有图片 26.5 * 4
let lineHeightX4 = lineHeight * 4
return height > lineHeightX4 ? lineHeightX4 : height
}
}
}
struct WendaVideo: HandyJSON {
}
struct WendaUser: HandyJSON {
var schema: String = ""
var total_digg: Int = 0
var totalDigg: String { return total_digg.convertString() }
var user_intro: String = ""
var is_following = false
var is_verify = false
var total_answer: Int = 0
var uname: String = ""
var user_id: String = ""
var create_time: TimeInterval = 0
var createTime: String { return create_time.convertString() }
var avatar_url: String = ""
var user_auth_info = UserAuthInfo()
}
struct WendaQuestion: HandyJSON {
/// 没有展开的高度
var foldHeight: CGFloat? {
// 10 + titleH! + 10 + 20 + 10 + thumbHeight + 10 + 20 + 10 + 41
return 131 + titleH! + content.thumbHeight!
}
/// 展开以后的高度
var unfoldHeight: CGFloat? {
// 10 + titleH! + 10 + content.textH! + 10 + thumbHeight + 10 + 20 + 10 + 41
return 111.0 + titleH! + content.textH! + content.thumbHeight!
}
var can_edit: Bool = false
var content = QuestionContent()
var qid: String = ""
var post_answer_url: String = ""
var concern_tag_list = [WendaConcernTag]()
var fold_reason = WendaFoldReason()
var follow_count: Int = 0
var followCount: String { return follow_count.convertString() }
var is_follow: Bool = false
var can_delete: Bool = false
var share_data = WendaShareData()
var show_edit: Bool = false
var title: String = ""
var titleH: CGFloat? {
return title.textHeight(fontSize: 18, width: screenWidth - 30)
}
var show_delete: Bool = false
var create_time: TimeInterval = 0
var createTime: String { return create_time.convertString() }
var nice_ans_count: Int = 0
var normal_ans_count: Int = 0
var answerCount: String { return (nice_ans_count + normal_ans_count).convertString() }
var user = WendaUser()
}
struct QuestionContent: HandyJSON {
/// 图片的高度
var thumbHeight: CGFloat? {
guard thumb_image_list.count != 0 else {
return 0
}
return thumb_image_list.first!.ratio * 166
}
var thumb_image_list = [ThumbImage]()
var text: String = ""
var textH: CGFloat? {
return text.textHeight(fontSize: 16, width: screenWidth - 30)
}
var large_image_list = [LargeImage]()
}
struct WendaShareData: HandyJSON {
var content: String = ""
var image_url: String = ""
var share_url: String = ""
var title: String = ""
}
| mit | 874bebb45a20d24751666eb09610ff12 | 27.842795 | 278 | 0.619833 | 3.7851 | false | false | false | false |
QuarkX/Quark | Sources/Quark/Venice/FileDescriptorStream/FileDescriptorStream.swift | 1 | 1721 | import CLibvenice
public final class FileDescriptorStream : Stream {
fileprivate var file: mfile?
public fileprivate(set) var closed = false
init(file: mfile) {
self.file = file
}
public convenience init(fileDescriptor: FileDescriptor) throws {
let file = fileattach(fileDescriptor)
try ensureLastOperationSucceeded()
self.init(file: file!)
}
deinit {
if let file = file, !closed {
fileclose(file)
}
}
}
extension FileDescriptorStream {
public func write(_ data: Data, length: Int, deadline: Double) throws -> Int {
try ensureFileIsOpen()
let bytesWritten = data.withUnsafeBytes {
filewrite(file, $0, length, deadline.int64milliseconds)
}
if bytesWritten == 0 {
try ensureLastOperationSucceeded()
}
return bytesWritten
}
public func read(into buffer: inout Data, length: Int, deadline: Double) throws -> Int {
try ensureFileIsOpen()
let bytesRead = buffer.withUnsafeMutableBytes {
filereadlh(file, $0, 1, length, deadline.int64milliseconds)
}
if bytesRead == 0 {
try ensureLastOperationSucceeded()
}
return bytesRead
}
public func flush(deadline: Double) throws {
try ensureFileIsOpen()
fileflush(file, deadline.int64milliseconds)
try ensureLastOperationSucceeded()
}
public func close() {
if !closed {
fileclose(file)
}
closed = true
}
private func ensureFileIsOpen() throws {
if closed {
throw StreamError.closedStream(data: Data())
}
}
}
| mit | d6818b22683685cbb4125dc0d9323603 | 22.902778 | 92 | 0.599651 | 4.959654 | false | false | false | false |
nathawes/swift | test/SILGen/witnesses.swift | 17 | 31550 | // RUN: %target-swift-emit-silgen -module-name witnesses -Xllvm -sil-full-demangle %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
infix operator <~>
func archetype_method<T: X>(x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses16archetype_method{{[_0-9a-zA-Z]*}}F{{.*}} : $@convention(thin) <T where T : X> (@in_guaranteed T, @in_guaranteed T) -> @out T {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes : {{.*}} : $@convention(witness_method: X) <τ_0_0 where τ_0_0 : X> (@in_guaranteed τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method: X) <τ_0_0 where τ_0_0 : X> (@in_guaranteed τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: }
func archetype_generic_method<T: X>(x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses24archetype_generic_method{{[_0-9a-zA-Z]*}}F{{.*}} : $@convention(thin) <T where T : X> (@in_guaranteed T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic : {{.*}} : $@convention(witness_method: X) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in_guaranteed τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method: X) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in_guaranteed τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: }
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses32archetype_associated_type_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : WithAssoc> (@in_guaranteed T, @in_guaranteed T.AssocType) -> @out T
// CHECK: apply %{{[0-9]+}}<T>
func archetype_associated_type_method<T: WithAssoc>(x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses23archetype_static_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : StaticMethod> (@in_guaranteed T) -> ()
func archetype_static_method<T: StaticMethod>(x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod : {{.*}} : $@convention(witness_method: StaticMethod) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses15protocol_method1xAA8LoadableVAA13Existentiable_p_tF : $@convention(thin) (@in_guaranteed Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo :
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses23protocol_generic_method1xAA8LoadableVAA13Existentiable_p_tF : $@convention(thin) (@in_guaranteed Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic :
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden [ossa] @$s9witnesses20protocol_objc_method1xyAA8ObjCAble_p_tF : $@convention(thin) (@guaranteed ObjCAble) -> ()
// CHECK: objc_method {{%.*}} : $@opened({{.*}}) ObjCAble, #ObjCAble.foo!foreign
func protocol_objc_method(x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x: Self) -> Self
mutating
func loadable(x: Loadable) -> Loadable
mutating
func addrOnly(x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x: A) -> A
mutating
func classes<A2: Classes>(x: A2) -> A2
static func <~>(_ x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssoc {
associatedtype AssocType
func useAssocType(x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load [trivial] %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @$s9witnesses16ConformingStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to [trivial] %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP8loadable{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @$s9witnesses16ConformingStructV8loadable{{[_0-9a-zA-Z]*}}F : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP8addrOnly{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @$s9witnesses16ConformingStructV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in_guaranteed AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in_guaranteed AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x: C) -> C { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP7generic{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @$s9witnesses16ConformingStructV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x: C2) -> C2 { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP7classes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : @guaranteed $τ_0_0, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @$s9witnesses16ConformingStructV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@guaranteed τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<τ_0_0>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@guaranteed τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $τ_0_0
// CHECK-NEXT: }
}
func <~>(_ x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16ConformingStructVAA1XA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW :
// CHECK: bb0([[ARG1:%.*]] : $*ConformingStruct, [[ARG2:%.*]] : $*ConformingStruct, [[ARG3:%.*]] : $*ConformingStruct, [[ARG4:%.*]] : $@thick ConformingStruct.Type):
// CHECK-NEXT: [[LOADED_ARG2:%.*]] = load [trivial] [[ARG2]] : $*ConformingStruct
// CHECK-NEXT: [[LOADED_ARG3:%.*]] = load [trivial] [[ARG3]] : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FUNC:%.*]] = function_ref @$s9witnesses3ltgoiyAA16ConformingStructVAD_ADtF : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[LOADED_ARG2]], [[LOADED_ARG3]]) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store [[FUNC_RESULT]] to [trivial] [[ARG1]] : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses15ConformingClassCAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[ARG1:%.*]] : $*ConformingClass, [[ARG2:%.*]] : $*ConformingClass, [[ARG3:%.*]] : $*ConformingClass):
// -- load and copy_value 'self' from inout witness 'self' parameter
// CHECK: [[ARG2_LOADED:%.*]] = load_borrow [[ARG2]] : $*ConformingClass
// CHECK: [[ARG3_LOADED:%.*]] = load_borrow [[ARG3]] : $*ConformingClass
// CHECK: [[FUNC:%.*]] = function_ref @$s9witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F
// CHECK: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[ARG2_LOADED]], [[ARG3_LOADED]]) : $@convention(method) (@guaranteed ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK: store [[FUNC_RESULT]] to [init] [[ARG1]] : $*ConformingClass
// CHECK: end_borrow [[ARG3_LOADED]]
// CHECK: } // end sil function '$s9witnesses15ConformingClassCAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW'
func loadable(x: Loadable) -> Loadable { return x }
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x: D) -> D { return x }
func classes<D2: Classes>(x: D2) -> D2 { return x }
}
func <~>(_ x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses15ConformingClassCAA0C7BoundedA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[C0:%.*]] : @guaranteed $ConformingClass, [[C1:%.*]] : @guaranteed $ConformingClass):
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@guaranteed ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses18ConformingAOStructVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @$s9witnesses18ConformingAOStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in_guaranteed ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in_guaranteed ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
func loadable(x: Loadable) -> Loadable { return x }
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x: D) -> D { return x }
func classes<D2: Classes>(x: D2) -> D2 { return x }
}
func <~>(_ x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x: E) -> E { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses23ConformsWithMoreGenericVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @$s9witnesses23ConformsWithMoreGenericV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func loadable<F>(x: F) -> F { return x }
mutating
func addrOnly<G>(x: G) -> G { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses23ConformsWithMoreGenericVAA1XA2aDP8addrOnly{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @$s9witnesses23ConformsWithMoreGenericV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func generic<H>(x: H) -> H { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses23ConformsWithMoreGenericVAA1XA2aDP7generic{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @$s9witnesses23ConformsWithMoreGenericV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func classes<I>(x: I) -> I { return x }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses23ConformsWithMoreGenericVAA1XA2aDP7classes{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $τ_0_0, [[ARG1:%.*]] : $*ConformsWithMoreGeneric):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK-NEXT: store [[ARG0_COPY]] to [init] [[SELF_BOX]] : $*τ_0_0
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @$s9witnesses23ConformsWithMoreGenericV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<τ_0_0>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = load [take] [[RESULT_BOX]] : $*τ_0_0
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*τ_0_0
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*τ_0_0
// CHECK-NEXT: return [[RESULT]] : $τ_0_0
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(_ x: J, y: K) -> K { return y }
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses23ConformsWithMoreGenericVAA1XA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW :
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @$s9witnesses3ltgoi{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16UnlabeledWitnessVAA18LabeledRequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW :
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses20UnlabeledSelfWitnessVAA07LabeledC11RequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW :
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses14LabeledWitnessVAA20UnlabeledRequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW :
func method(x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses18LabeledSelfWitnessVAA09UnlabeledC11RequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW :
func method(_ x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses14ImmutableModelVAA19ReadOnlyRequirementA2aDP4propSSvgTW :
let prop: String = "a"
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses14ImmutableModelVAA19ReadOnlyRequirementA2aDP4propSSvgZTW :
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16NonFailableModelVAA0C11Requirement{{[_0-9a-zA-Z]*}}fCTW :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16NonFailableModelVAA0bC10Refinement{{[_0-9a-zA-Z]*}}fCTW :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16NonFailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW :
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses13FailableModelVAA0B11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses13FailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0([[SELF:%[0-9]+]] : $*Optional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @$s9witnesses13FailableModelV{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: store [[INNER]] to [trivial] [[SELF]]
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16IUOFailableModelVAA21NonFailableRefinement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @$s9witnesses16IUOFailableModelV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel>
// CHECK: bb2([[RESULT:%.*]] : $IUOFailableModel):
// CHECK: store [[RESULT]] to [trivial] [[SELF]] : $*IUOFailableModel
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21NonFailableClassModelCAA0cD11Requirement{{[_0-9a-zA-Z]*}}fCTW :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21NonFailableClassModelCAA0bcD10Refinement{{[_0-9a-zA-Z]*}}fCTW :
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21NonFailableClassModelCAA011IUOFailableD11Requirement{{[_0-9a-zA-Z]*}}fCTW :
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses18FailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses18FailableClassModelCAA011IUOFailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: [[FUNC:%.*]] = function_ref @$s9witnesses18FailableClassModelC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: return [[INNER]] : $Optional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0({{.*}}):
// CHECK: [[FUNC:%.*]] = function_ref @$s9witnesses21IUOFailableClassModelC3fooACSgSi_tcfC : $@convention(method) (Int, @thick IUOFailableClassModel.Type) -> @owned Optional<IUOFailableClassModel>
// CHECK: [[VALUE:%.*]] = apply [[FUNC]]({{.*}})
// CHECK: switch_enum [[VALUE]] : $Optional<IUOFailableClassModel>, case #Optional.some!enumelt: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NONEBB:bb[0-9]+]]
//
// CHECK: [[NONEBB]]:
// CHECK: unreachable
//
// CHECK: [[SOMEBB]]([[RESULT:%.*]] : @owned $IUOFailableClassModel)
// CHECK: return [[RESULT]] : $IUOFailableClassModel
// CHECK: } // end sil function '$s9witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21IUOFailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW
init!(foo: Int) {}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses21IUOFailableClassModelCAA08FailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: [[FUNC:%.*]] = function_ref @$s9witnesses21IUOFailableClassModelC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: return [[INNER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
associatedtype Assoc
}
protocol GenericParameterNameCollisionProtocol {
func foo<T>(_ x: T)
associatedtype Assoc2
func bar<T>(_ x: (T) -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionProtocol {
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3fooyyqd__lFTW :
// CHECK: bb0(%0 : $*τ_1_0, %1 : $*GenericParameterNameCollision<τ_0_0>):
// CHECK: apply {{%.*}}<τ_0_0, τ_1_0>
func foo<U>(_ x: U) {}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3baryy6Assoc2Qzqd__XElFTW :
// CHECK: bb0(%0 : ${{.*}}, %1 : $*{{.*}}):
// CHECK: apply {{%.*}}<τ_0_0, τ_1_0>
func bar<V>(_ x: (V) -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in modify works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP5widthSivMTW :
// CHECK: bb0([[ARG2:%.*]] : $*PropertyRequirementWitnessFromBase):
// CHECK-NEXT: [[ARG2_LOADED:%[0-9][0-9]*]] = load_borrow [[ARG2]]
// CHECK-NEXT: [[CAST_ARG2_LOADED:%[0-9][0-9]*]] = upcast [[ARG2_LOADED]] : $PropertyRequirementWitnessFromBase to $PropertyRequirementBase
// CHECK-NEXT: [[METH:%.*]] = class_method [[CAST_ARG2_LOADED]] : $PropertyRequirementBase, #PropertyRequirementBase.width!modify
// CHECK-NEXT: ([[RES:%.*]], [[TOKEN:%.*]]) = begin_apply [[METH]]([[CAST_ARG2_LOADED]]) : $@yield_once @convention(method) (@guaranteed PropertyRequirementBase) -> @yields @inout Int
// CHECK-NEXT: yield [[RES]]
// CHECK: end_apply [[TOKEN]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ()
// CHECK-NEXT: end_borrow [[ARG2_LOADED]]
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP6heightSivMZTW :
// CHECK: [[OBJ:%.*]] = upcast %0 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @$s9witnesses23PropertyRequirementBaseC6heightSivMZ
// CHECK-NEXT: ([[RES:%.*]], [[TOKEN:%.*]]) = begin_apply [[METH]]
// CHECK-NEXT: yield [[RES]]
// CHECK: end_apply [[TOKEN]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ()
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP5depthSivMTW
// CHECK: bb0([[ARG2:%.*]] : $*PropertyRequirementWitnessFromBase):
// CHECK: [[ARG2_LOADED:%[0-9][0-9]*]] = load_borrow [[ARG2]]
// CHECK: [[METH:%.*]] = class_method [[ARG2_LOADED]] : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!modify
// CHECK-NEXT: ([[RES:%.*]], [[TOKEN:%.*]]) = begin_apply [[METH]]([[ARG2_LOADED]]) : $@yield_once @convention(method) (@guaranteed PropertyRequirementWitnessFromBase) -> @yields @inout Int
// CHECK-NEXT: yield [[RES]]
// CHECK: end_apply [[TOKEN]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ()
// CHECK-NEXT: end_borrow [[ARG2_LOADED]]
// CHECK-NEXT: return [[TUPLE]]
}
protocol Crashable {
func crash()
}
class CrashableBase {
func crash() {}
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses16GenericCrashableCyxGAA0C0A2aEP5crashyyFTW :
// CHECK: bb0(%0 : $*GenericCrashable<τ_0_0>):
// CHECK-NEXT: [[SELF:%.*]] = load_borrow %0 : $*GenericCrashable<τ_0_0>
// CHECK-NEXT: [[BASE:%.*]] = upcast [[SELF]] : $GenericCrashable<τ_0_0> to $CrashableBase
// CHECK-NEXT: [[FN:%.*]] = class_method [[BASE]] : $CrashableBase, #CrashableBase.crash : (CrashableBase) -> () -> (), $@convention(method) (@guaranteed CrashableBase) -> ()
// CHECK-NEXT: apply [[FN]]([[BASE]]) : $@convention(method) (@guaranteed CrashableBase) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: end_borrow [[SELF]]
// CHECK-NEXT: return [[RESULT]] : $()
class GenericCrashable<T> : CrashableBase, Crashable {}
// rdar://problem/35297911: allow witness with a noescape parameter to
// match a requirement with an escaping paameter.
protocol EscapingReq {
func f(_: @escaping (Int) -> Int)
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses18EscapingCovarianceVAA0B3ReqA2aDP1fyyS2icFTW :
// CHECK-NOT: return
// CHECK: convert_escape_to_noescape [not_guaranteed] %0
// CHECK: return
struct EscapingCovariance: EscapingReq {
func f(_: (Int) -> Int) { }
}
protocol InoutFunctionReq {
associatedtype T
func updateFunction(x: inout () -> T)
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9witnesses13InoutFunctionVAA0bC3ReqA2aDP06updateC01xy1TQzycz_tFTW
// CHECK: bb0(%0 : $*{{.*}}, %1 : $*InoutFunction):
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_guaranteed () -> ()
// Reabstract the contents of the inout argument into the temporary.
// CHECK-NEXT: [[OLD_FN:%.*]] = load [take] %0
// CHECK-NEXT: [[OLD_FN_CONV:%.*]] = convert_function [[OLD_FN]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK:%.*]] = function_ref @$sytIegr_Ieg_TR
// CHECK-NEXT: [[THUNKED_OLD_FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[OLD_FN_CONV]])
// CHECK-NEXT: store [[THUNKED_OLD_FN]] to [init] [[TEMP]] :
// Call the function.
// CHECK-NEXT: [[SELF:%.*]] = load [trivial] %1 : $*InoutFunction
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s9witnesses13InoutFunctionV06updateC01xyyycz_tF :
// CHECK-NEXT: apply [[T0]]([[TEMP]], [[SELF]])
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ()
// Reabstract the contents of the temporary back into the inout argument.
// CHECK-NEXT: [[NEW_FN:%.*]] = load [take] [[TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[THUNK:%.*]] = function_ref @$sIeg_ytIegr_TR
// CHECK-NEXT: [[THUNKED_NEW_FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[NEW_FN]])
// CHECK-NEXT: [[THUNKED_NEW_FN_CONV:%.*]] = convert_function [[THUNKED_NEW_FN]]
// CHECK-NEXT: store [[THUNKED_NEW_FN_CONV]] to [init] %0 :
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: } // end sil function '$s9witnesses13InoutFunctionVAA0bC3ReqA2aDP06updateC01xy1TQzycz_tFTW'
struct InoutFunction : InoutFunctionReq {
func updateFunction(x: inout () -> ()) {}
}
protocol Base {
func foo()
}
protocol Sub : Base {
func bar()
}
struct MyImpl :Sub {
func bar() {}
func foo() {}
}
// protocol witness for witnesses.Sub.bar() -> () in conformance witnesses.MyImpl : witnesses.Sub in witnesses
// CHECK: sil private [transparent] [thunk] [ossa] @$s9witnesses6MyImplVAA3SubA2aDP3baryyFTW :
// protocol witness for witnesses.Base.foo() -> () in conformance witnesses.MyImpl : witnesses.Base in witnesses
// CHECK: sil private [transparent] [thunk] [ossa] @$s9witnesses6MyImplVAA4BaseA2aDP3fooyyFTW :
| apache-2.0 | 88110657108dc577713376cdabc7f707 | 53.123924 | 239 | 0.657794 | 3.178932 | false | false | false | false |
mluedke2/testmaster | TestMaster/MainView.swift | 1 | 1505 | //
// MainView.swift
// TestMaster
//
// Created by Matt Luedke on 3/28/16.
//
//
import Foundation
import UIKit
import SnapKit
class MainView: UIView {
var collectionView: UICollectionView!
private let titleLabel = UILabel()
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .whiteColor()
titleLabel.text = "My Course Wishlist"
titleLabel.textAlignment = .Center
addSubview(titleLabel)
titleLabel.snp_makeConstraints { make in
make.top.equalTo(self).offset(25)
make.centerX.equalTo(self)
make.height.equalTo(40)
make.width.equalTo(200)
}
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 150, height: 150)
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.collectionViewLayout = layout
collectionView.backgroundColor = .whiteColor()
addSubview(collectionView)
collectionView.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(25)
make.left.equalTo(self)
make.right.equalTo(self)
make.bottom.equalTo(self)
}
}
func updateTitle(newTitle: String) {
titleLabel.text = newTitle
}
func getTitle() -> String? {
return titleLabel.text
}
}
| mit | 7823bc9e12a5025ee08bed1d11a02d03 | 24.083333 | 86 | 0.689037 | 4.263456 | false | false | false | false |
OpenStack-mobile/OAuth2-Swift | Sources/OAuth2/ResourceOwnerPasswordCredentialsGrant.swift | 1 | 4723 | //
// ResourceOwnerPasswordCredentialsGrant.swift
// OAuth2
//
// Created by Alsey Coleman Miller on 12/16/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
import SwiftFoundation
/// Resource Owner Password Credentials Grant OAuth2 flow
public struct ResourceOwnerPasswordCredentialsGrant {
public struct Request: AccessTokenRequest {
public enum Parameter: String {
case grant_type, scope, client_id, client_secret, username, password
}
public static let grantType: AccessTokenGrantType = .password
/// The URL of the OAuth2 endpoint for access token grants.
public var endpoint: URL
public var scope: String?
public var username: String
public var password: String
public var clientCredentials: (identifier: String, secret: String)?
public func toURLRequest() -> HTTP.Request {
var parameters = [Parameter: String]()
parameters[.grant_type] = type(of: self).grantType.rawValue
parameters[.scope] = scope
parameters[.username] = username
parameters[.password] = password
if let (clientID, clientSecret) = clientCredentials {
parameters[.client_id] = clientID
parameters[.client_secret] = clientSecret
}
// crashes compiler
//let stringParameters = parameters.reduce([String: String](), { $0.0[$0.1.key.rawValue] = $0.1.value })
var stringParameters = [String: String](minimumCapacity: parameters.count)
parameters.forEach { stringParameters[$0.0.rawValue] = $0.value }
let formURLEncoded = FormURLEncoded(parameters: stringParameters)
return HTTP.Request(url: endpoint,
body: formURLEncoded.toData(),
headers: ["Content-Type": "application/x-www-form-urlencoded"],
method: .POST)
}
}
public struct Response {
public struct Success: RefreshableAccessTokenResponse, JSONDecodable {
public static let grantType: AccessTokenGrantType = .clientCredentials
public let accessToken: String
public let tokenType: String
public let expires: TimeInterval?
public let refreshToken: String?
public init?(urlResponse: HTTP.Response) {
guard urlResponse.statusCode == HTTP.StatusCode.OK.rawValue,
let jsonString = String(UTF8Data: urlResponse.body),
let json = JSON.Value(string: jsonString)
else { return nil }
self.init(JSONValue: json)
}
public init?(JSONValue: JSON.Value) {
guard let JSONObject = JSONValue.objectValue,
let accessToken = JSONObject[AccessTokenResponseParameter.access_token.rawValue]?.stringValue,
let tokenType = JSONObject[AccessTokenResponseParameter.token_type.rawValue]?.stringValue
else { return nil }
self.accessToken = accessToken
self.tokenType = tokenType
if let expires = JSONObject[AccessTokenResponseParameter.expires_in.rawValue]?.integerValue {
self.expires = TimeInterval(expires)
} else {
self.expires = nil
}
self.refreshToken = JSONObject[AccessTokenResponseParameter.refresh_token.rawValue]?.stringValue
}
}
/// Resource Owner Password Credentials Grant Error Response
public struct Error: AccessTokenErrorResponseJSON {
public let code: AccessTokenErrorCode
public let errorDescription: String?
public let errorURI: String?
public init(code: AccessTokenErrorCode, errorDescription: String? = nil, errorURI: String? = nil) {
self.code = code
self.errorDescription = errorDescription
self.errorURI = errorURI
}
}
}
}
| mit | 9e8cbdf5a8f6802099607763ef4ddf52 | 34.772727 | 116 | 0.528801 | 6.346774 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/SwiftScan/DependencyGraphBuilder.swift | 1 | 20829 | //===--- DependencyGraphBuilder.swift -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CSwiftScan
internal extension SwiftScan {
/// From a reference to a binary-format dependency graph returned by libSwiftScan,
/// construct an instance of an `InterModuleDependencyGraph`.
func constructGraph(from scannerGraphRef: swiftscan_dependency_graph_t,
moduleAliases: [String: String]?) throws
-> InterModuleDependencyGraph {
let mainModuleNameRef =
api.swiftscan_dependency_graph_get_main_module_name(scannerGraphRef)
let mainModuleName = try toSwiftString(mainModuleNameRef)
let dependencySetRefOrNull = api.swiftscan_dependency_graph_get_dependencies(scannerGraphRef)
guard let dependencySetRef = dependencySetRefOrNull else {
throw DependencyScanningError.missingField("dependency_graph.dependencies")
}
var resultGraph = InterModuleDependencyGraph(mainModuleName: mainModuleName)
// Turn the `swiftscan_dependency_set_t` into an array of `swiftscan_dependency_info_t`
// references we can iterate through in order to construct `ModuleInfo` objects.
let moduleRefArray = Array(UnsafeBufferPointer(start: dependencySetRef.pointee.modules,
count: Int(dependencySetRef.pointee.count)))
for moduleRefOrNull in moduleRefArray {
guard let moduleRef = moduleRefOrNull else {
throw DependencyScanningError.missingField("dependency_set_t.modules[_]")
}
let (moduleId, moduleInfo) = try constructModuleInfo(from: moduleRef, moduleAliases: moduleAliases)
resultGraph.modules[moduleId] = moduleInfo
}
return resultGraph
}
/// From a reference to a binary-format set of module imports return by libSwiftScan pre-scan query,
/// construct an instance of an `InterModuleDependencyImports` set
func constructImportSet(from importSetRef: swiftscan_import_set_t,
with moduleAliases: [String: String]?) throws
-> InterModuleDependencyImports {
guard let importsRef = api.swiftscan_import_set_get_imports(importSetRef) else {
throw DependencyScanningError.missingField("import_set.imports")
}
return InterModuleDependencyImports(imports: try toSwiftStringArray(importsRef.pointee), moduleAliases: moduleAliases)
}
/// From a reference to a binary-format dependency graph collection returned by libSwiftScan batch scan query,
/// corresponding to the specified batch scan input (`BatchScanModuleInfo`), construct instances of
/// `InterModuleDependencyGraph` for each result.
func constructBatchResultGraphs(for batchInfos: [BatchScanModuleInfo],
moduleAliases: [String: String]?,
from batchResultRef: swiftscan_batch_scan_result_t) throws
-> [ModuleDependencyId: [InterModuleDependencyGraph]] {
var resultMap: [ModuleDependencyId: [InterModuleDependencyGraph]] = [:]
let resultGraphRefArray = Array(UnsafeBufferPointer(start: batchResultRef.results,
count: Int(batchResultRef.count)))
// Note, respective indices of the batch scan input and the returned result must be aligned.
for (index, resultGraphRefOrNull) in resultGraphRefArray.enumerated() {
guard let resultGraphRef = resultGraphRefOrNull else {
throw DependencyScanningError.dependencyScanFailed
}
let decodedGraph = try constructGraph(from: resultGraphRef, moduleAliases: moduleAliases)
let moduleId: ModuleDependencyId
switch batchInfos[index] {
case .swift(let swiftModuleBatchScanInfo):
moduleId = .swift(swiftModuleBatchScanInfo.swiftModuleName)
case .clang(let clangModuleBatchScanInfo):
moduleId = .clang(clangModuleBatchScanInfo.clangModuleName)
}
// Update the map with either yet another graph or create an entry for this module
if resultMap[moduleId] != nil {
resultMap[moduleId]!.append(decodedGraph)
} else {
resultMap[moduleId] = [decodedGraph]
}
}
return resultMap
}
}
private extension SwiftScan {
/// From a reference to a binary-format module dependency module info returned by libSwiftScan,
/// construct an instance of an `ModuleInfo` as used by the driver
func constructModuleInfo(from moduleInfoRef: swiftscan_dependency_info_t,
moduleAliases: [String: String]?)
throws -> (ModuleDependencyId, ModuleInfo) {
// Decode the module name and module kind
let encodedModuleName =
try toSwiftString(api.swiftscan_module_info_get_module_name(moduleInfoRef))
let moduleId = try decodeModuleNameAndKind(from: encodedModuleName, moduleAliases: moduleAliases)
// Decode module path and source file locations
let modulePathStr = try toSwiftString(api.swiftscan_module_info_get_module_path(moduleInfoRef))
let modulePath = TextualVirtualPath(path: try VirtualPath.intern(path: modulePathStr))
let sourceFiles: [String]?
if let sourceFilesSetRef = api.swiftscan_module_info_get_source_files(moduleInfoRef) {
sourceFiles = try toSwiftStringArray(sourceFilesSetRef.pointee)
} else {
sourceFiles = nil
}
// Decode all dependencies of this module
let directDependencies: [ModuleDependencyId]?
if let encodedDirectDepsRef = api.swiftscan_module_info_get_direct_dependencies(moduleInfoRef) {
let encodedDirectDependencies = try toSwiftStringArray(encodedDirectDepsRef.pointee)
directDependencies =
try encodedDirectDependencies.map { try decodeModuleNameAndKind(from: $0, moduleAliases: moduleAliases) }
} else {
directDependencies = nil
}
guard let moduleDetailsRef = api.swiftscan_module_info_get_details(moduleInfoRef) else {
throw DependencyScanningError.missingField("modules[\(moduleId)].details")
}
let details = try constructModuleDetails(from: moduleDetailsRef)
return (moduleId, ModuleInfo(modulePath: modulePath, sourceFiles: sourceFiles,
directDependencies: directDependencies,
details: details))
}
/// From a reference to a binary-format module info details object info returned by libSwiftScan,
/// construct an instance of an `ModuleInfo`.Details as used by the driver.
/// The object returned by libSwiftScan is a union so ensure to execute dependency-specific queries.
func constructModuleDetails(from moduleDetailsRef: swiftscan_module_details_t)
throws -> ModuleInfo.Details {
let moduleKind = api.swiftscan_module_detail_get_kind(moduleDetailsRef)
switch moduleKind {
case SWIFTSCAN_DEPENDENCY_INFO_SWIFT_TEXTUAL:
return .swift(try constructSwiftTextualModuleDetails(from: moduleDetailsRef))
case SWIFTSCAN_DEPENDENCY_INFO_SWIFT_BINARY:
return .swiftPrebuiltExternal(try constructSwiftBinaryModuleDetails(from: moduleDetailsRef))
case SWIFTSCAN_DEPENDENCY_INFO_SWIFT_PLACEHOLDER:
return .swiftPlaceholder(try constructPlaceholderModuleDetails(from: moduleDetailsRef))
case SWIFTSCAN_DEPENDENCY_INFO_CLANG:
return .clang(try constructClangModuleDetails(from: moduleDetailsRef))
default:
throw DependencyScanningError.unsupportedDependencyDetailsKind(Int(moduleKind.rawValue))
}
}
/// Construct a `SwiftModuleDetails` from a `swiftscan_module_details_t` reference
func constructSwiftTextualModuleDetails(from moduleDetailsRef: swiftscan_module_details_t)
throws -> SwiftModuleDetails {
let moduleInterfacePath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_module_interface_path)
let compiledModuleCandidates =
try getOptionalPathArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_compiled_module_candidates)
let bridgingHeaderPath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_bridging_header_path)
let bridgingSourceFiles =
try getOptionalPathArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_bridging_source_files)
let commandLine =
try getOptionalStringArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_command_line)
let extraPcmArgs =
try getStringArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_extra_pcm_args,
fieldName: "extraPCMArgs")
let contextHash =
try getOptionalStringDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_textual_detail_get_context_hash)
let isFramework = api.swiftscan_swift_textual_detail_get_is_framework(moduleDetailsRef)
return SwiftModuleDetails(moduleInterfacePath: moduleInterfacePath,
compiledModuleCandidates: compiledModuleCandidates,
bridgingHeaderPath: bridgingHeaderPath,
bridgingSourceFiles: bridgingSourceFiles,
commandLine: commandLine,
contextHash: contextHash,
extraPcmArgs: extraPcmArgs,
isFramework: isFramework)
}
/// Construct a `SwiftPrebuiltExternalModuleDetails` from a `swiftscan_module_details_t` reference
func constructSwiftBinaryModuleDetails(from moduleDetailsRef: swiftscan_module_details_t)
throws -> SwiftPrebuiltExternalModuleDetails {
let compiledModulePath =
try getPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_binary_detail_get_compiled_module_path,
fieldName: "swift_binary_detail.compiledModulePath")
let moduleDocPath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_binary_detail_get_module_doc_path)
let moduleSourceInfoPath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_binary_detail_get_module_source_info_path)
return try SwiftPrebuiltExternalModuleDetails(compiledModulePath: compiledModulePath,
moduleDocPath: moduleDocPath,
moduleSourceInfoPath: moduleSourceInfoPath)
}
/// Construct a `SwiftPlaceholderModuleDetails` from a `swiftscan_module_details_t` reference
func constructPlaceholderModuleDetails(from moduleDetailsRef: swiftscan_module_details_t)
throws -> SwiftPlaceholderModuleDetails {
let moduleDocPath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_placeholder_detail_get_module_doc_path)
let moduleSourceInfoPath =
try getOptionalPathDetail(from: moduleDetailsRef,
using: api.swiftscan_swift_placeholder_detail_get_module_source_info_path)
return SwiftPlaceholderModuleDetails(moduleDocPath: moduleDocPath,
moduleSourceInfoPath: moduleSourceInfoPath)
}
/// Construct a `ClangModuleDetails` from a `swiftscan_module_details_t` reference
func constructClangModuleDetails(from moduleDetailsRef: swiftscan_module_details_t)
throws -> ClangModuleDetails {
let moduleMapPath =
try getPathDetail(from: moduleDetailsRef,
using: api.swiftscan_clang_detail_get_module_map_path,
fieldName: "clang_detail.moduleMapPath")
let contextHash =
try getStringDetail(from: moduleDetailsRef,
using: api.swiftscan_clang_detail_get_context_hash,
fieldName: "clang_detail.contextHash")
let commandLine =
try getStringArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_clang_detail_get_command_line,
fieldName: "clang_detail.commandLine")
let capturedPCMArgs : Set<[String]>?
if clangDetailsHaveCapturedPCMArgs {
let capturedArgs = try getStringArrayDetail(from: moduleDetailsRef,
using: api.swiftscan_clang_detail_get_captured_pcm_args,
fieldName: "clang_detail.capturedPCMArgs")
capturedPCMArgs = [capturedArgs]
} else {
capturedPCMArgs = nil
}
return ClangModuleDetails(moduleMapPath: moduleMapPath,
contextHash: contextHash,
commandLine: commandLine,
capturedPCMArgs: capturedPCMArgs)
}
}
internal extension SwiftScan {
/// Convert a `swiftscan_string_ref_t` reference to a Swift `String`, assuming the reference is to a valid string
/// (non-null)
func toSwiftString(_ string_ref: swiftscan_string_ref_t) throws -> String {
if string_ref.length == 0 {
return ""
}
// If the string is of a positive length, the pointer cannot be null
guard let dataPtr = string_ref.data else {
throw DependencyScanningError.invalidStringPtr
}
return String(bytesNoCopy: UnsafeMutableRawPointer(mutating: dataPtr),
length: string_ref.length,
encoding: String.Encoding.utf8, freeWhenDone: false)!
}
/// Convert a `swiftscan_string_set_t` reference to a Swift `[String]`, assuming the individual string references
/// are to a valid strings (non-null)
func toSwiftStringArray(_ string_set: swiftscan_string_set_t) throws -> [String] {
var result: [String] = []
let stringRefArray = Array(UnsafeBufferPointer(start: string_set.strings,
count: Int(string_set.count)))
for stringRef in stringRefArray {
result.append(try toSwiftString(stringRef))
}
return result
}
/// Convert a `swiftscan_string_set_t` reference to a Swift `Set<String>`, assuming the individual string references
/// are to a valid strings (non-null)
func toSwiftStringSet(_ string_set: swiftscan_string_set_t) throws -> Set<String> {
var result = Set<String>()
let stringRefArray = Array(UnsafeBufferPointer(start: string_set.strings,
count: Int(string_set.count)))
for stringRef in stringRefArray {
result.insert(try toSwiftString(stringRef))
}
return result
}
}
private extension SwiftScan {
/// From a `swiftscan_module_details_t` reference, extract a `TextualVirtualPath?` detail using the specified API query
func getOptionalPathDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t)
-> swiftscan_string_ref_t)
throws -> TextualVirtualPath? {
let strDetail = try getOptionalStringDetail(from: detailsRef, using: query)
return strDetail != nil ? TextualVirtualPath(path: try VirtualPath.intern(path: strDetail!)) : nil
}
/// From a `swiftscan_module_details_t` reference, extract a `String?` detail using the specified API query
func getOptionalStringDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t)
-> swiftscan_string_ref_t)
throws -> String? {
let detailRef = query(detailsRef)
guard detailRef.length != 0 else { return nil }
assert(detailRef.data != nil)
return try toSwiftString(detailRef)
}
/// From a `swiftscan_module_details_t` reference, extract a `TextualVirtualPath` detail using the specified API
/// query, making sure the reference is to a non-null (and non-empty) path.
func getPathDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t) -> swiftscan_string_ref_t,
fieldName: String)
throws -> TextualVirtualPath {
let strDetail = try getStringDetail(from: detailsRef, using: query, fieldName: fieldName)
return TextualVirtualPath(path: try VirtualPath.intern(path: strDetail))
}
/// From a `swiftscan_module_details_t` reference, extract a `String` detail using the specified API query,
/// making sure the reference is to a non-null (and non-empty) string.
func getStringDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t) -> swiftscan_string_ref_t,
fieldName: String) throws -> String {
guard let result = try getOptionalStringDetail(from: detailsRef, using: query) else {
throw DependencyScanningError.missingField(fieldName)
}
return result
}
/// From a `swiftscan_module_details_t` reference, extract a `[TextualVirtualPath]?` detail using the specified API
/// query
func getOptionalPathArrayDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t)
-> UnsafeMutablePointer<swiftscan_string_set_t>?)
throws -> [TextualVirtualPath]? {
guard let strArrDetail = try getOptionalStringArrayDetail(from: detailsRef, using: query) else {
return nil
}
return try strArrDetail.map { TextualVirtualPath(path: try VirtualPath.intern(path: $0)) }
}
/// From a `swiftscan_module_details_t` reference, extract a `[String]?` detail using the specified API query
func getOptionalStringArrayDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t)
-> UnsafeMutablePointer<swiftscan_string_set_t>?)
throws -> [String]? {
guard let detailRef = query(detailsRef) else { return nil }
return try toSwiftStringArray(detailRef.pointee)
}
/// From a `swiftscan_module_details_t` reference, extract a `[String]` detail using the specified API query,
/// making sure individual string references are non-null (and non-empty) strings.
func getStringArrayDetail(from detailsRef: swiftscan_module_details_t,
using query: (swiftscan_module_details_t)
-> UnsafeMutablePointer<swiftscan_string_set_t>?,
fieldName: String) throws -> [String] {
guard let result = try getOptionalStringArrayDetail(from: detailsRef, using: query) else {
throw DependencyScanningError.missingField(fieldName)
}
return result
}
}
private extension SwiftScan {
/// Decode the module name returned by libSwiftScan into a `ModuleDependencyId`
/// libSwiftScan encodes the module's name using the following scheme:
/// `<module-kind>:<module-name>`
/// where `module-kind` is one of:
/// "swiftTextual"
/// "swiftBinary"
/// "swiftPlaceholder"
/// "clang""
func decodeModuleNameAndKind(from encodedName: String,
moduleAliases: [String: String]?) throws -> ModuleDependencyId {
switch encodedName {
case _ where encodedName.starts(with: "swiftTextual:"):
var namePart = String(encodedName.suffix(encodedName.count - "swiftTextual:".count))
if let moduleAliases = moduleAliases, let realName = moduleAliases[namePart] {
namePart = realName
}
return .swift(namePart)
case _ where encodedName.starts(with: "swiftBinary:"):
var namePart = String(encodedName.suffix(encodedName.count - "swiftBinary:".count))
if let moduleAliases = moduleAliases, let realName = moduleAliases[namePart] {
namePart = realName
}
return .swiftPrebuiltExternal(namePart)
case _ where encodedName.starts(with: "swiftPlaceholder:"):
return .swiftPlaceholder(String(encodedName.suffix(encodedName.count - "swiftPlaceholder:".count)))
case _ where encodedName.starts(with: "clang:"):
return .clang(String(encodedName.suffix(encodedName.count - "clang:".count)))
default:
throw DependencyScanningError.moduleNameDecodeFailure(encodedName)
}
}
}
| apache-2.0 | de8710a831dd77e5ceb1ff8418a68afd | 50.684864 | 122 | 0.678621 | 4.66495 | false | false | false | false |
huonw/swift | test/Constraints/diagnostics.swift | 1 | 54337 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g())
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '((Int, Double)) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{'myMap' is unavailable: call the 'map()' method on the sequence}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot invoke 'count' with no arguments}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{type of expression is ambiguous without more context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-warning {{deprecated}}
a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{11-11=x: 5, }} {{15-21=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{17-17=x: 5, }} {{21-27=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// SR-2505: "Call arguments did not match up" assertion
// Here we're simulating the busted Swift 3 behavior -- see
// test/Constraints/diagnostics_swift4.swift for the correct
// behavior.
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
// FIXME: emit a warning saying this becomes an error in Swift 4
let c_2505 = C_2505(arg: [C2_2505()])
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{35-41=}} {{42-43=}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{18-18=Float(}} {{34-34=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{24-24=Float(}} {{27-27=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{16-16=Int(}} {{19-19=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'String'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(3) * "0"
struct S {}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'S'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note {{found this candidate}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Double'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Double, Double)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{argument 'foo' must precede argument 'b'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{argument 'a' must precede argument 'c'}} {{14-14=a: { !$0 }, }} {{26-38=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{argument 'x' must precede unnamed argument #1}} {{12-12=x: 20, }} {{21-28=}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 {{ambiguous use of operator '+'}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {}
// expected-note@-1 {{in call to function 'elephant'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{generic parameter 'U' could not be inferred}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{type of expression is ambiguous without more context}}
// FIXME: terrible diagnostic
}
| apache-2.0 | 7d648bfc1c2b52fc84501ceca61caeb7 | 43.502048 | 210 | 0.662624 | 3.522886 | false | false | false | false |
networkextension/SFSocket | SFSocket/tcp/HTTPProxyConnector.swift | 1 | 8016 | //
// HTTPProxyConnector.swift
// SimpleTunnel
//
// Created by yarshure on 15/11/11.
// Copyright © 2015年 Apple Inc. All rights reserved.
//
import Foundation
import AxLogger
public enum SFConnectionMode:String {
case HTTP = "HTTP"
case HTTPS = "HTTPS"
case TCP = "TCP"
//case CONNECT = "CONNECT"
public var description: String {
switch self {
case .HTTP: return "HTTP"
case .HTTPS: return "HTTPS"
case .TCP: return "TCP"
//case CONNECT: return "CONNECT"
}
}
}
public class HTTPProxyConnector:ProxyConnector {
var connectionMode:SFConnectionMode = .HTTP
public var reqHeader:SFHTTPRequestHeader?
public var respHeader:SFHTTPResponseHeader?
var httpConnected:Bool = false
var headerData:Data = Data()
static let ReadTag:Int = -2000
// https support current don't support
deinit {
//reqHeader = nil
//respHeader = nil
AxLogger.log("\(cIDString) deinit", level: .Debug)
}
func sendReq() {
if let req = reqHeader {
if let data = req.buildCONNECTHead(self.proxy) {
AxLogger.log("\(cIDString) sending CONNECTHead \(data) \(req.method)",level: .Debug)
self.writeData(data, withTag: HTTPProxyConnector.ReadTag)
}else {
AxLogger.log("\(cIDString) buildCONNECTHead error",level: .Error)
}
}else {
//sleep(1)
//sendReq()
AxLogger.log("\(cIDString) not reqHeader error",level: .Error)
}
}
func recvHeaderData(data:Data) ->Int{
// only use display response status,recent request feature need
if let r = data.range(of:hData, options: Data.SearchOptions.init(rawValue: 0)){
// body found
if headerData.count == 0 {
headerData = data
}else {
headerData.append( data)
}
//headerData.append( data.subdata(in: r))
respHeader = SFHTTPResponseHeader(data: headerData)
if let r = respHeader, r.sCode != 200 {
AxLogger.log("\(self) CONNECT status\(r.sCode) ",level: .Error)
//有bug
//let e = NSError(domain:errDomain , code: 10,userInfo:["reason":"http auth failure!!!"])
AxLogger.log("socketDidCloseReadStream \(data)",level:.Error)
self.forceDisconnect()
//sendReq()
//NSLog("CONNECT status\(r.sCode) ")
}
return r.upperBound // https need delete CONNECT respond
}else {
headerData.append(data)
}
return 0
}
override func readCallback(data: Data?, tag: Int) {
guard let data = data else {
AxLogger.log("\(cIDString) read nil", level: .Debug)
return
}
queueCall {
//AxLogger.log("read data \(data)", level: .Debug)
if self.httpConnected == false {
if self.respHeader == nil {
let len = self.recvHeaderData(data: data)
if len == 0{
AxLogger.log("http don't found resp header",level: .Warning)
}else {
//找到resp header
self.httpConnected = true
if let d = self.delegate {
d.didConnect(self)
}
if len < data.count {
let dataX = data.subdata(in: Range(len ..< data.count ))
//delegate?.connector(self, didReadData: dataX, withTag: 0)
autoreleasepool(invoking: {
self.delegate?.didReadData( dataX, withTag: tag, from: self)
})
//AxLogger.log("\(cIDString) CONNECT response data\(data)",level: .Error)
}
}
}
//self.readDataWithTag(-1)
}else {
autoreleasepool(invoking: {
self.delegate?.didReadData( data, withTag: tag, from: self)
})
}
}
}
override public func socketConnectd() {
if httpConnected == false {
self.sendReq()
}else {
self.delegate?.didConnect( self)
}
}
public override func sendData(data: Data, withTag tag: Int) {
if writePending {
AxLogger.log("Socket-\(cID) writePending error", level: .Debug)
return
}
writePending = true
if isConnected == false {
AxLogger.log("isConnected error", level: .Error)
return
}
self.connection!.write(data) {[weak self] error in
guard let strong = self else {return}
strong.writePending = false
guard error == nil else {
AxLogger.log("NWTCPSocket got an error when writing data: \(error!.localizedDescription)",level: .Debug)
strong.forceDisconnect()
return
}
strong.queueCall {
if strong.httpConnected == false {
strong.readDataWithTag(HTTPProxyConnector.ReadTag)
}else {
strong.queueCall { autoreleasepool {
strong.delegate?.didWriteData(data, withTag: tag, from: strong)
}}
}
}
strong.checkStatus()
}
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == "state" else {
return
}
//crash
if object == nil {
AxLogger.log("\(cIDString) connection lost", level: .Error)
disconnect()
return
}
if let error = connection?.error {
AxLogger.log("Socket-\(cIDString) state: \(error.localizedDescription)", level: .Debug)
}
switch connection!.state {
case .connected:
queueCall {[weak self] in
if let strong = self {
strong.socketConnectd()
}
}
case .disconnected:
cancel()
case .cancelled:
queueCall {
if let delegate = self.delegate{
delegate.didDisconnect(self)
}
//self.delegate = nil
}
default:
break
// case .Connecting:
// stateString = "Connecting"
// case .Waiting:
// stateString = "Waiting"
// case .Invalid:
// stateString = "Invalid"
}
// if let x = connection.endpoint as! NWHostEndpoint {
//
// }
if let error = connection!.error {
AxLogger.log("\(cIDString) \(error.localizedDescription)", level: .Error)
}
AxLogger.log("\(cIDString) stat: \(connection!.state.description)", level: .Debug)
}
public static func connectorWithSelectorPolicy(targetHostname hostname:String, targetPort port:UInt16,p:SFProxy) ->HTTPProxyConnector{
let c:HTTPProxyConnector = HTTPProxyConnector(p: p)
//c.manager = man
//c.cIDFunc()
c.targetHost = hostname
c.targetPort = port
//c.start()
return c
}
}
| bsd-3-clause | 7b65ca5f11ce0b6ac18085ec69cf415a | 32.3625 | 158 | 0.486449 | 4.995009 | false | false | false | false |
innominds-mobility/swift-custom-ui-elements | swift-custom-ui/InnoUI/InnoProgressViewBar.swift | 1 | 3619 | //
// InnoProgressViewBar.swift
// swift-custom-ui
//
// Created by Deepthi Muramshetty on 10/05/17.
// Copyright © 2017 Innominds Mobility. All rights reserved.
//
import UIKit
/// The purpose of this class is to provide custom view for showing progress in a bar.
/// The `InnoProgressViewBar` class is a subclass of the `UIView`.
@IBDesignable public class InnoProgressViewBar: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
/// IBInspectable for Progress of InnoProgressViewBar.
@IBInspectable public var progressValue: CGFloat = 0.0 {
didSet {
self.drawProgressBarLayer(incremented: progressValue)
}
}
/// IBInspectable for Bar corner radius of InnoProgressViewBar.
@IBInspectable public var barCornerRadius: CGFloat = 0.0 {
didSet {
self.layer.masksToBounds = true
self.layer.cornerRadius = barCornerRadius
}
}
/// IBInspectable for Bar color of InnoProgressViewBar.
@IBInspectable public var barColor: UIColor = UIColor.clear
/// IBInspectable for Progress color of InnoProgressViewBar.
@IBInspectable public var progressColor: UIColor = UIColor.green
/// Performing custom drawing for Progress bar.
///
/// - Parameter rect: The portion of the view’s bounds that needs to be updated.
override public func draw(_ rect: CGRect) {
// Add ARCs
self.drawDefaultBarLayer()
self.drawProgressBarLayer(incremented: self.progressValue)
}
/// Shape layer for Progress default bar.
var borderLayer: CAShapeLayer = CAShapeLayer()
/// Shape layer for Progress bar.
let progressBarLayer: CAShapeLayer = CAShapeLayer()
// MARK: Drawing default bar layer method
/// This method draws default rectangle bar layer on a bezier path and fills default color to it.
/// This layer is added as a sublayer for self.
func drawDefaultBarLayer() {
/// Path for default bar.
let bezierPath = UIBezierPath(roundedRect:bounds, cornerRadius: self.barCornerRadius)
bezierPath.close()
borderLayer.path = bezierPath.cgPath
borderLayer.fillColor = self.barColor.cgColor
borderLayer.strokeEnd = 0
self.layer.addSublayer(borderLayer)
}
// MARK: Drawing Progress Bar layer Method
/// This method draws/redraws progress bar layer on bezier path and fills progress color to it.
/// This layer is added as a sublayer for 'borderLayer'.
/// For every change in progress value, this method is called.
///
/// - Parameter incremented: Progress value
func drawProgressBarLayer(incremented: CGFloat) {
if incremented*(bounds.width-10)/100 <= bounds.width - 10 {
progressBarLayer.removeFromSuperlayer()
/// Path for progress bar.
let bezierPathProgessBar = UIBezierPath(roundedRect: CGRect(x:5, y: 5,
width:incremented*(bounds.width-10)/100,
height:bounds.height - 10),
cornerRadius: self.barCornerRadius)
bezierPathProgessBar.close()
progressBarLayer.path = bezierPathProgessBar.cgPath
progressBarLayer.fillColor = self.progressColor.cgColor
borderLayer.addSublayer(progressBarLayer)
}
}
}
| gpl-3.0 | d91438957b0afafa1dc47f949618b9cd | 39.629213 | 108 | 0.647954 | 5.029207 | false | false | false | false |
thelukester92/swift-engine | swift-engine/Engine/Classes/LGSpriteSheet.swift | 1 | 1409 | //
// LGSpriteSheet.swift
// swift-engine
//
// Created by Luke Godfrey on 6/7/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import SpriteKit
public class LGSpriteSheet
{
var texture: SKTexture
var textureName: String
var width: Int
var height: Int
var rows: Int { return Int(texture.size().height) / height }
var cols: Int { return Int(texture.size().width) / width }
public init(textureName: String, frameWidth: Int, frameHeight: Int)
{
self.texture = SKTexture(imageNamed: textureName)
self.textureName = textureName
self.width = frameWidth
self.height = frameHeight
}
public init(textureName: String, rows: Int, cols: Int)
{
self.texture = SKTexture(imageNamed: textureName)
self.textureName = textureName
self.width = Int(texture.size().width) / cols
self.height = Int(texture.size().height) / rows
}
public func textureAt(#row: Int, col: Int) -> SKTexture?
{
if row < 0 || col < 0
{
return nil
}
let rect = CGRect(
x: CGFloat(col * width) / texture.size().width,
y: CGFloat((rows - row - 1) * height) / texture.size().height,
width: CGFloat(width) / texture.size().width,
height: CGFloat(height) / texture.size().height
)
return SKTexture(rect: rect, inTexture: texture)
}
public func textureAtPosition(pos: Int) -> SKTexture?
{
return textureAt(row: (pos - 1) / cols, col: (pos - 1) % cols)
}
}
| mit | 6e324bf5ce141bbd6f0ec7490ab30b92 | 22.881356 | 68 | 0.66572 | 3.069717 | false | false | false | false |
crossroadlabs/Boilerplate | Sources/Boilerplate/Equatable.swift | 2 | 3456 | //===--- Equatable.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
public protocol NonStrictEquatable {
func isEqual(to other:NonStrictEquatable) -> Bool
}
public func ==<A : NonStrictEquatable, B : NonStrictEquatable>(lhs:A, rhs:B) -> Bool {
return lhs.isEqual(to: rhs)
}
public func !=<A : NonStrictEquatable, B : NonStrictEquatable>(lhs:A, rhs:B) -> Bool {
return !lhs.isEqual(to: rhs)
}
public func ==<T : Equatable & NonStrictEquatable>(lhs: T, rhs: T) -> Bool {
return lhs.isEqual(to: rhs)
}
public func !=<T : Equatable & NonStrictEquatable>(lhs: T, rhs: T) -> Bool {
return !lhs.isEqual(to: rhs)
}
//I would as well add protocol Equatable to collections, but unfortunately it's not possible in current Swift (2.1 at the moment of writing)
/*public protocol NonStrictEquatableCollection {
}
extension NonStrictEquatableCollection {
func ==<T : CollectionType where T.Generator.Element : NonStrictEquatable>(lhs: T, rhs: T) -> Bool
}*/
#if swift(>=3.0)
public func ==<T : Collection>(lhs: T, rhs: T) -> Bool where T.Iterator.Element == NonStrictEquatable {
if lhs.count != rhs.count {
return false
}
let zip = lhs.zipWith(other: rhs)
for (lhsv, rhsv) in zip {
if !lhsv.isEqual(to: rhsv) {
return false
}
}
return true
}
/// rewritten because can return early
public func !=<T : Collection>(lhs: T, rhs: T) -> Bool where T.Iterator.Element == NonStrictEquatable {
if lhs.count != rhs.count {
return true
}
let zip = lhs.zipWith(other: rhs)
for (lhsv, rhsv) in zip {
if lhsv.isEqual(to: rhsv) {
return false
}
}
return true
}
#else
@warn_unused_result
public func ==<T : Collection where T.Generator.Element == NonStrictEquatable>(lhs: T, rhs: T) -> Bool {
if lhs.count != rhs.count {
return false
}
let zip = lhs.zipWith(other: rhs)
for (lhsv, rhsv) in zip {
if !lhsv.isEqual(to: rhsv) {
return false
}
}
return true
}
/// rewritten because can return early
@warn_unused_result
public func !=<T : Collection where T.Generator.Element == NonStrictEquatable>(lhs: T, rhs: T) -> Bool {
if lhs.count != rhs.count {
return true
}
let zip = lhs.zipWith(other: rhs)
for (lhsv, rhsv) in zip {
if lhsv.isEqual(to: rhsv) {
return false
}
}
return true
}
#endif
| apache-2.0 | 03d75ddaca2cb4c6231ee38c16797078 | 27.8 | 140 | 0.564525 | 4.153846 | false | false | false | false |
freshOS/Komponents | Source/Image.swift | 1 | 1889 | //
// Image.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 12/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
public struct Image: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public var children = [IsNode]()
let props: ImageProps
public var layout: Layout
public let ref: UnsafeMutablePointer<UIImageView>?
public init(_ image: UIImage = UIImage(),
props: ((inout ImageProps) -> Void)? = nil,
layout: Layout? = nil,
ref: UnsafeMutablePointer<UIImageView>? = nil) {
var defaultProps = ImageProps()
defaultProps.image = image
if let p = props {
var prop = defaultProps
p(&prop)
self.props = prop
} else {
self.props = defaultProps
}
self.layout = layout ?? Layout()
self.ref = ref
}
}
public func == (lhs: Image, rhs: Image) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public struct ImageProps: HasViewProps, Equatable, Hashable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public var image = UIImage()
public var contentMode = UIView.ContentMode.scaleToFill
public var hashValue: Int {
return viewPropsHash
^ image.hashValue
^ contentMode.hashValue
}
}
public func == (lhs: ImageProps, rhs: ImageProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | e2341509f6fe8595e98ce6f8ed003f29 | 27.179104 | 64 | 0.620233 | 4.604878 | false | false | false | false |
Akcbryant/TTT | TTTViewController.swift | 1 | 3566 | import Foundation
import UIKit
enum CurrentState: String {
case Begin = "Pick your piece."
case Draw = "That's a DRAW. Try again!"
case ComputerTurn = "I'm Moving!"
case HumanTurn = "It's your turn!"
case ComputerWin = "Computers rule! Pick again!"
}
public class TTTViewController: UIViewController, TTTViewDelegate {
var currentBoard = Board()
var tttEngine = TTT()
var tttBoardView: TTTView?
var currentState = CurrentState.Begin {
didSet {
tttBoardView?.infoLabel.text = currentState.rawValue
checkCurrentState()
}
}
public override func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
tttBoardView = TTTView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
view.addSubview(tttBoardView!)
tttBoardView!.delegate = self
}
/**
Checks validity of move and processes it if it is valid.
- parameter position: Position that was tapped.
*/
func gridPressed(position: Int, sender: UIButton) {
if currentBoard.configuration[position] == Player.Empty {
processMove(position, player: tttEngine.human, board: currentBoard)
}
}
/**
Serves to read current state of the board and get the appropriate next step/move.
*/
func checkCurrentState() {
if currentState == .ComputerTurn {
let nextMove = tttEngine.getNextMove(currentBoard)
processMove(nextMove, player: tttEngine.computer, board: currentBoard)
}
}
/**
Takes a possible move and takes the appropriate action based on the current state of the board.
- parameter position: The place one wants to move.
- parameter player: The player that wishes to move.
- parameter board: The board upon which one wants to move.
*/
func processMove(position: Int, player: Player, board: Board) {
if tttEngine.isFinished(board) {
currentState = .Draw
} else if tttEngine.checkForWinner(board, player: tttEngine.computer) {
currentState = .ComputerWin
} else if player == tttEngine.human {
currentBoard = tttEngine.makeMove(position, player: player, board: board)
tttBoardView?.renderMove(position, player: player)
currentState = .ComputerTurn
} else if player == tttEngine.computer {
currentBoard = tttEngine.makeMove(position, player: player, board: board)
tttBoardView?.renderMove(position, player: player)
if tttEngine.checkForWinner(currentBoard, player: tttEngine.computer) {
currentState = .ComputerWin
} else {
currentState = .HumanTurn
}
}
}
func xButtonPressed(sender: UIButton) {
resetBoard()
tttEngine.human = .Player1
tttEngine.computer = .Player2
currentState = .HumanTurn
}
func oButtonPressed(sender: UIButton) {
resetBoard()
tttEngine.human = .Player2
tttEngine.computer = .Player1
computerFirstMove()
}
func computerFirstMove() {
currentState = .HumanTurn
currentBoard = tttEngine.makeMove(0, player: tttEngine.computer, board: currentBoard)
tttBoardView?.renderMove(0, player: tttEngine.computer)
}
func resetBoard() {
currentBoard = Board()
tttBoardView?.resetButtons()
currentState = .Begin
}
}
| mit | 6eb69f18a96e86bd20fe7d50ea869f08 | 32.018519 | 109 | 0.625351 | 4.429814 | false | false | false | false |
JanNash/Swango | Djaft/Sources/Classes/DJRefinableQuerySet.swift | 2 | 3890 | //
// DJRefinableQuerySet.swift
// Djaft
//
// Created by Jan Nash on 22/11/15.
// Copyright © 2015 Jan Nash. All rights reserved.
//
import Foundation
import CoreData
//import Synchronized
// MARK: // Public
// MARK: Interface
public extension DJRefinableQuerySet {
// Get Sliced QuerySet
// (Does not evaluate, returns DJFinalQuerySet that does not allow more refinements)
public subscript(startIndex: Int, endIndex: Int) -> DJFinalQuerySet<T> {
return self._getSlicedQuerySet(startIndex, endIndex: endIndex)
}
// Get Objects From Start To End With Step
// (Evaluates)
public subscript(startIndex: Int, endIndex: Int, stepSize: Int) -> [T] {
return self._objectsFromStart(startIndex, toEnd: endIndex, withStepSize: stepSize)
}
// QuerySet Generation
public func filter(params: String...) -> DJRefinableQuerySet {
return self._querySetCreator.__filter__(params)
}
public func exclude(params: String...) -> DJRefinableQuerySet {
return self._querySetCreator.__exclude__(params)
}
public func orderBy(params: String...) -> DJRefinableQuerySet {
return self._querySetCreator.__orderBy__(params)
}
}
// MARK: Class Declaration
public class DJRefinableQuerySet<T: NSManagedObject>: DJMetaQuerySet<T> {
override init(withClass klass: NSManagedObject.Type,
objectContext: NSManagedObjectContext? = nil,
filters: [String] = [],
excludes: [String] = [],
orderBys: [String]? = nil,
fetchedObjects: [T]? = nil) {
super.init(
withClass: klass,
objectContext: objectContext,
filters: filters,
excludes: excludes,
orderBys: orderBys,
fetchedObjects: fetchedObjects
)
}
private var __querySetCreator: DJQuerySetCreator<T>!
}
// MARK: // Private
// MARK: Computed Properties
private extension DJRefinableQuerySet {
private var _querySetCreator: DJQuerySetCreator<T> {
if self.__querySetCreator == nil {
self.__querySetCreator = DJQuerySetCreator(
withClass: self.klass_,
objectContext: self.objectContext,
filters: self.filters,
excludes: self.excludes,
orderBys: self.orderBys
)
}
return self.__querySetCreator
}
}
// MARK: Get Sliced QuerySet
private extension DJRefinableQuerySet {
private func _getSlicedQuerySet(startIndex: Int, endIndex: Int) -> DJFinalQuerySet<T> {
var objects: [T]?
if self.isFetched {
objects = self.objects_()
}
var limit: Int = endIndex - startIndex
if limit <= 0 {
print("WARNING: Created SlicedQuerySet with a limit <= 0. " +
"This is most likely caused by an erratic subscript-usage. " +
"This QuerySet will never return any objects.")
limit = 0
}
return DJFinalQuerySet(
_withClass: self.klass_,
objectContext: self.objectContext,
offset: startIndex,
limit: limit,
filters: self.filters,
excludes: self.excludes,
orderBys: self.orderBys,
fetchedObjects: objects
)
}
}
// MARK: Get Objects From Start To End With Step
private extension DJMetaQuerySet {
private func _objectsFromStart(startIndex: Int, toEnd endIndex: Int, withStepSize stepSize: Int) -> [T] {
// self.evaluate()
var result: [T] = []
var index: Int = startIndex
while index < endIndex {
result.append(self[index]!)
index += stepSize
}
return result
}
}
| mit | 94527fca5a2647d22589453d42bdb6d4 | 29.865079 | 109 | 0.58704 | 4.511601 | false | false | false | false |
DJLectr0/StockExchangeGame | stockexchange/ChangePriceTableViewCell.swift | 1 | 2242 | //
// ChangePriceTableViewCell.swift
// stockexchange
//
// Created by Leonardo Galli on 21.06.15.
// Copyright (c) 2015 SleepyImpStudio. All rights reserved.
//
import UIKit
public class ChangePriceTableViewCell: UITableViewCell {
@IBOutlet weak var priceField: UITextField!
@IBOutlet weak var productName: UILabel!
@IBAction func changePrice(sender: UITextField) {
println(sender.text)
}
public override func layoutSubviews(){
var toolbar = UIToolbar.new()
toolbar.frame.size.height = 35
var doneButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "hideKeyboard")
var space:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
var items = [AnyObject]()
items.append(space)
items.append(doneButton)
toolbar.items = items
priceField.inputAccessoryView = toolbar
}
public func configure(product: String) {
self.productName.text = product
}
func hideKeyboard() {
println("Test")
priceField.resignFirstResponder()
var defaults = NSUserDefaults.standardUserDefaults()
var game = defaults.valueForKey("game")
var url = "http://leonardogalli.ch/stockexchange/changePrice.php?game=\(game as! String)&price=\(self.priceField.text)&product=" + self.productName.text!
url = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
println(url)
send(url, f: { (result) -> () in
println(result)
})
}
public override func prepareForReuse() {
super.prepareForReuse()
self.priceField.text = ""
}
func send(url: String, f: (String)-> ()) {
var request = NSURLRequest(URL: NSURL(string: url)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error)
var reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
f(reply! as String)
}
}
| mit | 7b419fbf70928ee94cfe1d0ccee0ae3a | 29.712329 | 161 | 0.632917 | 4.863341 | false | false | false | false |
Appsaurus/Infinity | Infinity/controls/default/DefaultRefreshAnimator.swift | 1 | 2687 | //
// DefaultRefreshAnimator.swift
// InfinitySample
//
// Created by Danis on 15/12/23.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
open class DefaultRefreshAnimator: UIView, CustomPullToRefreshAnimator {
open var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
open var circleLayer: CAShapeLayer = CAShapeLayer()
public override init(frame: CGRect) {
super.init(frame: frame)
activityIndicatorView.isHidden = true
activityIndicatorView.hidesWhenStopped = true
circleLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)).cgPath
circleLayer.strokeColor = UIColor.gray.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineWidth = 3
circleLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(-M_PI/2)))
circleLayer.strokeStart = 0
circleLayer.strokeEnd = 0
self.addSubview(activityIndicatorView)
self.layer.addSublayer(circleLayer)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
activityIndicatorView.frame = self.bounds
circleLayer.frame = self.bounds
}
open func animateState(_ state: PullToRefreshState) {
switch state {
case .none:
stopAnimating()
case .releasing(let progress):
self.updateCircle(progress)
case .loading:
startAnimating()
}
}
func startAnimating() {
circleLayer.isHidden = true
circleLayer.strokeEnd = 0
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
}
func stopAnimating() {
circleLayer.isHidden = false
activityIndicatorView.isHidden = true
activityIndicatorView.stopAnimating()
}
func updateCircle(_ progress: CGFloat) {
CATransaction.begin()
CATransaction.setDisableActions(true)
circleLayer.strokeStart = 0
// 为了让circle增长速度在开始时比较慢,后来加快,这样更好看
circleLayer.strokeEnd = progress * progress
CATransaction.commit()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 7b5dfb0097947441e373672de13f2eff | 31.121951 | 116 | 0.659453 | 5.289157 | false | false | false | false |
Vostro162/VaporTelegram | Sources/App/InlineQueryResultDocument.swift | 1 | 1113 | //
// InlineQueryResultDocument.swift
// VaporTelegram
//
// Created by Marius Hartig on 05.06.17.
//
//
import Foundation
struct InlineQueryResultDocument: InlineQuery {
let id: String
let type: String
let url: URL
let title: String
let mimeType: String
let caption: String?
let description: String?
let thumbURL: URL?
let thumbWidth: Int?
let thumbHeight: Int?
let replyMarkup: ReplyMarkup?
public init(
id: String,
type: String,
url: URL,
title: String,
mimeType: String,
caption: String?,
description: String?,
thumbURL: URL?,
thumbWidth: Int?,
thumbHeight: Int?,
replyMarkup: ReplyMarkup?
) {
self.id = id
self.type = type
self.url = url
self.title = title
self.mimeType = mimeType
self.caption = caption
self.description = description
self.thumbURL = thumbURL
self.thumbWidth = thumbWidth
self.thumbHeight = thumbHeight
self.replyMarkup = replyMarkup
}
}
| mit | 05914fdcc9485f965a71101e90687523 | 20.823529 | 47 | 0.5885 | 4.46988 | false | false | false | false |
Meru-Interactive/iOSC | swiftOSC/Communication/OSCClient.swift | 1 | 564 | import Foundation
public class OSCClient {
public var address: String
public var port: Int
public init(address: String, port: Int){
self.address = address
self.port = port
}
public func send(_ element: OSCElement){
var data = element.data
if data.count > 9216 {
print("OSCPacket is too large. Must be smaller than 9200 bytes")
} else {
let client = UDPClient(addr: address, port: port)
_ = client.send(data:data)
_ = client.close()
}
}
}
| mit | cef4c01aab254542959fef331d54a0fe | 25.857143 | 76 | 0.56383 | 4.116788 | false | false | false | false |
tominated/Quake-3-BSP-Renderer | Quake 3 BSP Renderer/Q3EntityParser.swift | 1 | 1474 | //
// Q3EntityParser.swift
// Quake 3 BSP Renderer
//
// Created by Thomas Brunoli on 13/8/17.
// Copyright © 2017 Thomas Brunoli. All rights reserved.
//
import Foundation
let openBrace = CharacterSet.init(charactersIn: "{")
let closeBrace = CharacterSet.init(charactersIn: "}")
let quote = CharacterSet.init(charactersIn: "\"")
class Q3EntityParser {
let scanner: Scanner
init(entitiesString: String) {
scanner = Scanner(string: entitiesString)
}
func parse() -> Array<Dictionary<String, String>> {
var entities = Array<Dictionary<String, String>>()
while scanner.scanCharacters(from: openBrace, into: nil) {
entities.append(parseEntity())
}
return entities
}
private func parseEntity() -> Dictionary<String, String> {
var entity = Dictionary<String, String>()
while !scanner.scanCharacters(from: closeBrace, into: nil) {
var rawKey: NSString?
var rawValue: NSString?
scanner.scanCharacters(from: quote, into: nil)
scanner.scanUpToCharacters(from: quote, into: &rawKey)
scanner.scanString("\" \"", into: nil)
scanner.scanUpToCharacters(from: quote, into: &rawValue)
scanner.scanCharacters(from: quote, into: nil)
if let key = rawKey, let value = rawValue {
entity[key as String] = value as String
}
}
return entity
}
}
| mit | 6f62e106645d1bfd18aa100896ea58c0 | 27.326923 | 68 | 0.619145 | 4.332353 | false | false | false | false |
CatchChat/Yep | YepKit/Persistence/Models.swift | 1 | 69863 | //
// Models.swift
// Yep
//
// Created by NIX on 15/3/20.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import MapKit
import YepNetworking
import RealmSwift
// 总是在这个队列里使用 Realm
//let realmQueue = dispatch_queue_create("com.Yep.realmQueue", DISPATCH_QUEUE_SERIAL)
public let realmQueue = dispatch_queue_create("com.Yep.realmQueue", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0))
// MARK: User
// 朋友的“状态”, 注意:上线后若要调整,只能增加新状态
public enum UserFriendState: Int {
case Stranger = 0 // 陌生人
case IssuedRequest = 1 // 已对其发出好友请求
case Normal = 2 // 正常状态的朋友
case Blocked = 3 // 被屏蔽
case Me = 4 // 自己
case Yep = 5 // Yep官方账号
}
public class Avatar: Object {
public dynamic var avatarURLString: String = ""
public dynamic var avatarFileName: String = ""
public dynamic var roundMini: NSData = NSData() // 60
public dynamic var roundNano: NSData = NSData() // 40
let users = LinkingObjects(fromType: User.self, property: "avatar")
public var user: User? {
return users.first
}
}
public class UserSkillCategory: Object {
public dynamic var skillCategoryID: String = ""
public dynamic var name: String = ""
public dynamic var localName: String = ""
public let skills = LinkingObjects(fromType: UserSkill.self, property: "category")
}
public class UserSkill: Object {
public dynamic var category: UserSkillCategory?
var skillCategory: SkillCellSkill.Category? {
if let category = category {
return SkillCellSkill.Category(rawValue: category.name)
}
return nil
}
public dynamic var skillID: String = ""
public dynamic var name: String = ""
public dynamic var localName: String = ""
public dynamic var coverURLString: String = ""
public let learningUsers = LinkingObjects(fromType: User.self, property: "learningSkills")
public let masterUsers = LinkingObjects(fromType: User.self, property: "masterSkills")
}
public class UserSocialAccountProvider: Object {
public dynamic var name: String = ""
public dynamic var enabled: Bool = false
}
public class UserDoNotDisturb: Object {
public dynamic var isOn: Bool = false
public dynamic var fromHour: Int = 22
public dynamic var fromMinute: Int = 0
public dynamic var toHour: Int = 7
public dynamic var toMinute: Int = 30
public var hourOffset: Int {
let localTimeZone = NSTimeZone.localTimeZone()
let totalSecondsOffset = localTimeZone.secondsFromGMT
let hourOffset = totalSecondsOffset / (60 * 60)
return hourOffset
}
public var minuteOffset: Int {
let localTimeZone = NSTimeZone.localTimeZone()
let totalSecondsOffset = localTimeZone.secondsFromGMT
let hourOffset = totalSecondsOffset / (60 * 60)
let minuteOffset = (totalSecondsOffset - hourOffset * (60 * 60)) / 60
return minuteOffset
}
public func serverStringWithHour(hour: Int, minute: Int) -> String {
if minute - minuteOffset > 0 {
return String(format: "%02d:%02d", (hour - hourOffset) % 24, (minute - minuteOffset) % 60)
} else {
return String(format: "%02d:%02d", (hour - hourOffset - 1) % 24, ((minute + 60) - minuteOffset) % 60)
}
}
public var serverFromString: String {
return serverStringWithHour(fromHour, minute: fromMinute)
}
public var serverToString: String {
return serverStringWithHour(toHour, minute: toMinute)
}
public var localFromString: String {
return String(format: "%02d:%02d", fromHour, fromMinute)
}
public var localToString: String {
return String(format: "%02d:%02d", toHour, toMinute)
}
}
public class User: Object {
public dynamic var userID: String = ""
public dynamic var username: String = ""
public dynamic var nickname: String = ""
public dynamic var introduction: String = ""
public dynamic var avatarURLString: String = ""
public dynamic var avatar: Avatar?
public dynamic var badge: String = ""
public dynamic var blogURLString: String = ""
public dynamic var blogTitle: String = ""
public override class func indexedProperties() -> [String] {
return ["userID"]
}
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var lastSignInUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var friendState: Int = UserFriendState.Stranger.rawValue
public dynamic var friendshipID: String = ""
public dynamic var isBestfriend: Bool = false
public dynamic var bestfriendIndex: Int = 0
public var canShowProfile: Bool {
return friendState != UserFriendState.Yep.rawValue
}
public dynamic var longitude: Double = 0
public dynamic var latitude: Double = 0
public dynamic var notificationEnabled: Bool = true
public dynamic var blocked: Bool = false
public dynamic var doNotDisturb: UserDoNotDisturb?
public var learningSkills = List<UserSkill>()
public var masterSkills = List<UserSkill>()
public var socialAccountProviders = List<UserSocialAccountProvider>()
public let messages = LinkingObjects(fromType: Message.self, property: "fromFriend")
let conversations = LinkingObjects(fromType: Conversation.self, property: "withFriend")
public var conversation: Conversation? {
return conversations.first
}
public let ownedGroups = LinkingObjects(fromType: Group.self, property: "owner")
public let belongsToGroups = LinkingObjects(fromType: Group.self, property: "members")
public let createdFeeds = LinkingObjects(fromType: Feed.self, property: "creator")
public var isMe: Bool {
if let myUserID = YepUserDefaults.userID.value {
return userID == myUserID
}
return false
}
public var mentionedUsername: String? {
if username.isEmpty {
return nil
} else {
return "@\(username)"
}
}
public var compositedName: String {
if username.isEmpty {
return nickname
} else {
return "\(nickname) @\(username)"
}
}
// 级联删除关联的数据对象
public func cascadeDeleteInRealm(realm: Realm) {
if let avatar = avatar {
if !avatar.avatarFileName.isEmpty {
NSFileManager.deleteAvatarImageWithName(avatar.avatarFileName)
}
realm.delete(avatar)
}
if let doNotDisturb = doNotDisturb {
realm.delete(doNotDisturb)
}
socialAccountProviders.forEach({
realm.delete($0)
})
realm.delete(self)
}
}
// MARK: Group
// Group 类型,注意:上线后若要调整,只能增加新状态
public enum GroupType: Int {
case Public = 0
case Private = 1
}
public class Group: Object {
public dynamic var groupID: String = ""
public dynamic var groupName: String = ""
public dynamic var notificationEnabled: Bool = true
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var owner: User?
public var members = List<User>()
public dynamic var groupType: Int = GroupType.Private.rawValue
public dynamic var withFeed: Feed?
public dynamic var includeMe: Bool = false
let conversations = LinkingObjects(fromType: Conversation.self, property: "withGroup")
public var conversation: Conversation? {
return conversations.first
}
// 级联删除关联的数据对象
public func cascadeDeleteInRealm(realm: Realm) {
withFeed?.cascadeDeleteInRealm(realm)
if let conversation = conversation {
realm.delete(conversation)
SafeDispatch.async {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.changedConversation, object: nil)
}
}
realm.delete(self)
}
}
// MARK: Message
public class Coordinate: Object {
public dynamic var latitude: Double = 0 // 合法范围 (-90, 90)
public dynamic var longitude: Double = 0 // 合法范围 (-180, 180)
// NOTICE: always use safe version property
public var safeLatitude: Double {
return abs(latitude) > 90 ? 0 : latitude
}
public var safeLongitude: Double {
return abs(longitude) > 180 ? 0 : longitude
}
public var locationCoordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: safeLatitude, longitude: safeLongitude)
}
public func safeConfigureWithLatitude(latitude: Double, longitude: Double) {
self.latitude = abs(latitude) > 90 ? 0 : latitude
self.longitude = abs(longitude) > 180 ? 0 : longitude
}
}
public enum MessageDownloadState: Int {
case NoDownload = 0 // 未下载
case Downloading = 1 // 下载中
case Downloaded = 2 // 已下载
}
public enum MessageMediaType: Int, CustomStringConvertible {
case Text = 0
case Image = 1
case Video = 2
case Audio = 3
case Sticker = 4
case Location = 5
case SectionDate = 6
case SocialWork = 7
case ShareFeed = 8
public var description: String {
switch self {
case .Text:
return "text"
case .Image:
return "image"
case .Video:
return "video"
case .Audio:
return "audio"
case .Sticker:
return "sticker"
case .Location:
return "location"
case .SectionDate:
return "sectionDate"
case .SocialWork:
return "socialWork"
case .ShareFeed:
return "shareFeed"
}
}
public var fileExtension: FileExtension? {
switch self {
case .Image:
return .JPEG
case .Video:
return .MP4
case .Audio:
return .M4A
default:
return nil // TODO: more
}
}
public var placeholder: String? {
switch self {
case .Text:
return nil
case .Image:
return NSLocalizedString("placeholder.image", comment: "")
case .Video:
return NSLocalizedString("placeholder.video", comment: "")
case .Audio:
return NSLocalizedString("placeholder.audio", comment: "")
case .Sticker:
return NSLocalizedString("placeholder.sticker", comment: "")
case .Location:
return NSLocalizedString("placeholder.location", comment: "")
case .SocialWork:
return NSLocalizedString("placeholder.socialWork", comment: "")
default:
return NSLocalizedString("placeholder.all_messages_read", comment: "")
}
}
}
public enum MessageSendState: Int, CustomStringConvertible {
case NotSend = 0
case Failed = 1
case Successed = 2
case Read = 3
public var description: String {
get {
switch self {
case NotSend:
return "NotSend"
case Failed:
return "Failed"
case Successed:
return "Sent"
case Read:
return "Read"
}
}
}
}
public class MediaMetaData: Object {
public dynamic var data: NSData = NSData()
public var string: String? {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
public class SocialWorkGithubRepo: Object {
public dynamic var repoID: Int = 0
public dynamic var name: String = ""
public dynamic var fullName: String = ""
public dynamic var URLString: String = ""
public dynamic var repoDescription: String = ""
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var synced: Bool = false
public class func getWithRepoID(repoID: Int, inRealm realm: Realm) -> SocialWorkGithubRepo? {
let predicate = NSPredicate(format: "repoID = %d", repoID)
return realm.objects(SocialWorkGithubRepo).filter(predicate).first
}
public func fillWithGithubRepo(githubRepo: GithubRepo) {
self.repoID = githubRepo.ID
self.name = githubRepo.name
self.fullName = githubRepo.fullName
self.URLString = githubRepo.URLString
self.repoDescription = githubRepo.description
self.createdUnixTime = githubRepo.createdAt.timeIntervalSince1970
}
public func fillWithFeedGithubRepo(githubRepo: DiscoveredFeed.GithubRepo) {
self.repoID = githubRepo.ID//(githubRepo.ID as NSString).integerValue
self.name = githubRepo.name
self.fullName = githubRepo.fullName
self.URLString = githubRepo.URLString
self.repoDescription = githubRepo.description
self.createdUnixTime = githubRepo.createdUnixTime
}
}
public class SocialWorkDribbbleShot: Object {
public dynamic var shotID: Int = 0
public dynamic var title: String = ""
public dynamic var htmlURLString: String = ""
public dynamic var imageURLString: String = ""
public dynamic var shotDescription: String = ""
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var synced: Bool = false
public class func getWithShotID(shotID: Int, inRealm realm: Realm) -> SocialWorkDribbbleShot? {
let predicate = NSPredicate(format: "shotID = %d", shotID)
return realm.objects(SocialWorkDribbbleShot).filter(predicate).first
}
public func fillWithDribbbleShot(dribbbleShot: DribbbleShot) {
self.shotID = dribbbleShot.ID
self.title = dribbbleShot.title
self.htmlURLString = dribbbleShot.htmlURLString
if let hidpi = dribbbleShot.images.hidpi where dribbbleShot.images.normal.contains("gif") {
self.imageURLString = hidpi
} else {
self.imageURLString = dribbbleShot.images.normal
}
if let description = dribbbleShot.description {
self.shotDescription = description
}
self.createdUnixTime = dribbbleShot.createdAt.timeIntervalSince1970
}
public func fillWithFeedDribbbleShot(dribbbleShot: DiscoveredFeed.DribbbleShot) {
self.shotID = dribbbleShot.ID//(dribbbleShot.ID as NSString).integerValue
self.title = dribbbleShot.title
self.htmlURLString = dribbbleShot.htmlURLString
self.imageURLString = dribbbleShot.imageURLString
if let description = dribbbleShot.description {
self.shotDescription = description
}
self.createdUnixTime = dribbbleShot.createdUnixTime
}
}
public class SocialWorkInstagramMedia: Object {
public dynamic var repoID: String = ""
public dynamic var linkURLString: String = ""
public dynamic var imageURLString: String = ""
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var synced: Bool = false
}
public enum MessageSocialWorkType: Int {
case GithubRepo = 0
case DribbbleShot = 1
case InstagramMedia = 2
public var accountName: String {
switch self {
case .GithubRepo: return "github"
case .DribbbleShot: return "dribbble"
case .InstagramMedia: return "instagram"
}
}
}
public class MessageSocialWork: Object {
public dynamic var type: Int = MessageSocialWorkType.GithubRepo.rawValue
public dynamic var githubRepo: SocialWorkGithubRepo?
public dynamic var dribbbleShot: SocialWorkDribbbleShot?
public dynamic var instagramMedia: SocialWorkInstagramMedia?
}
public class Message: Object {
public dynamic var messageID: String = ""
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var arrivalUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var mediaType: Int = MessageMediaType.Text.rawValue
public dynamic var textContent: String = ""
public var recalledTextContent: String {
let nickname = fromFriend?.nickname ?? ""
return String(format: NSLocalizedString("recalledMessage%@", comment: ""), nickname)
}
public var blockedTextContent: String {
let nickname = fromFriend?.nickname ?? ""
return String(format: NSLocalizedString("Ooops! You've been blocked.", comment: ""), nickname)
}
public dynamic var openGraphDetected: Bool = false
public dynamic var openGraphInfo: OpenGraphInfo?
public dynamic var coordinate: Coordinate?
public dynamic var attachmentURLString: String = ""
public dynamic var localAttachmentName: String = ""
public dynamic var thumbnailURLString: String = ""
public dynamic var localThumbnailName: String = ""
public dynamic var attachmentID: String = ""
public dynamic var attachmentExpiresUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 + (6 * 60 * 60 * 24) // 6天,过期时间s3为7天,客户端防止误差减去1天
public var imageFileURL: NSURL? {
if !localAttachmentName.isEmpty {
return NSFileManager.yepMessageImageURLWithName(localAttachmentName)
}
return nil
}
public var videoFileURL: NSURL? {
if !localAttachmentName.isEmpty {
return NSFileManager.yepMessageVideoURLWithName(localAttachmentName)
}
return nil
}
public var videoThumbnailFileURL: NSURL? {
if !localThumbnailName.isEmpty {
return NSFileManager.yepMessageImageURLWithName(localThumbnailName)
}
return nil
}
public var audioFileURL: NSURL? {
if !localAttachmentName.isEmpty {
return NSFileManager.yepMessageAudioURLWithName(localAttachmentName)
}
return nil
}
public var imageKey: String {
return "image-\(messageID)-\(localAttachmentName)-\(attachmentURLString)"
}
public var mapImageKey: String {
return "mapImage-\(messageID)"
}
public var nicknameWithTextContent: String {
if let nickname = fromFriend?.nickname {
return String(format: NSLocalizedString("nicknameWithTextContent_%@_%@", comment: ""), nickname, textContent)
} else {
return textContent
}
}
public var thumbnailImage: UIImage? {
switch mediaType {
case MessageMediaType.Image.rawValue:
if let imageFileURL = imageFileURL {
return UIImage(contentsOfFile: imageFileURL.path!)
}
case MessageMediaType.Video.rawValue:
if let imageFileURL = videoThumbnailFileURL {
return UIImage(contentsOfFile: imageFileURL.path!)
}
default:
return nil
}
return nil
}
public dynamic var mediaMetaData: MediaMetaData?
public dynamic var socialWork: MessageSocialWork?
public dynamic var downloadState: Int = MessageDownloadState.NoDownload.rawValue
public dynamic var sendState: Int = MessageSendState.NotSend.rawValue
public dynamic var readed: Bool = false
public dynamic var mediaPlayed: Bool = false // 音频播放过,图片查看过等
public dynamic var hidden: Bool = false // 隐藏对方消息,使之不再显示
public dynamic var deletedByCreator: Bool = false
public dynamic var blockedByRecipient: Bool = false
public var isIndicator: Bool {
return deletedByCreator || blockedByRecipient
}
public dynamic var fromFriend: User?
public dynamic var conversation: Conversation?
public var isReal: Bool {
if socialWork != nil {
return false
}
if mediaType == MessageMediaType.SectionDate.rawValue {
return false
}
return true
}
public func deleteAttachmentInRealm(realm: Realm) {
if let mediaMetaData = mediaMetaData {
realm.delete(mediaMetaData)
}
// 除非没有谁指向 openGraphInfo,不然不能删除它
if let openGraphInfo = openGraphInfo {
if openGraphInfo.feeds.isEmpty {
if openGraphInfo.messages.count == 1, let first = openGraphInfo.messages.first where first == self {
realm.delete(openGraphInfo)
}
}
}
switch mediaType {
case MessageMediaType.Image.rawValue:
NSFileManager.removeMessageImageFileWithName(localAttachmentName)
case MessageMediaType.Video.rawValue:
NSFileManager.removeMessageVideoFilesWithName(localAttachmentName, thumbnailName: localThumbnailName)
case MessageMediaType.Audio.rawValue:
NSFileManager.removeMessageAudioFileWithName(localAttachmentName)
case MessageMediaType.Location.rawValue:
NSFileManager.removeMessageImageFileWithName(localAttachmentName)
case MessageMediaType.SocialWork.rawValue:
if let socialWork = socialWork {
if let githubRepo = socialWork.githubRepo {
realm.delete(githubRepo)
}
if let dribbbleShot = socialWork.dribbbleShot {
realm.delete(dribbbleShot)
}
if let instagramMedia = socialWork.instagramMedia {
realm.delete(instagramMedia)
}
realm.delete(socialWork)
}
default:
break // TODO: if have other message media need to delete
}
}
public func deleteInRealm(realm: Realm) {
deleteAttachmentInRealm(realm)
realm.delete(self)
}
public func updateForDeletedFromServerInRealm(realm: Realm) {
deletedByCreator = true
// 删除附件
deleteAttachmentInRealm(realm)
// 再将其变为文字消息
sendState = MessageSendState.Read.rawValue
readed = true
textContent = ""
mediaType = MessageMediaType.Text.rawValue
}
}
public class Draft: Object {
public dynamic var messageToolbarState: Int = MessageToolbarState.Default.rawValue
public dynamic var text: String = ""
}
// MARK: Conversation
public enum ConversationType: Int {
case OneToOne = 0 // 一对一对话
case Group = 1 // 群组对话
public var nameForServer: String {
switch self {
case .OneToOne:
return "User"
case .Group:
return "Circle"
}
}
public var nameForBatchMarkAsRead: String {
switch self {
case .OneToOne:
return "users"
case .Group:
return "circles"
}
}
}
public class Conversation: Object {
public var fakeID: String? {
if invalidated {
return nil
}
switch type {
case ConversationType.OneToOne.rawValue:
if let withFriend = withFriend {
return "user_" + withFriend.userID
}
case ConversationType.Group.rawValue:
if let withGroup = withGroup {
return "group_" + withGroup.groupID
}
default:
return nil
}
return nil
}
public var recipientID: String? {
switch type {
case ConversationType.OneToOne.rawValue:
if let withFriend = withFriend {
return withFriend.userID
}
case ConversationType.Group.rawValue:
if let withGroup = withGroup {
return withGroup.groupID
}
default:
return nil
}
return nil
}
public var recipient: Recipient? {
if let recipientType = ConversationType(rawValue: type), recipientID = recipientID {
return Recipient(type: recipientType, ID: recipientID)
}
return nil
}
public var mentionInitUsers: [UsernamePrefixMatchedUser] {
let users = messages.flatMap({ $0.fromFriend }).filter({ !$0.invalidated }).filter({ !$0.username.isEmpty && !$0.isMe })
let usernamePrefixMatchedUser = users.map({
UsernamePrefixMatchedUser(
userID: $0.userID,
username: $0.username,
nickname: $0.nickname,
avatarURLString: $0.avatarURLString,
lastSignInUnixTime: $0.lastSignInUnixTime
)
})
let uniqueSortedUsers = Array(Set(usernamePrefixMatchedUser)).sort({
$0.lastSignInUnixTime > $1.lastSignInUnixTime
})
return uniqueSortedUsers
}
public dynamic var type: Int = ConversationType.OneToOne.rawValue
public dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var withFriend: User?
public dynamic var withGroup: Group?
public dynamic var draft: Draft?
public let messages = LinkingObjects(fromType: Message.self, property: "conversation")
public dynamic var unreadMessagesCount: Int = 0
public dynamic var hasUnreadMessages: Bool = false
public dynamic var mentionedMe: Bool = false
public dynamic var lastMentionedMeUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 - 60*60*12 // 默认为此Conversation创建时间之前半天
public dynamic var hasOlderMessages: Bool = true
public var latestValidMessage: Message? {
return messages.filter({ ($0.hidden == false) && ($0.isIndicator == false && ($0.mediaType != MessageMediaType.SectionDate.rawValue)) }).sort({ $0.createdUnixTime > $1.createdUnixTime }).first
}
public var latestMessageTextContentOrPlaceholder: String? {
guard let latestValidMessage = latestValidMessage else {
return nil
}
if let mediaType = MessageMediaType(rawValue: latestValidMessage.mediaType), placeholder = mediaType.placeholder {
return placeholder
} else {
return latestValidMessage.textContent
}
}
public var needDetectMention: Bool {
return type == ConversationType.Group.rawValue
}
}
// MARK: Feed
//enum AttachmentKind: String {
//
// case Image = "image"
// case Thumbnail = "thumbnail"
// case Audio = "audio"
// case Video = "video"
//}
public class Attachment: Object {
//dynamic var kind: String = ""
public dynamic var metadata: String = ""
public dynamic var URLString: String = ""
}
public class FeedAudio: Object {
public dynamic var feedID: String = ""
public dynamic var URLString: String = ""
public dynamic var metadata: NSData = NSData()
public dynamic var fileName: String = ""
public var belongToFeed: Feed? {
return LinkingObjects(fromType: Feed.self, property: "audio").first
}
public var audioFileURL: NSURL? {
if !fileName.isEmpty {
if let fileURL = NSFileManager.yepMessageAudioURLWithName(fileName) {
return fileURL
}
}
return nil
}
public class func feedAudioWithFeedID(feedID: String, inRealm realm: Realm) -> FeedAudio? {
let predicate = NSPredicate(format: "feedID = %@", feedID)
return realm.objects(FeedAudio).filter(predicate).first
}
public var audioMetaInfo: (duration: NSTimeInterval, samples: [CGFloat])? {
if let metaDataInfo = decodeJSON(metadata) {
if let
duration = metaDataInfo[Config.MetaData.audioDuration] as? NSTimeInterval,
samples = metaDataInfo[Config.MetaData.audioSamples] as? [CGFloat] {
return (duration, samples)
}
}
return nil
}
public func deleteAudioFile() {
guard !fileName.isEmpty else {
return
}
NSFileManager.removeMessageAudioFileWithName(fileName)
}
}
public class FeedLocation: Object {
public dynamic var name: String = ""
public dynamic var coordinate: Coordinate?
}
public class OpenGraphInfo: Object {
public dynamic var URLString: String = ""
public dynamic var siteName: String = ""
public dynamic var title: String = ""
public dynamic var infoDescription: String = ""
public dynamic var thumbnailImageURLString: String = ""
public let messages = LinkingObjects(fromType: Message.self, property: "openGraphInfo")
public let feeds = LinkingObjects(fromType: Feed.self, property: "openGraphInfo")
public override class func primaryKey() -> String? {
return "URLString"
}
public override class func indexedProperties() -> [String] {
return ["URLString"]
}
public convenience init(URLString: String, siteName: String, title: String, infoDescription: String, thumbnailImageURLString: String) {
self.init()
self.URLString = URLString
self.siteName = siteName
self.title = title
self.infoDescription = infoDescription
self.thumbnailImageURLString = thumbnailImageURLString
}
public class func withURLString(URLString: String, inRealm realm: Realm) -> OpenGraphInfo? {
return realm.objects(OpenGraphInfo).filter("URLString = %@", URLString).first
}
}
extension OpenGraphInfo: OpenGraphInfoType {
public var URL: NSURL {
return NSURL(string: URLString)!
}
}
public class Feed: Object {
public dynamic var feedID: String = ""
public dynamic var allowComment: Bool = true
public dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var creator: User?
public dynamic var distance: Double = 0
public dynamic var messagesCount: Int = 0
public dynamic var body: String = ""
public dynamic var kind: String = FeedKind.Text.rawValue
public var attachments = List<Attachment>()
public dynamic var socialWork: MessageSocialWork?
public dynamic var audio: FeedAudio?
public dynamic var location: FeedLocation?
public dynamic var openGraphInfo: OpenGraphInfo?
public dynamic var skill: UserSkill?
public dynamic var group: Group?
public dynamic var deleted: Bool = false // 已被管理员或建立者删除
// 级联删除关联的数据对象
public func cascadeDeleteInRealm(realm: Realm) {
attachments.forEach {
realm.delete($0)
}
if let socialWork = socialWork {
if let githubRepo = socialWork.githubRepo {
realm.delete(githubRepo)
}
if let dribbbleShot = socialWork.dribbbleShot {
realm.delete(dribbbleShot)
}
if let instagramMedia = socialWork.instagramMedia {
realm.delete(instagramMedia)
}
realm.delete(socialWork)
}
if let audio = audio {
audio.deleteAudioFile()
realm.delete(audio)
}
if let location = location {
if let coordinate = location.coordinate {
realm.delete(coordinate)
}
realm.delete(location)
}
// 除非没有谁指向 openGraphInfo,不然不能删除它
if let openGraphInfo = openGraphInfo {
if openGraphInfo.messages.isEmpty {
if openGraphInfo.feeds.count == 1, let first = openGraphInfo.messages.first where first == self {
realm.delete(openGraphInfo)
}
}
}
realm.delete(self)
}
}
// MARK: Offline JSON
public enum OfflineJSONName: String {
case Feeds
case DiscoveredUsers
case GeniusInterviews
}
public class OfflineJSON: Object {
public dynamic var name: String!
public dynamic var data: NSData!
public override class func primaryKey() -> String? {
return "name"
}
public convenience init(name: String, data: NSData) {
self.init()
self.name = name
self.data = data
}
public var JSON: JSONDictionary? {
return decodeJSON(data)
}
public class func withName(name: OfflineJSONName, inRealm realm: Realm) -> OfflineJSON? {
return realm.objects(OfflineJSON).filter("name = %@", name.rawValue).first
}
}
public class UserLocationName: Object {
public dynamic var userID: String = ""
public dynamic var locationName: String = ""
public override class func primaryKey() -> String? {
return "userID"
}
public override class func indexedProperties() -> [String] {
return ["userID"]
}
public convenience init(userID: String, locationName: String) {
self.init()
self.userID = userID
self.locationName = locationName
}
public class func withUserID(userID: String, inRealm realm: Realm) -> UserLocationName? {
return realm.objects(UserLocationName).filter("userID = %@", userID).first
}
}
public class SubscriptionViewShown: Object {
public dynamic var groupID: String = ""
public override class func primaryKey() -> String? {
return "groupID"
}
public override class func indexedProperties() -> [String] {
return ["groupID"]
}
public convenience init(groupID: String) {
self.init()
self.groupID = groupID
}
public class func canShow(groupID groupID: String) -> Bool {
guard let realm = try? Realm() else {
return false
}
return realm.objects(SubscriptionViewShown).filter("groupID = %@", groupID).isEmpty
}
}
// MARK: Helpers
public func normalFriends() -> Results<User> {
let realm = try! Realm()
let predicate = NSPredicate(format: "friendState = %d", UserFriendState.Normal.rawValue)
return realm.objects(User).filter(predicate).sorted("lastSignInUnixTime", ascending: false)
}
public func normalUsers() -> Results<User> {
let realm = try! Realm()
let predicate = NSPredicate(format: "friendState != %d", UserFriendState.Blocked.rawValue)
return realm.objects(User).filter(predicate)
}
public func userSkillWithSkillID(skillID: String, inRealm realm: Realm) -> UserSkill? {
let predicate = NSPredicate(format: "skillID = %@", skillID)
return realm.objects(UserSkill).filter(predicate).first
}
public func userSkillCategoryWithSkillCategoryID(skillCategoryID: String, inRealm realm: Realm) -> UserSkillCategory? {
let predicate = NSPredicate(format: "skillCategoryID = %@", skillCategoryID)
return realm.objects(UserSkillCategory).filter(predicate).first
}
public func userWithUserID(userID: String, inRealm realm: Realm) -> User? {
let predicate = NSPredicate(format: "userID = %@", userID)
#if DEBUG
let users = realm.objects(User).filter(predicate)
if users.count > 1 {
println("Warning: same userID: \(users.count), \(userID)")
}
#endif
return realm.objects(User).filter(predicate).first
}
public func meInRealm(realm: Realm) -> User? {
guard let myUserID = YepUserDefaults.userID.value else {
return nil
}
return userWithUserID(myUserID, inRealm: realm)
}
public func me() -> User? {
guard let realm = try? Realm() else {
return nil
}
return meInRealm(realm)
}
public func userWithUsername(username: String, inRealm realm: Realm) -> User? {
let predicate = NSPredicate(format: "username = %@", username)
return realm.objects(User).filter(predicate).first
}
public func userWithAvatarURLString(avatarURLString: String, inRealm realm: Realm) -> User? {
let predicate = NSPredicate(format: "avatarURLString = %@", avatarURLString)
return realm.objects(User).filter(predicate).first
}
public func conversationWithDiscoveredUser(discoveredUser: DiscoveredUser, inRealm realm: Realm) -> Conversation? {
var stranger = userWithUserID(discoveredUser.id, inRealm: realm)
if stranger == nil {
let newUser = User()
newUser.userID = discoveredUser.id
newUser.friendState = UserFriendState.Stranger.rawValue
realm.add(newUser)
stranger = newUser
}
guard let user = stranger else {
return nil
}
// 更新用户信息
user.lastSignInUnixTime = discoveredUser.lastSignInUnixTime
user.username = discoveredUser.username ?? ""
user.nickname = discoveredUser.nickname
if let introduction = discoveredUser.introduction {
user.introduction = introduction
}
user.avatarURLString = discoveredUser.avatarURLString
user.longitude = discoveredUser.longitude
user.latitude = discoveredUser.latitude
if let badge = discoveredUser.badge {
user.badge = badge
}
if let blogURLString = discoveredUser.blogURLString {
user.blogURLString = blogURLString
}
// 更新技能
user.learningSkills.removeAll()
let learningUserSkills = userSkillsFromSkills(discoveredUser.learningSkills, inRealm: realm)
user.learningSkills.appendContentsOf(learningUserSkills)
user.masterSkills.removeAll()
let masterUserSkills = userSkillsFromSkills(discoveredUser.masterSkills, inRealm: realm)
user.masterSkills.appendContentsOf(masterUserSkills)
// 更新 Social Account Provider
user.socialAccountProviders.removeAll()
let socialAccountProviders = userSocialAccountProvidersFromSocialAccountProviders(discoveredUser.socialAccountProviders)
user.socialAccountProviders.appendContentsOf(socialAccountProviders)
if user.conversation == nil {
let newConversation = Conversation()
newConversation.type = ConversationType.OneToOne.rawValue
newConversation.withFriend = user
realm.add(newConversation)
}
return user.conversation
}
public func groupWithGroupID(groupID: String, inRealm realm: Realm) -> Group? {
let predicate = NSPredicate(format: "groupID = %@", groupID)
return realm.objects(Group).filter(predicate).first
}
public func refreshGroupTypeForAllGroups() {
if let realm = try? Realm() {
realm.beginWrite()
realm.objects(Group).forEach({
if $0.withFeed == nil {
$0.groupType = GroupType.Private.rawValue
println("We have group with NO feed")
}
})
let _ = try? realm.commitWrite()
}
}
public func feedWithFeedID(feedID: String, inRealm realm: Realm) -> Feed? {
let predicate = NSPredicate(format: "feedID = %@", feedID)
#if DEBUG
let feeds = realm.objects(Feed).filter(predicate)
if feeds.count > 1 {
println("Warning: same feedID: \(feeds.count), \(feedID)")
}
#endif
return realm.objects(Feed).filter(predicate).first
}
public func filterValidFeeds(feeds: Results<Feed>) -> [Feed] {
let validFeeds: [Feed] = feeds
.filter({ $0.deleted == false })
.filter({ $0.creator != nil})
.filter({ $0.group?.conversation != nil })
.filter({ ($0.group?.includeMe ?? false) })
return validFeeds
}
public func filterValidMessages(messages: Results<Message>) -> [Message] {
let validMessages: [Message] = messages
.filter({ $0.hidden == false })
.filter({ $0.isIndicator == false })
.filter({ $0.isReal == true })
.filter({ !($0.fromFriend?.isMe ?? true)})
.filter({ $0.conversation != nil })
return validMessages
}
public func filterValidMessages(messages: [Message]) -> [Message] {
let validMessages: [Message] = messages
.filter({ $0.hidden == false })
.filter({ $0.isIndicator == false })
.filter({ $0.isReal == true })
.filter({ !($0.fromFriend?.isMe ?? true) })
.filter({ $0.conversation != nil })
return validMessages
}
public func feedConversationsInRealm(realm: Realm) -> Results<Conversation> {
let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d", GroupType.Public.rawValue)
let a = SortDescriptor(property: "mentionedMe", ascending: false)
let b = SortDescriptor(property: "hasUnreadMessages", ascending: false)
let c = SortDescriptor(property: "updatedUnixTime", ascending: false)
return realm.objects(Conversation).filter(predicate).sorted([a, b, c])
}
public func mentionedMeInFeedConversationsInRealm(realm: Realm) -> Bool {
let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d AND mentionedMe = true", GroupType.Public.rawValue)
return realm.objects(Conversation).filter(predicate).count > 0
}
public func countOfConversationsInRealm(realm: Realm) -> Int {
return realm.objects(Conversation).filter({ !$0.invalidated }).count
}
public func countOfConversationsInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Int {
let predicate = NSPredicate(format: "type = %d", conversationType.rawValue)
return realm.objects(Conversation).filter(predicate).count
}
public func countOfUnreadMessagesInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Int {
switch conversationType {
case .OneToOne:
let predicate = NSPredicate(format: "readed = false AND fromFriend != nil AND fromFriend.friendState != %d AND conversation != nil AND conversation.type = %d", UserFriendState.Me.rawValue, conversationType.rawValue)
return realm.objects(Message).filter(predicate).count
case .Group: // Public for now
let predicate = NSPredicate(format: "includeMe = true AND groupType = %d", GroupType.Public.rawValue)
let count = realm.objects(Group).filter(predicate).map({ $0.conversation }).flatMap({ $0 }).filter({ !$0.invalidated }).map({ $0.hasUnreadMessages ? 1 : 0 }).reduce(0, combine: +)
return count
}
}
public func countOfUnreadMessagesInConversation(conversation: Conversation) -> Int {
return conversation.messages.filter({ message in
if let fromFriend = message.fromFriend {
return (message.readed == false) && (fromFriend.friendState != UserFriendState.Me.rawValue)
} else {
return false
}
}).count
}
public func firstValidMessageInMessageResults(results: Results<Message>) -> (message: Message, headInvalidMessageIDSet: Set<String>)? {
var headInvalidMessageIDSet: Set<String> = []
for message in results {
if !message.deletedByCreator && (message.mediaType != MessageMediaType.SectionDate.rawValue) {
return (message, headInvalidMessageIDSet)
} else {
headInvalidMessageIDSet.insert(message.messageID)
}
}
return nil
}
public func latestValidMessageInRealm(realm: Realm) -> Message? {
let latestGroupMessage = latestValidMessageInRealm(realm, withConversationType: .Group)
let latestOneToOneMessage = latestValidMessageInRealm(realm, withConversationType: .OneToOne)
let latestMessage: Message? = [latestGroupMessage, latestOneToOneMessage].flatMap({ $0 }).sort({ $0.createdUnixTime > $1.createdUnixTime }).first
return latestMessage
}
public func latestValidMessageInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Message? {
switch conversationType {
case .OneToOne:
let predicate = NSPredicate(format: "hidden = false AND deletedByCreator = false AND blockedByRecipient == false AND mediaType != %d AND fromFriend != nil AND conversation != nil AND conversation.type = %d", MessageMediaType.SocialWork.rawValue, conversationType.rawValue)
return realm.objects(Message).filter(predicate).sorted("updatedUnixTime", ascending: false).first
case .Group: // Public for now
let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d", GroupType.Public.rawValue)
let messages: [Message]? = realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false).first?.messages.sort({ $0.createdUnixTime > $1.createdUnixTime })
return messages?.filter({ ($0.hidden == false) && ($0.isIndicator == false) && ($0.mediaType != MessageMediaType.SectionDate.rawValue)}).first
}
}
public func latestUnreadValidMessageInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Message? {
switch conversationType {
case .OneToOne:
let predicate = NSPredicate(format: "readed = false AND hidden = false AND deletedByCreator = false AND blockedByRecipient == false AND mediaType != %d AND fromFriend != nil AND conversation != nil AND conversation.type = %d", MessageMediaType.SocialWork.rawValue, conversationType.rawValue)
return realm.objects(Message).filter(predicate).sorted("updatedUnixTime", ascending: false).first
case .Group: // Public for now
let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d", GroupType.Public.rawValue)
let messages: [Message]? = realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false).first?.messages.filter({ $0.readed == false && $0.fromFriend?.userID != YepUserDefaults.userID.value }).sort({ $0.createdUnixTime > $1.createdUnixTime })
return messages?.filter({ ($0.hidden == false) && ($0.isIndicator == false) && ($0.mediaType != MessageMediaType.SectionDate.rawValue) }).first
}
}
public func saveFeedWithDiscoveredFeed(feedData: DiscoveredFeed, group: Group, inRealm realm: Realm) {
// save feed
var _feed = feedWithFeedID(feedData.id, inRealm: realm)
if _feed == nil {
let newFeed = Feed()
newFeed.feedID = feedData.id
newFeed.allowComment = feedData.allowComment
newFeed.createdUnixTime = feedData.createdUnixTime
newFeed.updatedUnixTime = feedData.updatedUnixTime
newFeed.creator = getOrCreateUserWithDiscoverUser(feedData.creator, inRealm: realm)
newFeed.body = feedData.body
if let feedSkill = feedData.skill {
newFeed.skill = userSkillsFromSkills([feedSkill], inRealm: realm).first
}
realm.add(newFeed)
_feed = newFeed
} else {
#if DEBUG
if _feed?.group == nil {
println("feed have not with group, it may old (not deleted with conversation before)")
}
#endif
}
guard let feed = _feed else {
return
}
// update feed
println("update feed: \(feedData.kind.rawValue), \(feed.feedID)")
feed.kind = feedData.kind.rawValue
feed.deleted = false
feed.group = group
group.withFeed = feed
group.groupType = GroupType.Public.rawValue
if let distance = feedData.distance {
feed.distance = distance
}
feed.messagesCount = feedData.messagesCount
if let attachment = feedData.attachment {
switch attachment {
case .Images(let attachments):
guard feed.attachments.isEmpty else {
break
}
feed.attachments.removeAll()
let attachments = attachmentFromDiscoveredAttachment(attachments)
feed.attachments.appendContentsOf(attachments)
case .Github(let repo):
guard feed.socialWork?.githubRepo == nil else {
break
}
let socialWork = MessageSocialWork()
socialWork.type = MessageSocialWorkType.GithubRepo.rawValue
let repoID = repo.ID
var socialWorkGithubRepo = SocialWorkGithubRepo.getWithRepoID(repoID, inRealm: realm)
if socialWorkGithubRepo == nil {
let newSocialWorkGithubRepo = SocialWorkGithubRepo()
newSocialWorkGithubRepo.fillWithFeedGithubRepo(repo)
realm.add(newSocialWorkGithubRepo)
socialWorkGithubRepo = newSocialWorkGithubRepo
}
if let socialWorkGithubRepo = socialWorkGithubRepo {
socialWorkGithubRepo.synced = true
}
socialWork.githubRepo = socialWorkGithubRepo
feed.socialWork = socialWork
case .Dribbble(let shot):
guard feed.socialWork?.dribbbleShot == nil else {
break
}
let socialWork = MessageSocialWork()
socialWork.type = MessageSocialWorkType.DribbbleShot.rawValue
let shotID = shot.ID
var socialWorkDribbbleShot = SocialWorkDribbbleShot.getWithShotID(shotID, inRealm: realm)
if socialWorkDribbbleShot == nil {
let newSocialWorkDribbbleShot = SocialWorkDribbbleShot()
newSocialWorkDribbbleShot.fillWithFeedDribbbleShot(shot)
realm.add(newSocialWorkDribbbleShot)
socialWorkDribbbleShot = newSocialWorkDribbbleShot
}
if let socialWorkDribbbleShot = socialWorkDribbbleShot {
socialWorkDribbbleShot.synced = true
}
socialWork.dribbbleShot = socialWorkDribbbleShot
feed.socialWork = socialWork
case .Audio(let audioInfo):
guard feed.audio == nil else {
break
}
let feedAudio = FeedAudio()
feedAudio.feedID = audioInfo.feedID
feedAudio.URLString = audioInfo.URLString
feedAudio.metadata = audioInfo.metaData
feed.audio = feedAudio
case .Location(let locationInfo):
guard feed.location == nil else {
break
}
let feedLocation = FeedLocation()
feedLocation.name = locationInfo.name
let coordinate = Coordinate()
coordinate.safeConfigureWithLatitude(locationInfo.latitude, longitude:locationInfo.longitude)
feedLocation.coordinate = coordinate
feed.location = feedLocation
case .URL(let info):
guard feed.openGraphInfo == nil else {
break
}
let openGraphInfo = OpenGraphInfo(URLString: info.URL.absoluteString, siteName: info.siteName, title: info.title, infoDescription: info.infoDescription, thumbnailImageURLString: info.thumbnailImageURLString)
realm.add(openGraphInfo, update: true)
feed.openGraphInfo = openGraphInfo
}
}
}
public func messageWithMessageID(messageID: String, inRealm realm: Realm) -> Message? {
if messageID.isEmpty {
return nil
}
let predicate = NSPredicate(format: "messageID = %@", messageID)
let messages = realm.objects(Message).filter(predicate)
return messages.first
}
public func avatarWithAvatarURLString(avatarURLString: String, inRealm realm: Realm) -> Avatar? {
let predicate = NSPredicate(format: "avatarURLString = %@", avatarURLString)
return realm.objects(Avatar).filter(predicate).first
}
public func tryGetOrCreateMeInRealm(realm: Realm) -> User? {
guard let userID = YepUserDefaults.userID.value else {
return nil
}
if let me = userWithUserID(userID, inRealm: realm) {
return me
} else {
let me = User()
me.userID = userID
me.friendState = UserFriendState.Me.rawValue
if let nickname = YepUserDefaults.nickname.value {
me.nickname = nickname
}
if let avatarURLString = YepUserDefaults.avatarURLString.value {
me.avatarURLString = avatarURLString
}
let _ = try? realm.write {
realm.add(me)
}
return me
}
}
public func mediaMetaDataFromString(metaDataString: String, inRealm realm: Realm) -> MediaMetaData? {
if let data = metaDataString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let mediaMetaData = MediaMetaData()
mediaMetaData.data = data
realm.add(mediaMetaData)
return mediaMetaData
}
return nil
}
public func oneToOneConversationsInRealm(realm: Realm) -> Results<Conversation> {
let predicate = NSPredicate(format: "type = %d", ConversationType.OneToOne.rawValue)
return realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false)
}
public func messagesInConversationFromFriend(conversation: Conversation) -> Results<Message> {
let predicate = NSPredicate(format: "conversation = %@ AND fromFriend.friendState != %d", argumentArray: [conversation, UserFriendState.Me.rawValue])
if let realm = conversation.realm {
return realm.objects(Message).filter(predicate).sorted("createdUnixTime", ascending: true)
} else {
let realm = try! Realm()
return realm.objects(Message).filter(predicate).sorted("createdUnixTime", ascending: true)
}
}
public func messagesInConversation(conversation: Conversation) -> Results<Message> {
let predicate = NSPredicate(format: "conversation = %@", argumentArray: [conversation])
if let realm = conversation.realm {
return realm.objects(Message).filter(predicate).sorted("createdUnixTime", ascending: true)
} else {
let realm = try! Realm()
return realm.objects(Message).filter(predicate).sorted("createdUnixTime", ascending: true)
}
}
public func messagesOfConversation(conversation: Conversation, inRealm realm: Realm) -> Results<Message> {
let predicate = NSPredicate(format: "conversation = %@ AND hidden = false", argumentArray: [conversation])
let messages = realm.objects(Message).filter(predicate).sorted("createdUnixTime", ascending: true)
return messages
}
public func handleMessageDeletedFromServer(messageID messageID: String) {
guard let
realm = try? Realm(),
message = messageWithMessageID(messageID, inRealm: realm)
else {
return
}
let _ = try? realm.write {
message.updateForDeletedFromServerInRealm(realm)
}
let messageIDs: [String] = [message.messageID]
SafeDispatch.async {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.deletedMessages, object: ["messageIDs": messageIDs])
}
}
public func tryCreateSectionDateMessageInConversation(conversation: Conversation, beforeMessage message: Message, inRealm realm: Realm, success: (Message) -> Void) {
let messages = messagesOfConversation(conversation, inRealm: realm)
if messages.count > 1 {
guard let index = messages.indexOf(message) else {
return
}
if let prevMessage = messages[safe: (index - 1)] {
if message.createdUnixTime - prevMessage.createdUnixTime > 180 { // TODO: Time Section
// 比新消息早一点点即可
let sectionDateMessageCreatedUnixTime = message.createdUnixTime - Config.Message.sectionOlderTimeInterval
let sectionDateMessageID = "sectionDate-\(sectionDateMessageCreatedUnixTime)"
if let _ = messageWithMessageID(sectionDateMessageID, inRealm: realm) {
// do nothing
} else {
// create a new SectionDate Message
let newSectionDateMessage = Message()
newSectionDateMessage.messageID = sectionDateMessageID
newSectionDateMessage.conversation = conversation
newSectionDateMessage.mediaType = MessageMediaType.SectionDate.rawValue
newSectionDateMessage.createdUnixTime = sectionDateMessageCreatedUnixTime
newSectionDateMessage.arrivalUnixTime = sectionDateMessageCreatedUnixTime
success(newSectionDateMessage)
}
}
}
}
}
public func nameOfConversation(conversation: Conversation) -> String? {
guard !conversation.invalidated else {
return nil
}
if conversation.type == ConversationType.OneToOne.rawValue {
if let withFriend = conversation.withFriend {
return withFriend.nickname
}
} else if conversation.type == ConversationType.Group.rawValue {
if let withGroup = conversation.withGroup {
return withGroup.groupName
}
}
return nil
}
public func lastChatDateOfConversation(conversation: Conversation) -> NSDate? {
guard !conversation.invalidated else {
return nil
}
let messages = messagesInConversation(conversation)
if let lastMessage = messages.last {
return NSDate(timeIntervalSince1970: lastMessage.createdUnixTime)
}
return nil
}
public func lastSignDateOfConversation(conversation: Conversation) -> NSDate? {
guard !conversation.invalidated else {
return nil
}
let messages = messagesInConversationFromFriend(conversation)
if let
lastMessage = messages.last,
user = lastMessage.fromFriend {
return NSDate(timeIntervalSince1970: user.lastSignInUnixTime)
}
return nil
}
public func blurredThumbnailImageOfMessage(message: Message) -> UIImage? {
guard !message.invalidated else {
return nil
}
if let mediaMetaData = message.mediaMetaData {
if let metaDataInfo = decodeJSON(mediaMetaData.data) {
if let blurredThumbnailString = metaDataInfo[Config.MetaData.blurredThumbnailString] as? String {
if let data = NSData(base64EncodedString: blurredThumbnailString, options: NSDataBase64DecodingOptions(rawValue: 0)) {
return UIImage(data: data)
}
}
}
}
return nil
}
public func audioMetaOfMessage(message: Message) -> (duration: Double, samples: [CGFloat])? {
guard !message.invalidated else {
return nil
}
if let mediaMetaData = message.mediaMetaData {
if let metaDataInfo = decodeJSON(mediaMetaData.data) {
if let
duration = metaDataInfo[Config.MetaData.audioDuration] as? Double,
samples = metaDataInfo[Config.MetaData.audioSamples] as? [CGFloat] {
return (duration, samples)
}
}
}
return nil
}
public func imageMetaOfMessage(message: Message) -> (width: CGFloat, height: CGFloat)? {
guard !message.invalidated else {
return nil
}
if let mediaMetaData = message.mediaMetaData {
if let metaDataInfo = decodeJSON(mediaMetaData.data) {
if let
width = metaDataInfo[Config.MetaData.imageWidth] as? CGFloat,
height = metaDataInfo[Config.MetaData.imageHeight] as? CGFloat {
return (width, height)
}
}
}
return nil
}
public func videoMetaOfMessage(message: Message) -> (width: CGFloat, height: CGFloat)? {
guard !message.invalidated else {
return nil
}
if let mediaMetaData = message.mediaMetaData {
if let metaDataInfo = decodeJSON(mediaMetaData.data) {
if let
width = metaDataInfo[Config.MetaData.videoWidth] as? CGFloat,
height = metaDataInfo[Config.MetaData.videoHeight] as? CGFloat {
return (width, height)
}
}
}
return nil
}
// MARK: Update with info
public func updateUserWithUserID(userID: String, useUserInfo userInfo: [String: AnyObject], inRealm realm: Realm) {
if let user = userWithUserID(userID, inRealm: realm) {
// 更新用户信息
if let lastSignInUnixTime = userInfo["last_sign_in_at"] as? NSTimeInterval {
user.lastSignInUnixTime = lastSignInUnixTime
}
if let username = userInfo["username"] as? String {
user.username = username
}
if let nickname = userInfo["nickname"] as? String {
user.nickname = nickname
}
if let introduction = userInfo["introduction"] as? String {
user.introduction = introduction
}
if let avatarInfo = userInfo["avatar"] as? JSONDictionary, avatarURLString = avatarInfo["url"] as? String {
user.avatarURLString = avatarURLString
}
if let longitude = userInfo["longitude"] as? Double {
user.longitude = longitude
}
if let latitude = userInfo["latitude"] as? Double {
user.latitude = latitude
}
if let badge = userInfo["badge"] as? String {
user.badge = badge
}
if let blogURLString = userInfo["website_url"] as? String {
user.blogURLString = blogURLString
}
if let blogTitle = userInfo["website_title"] as? String {
user.blogTitle = blogTitle
}
// 更新技能
if let learningSkillsData = userInfo["learning_skills"] as? [JSONDictionary] {
user.learningSkills.removeAll()
let userSkills = userSkillsFromSkillsData(learningSkillsData, inRealm: realm)
user.learningSkills.appendContentsOf(userSkills)
}
if let masterSkillsData = userInfo["master_skills"] as? [JSONDictionary] {
user.masterSkills.removeAll()
let userSkills = userSkillsFromSkillsData(masterSkillsData, inRealm: realm)
user.masterSkills.appendContentsOf(userSkills)
}
// 更新 Social Account Provider
if let providersInfo = userInfo["providers"] as? [String: Bool] {
user.socialAccountProviders.removeAll()
for (name, enabled) in providersInfo {
let provider = UserSocialAccountProvider()
provider.name = name
provider.enabled = enabled
user.socialAccountProviders.append(provider)
}
}
}
}
// MARK: Delete
private func clearMessagesOfConversation(conversation: Conversation, inRealm realm: Realm, keepHiddenMessages: Bool) {
let messages: [Message]
if keepHiddenMessages {
messages = conversation.messages.filter({ $0.hidden == false })
} else {
messages = conversation.messages.map({ $0 })
}
// delete attachments of messages
messages.forEach { $0.deleteAttachmentInRealm(realm) }
// delete all messages in conversation
realm.delete(messages)
}
public func deleteConversation(conversation: Conversation, inRealm realm: Realm, needLeaveGroup: Bool = true, afterLeaveGroup: (() -> Void)? = nil) {
defer {
realm.refresh()
}
clearMessagesOfConversation(conversation, inRealm: realm, keepHiddenMessages: false)
// delete conversation from server
let recipient = conversation.recipient
if let recipient = recipient where recipient.type == .OneToOne {
deleteConversationWithRecipient(recipient, failureHandler: nil, completion: {
println("deleteConversationWithRecipient \(recipient)")
})
}
// delete conversation, finally
if let group = conversation.withGroup {
if let feed = conversation.withGroup?.withFeed {
feed.cascadeDeleteInRealm(realm)
}
let groupID = group.groupID
if needLeaveGroup {
leaveGroup(groupID: groupID, failureHandler: nil, completion: {
println("leaved group: \(groupID)")
afterLeaveGroup?()
})
} else {
println("deleteConversation, not need leave group: \(groupID)")
if let recipient = recipient where recipient.type == .Group {
deleteConversationWithRecipient(recipient, failureHandler: nil, completion: {
println("deleteConversationWithRecipient \(recipient)")
})
}
}
realm.delete(group)
}
realm.delete(conversation)
}
public func tryDeleteOrClearHistoryOfConversation(conversation: Conversation, inViewController vc: UIViewController, whenAfterClearedHistory afterClearedHistory: () -> Void, afterDeleted: () -> Void, orCanceled cancelled: () -> Void) {
guard let realm = conversation.realm else {
cancelled()
return
}
let clearMessages: () -> Void = {
// clear from server
if let recipient = conversation.recipient {
clearHistoryOfConversationWithRecipient(recipient, failureHandler: nil, completion: {
println("clearHistoryOfConversationWithRecipient \(recipient)")
})
}
realm.beginWrite()
clearMessagesOfConversation(conversation, inRealm: realm, keepHiddenMessages: true)
_ = try? realm.commitWrite()
}
let delete: () -> Void = {
realm.beginWrite()
deleteConversation(conversation, inRealm: realm)
_ = try? realm.commitWrite()
realm.refresh()
}
// show ActionSheet before delete
let deleteAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let clearHistoryAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("title.clear_history", comment: ""), style: .Default) { _ in
clearMessages()
afterClearedHistory()
}
deleteAlertController.addAction(clearHistoryAction)
let deleteAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("Delete", comment: ""), style: .Destructive) { _ in
delete()
afterDeleted()
}
deleteAlertController.addAction(deleteAction)
let cancelAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .Cancel) { _ in
cancelled()
}
deleteAlertController.addAction(cancelAction)
vc.presentViewController(deleteAlertController, animated: true, completion: nil)
}
public func clearUselessRealmObjects() {
dispatch_async(realmQueue) {
guard let realm = try? Realm() else {
return
}
defer {
realm.refresh()
}
println("do clearUselessRealmObjects")
realm.beginWrite()
// Message
do {
// 7天前
let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: -(60 * 60 * 24 * 7)).timeIntervalSince1970
//let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: 0).timeIntervalSince1970 // for test
let predicate = NSPredicate(format: "createdUnixTime < %f", oldThresholdUnixTime)
let oldMessages = realm.objects(Message).filter(predicate)
println("oldMessages.count: \(oldMessages.count)")
oldMessages.forEach({
$0.deleteAttachmentInRealm(realm)
realm.delete($0)
})
}
// Feed
do {
let predicate = NSPredicate(format: "group == nil")
let noGroupFeeds = realm.objects(Feed).filter(predicate)
println("noGroupFeeds.count: \(noGroupFeeds.count)")
noGroupFeeds.forEach({
if let group = $0.group {
group.cascadeDeleteInRealm(realm)
} else {
$0.cascadeDeleteInRealm(realm)
}
})
}
do {
// 2天前
let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: -(60 * 60 * 24 * 2)).timeIntervalSince1970
//let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: 0).timeIntervalSince1970 // for test
let predicate = NSPredicate(format: "group != nil AND group.includeMe = false AND createdUnixTime < %f", oldThresholdUnixTime)
let notJoinedFeeds = realm.objects(Feed).filter(predicate)
println("notJoinedFeeds.count: \(notJoinedFeeds.count)")
notJoinedFeeds.forEach({
if let group = $0.group {
group.cascadeDeleteInRealm(realm)
} else {
$0.cascadeDeleteInRealm(realm)
}
})
}
// User
do {
// 7天前
let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: -(60 * 60 * 24 * 7)).timeIntervalSince1970
//let oldThresholdUnixTime = NSDate(timeIntervalSinceNow: 0).timeIntervalSince1970 // for test
let predicate = NSPredicate(format: "friendState == %d AND createdUnixTime < %f", UserFriendState.Stranger.rawValue, oldThresholdUnixTime)
//let predicate = NSPredicate(format: "friendState == %d ", UserFriendState.Stranger.rawValue)
let strangers = realm.objects(User).filter(predicate)
// 再仔细过滤,避免把需要的去除了(参与对话的,有Group的,Feed创建着,关联有消息的)
let realStrangers = strangers.filter({
if $0.conversation == nil && $0.belongsToGroups.isEmpty && $0.ownedGroups.isEmpty && $0.createdFeeds.isEmpty && $0.messages.isEmpty {
return true
}
return false
})
println("realStrangers.count: \(realStrangers.count)")
realStrangers.forEach({
$0.cascadeDeleteInRealm(realm)
})
}
// Group
let _ = try? realm.commitWrite()
}
}
| mit | 7eed88b2fed7e2d8a1c3a67e5b0450a6 | 30.484531 | 299 | 0.646735 | 4.945544 | false | false | false | false |
hermantai/samples | ios/cs193p/CardMatching/CardMatching/MemoryGame.swift | 1 | 6160 | //
// MemoryGame.swift
// CardMatching
//
// Created by Herman (Heung) Tai on 10/25/21.
//
import Foundation
struct MemoryGame<CardContent: Equatable> {
private(set) var cards: [Card] = []
// Track the scores of the game.
private(set) var scores = Scores()
private var indexOfTheOneAndOnlyFaceUpCard: Int? {
get { cards.indices.filter{cards[$0].isFaceUp}.oneAndOnly }
set { cards.indices.forEach{ cards[$0].isFaceUp = $0 == newValue } }
}
// Track the cards the user has seen, e.g. the card is flipped up, then down because of an unmatch
private var indicesForCardsSeen = Set<Int>()
init(numberOfPairsOfCards: Int, createCardContent: (Int) -> CardContent) {
for pairIndex in 0..<numberOfPairsOfCards {
let cardContent = createCardContent(pairIndex)
cards.append(Card(content: cardContent, id: pairIndex * 2))
cards.append(Card(content: cardContent, id: pairIndex * 2 + 1))
}
cards.shuffle()
}
mutating func removeCards() {
cards.removeAll()
}
/// The user chooses a card in the game.
mutating func choose(_ card: Card) {
// Notice that most of the mutation has to be done with cards[index]... without being assigned
// to any variables because Card is a struct.
if let chosenCardIndex = cards.firstIndex(where: {$0.id == card.id}),
!cards[chosenCardIndex].isFaceUp && !cards[chosenCardIndex].isMatched {
if let potentialMatchIndex = indexOfTheOneAndOnlyFaceUpCard {
if cards[potentialMatchIndex].content == cards[chosenCardIndex].content {
cards[potentialMatchIndex].isMatched = true
cards[chosenCardIndex].isMatched = true
scores.matches += 1
}
cards[chosenCardIndex].isFaceUp = true
} else {
for cardIndex in cards.indices {
if cards[cardIndex].isFaceUp {
if !cards[cardIndex].isMatched && indicesForCardsSeen.contains(cardIndex) {
scores.numberOfTimesSeenForUnmatchedCards += 1
} else if !indicesForCardsSeen.contains(cardIndex) {
indicesForCardsSeen.insert(cardIndex)
}
}
}
// This assignment sets the chosen card's isFaceUp to be true.
indexOfTheOneAndOnlyFaceUpCard = chosenCardIndex
}
}
}
mutating func pauseGame() {
cards.indices.forEach{ cards[$0].hidden = true }
}
mutating func resumeGame() {
cards.indices.forEach{ cards[$0].hidden = false }
}
struct Card: Identifiable {
var isFaceUp = false {
didSet {
if isFaceUp && !hidden {
faceUpCountDownTimer.start()
} else {
faceUpCountDownTimer.pause()
}
}
}
var isMatched = false {
didSet {
faceUpCountDownTimer.pause()
}
}
/// If the card is hidden, it is assumed not being seen by any users even the card is faced up.
fileprivate var hidden = false {
didSet {
if oldValue == hidden {
return
}
// If we are hidding the card and the card is faced up, pause the time.
if hidden && isFaceUp {
faceUpCountDownTimer.pause()
}
// If we are unhidding the card and the card is faced up, resume the time.
if !hidden && isFaceUp {
faceUpCountDownTimer.start()
}
}
}
var content: CardContent
var id: Int
/// Count down for the time period that the card is faced up and is not matched.
private(set) var faceUpCountDownTimer = CountDownTimer()
// whether we are currently face up, unmatched and have not yet used up the bonus window
var isConsumingBonusTime: Bool {
return isFaceUp && !isMatched && faceUpCountDownTimer.isCountingDown
}
}
struct Scores {
var matches = 0
var numberOfTimesSeenForUnmatchedCards = 0
var score: Int {
matches * 2 - numberOfTimesSeenForUnmatchedCards
}
}
}
/// A timer that counts down from a given duration.
struct CountDownTimer {
/// The duration the timer counts down from.
var countDownDuration: TimeInterval = 6
/// The countdown time remaining.
var countDownRemaining: TimeInterval {
return max(0, countDownDuration - lapsedTime)
}
/// Returns true if the timer is still counting time, i.e. there is time left.
var isCountingDown: Bool {
countDownRemaining > 0
}
/// Fraction of the countdown remaining, between 0 to 1.
var fractionOfCountDownRemaining: Double {
(countDownDuration > 0 && countDownRemaining > 0) ? countDownRemaining/countDownDuration : 0
}
// how long this card has ever been face up
private var lapsedTime: TimeInterval {
if let lastStartedDate = self.lastStartedDate {
return pastLapsedTime + Date().timeIntervalSince(lastStartedDate)
} else {
return pastLapsedTime
}
}
private var lastStartedDate: Date?
private var pastLapsedTime: TimeInterval = 0
/// Start/resume the count down. After the countdown is finished, this does not do anything anymore.
mutating func start() {
if isCountingDown, lastStartedDate == nil {
lastStartedDate = Date()
}
}
/// Pause the count down.
mutating func pause() {
pastLapsedTime = lapsedTime
self.lastStartedDate = nil
}
}
extension Array {
var oneAndOnly: Element? {
if count == 1 {
return first
} else {
return nil
}
}
}
| apache-2.0 | 6eb86906069f867f046ecabb65917094 | 33.222222 | 104 | 0.570942 | 4.816263 | false | false | false | false |
LiuDeng/turns | q/AppDelegate.swift | 2 | 3840 | //
// AppDelegate.swift
// q
//
// Created by Jesse Shawl on 5/7/15.
// Copyright (c) 2015 Jesse Shawl. All rights reserved.
//
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var pushNotificationController:PushNotificationController?
var authViewController:AuthenticationsViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
self.pushNotificationController = PushNotificationController()
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
let currentInstallation = PFInstallation.currentInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackgroundWithBlock { (succeeded, e) -> Void in
//code
}
println("tokenString: \(tokenString)")
NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "token")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("didReceiveRemoteNotification")
PFPush.handlePush(userInfo)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("Couldn’t register: \(error)")
}
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:.
}
}
| mit | 364f4b93c6427ce4879f1ff46354cc79 | 46.382716 | 285 | 0.736842 | 5.886503 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/UniversityClassSchedule/controller/UniversityClassScheduleDepartmentsViewController.swift | 1 | 2749 | //
// UniversityClassScheduleDepartmentsViewController.swift
// byuSuite
//
// Created by Erik Brady on 11/14/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
class UniversityClassScheduleDepartmentsViewController: ByuSearchTableDataViewController, SemesterButtonDelegate {
//MARK: IBOutlets
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Private Properties
private var departments = [RegTeachingArea]()
private var yearTerm: YearTerm2?
override func viewDidLoad() {
super.viewDidLoad()
//Data will be loaded after the semester button has loaded the current Year Term
navigationItem.rightBarButtonItem = SemesterButton2(delegate: self)
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCourses",
let vc = segue.destination as? UniversityClassScheduleCoursesViewController,
let yearTerm = yearTerm, let teachingArea: RegTeachingArea = objectForSender(cellSender: sender) {
vc.yearTerm = yearTerm
vc.teachingArea = teachingArea
}
}
//MARK: SemesterButtonDelegate Methods
func createButtonSucceeded(button: SemesterButton2) {
yearTerm = button.selectedYearTerm
loadTeachingAreas()
}
func createButtonFailed(button: SemesterButton2) {
spinner.stopAnimating()
super.displayAlert(message: "Unable to Load Year Terms")
}
func selectedYearTerm(yearTerm: YearTerm2) {
self.yearTerm = yearTerm
spinner.startAnimating()
loadTeachingAreas()
}
func displaySemesterButtonActions(button: SemesterButton2, title: String, actions: [UIAlertAction]) {
super.displayActionSheet(from: self, title: title, actions: actions)
}
//MARK: Custom Methods
private func loadTeachingAreas() {
if let code = yearTerm?.code {
RegistrationClient2.getTeachingAreas(yearTermCode: code, callback: { (teachingAreas, error) in
self.spinner.stopAnimating()
if let teachingAreas = teachingAreas {
self.departments = teachingAreas
self.loadTableData()
} else {
super.displayAlert(error: error)
}
})
}
}
private func loadTableData() {
var tempDepartments = [Character: [Row]]()
for teachingArea in departments {
if let firstLetter = teachingArea.code.uppercased().first {
if tempDepartments[firstLetter] == nil {
tempDepartments[firstLetter] = [Row]()
}
tempDepartments[firstLetter]?.append(Row(text: teachingArea.code, detailText: teachingArea.title, object: teachingArea))
}
}
masterTableData = TableData(sections: tempDepartments.keys.map { Section(title: "\($0)", rows: tempDepartments[$0] ?? []) }.sorted { $0.title ?? "" < $1.title ?? "" })
self.tableView.reloadData()
}
}
| apache-2.0 | 05965edc217d1cb8685e64d37bc1e6a1 | 28.869565 | 169 | 0.729622 | 3.864979 | false | false | false | false |
chriscox/material-components-ios | components/AppBar/examples/AppBarInterfaceBuilderExampleController.swift | 1 | 2318 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents
class AppBarInterfaceBuilderSwiftExample: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
let appBar = MDCAppBar()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonAppBarInterfaceBuilderSwiftExampleSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
commonAppBarInterfaceBuilderSwiftExampleSetup()
}
func commonAppBarInterfaceBuilderSwiftExampleSetup() {
appBar.navigationBar.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes =
[ NSForegroundColorAttributeName: UIColor.white ]
addChildViewController(appBar.headerViewController)
let color = UIColor(white: 0.1, alpha:1)
appBar.headerViewController.headerView.backgroundColor = color
}
override func viewDidLoad() {
super.viewDidLoad()
appBar.headerViewController.headerView.trackingScrollView = scrollView
scrollView.delegate = appBar.headerViewController
appBar.addSubviewsToParent()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
// Ensure that our status bar is white.
return .lightContent
}
}
// MARK: Catalog by convention
extension AppBarInterfaceBuilderSwiftExample {
class func catalogBreadcrumbs() -> [String] {
return ["App Bar", "Interface Builder (Swift)"]
}
class func catalogStoryboardName() -> String {
return "AppBarInterfaceBuilderExampleController"
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
| apache-2.0 | b8feb41684d6449415c4065639b70c1e | 28.717949 | 84 | 0.768335 | 5.094505 | false | false | false | false |
vscarpenter/InventoryTracker | InventoryTracker/ViewController.swift | 1 | 967 | //
// ViewController.swift
// InventoryTracker
//
// Created by Vinny Carpenter on 1/1/15.
// Copyright (c) 2015 Vinny Carpenter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
getListOfFilesFromDocDirectory()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
getListOfFilesFromDocDirectory()
}
func getListOfFilesFromDocDirectory() {
var docDir = documentsDirectory()
let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath(docDir)
var stringBuffer: String = ""
while let file: AnyObject = files?.nextObject() {
stringBuffer += file.description
stringBuffer += "\n"
}
textView.text = stringBuffer
}
}
| mit | b50f1f8cf45f40a2e54fc07340582c03 | 21.488372 | 60 | 0.627715 | 4.835 | false | false | false | false |
tardieu/swift | benchmark/single-source/ArrayAppend.swift | 5 | 7147 | //===--- ArrayAppend.swift ------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This test checks the performance of appending to an array.
import TestsUtils
// Append single element
@inline(never)
public func run_ArrayAppend(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<40000 {
nums.append(1)
}
}
}
}
// Append single element with reserve
@inline(never)
public func run_ArrayAppendReserved(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
nums.reserveCapacity(40000)
for _ in 0..<40000 {
nums.append(1)
}
}
}
}
// Append a sequence. Length of sequence unknown so
// can't pre-reserve capacity.
@inline(never)
public func run_ArrayAppendSequence(_ N: Int) {
let seq = stride(from: 0, to: 10_000, by: 1)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
nums.append(contentsOf: seq)
}
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendArrayOfInt(_ N: Int) {
let other = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
nums.append(contentsOf: other)
}
}
}
}
// Identical to run_ArrayAppendArrayOfInt
// except +=, to check equally performant.
@inline(never)
public func run_ArrayPlusEqualArrayOfInt(_ N: Int) {
let other = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendStrings(_ N: Int) {
let other = stride(from: 0, to: 10_000, by: 1).map { "\($0)" }
for _ in 0..<N {
for _ in 0..<10 {
var nums = [String]()
// lower inner count due to string slowness
for _ in 0..<4 {
nums += other
}
}
}
}
struct S<T,U> {
var x: T
var y: U
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendGenericStructs(_ N: Int) {
let other = Array(repeating: S(x: 3, y: 4.2), count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [S<Int,Double>]()
for _ in 0..<8 {
nums += other
}
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendOptionals(_ N: Int) {
let other: [Int?] = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int?]()
for _ in 0..<8 {
nums += other
}
}
}
}
// Append a lazily-mapped array. Length of sequence known so
// can pre-reserve capacity, but no optimization points used.
@inline(never)
public func run_ArrayAppendLazyMap(_ N: Int) {
let other = Array(0..<10_000).lazy.map { $0 * 2 }
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
}
// Append a Repeat collection. Length of sequence known so
// can pre-reserve capacity, but no optimization points used.
@inline(never)
public func run_ArrayAppendRepeatCol(_ N: Int) {
let other = repeatElement(1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
}
// Append an array as a generic sequence to another array
@inline(never)
public func appendFromGeneric<
S: Sequence
>(array: inout [S.Iterator.Element], sequence: S) {
array.append(contentsOf: sequence)
}
@inline(never)
public func run_ArrayAppendFromGeneric(_ N: Int) {
let other = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
appendFromGeneric(array: &nums, sequence: other)
}
}
}
}
// Append an array to an array as a generic range replaceable collection.
@inline(never)
public func appendToGeneric<
R: RangeReplaceableCollection
>(collection: inout R, array: [R.Iterator.Element]) {
collection.append(contentsOf: array)
}
@inline(never)
public func run_ArrayAppendToGeneric(_ N: Int) {
let other = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
appendToGeneric(collection: &nums, array: other)
}
}
}
}
// Append an array as a generic sequence to an array as a generic range
// replaceable collection.
@inline(never)
public func appendToFromGeneric<
R: RangeReplaceableCollection, S: Sequence
>(collection: inout R, sequence: S)
where R.Iterator.Element == S.Iterator.Element {
collection.append(contentsOf: sequence)
}
@inline(never)
public func run_ArrayAppendToFromGeneric(_ N: Int) {
let other = Array(repeating: 1, count: 10_000)
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<8 {
appendToFromGeneric(collection: &nums, sequence: other)
}
}
}
}
// Append a single element array with the += operator
@inline(never)
public func run_ArrayPlusEqualSingleElementCollection(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<40_000 {
nums += [1]
}
}
}
}
// Append a five element array with the += operator
@inline(never)
public func run_ArrayPlusEqualFiveElementCollection(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
for _ in 0..<40_000 {
nums += [1, 2, 3, 4, 5]
}
}
}
}
// Append the utf8 elements of an ascii string to a [UInt8]
@inline(never)
public func run_ArrayAppendAscii(_ N: Int) {
let s = "the quick brown fox jumps over the lazy dog!"
for _ in 0..<N {
for _ in 0..<10 {
var nums = [UInt8]()
for _ in 0..<10_000 {
nums += s.utf8
}
}
}
}
// Append the utf8 elements of an ascii string to a [UInt8]
@inline(never)
public func run_ArrayAppendLatin1(_ N: Int) {
let s = "the quick brown fox jumps over the lazy dog\u{00A1}"
for _ in 0..<N {
for _ in 0..<10 {
var nums = [UInt8]()
for _ in 0..<10_000 {
nums += s.utf8
}
}
}
}
// Append the utf8 elements of an ascii string to a [UInt8]
@inline(never)
public func run_ArrayAppendUTF16(_ N: Int) {
let s = "the quick brown 🦊 jumps over the lazy dog"
for _ in 0..<N {
for _ in 0..<10 {
var nums = [UInt8]()
for _ in 0..<10_000 {
nums += s.utf8
}
}
}
}
| apache-2.0 | dfa53ac9f04b33282bdd993a1073c7b5 | 21.971061 | 80 | 0.575588 | 3.408397 | false | false | false | false |
tilltue/TLPhotoPicker | TLPhotoPicker/Classes/TLAssetPreviewViewController.swift | 1 | 7172 | import UIKit
import Photos
import PhotosUI
open class TLAssetPreviewViewController: UIViewController {
fileprivate var player: AVPlayer?
fileprivate var playerLayer: AVPlayerLayer?
fileprivate let imageView: UIImageView = {
let view = UIImageView()
view.clipsToBounds = false
view.contentMode = .scaleAspectFill
return view
}()
fileprivate let livePhotoView = PHLivePhotoView()
open var asset: PHAsset? {
didSet {
guard let asset = self.asset else {
livePhotoView.livePhoto = nil
imageView.image = nil
return
}
updatePreferredContentSize(for: asset, isPortrait: UIApplication.shared.orientation?.isPortrait == true)
if asset.mediaType == .image {
previewImage(from: asset)
} else {
previewVideo(from: asset)
}
}
}
override open func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
playerLayer?.frame = imageView.bounds
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if let asset = self.asset {
updatePreferredContentSize(for: asset, isPortrait: size.height > size.width)
}
}
deinit {
player?.pause()
}
}
private extension TLAssetPreviewViewController {
func setupViews() {
view.backgroundColor = .previewBackground
view.addAligned(imageView)
view.addAligned(livePhotoView)
}
func fetchImage(for asset: PHAsset, canHandleDegraded: Bool = true, completion: @escaping ((UIImage?) -> Void)) {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .opportunistic
PHCachingImageManager.default().requestImage(
for: asset,
targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight),
contentMode: .aspectFit,
options: options,
resultHandler: { (image, info) in
if !canHandleDegraded {
if let isDegraded = info?[PHImageResultIsDegradedKey] as? Bool, isDegraded {
return
}
}
completion(image)
})
}
func updatePreferredContentSize(for asset: PHAsset, isPortrait: Bool) {
guard asset.pixelWidth != 0 && asset.pixelHeight != 0 else { return }
let contentScale: CGFloat = 1
let assetWidth = CGFloat(asset.pixelWidth)
let assetHeight = CGFloat(asset.pixelHeight)
let assetRatio = assetHeight / assetWidth
let screenWidth = isPortrait ? UIScreen.main.bounds.width : UIScreen.main.bounds.height
let screenHeight = isPortrait ? UIScreen.main.bounds.height : UIScreen.main.bounds.width
let screenRatio = screenHeight / screenWidth
if assetRatio > screenRatio {
let scale = screenHeight / assetHeight
preferredContentSize = CGSize(width: assetWidth * scale * contentScale, height: assetHeight * scale * contentScale)
} else {
let scale = screenWidth / assetWidth
preferredContentSize = CGSize(width: assetWidth * scale * contentScale, height: assetHeight * scale * contentScale)
}
}
func previewVideo(from asset: PHAsset) {
livePhotoView.isHidden = true
PHCachingImageManager.default().requestAVAsset(
forVideo: asset,
options: nil,
resultHandler: { (avAsset, audio, info) in
DispatchQueue.main.async { [weak self] in
self?.imageView.isHidden = false
if let avAsset = avAsset {
let playerItem = AVPlayerItem(asset: avAsset)
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
playerLayer.masksToBounds = true
playerLayer.frame = self?.imageView.bounds ?? .zero
self?.imageView.layer.addSublayer(playerLayer)
self?.playerLayer = playerLayer
self?.player = player
player.play()
} else {
self?.previewPhoto(from: asset)
}
}
})
}
func previewImage(from asset: PHAsset) {
imageView.isHidden = true
livePhotoView.isHidden = false
if asset.mediaSubtypes == .photoLive {
previewLivePhoto(from: asset)
} else {
previewPhoto(from: asset)
}
}
func previewLivePhoto(from asset: PHAsset) {
let options = PHLivePhotoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .opportunistic
PHCachingImageManager.default().requestLivePhoto(
for: asset,
targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight),
contentMode: .aspectFill,
options: options,
resultHandler: { [weak self] (livePhoto, info) in
if let livePhoto = livePhoto, info?[PHImageErrorKey] == nil {
self?.livePhotoView.livePhoto = livePhoto
self?.livePhotoView.startPlayback(with: .full)
} else {
self?.previewPhoto(from: asset)
}
})
}
func previewPhoto(from asset: PHAsset) {
imageView.isHidden = false
fetchImage(for: asset, canHandleDegraded: false, completion: { self.imageView.image = $0 })
}
}
private extension UIColor {
static var previewBackground: UIColor {
if #available(iOS 13.0, *) {
return .systemBackground
} else {
return .white
}
}
}
private extension UIView {
func addAligned(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: leadingAnchor),
view.trailingAnchor.constraint(equalTo: trailingAnchor),
view.topAnchor.constraint(equalTo: topAnchor),
view.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
private extension UIApplication {
var orientation: UIInterfaceOrientation? {
if #available(iOS 13.0, *) {
return windows.first(where: { $0.isKeyWindow })?.windowScene?.interfaceOrientation
} else {
return statusBarOrientation
}
}
}
| mit | e5bb2325fcbc4071a962329b69c5b8dc | 34.156863 | 127 | 0.580452 | 5.638365 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/iOS/RootViewController.swift | 12 | 873 | //
// RootViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
public class RootViewController : UITableViewController {
public override func viewDidLoad() {
super.viewDidLoad()
// force load
_ = GitHubSearchRepositoriesAPI.sharedAPI
_ = DefaultWikipediaAPI.sharedAPI
_ = DefaultImageService.sharedImageService
_ = DefaultWireframe.shared
_ = MainScheduler.instance
_ = Dependencies.sharedDependencies.reachabilityService
let geoService = GeolocationService.instance
geoService.authorized.drive(onNext: { _ in
}).dispose()
geoService.location.drive(onNext: { _ in
}).dispose()
}
}
| mit | f422e643beecdc01c8c296c0d6530106 | 24.647059 | 63 | 0.65711 | 4.844444 | false | false | false | false |
Produkt/Pelican | src/ZIP/Unzipper.swift | 1 | 12928 | //
// Unzipper.swift
// Pelican
//
// Created by Daniel Garcia on 10/12/2016.
// Copyright © 2016 Produkt Studio. All rights reserved.
//
import minizip
import Result
public struct ZipFileInfo: FileInfo {
public let fileName: String
public let fileCRC: UInt
public let timestamp: Date
public let compressedSize: UInt
public let uncompressedSize: UInt
public let isDirectory: Bool
public let index: UInt
}
class AllContentUnzipper: Unzipper {
init(sourcePath: String, destinationPath: String) {
super.init(sourcePath: sourcePath, destinationPath: destinationPath)
}
func unzip() -> UnpackContentResult {
let startDate = Date()
do {
let unzippedFilesInfo = try unzipAllContent()
let finishDate = Date()
return .success(UnpackContentSummary(startDate: startDate, finishDate: finishDate, unpackedFiles: unzippedFilesInfo))
} catch (let unpackError) {
return .failure(UnpackError(underlyingError: unpackError))
}
}
private func unzipAllContent() throws -> [ZipFileInfo] {
var unzippedFilesInfo = [ZipFileInfo]()
do {
try openZipFile()
defer {
closeZipFile()
}
guard let destinationPath = destinationPath else {
throw UnzipError.RequiredDestinationPathNotDefined
}
var thereAreMoreFiles = true
repeat {
let unzipResult = unzipCurrentFile(in: destinationPath)
switch unzipResult {
case .success( _, let fileInfo):
unzippedFilesInfo.append(fileInfo)
case .failure(let error):
throw error
}
index += 1
do {
try advanceNextFile()
} catch { thereAreMoreFiles = false }
} while thereAreMoreFiles
} catch(let error) { throw error }
return unzippedFilesInfo
}
}
class SingleFileUnzipper: Unzipper {
fileprivate let fileInfo: ZipFileInfo
init(fileInfo: ZipFileInfo, sourcePath: String) {
self.fileInfo = fileInfo
super.init(sourcePath: sourcePath)
}
func unzip() -> UnpackFileResult {
do {
let fileContent = try unzipContent(for: fileInfo)
return .success(fileContent)
} catch (let unpackError) {
return .failure(UnpackError(underlyingError: unpackError))
}
}
private func unzipContent(for fileInfo: FileInfo) throws -> Data {
var fileData: Data! = nil
do {
try openZipFile()
defer {
closeZipFile()
}
try advanceCurrentFile(to: fileInfo)
fileData = try loadCurrentFileData()
} catch (let error) { throw error }
return fileData
}
private func loadCurrentFileData() throws -> Data {
let container = temporaryContainer()
defer {
delete(temporaryContainer: container)
}
let unzipResult = unzipCurrentFile(in: container)
switch unzipResult {
case .success(let filePath, _):
guard let fileData = Data.data(contentsOfFile: filePath) else {
throw UnzipError.UndefinedError(info: "Unable to load unzipped file at path \(filePath)")
}
return fileData
case .failure(let error):
throw error
}
}
private func temporaryContainer() -> String {
return NSTemporaryDirectory().appendingPathComponent(NSUUID().uuidString)
}
private func delete(temporaryContainer: String) {
try? fileManager.removeItem(atPath: temporaryContainer)
}
}
class ContentInfoUnzipper: Unzipper {
public typealias ContentInfoResult = Result<[ZipFileInfo], UnpackError>
public typealias ContentInfoCompletion = (ContentInfoResult) -> Void
init(sourcePath: String) {
super.init(sourcePath: sourcePath)
}
func unzip() -> ContentInfoResult {
do {
let contentInfo = try contentFilesInfo()
return Result.success(contentInfo)
} catch(let error) {
return Result.failure(UnpackError(underlyingError: error))
}
}
private func contentFilesInfo() throws -> [ZipFileInfo] {
var contentFilesInfo = [ZipFileInfo]()
do {
try openZipFile()
defer {
closeZipFile()
}
var thereAreMoreFiles = true
repeat {
let fileInfo = try openCurrentFileAndLoadFileInfo()
contentFilesInfo.append(fileInfo)
index += 1
do {
try advanceNextFile()
} catch { thereAreMoreFiles = false }
} while thereAreMoreFiles
} catch(let error) { throw error }
return contentFilesInfo
}
private func openCurrentFileAndLoadFileInfo() throws -> ZipFileInfo {
let openCurrentFileResult = unzOpenCurrentFile(zip)
guard openCurrentFileResult == UNZ_OK else {
throw UnzipError.UnableToOpenFile(index: index)
}
defer {
unzCloseCurrentFile(zip)
}
guard var fileInfo = currentFileInfo() else {
throw UnzipError.UnableToReadFileInfo(index: index)
}
var zipFileInfo: ZipFileInfo! = nil
do {
zipFileInfo = try createAZipFileInfo(from: &fileInfo)
} catch(let error) { throw error }
return zipFileInfo
}
}
class Unzipper {
fileprivate enum UnzipError: Error {
case RequiredDestinationPathNotDefined
case UnableToReadZipFileAttributes
case UnableToOpenZipFile
case UnableToOpenFile(index: UInt)
case UnableToReadFileInfo(index: UInt)
case UnableToCreateFileContainer(path: String, index: UInt)
case UnableToWriteFile(path: String, index: UInt)
case UndefinedError(info: String)
}
private struct EOF: Error {
}
fileprivate var zip: zipFile?
fileprivate let sourcePath: String
fileprivate let destinationPath: String?
fileprivate let overwrite: Bool = true
fileprivate let bufferSize: UInt32 = 4096
fileprivate var buffer: Array<CUnsignedChar>
fileprivate let fileManager = FileManager.default
fileprivate var index: UInt = 0
private init() {
// This init is never used.
// Is here just to avoid direct instantiation and get a similar effect of an abtract class
self.sourcePath = ""
self.destinationPath = ""
self.buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize))
}
fileprivate init(sourcePath: String, destinationPath: String? = nil) {
self.sourcePath = sourcePath
self.destinationPath = destinationPath
self.buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize))
}
fileprivate func unzipCurrentFile(in destinationPath: String) -> Result<(filePath: String, fileInfo: ZipFileInfo), UnzipError> {
let openCurrentFileResult = unzOpenCurrentFile(zip)
guard openCurrentFileResult == UNZ_OK else {
return .failure(UnzipError.UnableToOpenFile(index: index))
}
defer {
unzCloseCurrentFile(zip)
}
guard var fileInfo = currentFileInfo() else {
return .failure(UnzipError.UnableToReadFileInfo(index: index))
}
let fullPath = destinationPath.appendingPathComponent(fileName(from: &fileInfo))
var zipFileInfo: ZipFileInfo!
do {
zipFileInfo = try createAZipFileInfo(from: &fileInfo)
} catch (let error) {
return .failure(error as! UnzipError)
}
let isDirectory = caclculateIfIsDirectory(fileInfo)
guard fileManager.fileExists(atPath: fullPath) == false || isDirectory || overwrite else {
return .success((filePath: fullPath, fileInfo: zipFileInfo as ZipFileInfo))
}
do {
try createEnclosingFolder(for: fullPath, isDirectory: isDirectory, at: index)
} catch {
return .failure(UnzipError.UnableToCreateFileContainer(path: fullPath, index: index))
}
writeCurrentFile(at: fullPath)
return .success((filePath: fullPath, fileInfo: zipFileInfo as ZipFileInfo))
}
fileprivate func advanceNextFile() throws {
let cursorResult = unzGoToNextFile(zip)
guard cursorResult == UNZ_OK && cursorResult != UNZ_END_OF_LIST_OF_FILE else {
throw EOF()
}
}
fileprivate func advanceCurrentFile(to fileInfo: FileInfo) throws {
index = 0
unzGoToFirstFile(zip)
while index < fileInfo.index {
let cursorResult = unzGoToNextFile(zip)
index += 1
guard cursorResult == UNZ_OK else { throw UnzipError.UnableToOpenFile(index: index) }
}
}
fileprivate func openZipFile() throws {
zip = unzOpen((sourcePath as NSString).utf8String)
var globalInfo: unz_global_info = unz_global_info()
unzGetGlobalInfo(zip, &globalInfo)
do {
_ = try fileManager.attributesOfItem(atPath: sourcePath)
} catch { throw UnzipError.UnableToReadZipFileAttributes }
let openFirstFileResult = unzGoToFirstFile(zip)
guard openFirstFileResult == UNZ_OK else { throw UnzipError.UnableToOpenZipFile }
}
fileprivate func currentFileInfo() -> unz_file_info? {
var fileInfo = unz_file_info()
memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size)
let getFileInfoResult = unzGetCurrentFileInfo(zip, &fileInfo, nil, 0, nil, 0, nil, 0)
guard getFileInfoResult == UNZ_OK else { return nil }
return fileInfo
}
fileprivate func createEnclosingFolder(for path: String, isDirectory: Bool, at index: UInt) throws {
let creationDate = Date()
let directoryAttributes = [FileAttributeKey.creationDate.rawValue : creationDate,
FileAttributeKey.modificationDate.rawValue : creationDate]
let folderToCreate = isDirectory ? path : path.deletingLastPathComponent
try fileManager.createDirectory(atPath: folderToCreate, withIntermediateDirectories: true, attributes: directoryAttributes)
}
fileprivate func caclculateIfIsDirectory(_ fileInfo: unz_file_info) -> Bool {
let fileNameSize = Int(fileInfo.size_filename) + 1
let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize)
defer {
free(fileName)
}
var isDirectory = false
let fileInfoSizeFileName = Int(fileInfo.size_filename) - 1
if fileName[fileInfoSizeFileName] == "/".cString(using: String.Encoding.utf8)?.first ||
fileName[fileInfoSizeFileName] == "\\".cString(using: String.Encoding.utf8)?.first {
isDirectory = true;
}
return isDirectory
}
fileprivate func fileName(from fileInfo: inout unz_file_info) -> String {
let fileNameSize = Int(fileInfo.size_filename) + 1
let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize)
defer {
free(fileName)
}
unzGetCurrentFileInfo(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0)
fileName[Int(fileInfo.size_filename)] = 0
return String(cString: fileName)
}
fileprivate func createAZipFileInfo(from unzFileInfo: inout unz_file_info) throws -> ZipFileInfo {
let isDirectory = caclculateIfIsDirectory(unzFileInfo)
let fileInfoName = fileName(from: &unzFileInfo)
let fileInfoDate = Date.date(MSDOSFormat: UInt32(unzFileInfo.dosDate))
let zipFileInfo = ZipFileInfo(fileName: fileInfoName,
fileCRC: unzFileInfo.crc,
timestamp: fileInfoDate,
compressedSize: unzFileInfo.compressed_size,
uncompressedSize: unzFileInfo.uncompressed_size,
isDirectory: isDirectory,
index: index)
return zipFileInfo
}
fileprivate func writeCurrentFile(at path: String) {
var filePointer: UnsafeMutablePointer<FILE>?
filePointer = fopen(path, "wb")
defer {
fclose(filePointer)
}
while filePointer != nil {
let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize)
if readBytes > 0 {
fwrite(buffer, Int(readBytes), 1, filePointer)
} else {
break
}
}
}
fileprivate func closeZipFile() {
unzClose(zip)
}
}
| gpl-3.0 | 7f8556ce8ee3a996922626aa6b695b26 | 34.908333 | 132 | 0.617081 | 4.907745 | false | false | false | false |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_Foundation/NSMutableAttributedString+Utils.swift | 1 | 2967 | //
// NSMutableAttributedString+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 1/18/18.
// Copyright © 2019 Anton Plebanovich. All rights reserved.
//
import UIKit
import RoutableLogger
public extension NSMutableAttributedString {
/// Sets font for the first occurence of text. If text is `nil` sets font for entire string.
func set(font: UIFont, for text: String? = nil) {
let range: NSRange
if let text = text {
range = mutableString.range(of: text)
} else {
range = fullRange
}
guard range.location != NSNotFound else {
RoutableLogger.logError("Unable to locate text", data: ["text": text, "self": self])
return
}
addAttribute(.font, value: font, range: range)
}
/// Sets aligment for the first occurence of text. If text is `nil` sets aligment for entire string.
func set(aligment: NSTextAlignment? = nil,
headIndent: CGFloat? = nil,
lineSpacing: CGFloat? = nil,
lineHeightMultiple: CGFloat? = nil,
for text: String? = nil) {
let range: NSRange
if let text = text {
range = mutableString.range(of: text)
} else {
range = fullRange
}
guard range.location != NSNotFound else {
RoutableLogger.logError("Unable to locate text", data: ["text": text, "self": self])
return
}
let paragraphStyle = NSMutableParagraphStyle()
if let aligment = aligment { paragraphStyle.alignment = aligment }
if let headIndent = headIndent { paragraphStyle.headIndent = headIndent }
if let lineSpacing = lineSpacing { paragraphStyle.lineSpacing = lineSpacing }
if let lineHeightMultiple = lineHeightMultiple { paragraphStyle.lineHeightMultiple = lineHeightMultiple }
addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
}
/// Sets text kern
func set(kern: CGFloat) {
addAttribute(.kern, value: kern, range: fullRange)
}
/// Makes text underlined
func setUnderline() {
addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: fullRange)
}
/// Makes text striked through
func setStrikethrough(text: String? = nil) {
let range: NSRange
if let text = text {
range = mutableString.range(of: text)
} else {
range = fullRange
}
guard range.location != NSNotFound else {
RoutableLogger.logError("Unable to locate text", data: ["text": text, "self": self])
return
}
addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: range)
addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
}
}
| mit | be65170ae27500650277ac4b0ae34bb3 | 33.894118 | 118 | 0.606541 | 5.001686 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigoKit/Supporting Files/ImageMetadata.swift | 1 | 23291 | //
// ImageMetadata.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 09/01/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import Foundation
import ImageIO
import UIKit
class ImageMetadata {
// MARK: - Private metadata properties
// Exif private metadata properties
/// See https://www.exiftool.org/TagNames/EXIF.html
let exifPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyExifUserComment, // User's comment
kCGImagePropertyExifSubjectLocation, // Image’s primary subject
kCGImagePropertyExifMakerNote // Information specified by the camera manufacturer
]
return properties
}()
// ExifEx private metadata properties
/// See https://www.exiftool.org/TagNames/EXIF.html
let exifExPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyExifCameraOwnerName, // Owner's name
kCGImagePropertyExifBodySerialNumber, // Serial numbers
kCGImagePropertyExifLensSerialNumber // Lens serial number
]
return properties
}()
// ExifAux private metadata properties
/// See https://www.exiftool.org/TagNames/EXIF.html
let exifAuxPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyExifAuxSerialNumber, // Serial number
kCGImagePropertyExifAuxLensSerialNumber, // Lens serial number
kCGImagePropertyExifAuxOwnerName // Owner's name
]
return properties
}()
// IPTC private metadata properties
/// See https://www.exiftool.org/TagNames/IPTC.html
/// See https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata
let iptcPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyIPTCContentLocationCode, // Content location code
kCGImagePropertyIPTCContentLocationName, // Content location name
kCGImagePropertyIPTCByline, // Name of the person who created the image
kCGImagePropertyIPTCBylineTitle, // Title of the person who created the image
kCGImagePropertyIPTCCity, // City where the image was created
kCGImagePropertyIPTCSubLocation, // Location within the city where the image was created
kCGImagePropertyIPTCProvinceState, // Province or state
kCGImagePropertyIPTCCountryPrimaryLocationCode, // Country primary location code
kCGImagePropertyIPTCCountryPrimaryLocationName, // Country primary location name
kCGImagePropertyIPTCOriginalTransmissionReference,// Call letter/number combination
kCGImagePropertyIPTCHeadline, // Summary of the contents of the image
kCGImagePropertyIPTCCredit, // Name of the service that provided the image
kCGImagePropertyIPTCSource, // Original owner of the image
kCGImagePropertyIPTCContact, // Contact information for further information
kCGImagePropertyIPTCWriterEditor, // Name of the person who wrote or edited the description
kCGImagePropertyIPTCCreatorContactInfo, // Creator’s contact info (dictionary)
]
return properties
}()
// PNG private metadata properties
/// See https://www.exiftool.org/TagNames/PNG.html
let pngPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyPNGAuthor // String that identifies the author
]
return properties
}()
// TIFF private metadata properties
let tiffPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyTIFFArtist // Artist who created the image
]
return properties
}()
// DNG private metadata properties
let dngPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyDNGCameraSerialNumber // Camera serial number
]
return properties
}()
// CIFF private metadata properties
let ciffPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyCIFFOwnerName, // Camera’s owner
kCGImagePropertyCIFFRecordID, // Number of images taken since the camera shipped
kCGImagePropertyCIFFCameraSerialNumber // Camera serial number
]
return properties
}()
// Canon private metadata properties
let canonPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyMakerCanonOwnerName, // Camera’s owner
kCGImagePropertyMakerCanonCameraSerialNumber // Camera serial number
]
return properties
}()
// Nikon private metadata properties
let nikonPrivateProperties: [CFString] = {
let properties = [kCGImagePropertyMakerNikonCameraSerialNumber // Camera’s owner
]
return properties
}()
}
extension CGImageMetadata {
// Remove CGImage private metadata
// The GPS metadata will be removed using the kCGImageMetadataShouldExcludeGPS option
public func stripPrivateMetadata() -> CGImageMetadata {
guard let metadata = CGImageMetadataCreateMutableCopy(self) else {
return self
}
// Get prefixes and keys of privata metadata
var dictOfKeys = [CFString : [CFString]]()
dictOfKeys[kCGImageMetadataPrefixExif] = ImageMetadata().exifPrivateProperties
dictOfKeys[kCGImageMetadataPrefixExifEX] = ImageMetadata().exifExPrivateProperties
dictOfKeys[kCGImageMetadataPrefixExifAux] = ImageMetadata().exifAuxPrivateProperties
dictOfKeys[kCGImageMetadataPrefixIPTCCore] = ImageMetadata().iptcPrivateProperties
dictOfKeys[kCGImageMetadataPrefixTIFF] = ImageMetadata().tiffPrivateProperties
if #available(iOS 11.3, *) {
dictOfKeys[kCGImageMetadataPrefixIPTCExtension] = ImageMetadata().iptcPrivateProperties
}
dictOfKeys[kCGImageMetadataPrefixXMPBasic] = ImageMetadata().pngPrivateProperties
// Loop over all tags
CGImageMetadataEnumerateTagsUsingBlock(self, nil, nil) { _, tag in
// Retrieve path
let prefix = CGImageMetadataTagCopyPrefix(tag)!
let name = CGImageMetadataTagCopyName(tag)!
let path = ((prefix as String) + ":" + (name as String)) as CFString
print("=> Tag: \(prefix):\(name)")
// Check presence of dictionary
if let properties = dictOfKeys[prefix] {
// Remove tag if it contains private data
if properties.contains(name as CFString) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
}
// Check remaining names
if ImageMetadata().pngPrivateProperties.contains(name) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
if ImageMetadata().dngPrivateProperties.contains(name) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
if ImageMetadata().ciffPrivateProperties.contains(name) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
if ImageMetadata().canonPrivateProperties.contains(name) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
if ImageMetadata().nikonPrivateProperties.contains(name) {
CGImageMetadataRemoveTagWithPath(metadata, nil, path as CFString)
return true
}
return true
}
return metadata
}
}
extension Dictionary where Key == CFString, Value == Any {
// Remove CGImage properties w/o GPS and other private data
public func stripPrivateProperties() -> [CFString:Any] {
var properties = self as [CFString:Any]
// Remove GPS dictionary
if let GPSdata = properties[kCGImagePropertyGPSDictionary] as? [CFString:Any] {
properties.removeValue(forKey: kCGImagePropertyGPSDictionary)
print("=> removed GPS metadata = \(GPSdata)")
}
// Get other dictionaries with keys of privata data
var dictOfKeys = [CFString : [CFString]]()
var exifPrivateProperties = ImageMetadata().exifPrivateProperties
exifPrivateProperties.append(contentsOf: ImageMetadata().exifExPrivateProperties)
dictOfKeys[kCGImagePropertyExifDictionary] = exifPrivateProperties
dictOfKeys[kCGImagePropertyExifAuxDictionary] = ImageMetadata().exifAuxPrivateProperties
dictOfKeys[kCGImagePropertyIPTCDictionary] = ImageMetadata().iptcPrivateProperties
dictOfKeys[kCGImagePropertyPNGDictionary] = ImageMetadata().pngPrivateProperties
dictOfKeys[kCGImagePropertyTIFFDictionary] = ImageMetadata().tiffPrivateProperties
dictOfKeys[kCGImagePropertyDNGDictionary] = ImageMetadata().dngPrivateProperties
dictOfKeys[kCGImagePropertyCIFFDictionary] = ImageMetadata().ciffPrivateProperties
dictOfKeys[kCGImagePropertyMakerCanonDictionary] = ImageMetadata().canonPrivateProperties
dictOfKeys[kCGImagePropertyMakerNikonDictionary] = ImageMetadata().nikonPrivateProperties
// Loop over the dictionaries
for dict in dictOfKeys {
// Check presence of dictionary
if var dictData = properties[dict.key] as? [CFString:Any] {
// Loop over the keys of private data
for key in dict.value {
// Remove private metadata if any
if let value = dictData[key] {
dictData.removeValue(forKey: key)
print("=> removed private metadata [\(key) : \(value)]")
}
}
// Update properties
properties[dict.key] = dictData
}
}
return properties
}
// Fix image properties from resized/converted image
mutating func fixContents(from image:CGImage) {
var metadata = self
// Extract image data from UIImage object (orientation managed)
guard let imageData = UIImage(cgImage: image).jpegData(compressionQuality: 1.0) else {
return
}
// Create image source from image data
guard let source = CGImageSourceCreateWithData(imageData as CFData, nil) else {
return
}
// Extract image source container properties
if let sourceMetadata = CGImageSourceCopyProperties(source, nil) as? [CFString : Any] {
// Update TIFF, GIF, etc. metadata from properties found in the container
metadata.fixProperties(from: sourceMetadata)
}
// Extract image properties from image data
if let imageMetadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString : Any] {
// Update TIFF, GIF, etc. metadata from properties found in the image
metadata.fixProperties(from: imageMetadata)
// Update/add DPI height from image properties
if let DPIheight = imageMetadata[kCGImagePropertyDPIHeight] {
metadata[kCGImagePropertyDPIHeight] = DPIheight
}
// Update/add DPI width from image properties
if let DPIwidth = imageMetadata[kCGImagePropertyDPIWidth] {
metadata[kCGImagePropertyDPIHeight] = DPIwidth
}
// Update/add width from image properties
if let width = imageMetadata[kCGImagePropertyPixelWidth] {
metadata[kCGImagePropertyPixelWidth] = width
}
// Update/add height from image properties
if let height = imageMetadata[kCGImagePropertyPixelHeight] {
metadata[kCGImagePropertyPixelHeight] = height
}
// Update/add depth from image properties
if let depth = imageMetadata[kCGImagePropertyDepth] {
metadata[kCGImagePropertyDepth] = depth
}
// The orientation was unchanged during the resize or conversion.
// So we keep the original orientation.
// if let orientation = imageMetadata[kCGImagePropertyOrientation] as? UInt32 {
// metadata[kCGImagePropertyOrientation] = CGImagePropertyOrientation(rawValue: orientation)
// }
// Update/add isFloat from image properties
if let isFloat = imageMetadata[kCGImagePropertyIsFloat] {
metadata[kCGImagePropertyIsFloat] = isFloat
}
// Update/add isIndexed from image properties
if let isIndexed = imageMetadata[kCGImagePropertyIsIndexed] {
metadata[kCGImagePropertyIsIndexed] = isIndexed
}
// Update/add asAlpha from image properties
if let asAlpha = imageMetadata[kCGImagePropertyHasAlpha] {
metadata[kCGImagePropertyHasAlpha] = asAlpha
}
// Update/add colour model from image properties
if let colorModel = imageMetadata[kCGImagePropertyColorModel] {
metadata[kCGImagePropertyColorModel] = colorModel
}
// Update/add ICC profile from image properties
if let iccProfile = imageMetadata[kCGImagePropertyProfileName] {
metadata[kCGImagePropertyProfileName] = iccProfile
}
}
self = metadata
}
// Fix image properties from (resized) image metadata
mutating func fixProperties(from imageMetadata: [CFString:Any]) {
var metadata = self
// Update TIFF dictionary from image metadata
if let imageTIFFDictionary = imageMetadata[kCGImagePropertyTIFFDictionary] as? [CFString : Any] {
// Image contains a TIFF dictionary
if var metadataTIFFDictionary = metadata[kCGImagePropertyTIFFDictionary] as? [CFString : Any] {
// A TIFF dictionary already exists -> update key/value pairs
for (k, v) in imageTIFFDictionary { metadataTIFFDictionary[k] = v }
metadata[kCGImagePropertyTIFFDictionary] = metadataTIFFDictionary
} else {
// No TIFF dictionary -> Add it
metadata[kCGImagePropertyTIFFDictionary] = imageTIFFDictionary
}
}
// Update/add GIF dictionary from image metadata
if let imageGIFDictionary = imageMetadata[kCGImagePropertyGIFDictionary] as? [CFString : Any] {
// Image contains a GIF dictionary
if var metadataGIFDictionary = metadata[kCGImagePropertyGIFDictionary] as? [CFString : Any] {
// A GIF dictionary already exists -> update key/value pairs
for (k, v) in imageGIFDictionary { metadataGIFDictionary[k] = v }
metadata[kCGImagePropertyGIFDictionary] = metadataGIFDictionary
} else {
// No GIF dictionary -> Add it
metadata[kCGImagePropertyGIFDictionary] = imageGIFDictionary
}
}
// Update/add JFIF dictionary from image metadata
if let imageJFIFDictionary = imageMetadata[kCGImagePropertyJFIFDictionary] as? [CFString : Any] {
// Image contains a JFIF dictionary
if var metadataJFIFDictionary = metadata[kCGImagePropertyJFIFDictionary] as? [CFString : Any] {
// A JIFF dictionary already exists -> update key/value pairs
for (k, v) in imageJFIFDictionary { metadataJFIFDictionary[k] = v }
metadata[kCGImagePropertyJFIFDictionary] = metadataJFIFDictionary
} else {
// No JIFF dictionary -> Add it
metadata[kCGImagePropertyJFIFDictionary] = imageJFIFDictionary
}
}
// Update/add Exif dictionary from image metadata
if let imageEXIFDictionary = imageMetadata[kCGImagePropertyExifDictionary] as? [CFString : Any] {
// Image contains an EXIF dictionary
if var metadataEXIFDictionary = metadata[kCGImagePropertyExifDictionary] as? [CFString : Any] {
// An EXIF dictionary already exists -> update key/value pairs
for (k, v) in imageEXIFDictionary { metadataEXIFDictionary[k] = v }
metadata[kCGImagePropertyExifDictionary] = metadataEXIFDictionary
} else {
// No EXIF dictionary -> Add it
metadata[kCGImagePropertyExifDictionary] = imageEXIFDictionary
}
}
// Update/add PNG dictionary from image metadata
if let imagePNGDictionary = imageMetadata[kCGImagePropertyPNGDictionary] as? [CFString : Any] {
// Image contains a PNG dictionary
if var metadataPNGDictionary = metadata[kCGImagePropertyPNGDictionary] as? [CFString : Any] {
// A PNG dictionary already exists -> update key/value pairs
for (k, v) in imagePNGDictionary { metadataPNGDictionary[k] = v }
metadata[kCGImagePropertyPNGDictionary] = metadataPNGDictionary
} else {
// No PNG dictionary -> Add it
metadata[kCGImagePropertyPNGDictionary] = imagePNGDictionary
}
}
// Update/add IPTC dictionary from image metadata
if let imageIPTCDictionary = metadata[kCGImagePropertyIPTCDictionary] as? [CFString : Any] {
// Image contains an IPTC dictionary
if var metadataIPTCDictionary = metadata[kCGImagePropertyIPTCDictionary] as? [CFString : Any] {
// A IPTC dictionary already exists -> update key/value pairs
for (k, v) in imageIPTCDictionary { metadataIPTCDictionary[k] = v }
metadata[kCGImagePropertyIPTCDictionary] = metadataIPTCDictionary
} else {
// No IPTC dictionary -> Add it
metadata[kCGImagePropertyIPTCDictionary] = imageIPTCDictionary
}
}
// Update/add GPS dictionary from image metadata
if let imageGPSDictionary = metadata[kCGImagePropertyGPSDictionary] as? [CFString : Any] {
// Image contains a GPS dictionary
if var metadataGPSDictionary = metadata[kCGImagePropertyGPSDictionary] as? [CFString : Any] {
// A IPTC dictionary already exists -> update key/value pairs
for (k, v) in imageGPSDictionary { metadataGPSDictionary[k] = v }
metadata[kCGImagePropertyGPSDictionary] = metadataGPSDictionary
} else {
// No IPTC dictionary -> Add it
metadata[kCGImagePropertyGPSDictionary] = imageGPSDictionary
}
}
// Update RAW dictionary from image metadata
if let imageRawDictionary = imageMetadata[kCGImagePropertyRawDictionary] as? [CFString : Any] {
// Image contains a RAW dictionary
if var metadataRawDictionary = metadata[kCGImagePropertyRawDictionary] as? [CFString : Any] {
// A Raw dictionary already exists -> update key/value pairs
for (k, v) in imageRawDictionary { metadataRawDictionary[k] = v }
metadata[kCGImagePropertyRawDictionary] = metadataRawDictionary
} else {
// No Raw dictionary -> Add it
metadata[kCGImagePropertyRawDictionary] = imageRawDictionary
}
}
// Update/add CIFF dictionary from image metadata
if let imageCIFFDictionary = imageMetadata[kCGImagePropertyCIFFDictionary] as? [CFString : Any] {
// Image contains a CIFF dictionary
if var metadataCIFFDictionary = metadata[kCGImagePropertyCIFFDictionary] as? [CFString : Any] {
// A CIFF dictionary already exists -> update key/value pairs
for (k, v) in imageCIFFDictionary { metadataCIFFDictionary[k] = v }
metadata[kCGImagePropertyCIFFDictionary] = metadataCIFFDictionary
} else {
// No CIFF dictionary -> Add it
metadata[kCGImagePropertyCIFFDictionary] = imageCIFFDictionary
}
}
// Update/add 8BIM dictionary from image metadata
if let image8BIMDictionary = imageMetadata[kCGImageProperty8BIMDictionary] as? [CFString : Any] {
// Image contains a 8BIM dictionary
if var metadata8BIMDictionary = metadata[kCGImageProperty8BIMDictionary] as? [CFString : Any] {
// A 8BIM dictionary already exists -> update key/value pairs
for (k, v) in image8BIMDictionary { metadata8BIMDictionary[k] = v }
metadata[kCGImageProperty8BIMDictionary] = metadata8BIMDictionary
} else {
// No 8BIM dictionary -> Add it
metadata[kCGImageProperty8BIMDictionary] = image8BIMDictionary
}
}
// Update/add DNG dictionary from image metadata
if let imageDNGDictionary = imageMetadata[kCGImagePropertyDNGDictionary] as? [CFString : Any] {
// Image contains a DNG dictionary
if var metadataDNGDictionary = metadata[kCGImagePropertyDNGDictionary] as? [CFString : Any] {
// A DNG dictionary already exists -> update key/value pairs
for (k, v) in imageDNGDictionary { metadataDNGDictionary[k] = v }
metadata[kCGImagePropertyDNGDictionary] = metadataDNGDictionary
} else {
// No DNG dictionary -> Add it
metadata[kCGImagePropertyDNGDictionary] = imageDNGDictionary
}
}
// Update/add ExifAux dictionary from image metadata
if let imageExifAuxDictionary = imageMetadata[kCGImagePropertyExifAuxDictionary] as? [CFString : Any] {
// Image contains an EXIF Aux dictionary
if var metadataExifAuxDictionary = metadata[kCGImagePropertyExifAuxDictionary] as? [CFString : Any] {
// An EXIF Aux dictionary already exists -> update key/value pairs
for (k, v) in imageExifAuxDictionary { metadataExifAuxDictionary[k] = v }
metadata[kCGImagePropertyExifAuxDictionary] = metadataExifAuxDictionary
} else {
// No EXIF Aux dictionary -> Add it
metadata[kCGImagePropertyExifAuxDictionary] = imageExifAuxDictionary
}
}
self = metadata
}
}
| mit | 79332b26f56281390d7b3cbf20e82499 | 48.215645 | 125 | 0.626616 | 5.41498 | false | false | false | false |
NijiDigital/NetworkStack | Sources/TokenManager.swift | 1 | 2101 | //
// TokenManager.swift
// Pods
//
// Created by Pierre DUCHENE on 31/05/2017.
//
//
import Foundation
import RxSwift
import RxCocoa
/**
TokenManager is responsible of token management for the NetworkStack
It manage the request flow, tu ensure that only one refresh token request was send,
and to prevent all observer when new token will arrive
*/
class TokenManager {
// MARK: - Properties
/// This observable is used to get a new token if needed
private let tokenFetcher: Observable<String>
/// using Rx Variable instead of direct String,
/// this way, when you call fetchToken(), access to value is only done at subscribe time
private let currentToken = BehaviorRelay<String?>(value: nil)
/// Using weak var for this property.
/// The goal is to automatiquely set back to nil when no more observer subscribe
private weak var currentFetcher: Observable<String>?
// MARK: - Init
init(tokenFetcher: Observable<String>) {
self.tokenFetcher = tokenFetcher
}
// MARK: - API
/**
This method get the current token or fetch a new one if needed.
*/
func fetchToken() -> Observable<String> {
return currentToken.asObservable()
.flatMap { token -> Observable<String> in
if let token = token {
return Observable.just(token)
} else {
let fetcher = self.currentFetcher ?? self.sharedTokenRequest()
self.currentFetcher = fetcher
return fetcher
}
}
.take(1) // Send .completed after the first .next received from inside the flatMap (because the .completed from inside the flatMap doesn't propagate ouside the flatMap)
}
func invalidateToken() {
self.currentToken.accept(nil)
}
// MARK: - Private helpers
/**
To get a new token, we using a shared observable. This way, only one fetch token request is made.
And all the observer was notified
*/
private func sharedTokenRequest() -> Observable<String> {
return tokenFetcher
.do(onNext: { [unowned self] token in
self.currentToken.accept(token)
})
.share()
}
}
| apache-2.0 | 48b9153355e9767d330c63480732d136 | 26.644737 | 174 | 0.680152 | 4.340909 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/CourseContentPageViewController.swift | 1 | 18199 | //
// CourseContentPageViewController.swift
// edX
//
// Created by Akiva Leffert on 5/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public protocol CourseContentPageViewControllerDelegate : class {
func courseContentPageViewController(controller : CourseContentPageViewController, enteredBlockWithID blockID : CourseBlockID, parentID : CourseBlockID)
}
extension CourseBlockDisplayType {
var isCacheable : Bool {
switch self {
case .Video: return false
case .Unknown, .HTML(_), .Outline, .Unit, .Discussion: return true
}
}
}
// Container for scrolling horizontally between different screens of course content
public class CourseContentPageViewController : UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, CourseBlockViewController, CourseOutlineModeControllerDelegate, StatusBarOverriding, InterfaceOrientationOverriding, OpenOnWebControllerDelegate,UIGestureRecognizerDelegate {
public typealias Environment = protocol<OEXAnalyticsProvider, DataManagerProvider, OEXRouterProvider>
private let initialLoadController : LoadStateViewController
private let environment : Environment
private var initialChildID : CourseBlockID?
public private(set) var blockID : CourseBlockID?
public var courseID : String {
return courseQuerier.courseID
}
private var openURLButtonItem : UIBarButtonItem?
private var contentLoader = BackedStream<ListCursor<CourseOutlineQuerier.GroupItem>>()
private let courseQuerier : CourseOutlineQuerier
private let modeController : CourseOutlineModeController
private lazy var webController : OpenOnWebController = OpenOnWebController(delegate: self)
weak var navigationDelegate : CourseContentPageViewControllerDelegate?
///Manages the caching of the viewControllers that have been viewed atleast once.
///Removes the ViewControllers from memory in case of a memory warning
private let cacheManager : BlockViewControllerCacheManager
//自定义标题
private var titleL : UILabel?
public init(environment : Environment, courseID : CourseBlockID, rootID : CourseBlockID?, initialChildID: CourseBlockID? = nil) {
self.environment = environment
self.blockID = rootID
self.initialChildID = initialChildID
courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID)
modeController = environment.dataManager.courseDataManager.freshOutlineModeController()
initialLoadController = LoadStateViewController()
cacheManager = BlockViewControllerCacheManager()
super.init(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
self.setViewControllers([initialLoadController], direction: .Forward, animated: false, completion: nil)
modeController.delegate = self
self.dataSource = self
self.delegate = self
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = barButtonFixedSpaceWidth
// navigationItem.rightBarButtonItems = [webController.barButtonItem, fixedSpace, modeController.barItem]
addStreamListeners()
}
func leftBarItemAction() {
self.navigationController?.popViewControllerAnimated(true)
}
public required init?(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewWillAppear(animated : Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: animated)
courseQuerier.blockWithID(blockID).extendLifetimeUntilFirstResult (success:
{ block in
self.environment.analytics.trackScreenWithName(OEXAnalyticsScreenUnitDetail, courseID: self.courseID, value: block.internalName)
},
failure: {
Logger.logError("ANALYTICS", "Unable to load block: \($0)")
}
)
loadIfNecessary()
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setToolbarHidden(true, animated: animated)
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
let leftButton = UIButton.init(frame: CGRectMake(0, 0, 48, 48))
leftButton.setImage(UIImage.init(named: "backImagee"), forState: .Normal)
leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -23, 0, 23)
leftButton.addTarget(self, action: #selector(leftBarItemAction), forControlEvents: .TouchUpInside)
self.navigationController?.interactivePopGestureRecognizer?.enabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
let leftBarItem = UIBarButtonItem.init(customView: leftButton)
self.navigationItem.leftBarButtonItem = leftBarItem
// This is super hacky. Controls like sliders - that depend on pan gestures were getting intercepted
// by the page view's scroll view. This seemed like the only solution.
// Filed http://www.openradar.appspot.com/radar?id=6188034965897216 against Apple to better expose
// this API.
// Verified on iOS9 and iOS 8
if let scrollView = (self.view.subviews.flatMap { return $0 as? UIScrollView }).first {
scrollView.delaysContentTouches = false
}
}
private func addStreamListeners() {
contentLoader.listen(self,
success : {[weak self] cursor -> Void in
if let owner = self,
controller = owner.controllerForBlock(cursor.current.block)
{
owner.setViewControllers([controller], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
self?.updateNavigationForEnteredController(controller)
}
else {
self?.initialLoadController.state = LoadState.failed(NSError.oex_courseContentLoadError())
self?.updateNavigationBars()
}
return
}, failure : {[weak self] error in
self?.initialLoadController.state = LoadState.failed(NSError.oex_courseContentLoadError())
}
)
}
private func loadIfNecessary() {
if !contentLoader.hasBacking {
let stream = courseQuerier.spanningCursorForBlockWithID(blockID, initialChildID: initialChildID, forMode: modeController.currentMode)
contentLoader.backWithStream(stream.firstSuccess())
}
}
private func toolbarItemWithGroupItem(item : CourseOutlineQuerier.GroupItem, adjacentGroup : CourseBlock?, direction : DetailToolbarButton.Direction, enabled : Bool) -> UIBarButtonItem {
let titleText : String
let moveDirection : UIPageViewControllerNavigationDirection
let isGroup = adjacentGroup != nil
switch direction {
case .Next:
titleText = isGroup ? Strings.nextUnit : Strings.next
// titleText = isGroup ? "下个单元" : "下一页"
moveDirection = .Forward
case .Prev:
titleText = isGroup ? Strings.previousUnit : Strings.previous
// titleText = isGroup ? "上个单元" : "上一页"
moveDirection = .Reverse
}
let destinationText = adjacentGroup?.displayName
let view = DetailToolbarButton(direction: direction, titleText: titleText, destinationText: destinationText) {[weak self] in
self?.moveInDirection(moveDirection)
}
view.sizeToFit()
let barButtonItem = UIBarButtonItem(customView: view)
barButtonItem.enabled = enabled
view.button.enabled = enabled
return barButtonItem
}
private func openOnWebInfoForBlock(block : CourseBlock) -> OpenOnWebController.Info {
return OpenOnWebController.Info(courseID: courseID, blockID: block.blockID, supported: block.displayType.isUnknown, URL: block.webURL)
}
private func updateNavigationBars() {
if let cursor = contentLoader.value {
let item = cursor.current
// only animate change if we haven't set a title yet, so the initial set happens without
// animation to make the push transition work right
let actions : () -> Void = {
// self.navigationItem.title = item.block.displayName
//添加标题文本
self.titleL = UILabel(frame:CGRect(x:0, y:0, width:40, height:40))
self.titleL?.text = item.block.displayName
self.navigationItem.titleView = self.titleL
self.titleL?.font = UIFont(name:"OpenSans",size:18.0)
self.titleL?.textColor = UIColor.whiteColor()
self.webController.info = self.openOnWebInfoForBlock(item.block)
}
if let navigationBar = navigationController?.navigationBar where navigationItem.title != nil {
let animated = navigationItem.title != nil
UIView.transitionWithView(navigationBar,
duration: 0.3 * (animated ? 1.0 : 0.0), options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: actions, completion: nil)
}
else {
actions()
}
let prevItem = toolbarItemWithGroupItem(item, adjacentGroup: item.prevGroup, direction: .Prev, enabled: cursor.hasPrev)
let nextItem = toolbarItemWithGroupItem(item, adjacentGroup: item.nextGroup, direction: .Next, enabled: cursor.hasNext)
self.setToolbarItems(
[
prevItem,
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
nextItem
], animated : true)
}
else {
self.toolbarItems = []
}
}
// MARK: Paging
private func siblingWithDirection(direction : UIPageViewControllerNavigationDirection, fromController viewController: UIViewController) -> UIViewController? {
let item : CourseOutlineQuerier.GroupItem?
switch direction {
case .Forward:
item = contentLoader.value?.peekNext()
case .Reverse:
item = contentLoader.value?.peekPrev()
}
return item.flatMap {
controllerForBlock($0.block)
}
}
private func updateNavigationForEnteredController(controller : UIViewController?) {
if let blockController = controller as? CourseBlockViewController,
cursor = contentLoader.value
{
cursor.updateCurrentToItemMatching {
blockController.blockID == $0.block.blockID
}
environment.analytics.trackViewedComponentForCourseWithID(courseID, blockID: cursor.current.block.blockID)
self.navigationDelegate?.courseContentPageViewController(self, enteredBlockWithID: cursor.current.block.blockID, parentID: cursor.current.parent)
}
self.updateNavigationBars()
}
private func moveInDirection(direction : UIPageViewControllerNavigationDirection) {
if let currentController = viewControllers?.first,
nextController = self.siblingWithDirection(direction, fromController: currentController)
{
self.setViewControllers([nextController], direction: direction, animated: true, completion: nil)
self.updateNavigationForEnteredController(nextController)
}
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
return siblingWithDirection(.Reverse, fromController: viewController)
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
return siblingWithDirection(.Forward, fromController: viewController)
}
public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
self.updateNavigationForEnteredController(pageViewController.viewControllers?.first)
}
// MARK: Course Outline Mode
public func courseOutlineModeChanged(courseMode: CourseOutlineMode) {
// If we change mode we want to pop the screen since it may no longer make sense.
// It's easy if we're at the top of the controller stack, but we need to be careful if we're not
if self.navigationController?.topViewController == self {
self.navigationController?.popViewControllerAnimated(true)
}
else {
let controllers = self.navigationController?.viewControllers.filter {
return $0 != self
}
self.navigationController?.viewControllers = controllers ?? []
}
}
public func viewControllerForCourseOutlineModeChange() -> UIViewController {
return self
}
func controllerForBlock(block : CourseBlock) -> UIViewController? {
let blockViewController : UIViewController?
if let cachedViewController = self.cacheManager.getCachedViewControllerForBlockID(block.blockID) {
blockViewController = cachedViewController
}
else {
// Instantiate a new VC from the router if not found in cache already
if let viewController = self.environment.router?.controllerForBlock(block, courseID: courseQuerier.courseID) {
if block.displayType.isCacheable {
cacheManager.addToCache(viewController, blockID: block.blockID)
}
blockViewController = viewController
}
else {
blockViewController = UIViewController()
assert(false, "Couldn't instantiate viewController for Block \(block)")
}
}
if let viewController = blockViewController {
preloadAdjacentViewControllersFromViewController(viewController)
return viewController
}
else {
assert(false, "Couldn't instantiate viewController for Block \(block)")
return nil
}
}
override public func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle(barStyle : self.navigationController?.navigationBar.barStyle)
}
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
if let controller = viewControllers?.last as? StatusBarOverriding as? UIViewController {
return controller
}
else {
return super.childViewControllerForStatusBarStyle()
}
}
override public func childViewControllerForStatusBarHidden() -> UIViewController? {
if let controller = viewControllers?.last as? StatusBarOverriding as? UIViewController {
return controller
}
else {
return super.childViewControllerForStatusBarHidden()
}
}
override public func shouldAutorotate() -> Bool {
return true
}
override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [.Portrait , .LandscapeLeft , .LandscapeRight]
}
private func preloadBlock(block : CourseBlock) {
guard !cacheManager.cacheHitForBlockID(block.blockID) else {
return
}
guard block.displayType.isCacheable else {
return
}
guard let controller = self.environment.router?.controllerForBlock(block, courseID: courseQuerier.courseID) else {
return
}
cacheManager.addToCache(controller, blockID: block.blockID)
if let preloadable = controller as? PreloadableBlockController {
preloadable.preloadData()
}
}
private func preloadAdjacentViewControllersFromViewController(controller : UIViewController) {
if let block = contentLoader.value?.peekNext()?.block {
preloadBlock(block)
}
if let block = contentLoader.value?.peekPrev()?.block {
preloadBlock(block)
}
}
public func presentationControllerForOpenOnWebController(controller: OpenOnWebController) -> UIViewController {
return self
}
}
// MARK: Testing
extension CourseContentPageViewController {
public func t_blockIDForCurrentViewController() -> Stream<CourseBlockID> {
return contentLoader.flatMap {blocks in
let controller = (self.viewControllers?.first as? CourseBlockViewController)
let blockID = controller?.blockID
let result = blockID.toResult()
return result
}
}
public var t_prevButtonEnabled : Bool {
return self.toolbarItems![0].enabled
}
public var t_nextButtonEnabled : Bool {
return self.toolbarItems![2].enabled
}
public func t_goForward() {
moveInDirection(.Forward)
}
public func t_goBackward() {
moveInDirection(.Reverse)
}
public var t_isRightBarButtonEnabled : Bool {
return self.webController.barButtonItem.enabled
}
} | apache-2.0 | b3b22ceabbfbda613c313e482bf7dbfc | 40.343964 | 305 | 0.660147 | 5.86208 | false | false | false | false |
DanielAsher/VIPER-SWIFT | VIPER-SWIFT/Classes/Modules/List/User Interface/Presenter/UpcomingDisplayItem.swift | 1 | 553 | //
// UpcomingDisplayItem.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
struct UpcomingDisplayItem : Equatable, CustomStringConvertible {
let title : String
let dueDate : String
var description : String {
return "\(title) -- \(dueDate)"
}
}
func == (leftSide: UpcomingDisplayItem, rightSide: UpcomingDisplayItem) -> Bool {
return rightSide.title == leftSide.title
&& rightSide.dueDate == rightSide.dueDate
} | mit | bae4afd4036a2f4b600f8b9b1b418b76 | 23.086957 | 81 | 0.672694 | 4.157895 | false | false | false | false |
alblue/swift | test/SILGen/modify_objc.swift | 2 | 7672 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/modify_objc.h %s | %FileCheck %s
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/modify_objc.h %s -enable-resilience | %FileCheck %s --check-prefix=RESILIENT
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/modify_objc.h %s -enable-testing | %FileCheck %s --check-prefix=TESTING
// REQUIRES: objc_interop
public protocol ProtocolWithBlockProperty {
// No abstraction difference between the native witness and the requirement.
var block: ((String?) -> Void)? { get set }
// Abstraction difference between the native witness and the requirement.
associatedtype DependentInput
var dependentBlock: ((DependentInput) -> Void)? { get set }
}
extension ClassWithBlockProperty : ProtocolWithBlockProperty {}
// Protocol witness for 'block'.
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$sSo22ClassWithBlockPropertyC11modify_objc08ProtocolbcD0A2cDP5blockySSSgcSgvMTW :
// CHECK-SAME: $@yield_once @convention(witness_method: ProtocolWithBlockProperty) (@inout ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: bb0([[SELF_INDIRECT:%.*]] : @trivial $*ClassWithBlockProperty):
// CHECK-NEXT: [[SELF:%.*]] = load_borrow [[SELF_INDIRECT]] : $*ClassWithBlockProperty
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$sSo22ClassWithBlockPropertyC5blockySSSgcSgvM
// CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[FN]]([[SELF]])
// CHECK-NEXT: yield [[ADDR]] : $*Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK-LABEL: sil shared [serializable] @$sSo22ClassWithBlockPropertyC5blockySSSgcSgvM :
// CHECK-SAME: $@yield_once @convention(method) (@guaranteed ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// Protocol witness for 'dependentBlock'
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$sSo22ClassWithBlockPropertyC11modify_objc08ProtocolbcD0A2cDP09dependentC0y14DependentInputQzcSgvMTW :
// CHECK-SAME: $@yield_once @convention(witness_method: ProtocolWithBlockProperty) (@inout ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK: bb0([[SELF_INDIRECT:%.*]] : @trivial $*ClassWithBlockProperty):
// CHECK-NEXT: [[SELF:%.*]] = load_borrow [[SELF_INDIRECT]] : $*ClassWithBlockProperty
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$sSo22ClassWithBlockPropertyC09dependentC0ySSSgcSgvM
// CHECK-NEXT: ([[YIELD_ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[FN]]([[SELF]])
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK-NEXT: [[IN_FUNCTION:%.*]] = load [take] [[YIELD_ADDR]]
// CHECK: bb3([[OUT_FUNCTION:%.*]] : @owned $Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>):
// CHECK-NEXT: store [[OUT_FUNCTION]] to [init] [[TEMP]] :
// CHECK-NEXT: yield [[TEMP]] : $*Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK-LABEL: sil shared [serializable] @$sSo22ClassWithBlockPropertyC09dependentC0ySSSgcSgvM :
// CHECK-SAME: $@yield_once @convention(method) (@guaranteed ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// Make sure 'modify' implementations for 'dynamic' properties go through
// accessors.
public protocol ProtocolWithIntProperty {
var x: Int { get set }
}
class HasDynamicStoredProperty : ProtocolWithIntProperty {
@objc dynamic var x: Int = 0
}
// CHECK-LABEL: sil shared @$s11modify_objc24HasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed HasDynamicStoredProperty) -> @yields @inout Int
// CHECK: objc_method %0 : $HasDynamicStoredProperty, #HasDynamicStoredProperty.x!getter.1.foreign
// CHECK: yield
// CHECK: objc_method %0 : $HasDynamicStoredProperty, #HasDynamicStoredProperty.x!setter.1.foreign
// CHECK: return
// CHECK: objc_method %0 : $HasDynamicStoredProperty, #HasDynamicStoredProperty.x!setter.1.foreign
// CHECK: unwind
// TESTING-LABEL: sil shared [serialized] @$s11modify_objc24HasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed HasDynamicStoredProperty) -> @yields @inout Int
class HasDynamicComputedProperty : ProtocolWithIntProperty {
@objc dynamic var x: Int { get { } set { } }
}
// CHECK-LABEL: sil shared @$s11modify_objc26HasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed HasDynamicComputedProperty) -> @yields @inout Int
// CHECK: objc_method %0 : $HasDynamicComputedProperty, #HasDynamicComputedProperty.x!getter.1.foreign
// CHECK: yield
// CHECK: objc_method %0 : $HasDynamicComputedProperty, #HasDynamicComputedProperty.x!setter.1.foreign
// CHECK: return
// CHECK: objc_method %0 : $HasDynamicComputedProperty, #HasDynamicComputedProperty.x!setter.1.foreign
// CHECK: unwind
// TESTING-LABEL: sil shared [serialized] @$s11modify_objc26HasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed HasDynamicComputedProperty) -> @yields @inout Int
// Make sure 'modify' implementations for public 'dynamic' properties
// are serialized.
public class PublicHasDynamicStoredProperty : ProtocolWithIntProperty {
@objc public dynamic var x: Int = 0
}
// CHECK-LABEL: sil shared [serialized] @$s11modify_objc30PublicHasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed PublicHasDynamicStoredProperty) -> @yields @inout Int
// RESILIENT-LABEL: sil shared [serialized] @$s11modify_objc30PublicHasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed PublicHasDynamicStoredProperty) -> @yields @inout Int
public class PublicHasDynamicComputedProperty : ProtocolWithIntProperty {
@objc public dynamic var x: Int { get { } set { } }
}
// CHECK-LABEL: sil shared [serialized] @$s11modify_objc32PublicHasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed PublicHasDynamicComputedProperty) -> @yields @inout Int
// RESILIENT-LABEL: sil shared [serialized] @$s11modify_objc32PublicHasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed PublicHasDynamicComputedProperty) -> @yields @inout Int
// ... even if the class inherits NSObject.
public class NSPublicHasDynamicStoredProperty : NSObject, ProtocolWithIntProperty {
@objc public dynamic var x: Int = 0
}
// CHECK-LABEL: sil shared [serialized] @$s11modify_objc32NSPublicHasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed NSPublicHasDynamicStoredProperty) -> @yields @inout Int
// RESILIENT-LABEL: sil shared [serialized] @$s11modify_objc32NSPublicHasDynamicStoredPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed NSPublicHasDynamicStoredProperty) -> @yields @inout Int
public class NSPublicHasDynamicComputedProperty : NSObject, ProtocolWithIntProperty {
@objc public dynamic var x: Int { get { } set { } }
}
// CHECK-LABEL: sil shared [serialized] @$s11modify_objc34NSPublicHasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed NSPublicHasDynamicComputedProperty) -> @yields @inout Int
// RESILIENT-LABEL: sil shared [serialized] @$s11modify_objc34NSPublicHasDynamicComputedPropertyC1xSivM : $@yield_once @convention(method) (@guaranteed NSPublicHasDynamicComputedProperty) -> @yields @inout Int
| apache-2.0 | eb7f40bbe29b2f8c04c232abd670fc7b | 66.298246 | 209 | 0.754692 | 3.859155 | false | false | false | false |
benlangmuir/swift | test/decl/protocol/conforms/inherited.swift | 7 | 6936 | // RUN: %target-typecheck-verify-swift
// Inheritable: method with 'Self' in contravariant position.
protocol P1 {
func f1a(_ x: Self?) -> Bool
func f1b(_ x: [Self])
func f1c(_ x: [String : Self])
}
// Inheritable: property with 'Self' in its signature.
protocol P2 {
var prop2: Self { get set }
}
protocol P2a {
var prop2a: Self { get set }
}
// Inheritable: subscript with 'Self' in its result type.
protocol P3 {
subscript (i: Int) -> Self { get }
}
// Inheritable: subscript with 'Self' in its index type.
protocol P4 {
subscript (s: Self) -> Int { get }
}
// Potentially inheritable: method returning Self
protocol P5 {
func f5() -> Self
}
protocol P5a {
func f5a() -> Self
}
// Inheritable: method returning Self
protocol P6 {
func f6() -> Self
}
// Inheritable: method involving associated type.
protocol P7 {
associatedtype Assoc
func f7() -> Assoc
}
// Inheritable: initializer requirement.
protocol P8 {
init(int: Int)
}
// Inheritable: operator requirement.
protocol P9 {
static func ==(x: Self, y: Self) -> Bool
}
// Never inheritable: method with 'Self' in invariant position.
struct G<T> {}
protocol P10 {
func f10(_ arr: G<Self>)
}
protocol P10a {
func f10a(_ arr: G<Self>)
}
// Never inheritable: method with 'Self' in curried position.
protocol P11 {
func f11() -> (_ x: Self) -> Int
}
// Inheritable: parameter is a function returning 'Self'.
protocol P12 {
func f12(_ s: () -> (Self, Self))
}
// Never inheritable: parameter is a function accepting 'Self'.
protocol P13 {
func f13(_ s: (Self) -> ())
}
// Inheritable: parameter is a function accepting a function
// accepting 'Self'.
protocol P14 {
func f14(_ s: ((Self) -> ()) -> ())
}
// Never inheritable: parameter is a function accepting a function
// returning 'Self'.
// Not Inheritable: method returning tuple containing 'Self'.
// Not Inheritable: method returning array of 'Self'.
// Not Inheritable: requirement with reference to covariant 'Self', if this
// reference is not the uncurried type, stripped of any optionality.
protocol P15 {
func f15(_ s: (() -> Self) -> ())
func f16() -> (Self, Self)
func f17() -> Array<Self>
func f18() -> (Never, Array<Self>)
}
extension P15 {
func f18() -> (Never, Array<Self>) {} // expected-note {{'f18()' declared here}}
}
// Class A conforms to everything that can be conformed to by a
// non-final class.
class A : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 {
// P1
func f1a(_ x: A?) -> Bool { return true }
func f1b(_ x: [A]) { }
func f1c(_ x: [String : A]) { }
// P2
var prop2: A { // expected-error{{property 'prop2' in non-final class 'A' must specify type 'Self' to conform to protocol 'P2'}}
get { return self }
set {}
}
// P2a
var prop2a: A { // expected-note {{'prop2a' declared here}}
get { return self }
set {}
}
// P3
subscript (i: Int) -> A { // expected-error{{subscript 'subscript(_:)' in non-final class 'A' must return 'Self' to conform to protocol 'P3'}}
get {
return self
}
}
// P4
subscript (a: A) -> Int {
get {
return 5
}
}
// P5
func f5() -> A { return self } // expected-error{{method 'f5()' in non-final class 'A' must return 'Self' to conform to protocol 'P5'}}
// P5a
func f5a() -> A { return self } // expected-note {{'f5a()' declared here}}
// P6
func f6() -> Self { return self }
// P7
func f7() -> Int { return 5 }
// P8
required init(int: Int) { }
// P10
func f10(_ arr: G<A>) { } // expected-error{{protocol 'P10' requirement 'f10' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}}
// P10a
func f10a(_ arr: G<A>) { } // expected-note {{'f10a' declared here}}
// P11
func f11() -> (_ x: A) -> Int { return { x in 5 } }
}
extension A: P2a, P5a, P10a {}
// expected-error@-1 {{property 'prop2a' in non-final class 'A' must specify type 'Self' to conform to protocol 'P2a'}}
// expected-error@-2 {{method 'f5a()' in non-final class 'A' must return 'Self' to conform to protocol 'P5a'}}
// expected-error@-3 {{protocol 'P10a' requirement 'f10a' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}}
// P9
func ==(x: A, y: A) -> Bool { return true }
// Class B inherits A; gets all of its conformances.
class B : A {
required init(int: Int) { }
}
func testB(_ b: B) {
var _: any P1 = b
var _: any P4 = b
var _: any P5 = b
var _: any P6 = b
var _: any P7 = b
var _: any P8 = b
var _: any P9 = b
}
// Class A5 conforms to P5 in an inheritable manner.
class A5 : P5 {
// P5
func f5() -> Self { return self }
}
// Class B5 inherits A5; gets all of its conformances.
class B5 : A5 { }
func testB5(_ b5: B5) {
var _: P5 = b5 // okay
}
// Class A8 conforms to P8 in an inheritable manner.
class A8 : P8 {
required init(int: Int) { }
}
class B8 : A8 {
required init(int: Int) { }
}
func testB8(_ b8: B8) {
var _: P8 = b8 // okay
}
// Class A9 conforms to everything.
final class A9 : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 {
// P1
func f1a(_ x: A9?) -> Bool { return true }
func f1b(_ x: [A9]) { }
func f1c(_ x: [String : A9]) { }
// P2
var prop2: A9 {
get { return self }
set {}
}
// P3
subscript (i: Int) -> A9 {
get {
return self
}
}
// P4
subscript (a: A9) -> Int {
get {
return 5
}
}
// P5
func f5() -> A9 { return self }
// P6
func f6() -> Self { return self }
// P7
func f7() -> Int { return 5 }
// P8
required init(int: Int) { }
// P10
func f10(_ arr: G<A9>) { }
// P11
func f11() -> (_ x: A9) -> Int { return { x in 5 } }
}
// P9
func ==(x: A9, y: A9) -> Bool { return true }
class A12 : P12 {
func f12(_ s: () -> (A12, A12)) {}
}
class A13 : P13 {
func f13(_ s: (A13) -> ()) {} // expected-error{{protocol 'P13' requirement 'f13' cannot be satisfied by a non-final class ('A13') because it uses 'Self' in a non-parameter, non-result type position}}
}
class A14 : P14 {
func f14(_ s: ((A14) -> ()) -> ()) {}
}
class A15 : P15 { // expected-error{{protocol 'P15' requirement 'f18()' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}}
func f15(_ s: (() -> A15) -> ()) {} // expected-error{{protocol 'P15' requirement 'f15' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}}
func f16() -> (A15, A15) {} // expected-error{{protocol 'P15' requirement 'f16()' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}}
func f17() -> Array<A15> {} // expected-error{{protocol 'P15' requirement 'f17()' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}}
}
| apache-2.0 | c8224e7abf346e0cfa35d932184b4ecf | 23.508834 | 208 | 0.60669 | 3.02354 | false | false | false | false |
Cunqi/CQPopupKit | CQPopupKit/PopupDialogue.swift | 1 | 5198 | //
// PopupDialogue.swift
// CQPopupKit
//
// Created by Cunqi.X on 8/13/16.
// Copyright © 2016 Cunqi Xiao. All rights reserved.
//
import UIKit
/// Popup dialogue delegate
public protocol PopupDialogueDelegate: class {
/**
When confirm button tapped, call invokePositiveAction to send confirmed data
- returns: confirmed data
*/
func prepareConfirmedData() -> AnyObject?
}
/// Popup view with navigation bar on the top, contains title, cancel button, confirm button
open class PopupDialogue: Popup {
// MARK: Public
/// Navigation bar view
open let navBar = UIView()
/// Title label
open let dialogueTitle = UILabel(frame: .zero)
/// Cancel button
open let cancel = UIButton(type: .system)
/// Confirm button
open let confirm = UIButton(type: .system)
/// Dialogue appearance
open var dialogueAppearance: PopupDialogueAppearance!
/// PopupDialogueDelegate
fileprivate weak var delegate: PopupDialogueDelegate?
// MARK: Initializer
/**
Creates a popup dialogue
- parameter title: Dialogue title text
- parameter contentView: Custom content view
- parameter positiveAction: Action when confirm button is tapped
- parameter negativeAction: Action when cancel button is tapped
- parameter cancelText: Cancel button text
- parameter confirmText: Confirm button text
- returns: Popup dialogue
*/
public init(title: String, contentView: UIView?, positiveAction: PopupAction?, negativeAction: PopupAction? = nil, cancelText: String = "Cancel", confirmText: String = "Choose") {
dialogueAppearance = CQAppearance.appearance.dialogue
super.init(contentView: contentView, positiveAction: positiveAction, negativeAction: negativeAction)
if let delegate = self.contentView as? PopupDialogueDelegate {
self.delegate = delegate
}
navBar.backgroundColor = dialogueAppearance.navBarBackgroundColor
dialogueTitle.text = title
dialogueTitle.font = dialogueAppearance.titleFont
dialogueTitle.textColor = dialogueAppearance.titleColor
dialogueTitle.textAlignment = .center
dialogueTitle.numberOfLines = 1
cancel.setTitle(cancelText, for: UIControlState())
cancel.addTarget(self, action: #selector(tapToDismiss), for: .touchUpInside)
confirm.setTitle(confirmText, for: UIControlState())
confirm.addTarget(self, action: #selector(tapToConfirm), for: .touchUpInside)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Bind constraints to navigation bar and content view
*/
override func installContentView() {
installNavBar()
installContent()
}
/**
When confirm button is tapped
*/
func tapToConfirm() {
guard let _ = self.delegate else {
self.tapToDismiss()
return
}
let popupInfo = self.delegate!.prepareConfirmedData()
invokePositiveAction(popupInfo)
}
fileprivate func installNavBar() {
// Cancel button
cancel.translatesAutoresizingMaskIntoConstraints = false
navBar.addSubview(cancel)
navBar.bindFrom("V:|[cancel]|", views: ["cancel": cancel])
navBar.bindWith(cancel, attribute: .leading)
navBar.bindWith(cancel, attribute: .width, multiplier: 0.25)
// Confirm button
confirm.translatesAutoresizingMaskIntoConstraints = false
navBar.addSubview(confirm)
navBar.bindFrom("V:|[confirm]|", views: ["confirm": confirm])
navBar.bindWith(confirm, attribute: .trailing)
navBar.bindWith(confirm, attribute: .width, multiplier: 0.25)
// Title Label
dialogueTitle.translatesAutoresizingMaskIntoConstraints = false
navBar.addSubview(dialogueTitle)
navBar.bindFrom("V:|[title]|", views: ["title": dialogueTitle])
navBar.bind(cancel, attribute: .trailing, to: dialogueTitle, toAttribute: .leading)
navBar.bind(confirm, attribute: .leading, to: dialogueTitle, toAttribute: .trailing)
// Bottom Separator
let bottomSeparator = UIView(frame: .zero)
bottomSeparator.backgroundColor = dialogueAppearance.separatorColor
bottomSeparator.translatesAutoresizingMaskIntoConstraints = false
navBar.addSubview(bottomSeparator)
navBar.bindFrom("H:|[separator]|", views: ["separator": bottomSeparator])
navBar.bindWith(bottomSeparator, attribute: .bottom)
navBar.bind(bottomSeparator, attribute: .height, to: nil, toAttribute: .notAnAttribute, constant: 1.0)
navBar.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(navBar)
container.bind(navBar, attribute: .height, to: nil, toAttribute: .notAnAttribute, constant: 44)
container.bindFrom("H:|[nav]|", views: ["nav": navBar])
container.bindWith(navBar, attribute: .top)
}
func installContent() {
if let content = contentView {
content.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(content)
container.bindFrom("H:|[content]|", views: ["content": content])
container.bindWith(content, attribute: .bottom)
container.bind(navBar, attribute: .bottom, to: content, toAttribute: .top)
}
}
}
| mit | 1c05e2800e2e8dd31068b2cea567d270 | 32.96732 | 181 | 0.712719 | 4.566784 | false | false | false | false |
anjana-somathilake/Video-Ops | VideoPlayRecord/PlayVideoViewController.swift | 1 | 2028 | //
// PlayVideoViewController.swift
// VideoPlayRecord
//
// Created by Andy on 2/1/15.
// Copyright (c) 2015 Ray Wenderlich. All rights reserved.
//
import UIKit
import MediaPlayer
import MobileCoreServices
class PlayVideoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playVideo(sender: AnyObject) {
startMediaBrowserFromViewController(self, usingDelegate: self)
}
func startMediaBrowserFromViewController(viewController: UIViewController, usingDelegate delegate: protocol<UINavigationControllerDelegate, UIImagePickerControllerDelegate>) -> Bool {
// 1
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) == false {
return false
}
// 2
let mediaUI = UIImagePickerController()
mediaUI.sourceType = .SavedPhotosAlbum
mediaUI.mediaTypes = [kUTTypeMovie as NSString as String]
mediaUI.allowsEditing = true
mediaUI.delegate = delegate
// 3
presentViewController(mediaUI, animated: true, completion: nil)
return true
}
}
// MARK: - UIImagePickerControllerDelegate
extension PlayVideoViewController: UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// 1
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
// 2
dismissViewControllerAnimated(true) {
// 3
if mediaType == kUTTypeMovie {
let moviePlayer = MPMoviePlayerViewController(contentURL: info[UIImagePickerControllerMediaURL] as! NSURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
}
}
}
}
// MARK: - UINavigationControllerDelegate
extension PlayVideoViewController: UINavigationControllerDelegate {
}
| mit | eb4bb440ada629e16b63e438edede263 | 27.971429 | 185 | 0.749014 | 5.408 | false | false | false | false |
sun409377708/swiftDemo | SinaSwiftPractice/SinaSwiftPractice/Classes/View/Main/Controller/JQTabBarController.swift | 1 | 3616 |
// JQTabBarController.swift
// SinaSwiftPractice
//
// Created by maoge on 16/11/10.
// Copyright © 2016年 maoge. All rights reserved.
//
import UIKit
class JQTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = UIColor.orange
//自定义tabBar
let tabbar = JQMainTabBar()
tabbar.composeClosure = {[weak self] in
print("按钮被dianji")
let composeView = JQComposeView()
composeView.show(targetVC: self)
}
//KVC赋值
self.setValue(tabbar, forKey: "tabBar")
//添加控制器 - 如果在自定义TabBar之前操作, 就没有默认第一个选择
addController()
}
func addController() {
var tempArrM = [UIViewController]()
tempArrM.append(self.addControllers(clsName: "JQHomeController", title: "首页", imageName: "tabbar_home", index: 0))
tempArrM.append(self.addControllers(clsName: "JQMessageController", title: "消息", imageName: "tabbar_message_center", index: 1))
tempArrM.append(self.addControllers(clsName: "JQDiscoverController", title: "发现", imageName: "tabbar_discover", index: 2))
tempArrM.append(self.addControllers(clsName: "JQProfileController", title: "我", imageName: "tabbar_profile", index: 3))
self.viewControllers = tempArrM
}
func addControllers(clsName: String, title: String, imageName: String, index: Int) -> UIViewController {
let cls = NSClassFromString("SinaSwiftPractice." + clsName) as? UIViewController.Type
guard let vc = cls?.init() else {
return UIViewController()
}
vc.navigationItem.title = title
vc.tabBarItem.tag = index
vc.tabBarItem.title = title
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
//设置偏移
vc.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .selected)
let nav = JQMainNavController(rootViewController: vc)
return nav
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
//UITabBarSwappableImageView
var index = 0
for subview in tabBar.subviews {
if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
if index == item.tag {
for target in subview.subviews {
if target.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
//执行动画
target.transform = CGAffineTransform.init(scaleX: 0.4, y: 0.4)
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: [], animations: {
target.transform = CGAffineTransform.identity
}, completion: { (_) in
})
}
}
}
index += 1
}
}
}
}
| mit | d2484702e5f97ee8335d7709594efc21 | 34.17 | 154 | 0.549047 | 5.249254 | false | false | false | false |
danielallsopp/Charts | Source/Charts/Animation/ChartAnimator.swift | 15 | 13249 | //
// ChartAnimator.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc
public protocol ChartAnimatorDelegate
{
/// Called when the Animator has stepped.
func chartAnimatorUpdated(chartAnimator: ChartAnimator)
/// Called when the Animator has stopped.
func chartAnimatorStopped(chartAnimator: ChartAnimator)
}
public class ChartAnimator: NSObject
{
public weak var delegate: ChartAnimatorDelegate?
public var updateBlock: (() -> Void)?
public var stopBlock: (() -> Void)?
/// the phase that is animated and influences the drawn values on the x-axis
public var phaseX: CGFloat = 1.0
/// the phase that is animated and influences the drawn values on the y-axis
public var phaseY: CGFloat = 1.0
private var _startTimeX: NSTimeInterval = 0.0
private var _startTimeY: NSTimeInterval = 0.0
private var _displayLink: NSUIDisplayLink!
private var _durationX: NSTimeInterval = 0.0
private var _durationY: NSTimeInterval = 0.0
private var _endTimeX: NSTimeInterval = 0.0
private var _endTimeY: NSTimeInterval = 0.0
private var _endTime: NSTimeInterval = 0.0
private var _enabledX: Bool = false
private var _enabledY: Bool = false
private var _easingX: ChartEasingFunctionBlock?
private var _easingY: ChartEasingFunctionBlock?
public override init()
{
super.init()
}
deinit
{
stop()
}
public func stop()
{
if (_displayLink != nil)
{
_displayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
_displayLink = nil
_enabledX = false
_enabledY = false
// If we stopped an animation in the middle, we do not want to leave it like this
if phaseX != 1.0 || phaseY != 1.0
{
phaseX = 1.0
phaseY = 1.0
if (delegate != nil)
{
delegate!.chartAnimatorUpdated(self)
}
if (updateBlock != nil)
{
updateBlock!()
}
}
if (delegate != nil)
{
delegate!.chartAnimatorStopped(self)
}
if (stopBlock != nil)
{
stopBlock?()
}
}
}
private func updateAnimationPhases(currentTime: NSTimeInterval)
{
if (_enabledX)
{
let elapsedTime: NSTimeInterval = currentTime - _startTimeX
let duration: NSTimeInterval = _durationX
var elapsed: NSTimeInterval = elapsedTime
if (elapsed > duration)
{
elapsed = duration
}
if (_easingX != nil)
{
phaseX = _easingX!(elapsed: elapsed, duration: duration)
}
else
{
phaseX = CGFloat(elapsed / duration)
}
}
if (_enabledY)
{
let elapsedTime: NSTimeInterval = currentTime - _startTimeY
let duration: NSTimeInterval = _durationY
var elapsed: NSTimeInterval = elapsedTime
if (elapsed > duration)
{
elapsed = duration
}
if (_easingY != nil)
{
phaseY = _easingY!(elapsed: elapsed, duration: duration)
}
else
{
phaseY = CGFloat(elapsed / duration)
}
}
}
@objc private func animationLoop()
{
let currentTime: NSTimeInterval = CACurrentMediaTime()
updateAnimationPhases(currentTime)
if (delegate != nil)
{
delegate!.chartAnimatorUpdated(self)
}
if (updateBlock != nil)
{
updateBlock!()
}
if (currentTime >= _endTime)
{
stop()
}
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
stop()
_startTimeX = CACurrentMediaTime()
_startTimeY = _startTimeX
_durationX = xAxisDuration
_durationY = yAxisDuration
_endTimeX = _startTimeX + xAxisDuration
_endTimeY = _startTimeY + yAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledX = xAxisDuration > 0.0
_enabledY = yAxisDuration > 0.0
_easingX = easingX
_easingY = easingY
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeX)
if (_enabledX || _enabledY)
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingFunctionFromOption(easingOptionX), easingY: easingFunctionFromOption(easingOptionY))
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easing, easingY: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: .EaseInOutSine)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_startTimeX = CACurrentMediaTime()
_durationX = xAxisDuration
_endTimeX = _startTimeX + xAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledX = xAxisDuration > 0.0
_easingX = easing
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeX)
if (_enabledX || _enabledY)
{
if _displayLink === nil
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
}
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
animate(xAxisDuration: xAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
animate(xAxisDuration: xAxisDuration, easingOption: .EaseInOutSine)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_startTimeY = CACurrentMediaTime()
_durationY = yAxisDuration
_endTimeY = _startTimeY + yAxisDuration
_endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY
_enabledY = yAxisDuration > 0.0
_easingY = easing
// Take care of the first frame if rendering is already scheduled...
updateAnimationPhases(_startTimeY)
if (_enabledX || _enabledY)
{
if _displayLink === nil
{
_displayLink = NSUIDisplayLink(target: self, selector: #selector(ChartAnimator.animationLoop))
_displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
}
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
animate(yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption))
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
animate(yAxisDuration: yAxisDuration, easingOption: .EaseInOutSine)
}
}
| apache-2.0 | 5a5dc863131ba9b829fae5fc4021adc0 | 39.148485 | 175 | 0.634689 | 5.443303 | false | false | false | false |
slavapestov/swift | test/decl/class/override.swift | 1 | 16052 | // RUN: %target-parse-verify-swift -parse-as-library
class A {
func ret_sametype() -> Int { return 0 }
func ret_subclass() -> A { return self }
func ret_subclass_rev() -> B { return B() }
func ret_nonclass_optional() -> Int? { return .None }
func ret_nonclass_optional_rev() -> Int { return 0 }
func ret_class_optional() -> B? { return .None }
func ret_class_optional_rev() -> A { return self }
func ret_class_uoptional() -> B! { return B() }
func ret_class_uoptional_rev() -> A { return self }
func ret_class_optional_uoptional() -> B? { return .None }
func ret_class_optional_uoptional_rev() -> A! { return self }
func param_sametype(x : Int) {}
func param_subclass(x : B) {}
func param_subclass_rev(x : A) {}
func param_nonclass_optional(x : Int) {}
func param_nonclass_optional_rev(x : Int?) {}
func param_class_optional(x : B) {}
func param_class_optional_rev(x : B?) {}
func param_class_uoptional(x : B) {}
func param_class_uoptional_rev(x : B!) {}
func param_class_optional_uoptional(x : B!) {}
func param_class_optional_uoptional_rev(x : B?) {}
}
class B : A {
override func ret_sametype() -> Int { return 1 }
override func ret_subclass() -> B { return self }
func ret_subclass_rev() -> A { return self }
override func ret_nonclass_optional() -> Int { return 0 }
func ret_nonclass_optional_rev() -> Int? { return 0 }
override func ret_class_optional() -> B { return self }
func ret_class_optional_rev() -> A? { return self }
override func ret_class_uoptional() -> B { return self }
func ret_class_uoptional_rev() -> A! { return self }
override func ret_class_optional_uoptional() -> B! { return self }
override func ret_class_optional_uoptional_rev() -> A? { return self }
override func param_sametype(x : Int) {}
override func param_subclass(x : A) {}
func param_subclass_rev(x : B) {}
override func param_nonclass_optional(x : Int?) {}
func param_nonclass_optional_rev(x : Int) {}
override func param_class_optional(x : B?) {}
func param_class_optional_rev(x : B) {}
override func param_class_uoptional(x : B!) {}
func param_class_uoptional_rev(x : B) {}
override func param_class_optional_uoptional(x : B?) {}
override func param_class_optional_uoptional_rev(x : B!) {}
}
class C<T> {
func ret_T() -> T {}
}
class D<T> : C<[T]> {
override func ret_T() -> [T] {}
}
class E {
var var_sametype: Int { get { return 0 } set {} }
var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional: Int? { get { return .None } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}}
var var_class_optional: F? { get { return .None } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_uoptional: F? { get { return .None } set {} }
var var_class_optional_uoptional_rev: E! { get { return self } set {} }
var ro_sametype: Int { return 0 }
var ro_subclass: E { return self }
var ro_subclass_rev: F { return F() }
var ro_nonclass_optional: Int? { return 0 }
var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}}
var ro_class_optional: F? { return .None }
var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_uoptional: F! { return F() }
var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_optional_uoptional: F? { return .None }
var ro_class_optional_uoptional_rev: E! { return self }
}
class F : E {
override var var_sametype: Int { get { return 0 } set {} }
override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}}
override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}}
override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}}
override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}}
override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F!' with covariant type 'F'}}
override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}}
override var var_class_optional_uoptional: F! { get { return .None } set {} }
override var var_class_optional_uoptional_rev: E? { get { return self } set {} }
override var ro_sametype: Int { return 0 }
override var ro_subclass: E { return self }
override var ro_subclass_rev: F { return F() }
override var ro_nonclass_optional: Int { return 0 }
override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var ro_class_optional: F { return self }
override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_uoptional: F { return F() }
override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}}
override var ro_class_optional_uoptional: F! { return .None }
override var ro_class_optional_uoptional_rev: E? { return self }
}
class G {
func f1(_: Int, int: Int) { }
func f2(_: Int, int: Int) { }
func f3(_: Int, int: Int) { }
func f4(_: Int, int: Int) { }
func f5(_: Int, int: Int) { }
func f6(_: Int, int: Int) { }
func f7(_: Int, int: Int) { }
func g1(_: Int, string: String) { } // expected-note{{potential overridden method 'g1(_:string:)' here}} {{28-28=string }}
func g1(_: Int, path: String) { } // expected-note{{potential overridden method 'g1(_:path:)' here}} {{28-28=path }}
}
class H : G {
override func f1(_: Int, _: Int) { } // expected-error{{argument names for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }}
override func f2(_: Int, value: Int) { } // expected-error{{argument names for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }}
override func f3(_: Int, value int: Int) { } // expected-error{{argument names for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}}
override func f4(_: Int, _ int: Int) { } // expected-error{{argument names for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}}
override func f5(_: Int, value inValue: Int) { } // expected-error{{argument names for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}}
override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument names for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}}
override func f7(_: Int, int value: Int) { } // okay
override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument names from any potential overrides}}
}
@objc class IUOTestBaseClass {
func none() {}
func oneA(_: AnyObject) {}
func oneB(x x: AnyObject) {}
func oneC(var x x: AnyObject) {} // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}}
func oneD(x: AnyObject) {}
func manyA(_: AnyObject, _: AnyObject) {}
func manyB(a: AnyObject, b: AnyObject) {}
func manyC(var a: AnyObject, // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'a' was never mutated; consider changing to 'let' constant}}
var b: AnyObject) {} // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'b' was never mutated; consider changing to 'let' constant}}
func result() -> AnyObject? { return nil }
func both(x: AnyObject) -> AnyObject? { return x }
init(_: AnyObject) {}
init(one: AnyObject) {}
init(a: AnyObject, b: AnyObject) {}
}
class IUOTestSubclass : IUOTestBaseClass {
override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func oneC(var x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{40-41=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{41-41=)}}
override func oneD(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyB(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyC(var a: AnyObject!, var b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{parameter 'b' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}}
// expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}}
override func both(x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{use '?' to make the result optional}} {{49-50=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}}
override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}}
override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
}
class IUOTestSubclass2 : IUOTestBaseClass {
override func oneA(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(var x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{40-41=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{41-41=)}}
override func oneD(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(x x: ImplicitlyUnwrappedOptional<AnyObject>) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'ImplicitlyUnwrappedOptional<AnyObject>'}}
// expected-note@-1 {{add parentheses to silence this warning}} {{27-27=(}} {{65-65=)}}
}
class IUOTestSubclassOkay : IUOTestBaseClass {
override func oneA(_: AnyObject?) {}
override func oneB(x x: (AnyObject!)) {}
override func oneC(x x: AnyObject) {}
override func result() -> (AnyObject!) { return nil }
}
| apache-2.0 | 441fb76fda186ab0006e75d01be9d470 | 70.026549 | 504 | 0.682906 | 3.855873 | false | false | false | false |
IGRSoft/IGRPhotoTweaks | Example/ExampleCropViewController.swift | 1 | 6356 | //
// ExampleCropViewController.swift
// IGRPhotoTweaks
//
// Created by Vitalii Parovishnyk on 2/7/17.
// Copyright © 2017 IGR Software. All rights reserved.
//
import IGRPhotoTweaks
import UIKit
import HorizontalDial
class ExampleCropViewController: IGRPhotoTweakViewController {
/**
Slider to change angle.
*/
@IBOutlet weak fileprivate var angleSlider: UISlider?
@IBOutlet weak fileprivate var angleLabel: UILabel?
@IBOutlet weak fileprivate var horizontalDial: HorizontalDial? {
didSet {
self.horizontalDial?.migneticOption = .none
}
}
// MARK: - Life Cicle
override func viewDidLoad() {
super.viewDidLoad()
self.setupSlider()
//FIXME: Zoom setup
//self.photoView.minimumZoomScale = 1.0;
//self.photoView.maximumZoomScale = 10.0;
}
//FIXME: Themes Preview
// override open func setupThemes() {
//
// IGRCropLine.appearance().backgroundColor = UIColor.green
// IGRCropGridLine.appearance().backgroundColor = UIColor.yellow
// IGRCropCornerView.appearance().backgroundColor = UIColor.purple
// IGRCropCornerLine.appearance().backgroundColor = UIColor.orange
// IGRCropMaskView.appearance().backgroundColor = UIColor.blue
// IGRPhotoContentView.appearance().backgroundColor = UIColor.gray
// IGRPhotoTweakView.appearance().backgroundColor = UIColor.brown
// }
fileprivate func setupSlider() {
self.angleSlider?.minimumValue = -Float(IGRRadianAngle.toRadians(90))
self.angleSlider?.maximumValue = Float(IGRRadianAngle.toRadians(90))
self.angleSlider?.value = 0.0
setupAngleLabelValue(radians: CGFloat((self.angleSlider?.value)!))
}
fileprivate func setupAngleLabelValue(radians: CGFloat) {
let intDegrees: Int = Int(IGRRadianAngle.toDegrees(radians))
self.angleLabel?.text = "\(intDegrees)°"
}
// MARK: - Rotation
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.view.layoutIfNeeded()
}) { (context) in
//
}
}
// MARK: - Actions
@IBAction func onChandeAngleSliderValue(_ sender: UISlider) {
let radians: CGFloat = CGFloat(sender.value)
setupAngleLabelValue(radians: radians)
self.changeAngle(radians: radians)
}
@IBAction func onEndTouchAngleControl(_ sender: UIControl) {
self.stopChangeAngle()
}
@IBAction func onTouchResetButton(_ sender: UIButton) {
self.angleSlider?.value = 0.0
self.horizontalDial?.value = 0.0
setupAngleLabelValue(radians: 0.0)
self.resetView()
}
@IBAction func onTouchCancelButton(_ sender: UIButton) {
self.dismissAction()
}
@IBAction func onTouchCropButton(_ sender: UIButton) {
cropAction()
}
@IBAction func onTouchAspectButton(_ sender: UIButton) {
let actionSheet = UIAlertController(title: nil,
message: nil,
preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Original", style: .default) { (action) in
self.resetAspectRect()
})
actionSheet.addAction(UIAlertAction(title: "Squere", style: .default) { (action) in
self.setCropAspectRect(aspect: "1:1")
})
actionSheet.addAction(UIAlertAction(title: "2:3", style: .default) { (action) in
self.setCropAspectRect(aspect: "2:3")
})
actionSheet.addAction(UIAlertAction(title: "3:5", style: .default) { (action) in
self.setCropAspectRect(aspect: "3:5")
})
actionSheet.addAction(UIAlertAction(title: "3:4", style: .default) { (action) in
self.setCropAspectRect(aspect: "3:4")
})
actionSheet.addAction(UIAlertAction(title: "5:7", style: .default) { (action) in
self.setCropAspectRect(aspect: "5:7")
})
actionSheet.addAction(UIAlertAction(title: "9:16", style: .default) { (action) in
self.setCropAspectRect(aspect: "9:16")
})
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(actionSheet, animated: true, completion: nil)
}
@IBAction func onTouchLockAspectRatioButton(_ sender: UISwitch) {
self.lockAspectRatio(sender.isOn)
}
//FIXME: Themes Preview
// override open func customBorderColor() -> UIColor {
// return UIColor.red
// }
//
// override open func customBorderWidth() -> CGFloat {
// return 2.0
// }
//
// override open func customCornerBorderWidth() -> CGFloat {
// return 4.0
// }
//
// override open func customCropLinesCount() -> Int {
// return 3
// }
//
// override open func customGridLinesCount() -> Int {
// return 4
// }
//
// override open func customCornerBorderLength() -> CGFloat {
// return 30.0
// }
//
// override open func customIsHighlightMask() -> Bool {
// return true
// }
//
// override open func customHighlightMaskAlphaValue() -> CGFloat {
// return 0.3
// }
override open func customCanvasInsets() -> UIEdgeInsets {
return UIEdgeInsets(top: UIDevice.current.orientation.isLandscape ? 40.0 : 100.0,
left: 0,
bottom: 0,
right: 0)
}
}
extension ExampleCropViewController: HorizontalDialDelegate {
func horizontalDialDidValueChanged(_ horizontalDial: HorizontalDial) {
let degrees = horizontalDial.value
let radians = IGRRadianAngle.toRadians(CGFloat(degrees))
self.setupAngleLabelValue(radians: radians)
self.changeAngle(radians: radians)
}
func horizontalDialDidEndScroll(_ horizontalDial: HorizontalDial) {
self.stopChangeAngle()
}
}
| mit | 64e772e33c40c20b728b2c0d33cc5d1e | 30.77 | 128 | 0.610639 | 4.558106 | false | false | false | false |
PiXeL16/BudgetShare | BudgetShareTests/Modules/BudgetCreate/BudgetCreateMoneyLeft/View/Mock/MockBudgetCreateMoneyLeftView.swift | 1 | 659 | //
// MockBudgetCreateAmountView.swift
// BudgetShareTests
//
// Created by Chris Jimenez on 7/23/17.
// Copyright © 2017 Chris Jimenez. All rights reserved.
//
@testable import BudgetShare
import UIKit
class MockBudgetCreateMoneyLeftView: BudgetCreateMoneyLeftViewing {
var controller: UIViewController?
var presenter: BudgetCreateMoneyLeftPresenter!
var budgetMoneyLeft: String = ""
var continueWasCalled = false
var continueSuccesfulWasCalled = false
func didTapContinue() {
continueWasCalled = true
}
func continueSuccesful() {
continueSuccesfulWasCalled = true
}
}
| mit | 0c82a9417e777d4e65819fe289f7184c | 20.933333 | 67 | 0.697568 | 4.7 | false | true | false | false |
airbnb/lottie-ios | Sources/Private/Utility/Interpolatable/KeyframeGroup+Extensions.swift | 3 | 2057 | //
// KeyframeGroup+Extensions.swift
// Lottie
//
// Created by JT Bergman on 6/20/22.
//
import CoreGraphics
import Foundation
extension KeyframeGroup where T == LottieVector1D {
/// Manually interpolates the keyframes so that they are defined linearly
///
/// This method uses `UnitBezier` to perform the interpolation. It will create one keyframe
/// for each frame of the animation. For instance, if it is given a keyframe at time 0 and a keyframe
/// at time 10, it will create 10 interpolated keyframes. It is currently not optimized.
func manuallyInterpolateKeyframes() -> ContiguousArray<Keyframe<T>> {
guard keyframes.count > 1 else {
return keyframes
}
var output = ContiguousArray<Keyframe<LottieVector1D>>()
for idx in 1 ..< keyframes.count {
let prev = keyframes[idx - 1]
let curr = keyframes[idx]
// The timing function is responsible for computing the expected progress
let outTangent = prev.outTangent?.pointValue ?? .zero
let inTangent = curr.inTangent?.pointValue ?? .init(x: 1, y: 1)
let timingFunction = UnitBezier(controlPoint1: outTangent, controlPoint2: inTangent)
// These values are used to compute new values in the adjusted keyframes
let difference = curr.value.value - prev.value.value
let startValue = prev.value.value
let startTime = prev.time
let duration = max(Int(curr.time - prev.time), 0)
// Create one interpolated keyframe for each time in the duration
for t in 0 ... duration {
let progress = timingFunction.value(
for: CGFloat(t) / CGFloat(duration),
epsilon: 0.005)
let value = startValue + Double(progress) * difference
output.append(
Keyframe<LottieVector1D>(
value: LottieVector1D(value),
time: startTime + CGFloat(t),
isHold: false,
inTangent: nil,
outTangent: nil,
spatialInTangent: nil,
spatialOutTangent: nil))
}
}
return output
}
}
| apache-2.0 | 79dfaeaecd519feda6b8699894fbf499 | 33.864407 | 103 | 0.65824 | 4.376596 | false | false | false | false |
AwesomeDennis/DXPhotoPicker | DXPhotoPicker/Classes/Views/DXPromptView.swift | 1 | 1110 | //
// DXPromptView.swift
// DXPhotosPickerDemo
//
// Created by DingXiao on 15/10/13.
// Copyright © 2015年 Dennis. All rights reserved.
//
import UIKit
public class DXPromptView: UIWindow {
convenience init(imageName: String?, message: String?) {
self.init()
self.isHidden = false
self.alpha = 1.0
self.windowLevel = UIWindowLevelStatusBar + 1.0
self.backgroundColor = UIColor(red: 0x17/255.0, green: 0x17/255.0, blue: 0x17/255.0, alpha: 0.9)
self.layer.masksToBounds = true
let image = UIImage(named: imageName!)
let imageView = UIImageView(image: image)
self.addSubview(imageView)
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14.0)
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.textAlignment = .center
label.numberOfLines = 0
label.text = message
label.sizeToFit()
self.addSubview(label)
}
public class func showWithImageName(imageName: String, message: String) {
}
}
| mit | 5693b11bdd7e57fca00a207e3f3e0802 | 27.384615 | 104 | 0.628726 | 4.054945 | false | false | false | false |
esttorhe/RxSwift | RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift | 1 | 4939 | //
// UICollectionView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import UIKit
extension UICollectionView {
// factories
override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxCollectionViewDelegateProxy(parentObject: self)
}
// proxies
public var rx_dataSource: DelegateProxy {
get {
return proxyForObject(self) as RxCollectionViewDataSourceProxy
}
}
// For more detailed explanations, take a look at `DelegateProxyType.swift`
public func rx_setDataSource(dataSource: UICollectionViewDataSource)
-> Disposable {
let proxy: RxCollectionViewDataSourceProxy = proxyForObject(self)
return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self)
}
// data source
// Registers reactive data source with collection view.
// Difference between reactive data source and UICollectionViewDataSource is that reactive
// has additional method:
//
// ```
// func collectionView(collectionView: UICollectionView, observedEvent: Event<Element>) -> Void
// ```
//
// If you want to register non reactive data source, please use `rx_setDataSource` method
public func rx_subscribeWithReactiveDataSource<DataSource: protocol<RxCollectionViewDataSourceType, UICollectionViewDataSource>>
(dataSource: DataSource)
-> Observable<DataSource.Element> -> Disposable {
return setProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { (_: RxCollectionViewDataSourceProxy, event) -> Void in
dataSource.collectionView(self, observedEvent: event)
}
}
// `reloadData` - items subscription methods (it's assumed that there is one section, and it is typed `Void`)
public func rx_subscribeItemsTo<Item>
(cellFactory: (UICollectionView, Int, Item) -> UICollectionViewCell)
-> Observable<[Item]> -> Disposable {
return { source in
let dataSource = RxCollectionViewReactiveArrayDataSource<Item>(cellFactory: cellFactory)
return self.rx_subscribeWithReactiveDataSource(dataSource)(source)
}
}
public func rx_subscribeItemsToWithCellIdentifier<Item, Cell: UICollectionViewCell>
(cellIdentifier: String, configureCell: (Int, Item, Cell) -> Void)
-> Observable<[Item]> -> Disposable {
return { source in
let dataSource = RxCollectionViewReactiveArrayDataSource<Item> { (cv, i, item) in
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cell = cv.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.rx_subscribeWithReactiveDataSource(dataSource)(source)
}
}
// events
public var rx_itemSelected: Observable<NSIndexPath> {
return rx_delegate.observe("collectionView:didSelectItemAtIndexPath:")
>- map { a in
return a[1] as! NSIndexPath
}
}
// typed events
public func rx_modelSelected<T>() -> Observable<T> {
return rx_itemSelected >- map { indexPath in
let dataSource: RxCollectionViewReactiveArrayDataSource<T> = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_subscribeItemsTo` methods was used.")
return dataSource.modelAtIndex(indexPath.item)!
}
}
}
// deprecated
extension UICollectionView {
@available(*, deprecated=1.7, message="Replaced by `rx_subscribeItemsToWithCellIdentifier`")
public func rx_subscribeItemsWithIdentifierTo<E, Cell where E : AnyObject, Cell : UICollectionViewCell>
(cellIdentifier: String, configureCell: (UICollectionView, NSIndexPath, E, Cell) -> Void)
(source: Observable<[E]>)
-> Disposable {
let l = rx_subscribeItemsToWithCellIdentifier(cellIdentifier) { (i: Int, e: E, cell: Cell) in
return configureCell(self, NSIndexPath(forItem: i, inSection: 0), e, cell)
}
return l(source)
}
@available(*, deprecated=1.7, message="Replaced by `rx_itemSelected`")
public func rx_itemTap() -> Observable<(UICollectionView, Int)> {
return rx_itemSelected
>- map { i in
return (self, i.item)
}
}
@available(*, deprecated=1.7, message="Replaced by `rx_modelSelected`")
public func rx_elementTap<E>() -> Observable<E> {
return rx_modelSelected()
}
}
| mit | 1f50e9697ab81103ba440d0bced1f2f8 | 37.889764 | 223 | 0.647904 | 5.231992 | false | false | false | false |
j4soft/lab-ios-swift-scrollview | ScrollView/ViewController.swift | 1 | 3168 | //
// ViewController.swift
// ScrollView
//
// Created by Jack on 16/09/15.
// Copyright © 2015 J4SOFT. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
registerForKeyboardNotifications()
setupTextFieldsShouldReturn()
hideKeyboardOnTouch()
}
// Setup text fields delegate to view controller.
func setupTextFieldsShouldReturn() {
for subview in contentView.subviews {
if subview is UITextField {
let textField = subview as! UITextField
textField.delegate = self
}
}
}
// Hides keyboard when pressing return key.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Setup tap gesture
func hideKeyboardOnTouch() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
// Hide keyboard (called when tapping outside text fields).
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
// Define notifications when keyboard will be shown or hidden.
func registerForKeyboardNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self,
selector: "keyboardWillBeShown:",
name: UIKeyboardWillShowNotification,
object: nil)
notificationCenter.addObserver(self,
selector: "keyboardWillBeHidden:",
name: UIKeyboardWillHideNotification,
object: nil)
}
// Scrolls scroll view by the height of the keyboard.
func keyboardWillBeShown(sender: NSNotification) {
let info: NSDictionary = sender.userInfo!
let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue
let keyboardSize: CGSize = value.CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
// Reset scroll view scrolling when keyboard hides.
func keyboardWillBeHidden(sender: NSNotification) {
let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
@IBAction func register(sender: AnyObject) {
for subview in contentView.subviews {
if subview is UITextField {
let textField = subview as! UITextField
NSLog("value: \(textField.text)")
}
}
}
}
| apache-2.0 | 32493b05e0b346905754cf2dfa40a0af | 32.691489 | 105 | 0.658352 | 5.76867 | false | false | false | false |
edx/edx-app-ios | Source/RegistrationFieldSelectViewController.swift | 1 | 8316 | //
// RegistrationFieldSelectViewController.swift
// edX
//
// Created by Muhammad Umer on 15/06/2020.
// Copyright © 2020 edX. All rights reserved.
//
import UIKit
public struct RegistrationSelectOptionViewModel {
public var name: String
public var value: String
init(name: String, value: String) {
self.name = name
self.value = value
}
}
class RegistrationSelectOptionViewCell : UITableViewCell {
static let identifier = String(describing: RegistrationSelectOptionViewCell.self)
// MARK: Initialize
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = .clear
contentView.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Configure Selection
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? .checkmark : .none
}
}
typealias RegistrationSelectOptionViewCompletion = (RegistrationSelectOptionViewModel?) -> Swift.Void
class RegistrationSelectOptionViewController: UIViewController {
// MARK: Properties
private var selectionHandler: RegistrationSelectOptionViewCompletion?
private var options = [RegistrationSelectOptionViewModel]()
private var filteredOptions: [RegistrationSelectOptionViewModel] = []
private var selectedItem: RegistrationSelectOptionViewModel?
private var searchViewHeight: CGFloat = 60
private var tableViewRowHeight: CGFloat = 44
private lazy var searchView: UIView = UIView()
private lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.backgroundColor = OEXStyles.shared().neutralXXLight()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.textField?.textColor = OEXStyles.shared().neutralBlackT()
searchController.searchBar.textField?.clearButtonMode = .whileEditing
return searchController
}()
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = tableViewRowHeight
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorColor = OEXStyles.shared().neutralLight()
tableView.backgroundColor = .clear
tableView.tableFooterView = UIView()
return tableView
}()
// MARK: Initialize
required init(options: [RegistrationSelectOptionViewModel], selectedItem: RegistrationSelectOptionViewModel?, selectionHandler: @escaping RegistrationSelectOptionViewCompletion) {
super.init(nibName: nil, bundle: nil)
self.options = options
self.selectedItem = selectedItem
self.selectionHandler = selectionHandler
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// http://stackoverflow.com/questions/32675001/uisearchcontroller-warning-attempting-to-load-the-view-of-a-view-controller/
searchController.loadViewIfNeeded()
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
tableView.register(RegistrationSelectOptionViewCell.self, forCellReuseIdentifier: RegistrationSelectOptionViewCell.identifier)
tableView.reloadData()
scrollToSelectedItem()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
preferredContentSize.height = (tableView.estimatedRowHeight * 4) + searchViewHeight
}
private func setupViews() {
searchView.addSubview(searchController.searchBar)
view.addSubview(searchView)
view.addSubview(tableView)
searchView.snp.makeConstraints { make in
make.top.equalTo(view)
make.leading.equalTo(view)
make.trailing.equalTo(view)
make.height.equalTo(searchViewHeight)
}
tableView.snp.makeConstraints { make in
make.top.equalTo(searchView.snp.bottom)
make.leading.equalTo(view)
make.trailing.equalTo(view)
make.bottom.equalTo(view)
}
searchController.isActive = true
searchController.searchBar.becomeFirstResponder()
definesPresentationContext = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
searchController.searchBar.snp.makeConstraints { make in
make.height.equalTo(searchViewHeight)
if isiPad() {
make.width.equalTo(view)
} else {
make.width.equalTo(searchView)
}
}
}
private func itemForCell(at indexPath: IndexPath) -> RegistrationSelectOptionViewModel {
if searchController.isActive {
return filteredOptions[indexPath.row]
} else {
return options[indexPath.row]
}
}
private func indexPathOfSelectedItem() -> IndexPath? {
guard let selectedItem = selectedItem else { return nil }
if searchController.isActive {
for row in 0 ..< filteredOptions.count {
if filteredOptions[row].name == selectedItem.name {
return IndexPath(row: row, section: 0)
}
}
} else {
for row in 0 ..< options.count {
if options[row].name == selectedItem.name {
return IndexPath(row: row, section: 0)
}
}
}
return nil
}
private func scrollToSelectedItem() {
guard let selectedIndexPath = indexPathOfSelectedItem() else { return }
tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .top)
}
}
// MARK: - UISearchResultsUpdating
extension RegistrationSelectOptionViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text, searchController.isActive {
filteredOptions = []
if searchText.count > 0 {
filteredOptions.append(contentsOf: options.filter { $0.name.hasPrefix(searchText) })
} else {
filteredOptions = options
}
}
tableView.reloadData()
}
}
// MARK: - TableViewDelegate
extension RegistrationSelectOptionViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = itemForCell(at: indexPath)
selectedItem = item
selectionHandler?(selectedItem)
}
}
// MARK: - TableViewDataSource
extension RegistrationSelectOptionViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive {
return filteredOptions.count
}
return options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = itemForCell(at: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: RegistrationSelectOptionViewCell.identifier) as! RegistrationSelectOptionViewCell
cell.textLabel?.text = item.name
if let selected = selectedItem, selected.name == item.name {
cell.setSelected(true, animated: true)
}
return cell
}
}
fileprivate extension UISearchBar {
var textField: UITextField? {
return value(forKey: "searchField") as? UITextField
}
}
| apache-2.0 | 7644a81312d673ee9f76ffa09515f929 | 34.534188 | 183 | 0.666386 | 5.554442 | false | false | false | false |
ajaybeniwal/IOS11AppStoreClone | IOS11AppStoreClone/IOS11AppStoreClone/UpdateViewController.swift | 1 | 6397 | //
// UpdateViewController.swift
// IOS11AppStoreClone
//
// Created by Ajay Singh on 26/10/17.
// Copyright © 2017 Ajay Singh. All rights reserved.
//
import UIKit
class UpdateViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
let tableView:UITableView = {
let tableView = UITableView(frame: CGRect.zero)
tableView.estimatedRowHeight = 80
tableView.tableFooterView = UIView()
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Updates"
tableView.register(UpdateTableViewCell.self, forCellReuseIdentifier: "updateCell")
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "updateCell", for: indexPath) as! UpdateTableViewCell
return cell;
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
}
class UpdateTableViewCell :UITableViewCell{
var numberTypeLabel:UILabel = {
var productTypeLabel = UILabel()
productTypeLabel.font = UIFont.systemFont(ofSize: 16)
productTypeLabel.textColor = UIColor.black
productTypeLabel.text = "Uber"
productTypeLabel.numberOfLines = 0;
return productTypeLabel
}()
var getAppButton:UIButton = {
var submitButton = UIButton()
submitButton.setTitle("UPDATE", for: UIControlState.normal)
submitButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.bold)
submitButton.setTitleColor(UIColor(red: 0/255, green: 149/255, blue: 255/255, alpha: 1), for: UIControlState.normal)
submitButton.layer.cornerRadius = 12
submitButton.layer.masksToBounds = true
submitButton.backgroundColor = UIColor(red: 224/255, green: 230/255, blue: 236/255, alpha: 1)
return submitButton
}()
var metaDataLabel:UILabel = {
var productTypeLabel = UILabel()
productTypeLabel.font = UIFont.systemFont(ofSize: 14)
productTypeLabel.textColor = UIColor.lightGray
productTypeLabel.text = "Version 61.03.45.67"
return productTypeLabel
}()
var appImageView:UIImageView = {
var imageView = UIImageView()
imageView.image = UIImage(named: "Uber")
imageView.layer.cornerRadius = 6
imageView.layer.masksToBounds = true
imageView.layer.borderColor = UIColor(red: 214/255, green: 214/255, blue: 214/255, alpha: 1).cgColor
return imageView
}()
var appDescriptionLabel:UILabel = {
var appDescriptionLabel = UILabel()
appDescriptionLabel.font = UIFont.systemFont(ofSize: 16)
appDescriptionLabel.textColor = UIColor.black
appDescriptionLabel.text = "We are listening to feedback and working hard to improve app"
appDescriptionLabel.numberOfLines = 0;
return appDescriptionLabel
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpSubViews()
}
func setUpSubViews(){
// self.contentView.addSubview(numberTypeLabel)
self.contentView.addSubview(appImageView)
appImageView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(numberTypeLabel)
numberTypeLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(metaDataLabel)
metaDataLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(getAppButton)
getAppButton.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(appDescriptionLabel)
appDescriptionLabel.translatesAutoresizingMaskIntoConstraints = false
/*Setting autolayout constraint using layout anchors instead of snapkit so that it is easy for beginners to learn */
appImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
appImageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
appImageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
appImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
numberTypeLabel.leadingAnchor.constraint(equalTo: appImageView.trailingAnchor, constant: 10).isActive = true
numberTypeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
getAppButton.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -15).isActive = true
getAppButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
getAppButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
metaDataLabel.leadingAnchor.constraint(equalTo: appImageView.trailingAnchor, constant: 10).isActive = true
metaDataLabel.topAnchor.constraint(equalTo: numberTypeLabel.bottomAnchor, constant: 5).isActive = true
appDescriptionLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
appDescriptionLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
appDescriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
appDescriptionLabel.topAnchor.constraint(equalTo: appImageView.bottomAnchor, constant: 5).isActive = true
}
}
| mit | 54c203b33be83cf6eeee89700d6aa4bf | 40.264516 | 124 | 0.699343 | 5.347826 | false | false | false | false |
NobodyNada/chatbot | Sources/Frontend/Commands/Filters/TrollCommandEnable.swift | 3 | 2147 | //
// TrollCommandEnable.swift
// FireAlarm
//
// Created by Jonathan Keller on 3/23/18.
//
import Foundation
import SwiftChatSE
import SwiftStack
class TrollCommandEnable: Command {
override class func usage() -> [String] {
return ["troll ..."]
}
override func run() throws {
if arguments.isEmpty {
reporter.trollSites = .all
reply("Watching a troll on all sites.")
return
}
var allSites = [SwiftStack.Site]()
allSites.reserveCapacity(200)
var hasMore = false
var page = 1
let pageSize = 100
repeat {
let response = try apiClient.fetchSites(parameters: ["per_page": String(pageSize), "page": String(page)])
guard let sites = response.items else {
reply("Failed to fetch sites!")
return
}
allSites.append(contentsOf: sites)
hasMore = response.has_more ?? false
page += 1
} while hasMore
var sites = [Site]()
sites.reserveCapacity(arguments.count)
for siteName in arguments {
guard let index = allSites.firstIndex(where: { $0.api_site_parameter == siteName || $0.site_url?.host == siteName }) else {
reply("Unknown site \(siteName).")
return
}
let apiSite = allSites[index]
guard let apiSiteParameter = apiSite.api_site_parameter, let domain = apiSite.site_url?.host else {
reply("Failed to retrieve site information!")
return
}
sites.append(Site(id: -1, apiSiteParameter: apiSiteParameter, domain: domain, initialProbability: 0))
}
sites.forEach { reporter.trollSites.add($0) }
switch reporter.trollSites {
case .all: reply("Watching a troll on all sites.")
case .sites(let sites): reply("Watching a troll on " + formatArray(sites.map { $0.domain }, conjunction: "and") + ".")
}
}
}
| mit | ba278d9ede32847f524d6714a213917e | 30.573529 | 135 | 0.539357 | 4.637149 | false | false | false | false |
kyotaw/ZaifSwift | ZaifSwiftTests/ZaifSwiftTests.swift | 1 | 78934 | //
// ZaifSwiftTests.swift
// ZaifSwiftTests
//
// Created by 渡部郷太 on 6/30/16.
// Copyright © 2016 watanabe kyota. All rights reserved.
//
import XCTest
import ZaifSwift
private let api = PrivateApi(apiKey: key_full, secretKey: secret_full)
class ZaifSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testGetInfo() {
// successfully complete
let successExpectation = self.expectation(description: "get_info success")
api.getInfo() { (err, res) in
XCTAssertNil(err, "get_info success. err is nil")
XCTAssertNotNil(res, "get_info success. res is not nil")
successExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// keys has no permission for get_info
let noPermissionExpectation = self.expectation(description: "no permission error")
let api2 = ZaifSwift.PrivateApi(apiKey: key_no_info, secretKey: secret_no_info)
api2.getInfo() { (err, res) in
XCTAssertNotNil(err, "no permission. err is not nil")
switch err!.errorType {
case ZaifSwift.ZSErrorType.INFO_API_NO_PERMISSION:
XCTAssertTrue(true, "no permission exception")
default:
XCTFail()
}
noPermissionExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
//invalid key
let invalidKeyExpectaion = self.expectation(description: "invalid key error")
let key_invalid = "INVALID"
let api6 = PrivateApi(apiKey: key_invalid, secretKey: secret_full)
api6.getInfo() { (err, res) in
XCTAssertNotNil(err, "invalid key. err is not nil")
XCTAssertTrue(true)
/*
switch err!.errorType {
case ZaifSwift.ZSErrorType.INVALID_API_KEY:
XCTAssertTrue(true)
default:
XCTFail()
}
*/
invalidKeyExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
//invalid secret
let invalidSecretExpectaion = self.expectation(description: "invalid secret error")
let secret_invalid = "INVALID"
let api5 = ZaifSwift.PrivateApi(apiKey: key_no_trade, secretKey: secret_invalid)
api5.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZaifSwift.ZSErrorType.INVALID_SIGNATURE:
XCTAssertTrue(true)
default:
XCTFail()
}
invalidSecretExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce exceeds limit
let nonceExceedExpectaion = self.expectation(description: "nonce exceed limit error")
let nonce = SerialNonce(initialValue: IntMax.max)
let _ = try! nonce.getNonce()
let api7 = PrivateApi(apiKey: key_full, secretKey: secret_full, nonce: nonce)
api7.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceExceedExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce out of range
let nonceOutOfRangeExpectaion = self.expectation(description: "nonce out of range error")
let nonce2 = SerialNonce(initialValue: IntMax.max)
let api8 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce2)
api8.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceOutOfRangeExpectaion.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// nonce not incremented
let nonceNotIncremented = self.expectation(description: "nonce not incremented error")
let nonce3 = SerialNonce(initialValue: 1)
let api9 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce3)
api9.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.NONCE_NOT_INCREMENTED:
XCTAssertTrue(true)
default:
XCTFail()
}
nonceNotIncremented.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// connection error
/*
let connectionErrorExpectation = self.expectationWithDescription("connection error")
let api5 = PrivateApi(apiKey: key_full, secretKey: secret_full)
api5.getInfo() { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.CONNECTION_ERROR:
XCTAssertTrue(true)
default:
XCTAssertTrue(true)
}
connectionErrorExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(10.0, handler: nil)
*/
}
func testTradeBtcJpy() {
// keys has no permission for trade
let noPermissionExpectation = self.expectation(description: "no permission error")
let api_no_trade = PrivateApi(apiKey: key_no_trade, secretKey: secret_no_trade)
let dummyOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001)
api_no_trade.trade(dummyOrder) { (err, res) in
XCTAssertNotNil(err, "no permission. err is not nil")
switch err!.errorType {
case ZSErrorType.TRADE_API_NO_PERMISSION:
XCTAssertTrue(true, "no permission exception")
default:
XCTFail()
}
noPermissionExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy btc_jpy
let btcJpyExpectation = self.expectation(description: "buy btc_jpy order success")
let btcOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001)
api.trade(btcOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price (border)
let btcJpyExpectation20 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder20 = Trade.Buy.Btc.In.Jpy.createOrder(5, amount: 0.0001)
api.trade(btcOrder20) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation20.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy btc_jpy with limit
let btcJpyExpectation4 = self.expectation(description: "buy btc_jpy order with limit success")
let btcOrder4 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60005)
api.trade(btcOrder4) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation4.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price
let btcJpyExpectation2 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder2 = Trade.Buy.Btc.In.Jpy.createOrder(60001, amount: 0.0001)
api.trade(btcOrder2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (border)
let btcJpyExpectation22 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder22 = Trade.Buy.Btc.In.Jpy.createOrder(4, amount: 0.0001)
api.trade(btcOrder22) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation22.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (minus)
let btcJpyExpectation11 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder11 = Trade.Buy.Btc.In.Jpy.createOrder(-60000, amount: 0.0001)
api.trade(btcOrder11) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation11.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid price (zero)
let btcJpyExpectation12 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder12 = Trade.Buy.Btc.In.Jpy.createOrder(0, amount: 0.0001)
api.trade(btcOrder12) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation12.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit
let btcJpyExpectation3 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder3 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60002)
api.trade(btcOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit (minus)
let btcJpyExpectation13 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder13 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: -60005)
api.trade(btcOrder13) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation13.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit (zero)
let btcJpyExpectation14 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder14 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 0)
api.trade(btcOrder14) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation14.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount
let btcJpyExpectation5 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder5 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00011)
api.trade(btcOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount (minus)
let btcJpyExpectation15 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder15 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: -0.0001)
api.trade(btcOrder15) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation15.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount (zero)
let btcJpyExpectation16 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder16 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0)
api.trade(btcOrder16) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation16.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell btc_jpy
let btcJpyExpectation6 = self.expectation(description: "sell btc_jpy order success")
let btcOrder6 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001)
api.trade(btcOrder6) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation6.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell btc_jpy with limit
let btcJpyExpectation7 = self.expectation(description: "sell btc_jpy order with limit success")
let btcOrder7 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001, limit: 79995)
api.trade(btcOrder7) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
btcJpyExpectation7.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// btc_jpy invalid price
let btcJpyExpectation8 = self.expectation(description: "btc_jpy order invalid price error")
let btcOrder8 = Trade.Sell.Btc.For.Jpy.createOrder(79999, amount: 0.0001)
api.trade(btcOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 5")
default:
XCTFail()
}
btcJpyExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid limit
let btcJpyExpectation9 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder9 = Trade.Buy.Btc.In.Jpy.createOrder(80000, amount: 0.0001, limit: 79998)
api.trade(btcOrder9) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 5")
default:
XCTFail()
}
btcJpyExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// btc_jpy invalid amount
let btcJpyExpectation10 = self.expectation(description: "btc_jpy order invalid limit error")
let btcOrder10 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00009)
api.trade(btcOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 0.0001")
default:
XCTFail()
}
btcJpyExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTradeMonaJpy() {
// buy mona_jpy
let monaJpyExpectation = self.expectation(description: "buy mona_jpy order success")
let monaOrder = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1)
api.trade(monaOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price (min)
let monaJpyExpectation60 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder60 = Trade.Buy.Mona.In.Jpy.createOrder(0.1, amount: 1)
api.trade(monaOrder60) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation60.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// buy mona_jpy with limit
let monaJpyExpectation2 = self.expectation(description: "buy mona_jpy order with limit success")
let monaOrder2 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 4.1)
api.trade(monaOrder2) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation2.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price
let monaJpyExpectation3 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder3 = Trade.Buy.Mona.In.Jpy.createOrder(4.01, amount: 1)
api.trade(monaOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (border)
let monaJpyExpectation34 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder34 = Trade.Buy.Mona.In.Jpy.createOrder(0.09, amount: 1)
api.trade(monaOrder34) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation34.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (minus)
let monaJpyExpectation33 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder33 = Trade.Buy.Mona.In.Jpy.createOrder(-4.0, amount: 1)
api.trade(monaOrder33) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation33.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid price (zero)
let monaJpyExpectation7 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder7 = Trade.Buy.Mona.In.Jpy.createOrder(0, amount: 1)
api.trade(monaOrder7) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit
let monaJpyExpectation4 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder4 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 3.99)
api.trade(monaOrder4) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit (minus)
let monaJpyExpectation8 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder8 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: -4.1)
api.trade(monaOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit (zero)
let monaJpyExpectation9 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder9 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 0)
api.trade(monaOrder9) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount (minus)
let monaJpyExpectation10 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder10 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: -1)
api.trade(monaOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount (zero)
let monaJpyExpectation5 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder5 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: 0)
api.trade(monaOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell mona_jpy
let monaJpyExpectation11 = self.expectation(description: "sell mona_jpy order success")
let monaOrder11 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1)
api.trade(monaOrder11) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation11.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell mona_jpy with limit
let monaJpyExpectation12 = self.expectation(description: "sell mona_jpy order with limit success")
let monaOrder12 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 5.9)
api.trade(monaOrder12) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaJpyExpectation12.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_jpy invalid price
let monaJpyExpectation13 = self.expectation(description: "mona_jpy order invalid price error")
let monaOrder13 = Trade.Sell.Mona.For.Jpy.createOrder(6.01, amount: 1)
api.trade(monaOrder13) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation13.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid limit
let monaJpyExpectation14 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder14 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 3.91)
api.trade(monaOrder14) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.1")
default:
XCTFail()
}
monaJpyExpectation14.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy invalid amount
let monaJpyExpectation15 = self.expectation(description: "mona_jpy order invalid limit error")
let monaOrder15 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0)
api.trade(monaOrder15) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaJpyExpectation15.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTradeMonaBtc() {
// buy mona_btc
let monaBtcExpectation = self.expectation(description: "buy mona_btc order success")
let monaOrder = Trade.Buy.Mona.In.Btc.createOrder(0.00000321, amount: 1)
api.trade(monaOrder) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// buy mona_btc (min)
let monaBtcExpectation22 = self.expectation(description: "buy mona_btc order success")
let monaOrder22 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1)
api.trade(monaOrder22) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation22.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// buy mona_btc with limit
let monaBtcExpectation2 = self.expectation(description: "buy mona_btc order with limit success")
let monaOrder2 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.00010001)
api.trade(monaOrder2) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation2.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_btc invalid price
let monaBtcExpectation3 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder3 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1)
api.trade(monaOrder3) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (border)
let monaBtcExpectation44 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder44 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1)
api.trade(monaOrder44) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation44.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (minus)
let monaBtcExpectation4 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder4 = Trade.Buy.Mona.In.Btc.createOrder(-0.00000001, amount: 1)
api.trade(monaOrder4) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid price (zero)
let monaBtcExpectation5 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder5 = Trade.Buy.Mona.In.Btc.createOrder(0, amount: 1)
api.trade(monaOrder5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit
let monaBtcExpectation6 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder6 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.000000019)
api.trade(monaOrder6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit (minus)
let monaBtcExpectation7 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder7 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: -0.00000002)
api.trade(monaOrder7) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit (zero)
let monaBtcExpectation8 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder8 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0)
api.trade(monaOrder8) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount (minus)
let monaBtcExpectation10 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder10 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: -1)
api.trade(monaOrder10) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount (zero)
let monaBtcExpectation55 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder55 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 0)
api.trade(monaOrder55) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation55.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// sell mona_btc
let monaBtcExpectation32 = self.expectation(description: "sell mona_btc order success")
let monaOrder32 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1)
api.trade(monaOrder32) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation32.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// sell mona_btc with limit
let monaBtcExpectation19 = self.expectation(description: "sell mona_btc order with limit success")
let monaOrder19 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 5.9)
api.trade(monaOrder19) { (err, res) in
XCTAssertNil(err)
XCTAssertNotNil(res)
monaBtcExpectation19.fulfill()
}
self.waitForExpectations(timeout: 10.0, handler: nil)
usleep(200)
// mona_btc invalid price
let monaBtcExpectation40 = self.expectation(description: "mona_btc order invalid price error")
let monaOrder40 = Trade.Sell.Mona.For.Btc.createOrder(0.000000019, amount: 1)
api.trade(monaOrder40) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "price unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation40.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid limit
let monaBtcExpectation64 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder64 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 0.000000009)
api.trade(monaOrder64) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "limit unit must be 0.00000001")
default:
XCTFail()
}
monaBtcExpectation64.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc invalid amount
let monaBtcExpectation54 = self.expectation(description: "mona_btc order invalid limit error")
let monaOrder54 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0)
api.trade(monaOrder54) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.INVALID_ORDER(let message):
XCTAssertEqual(message, "amount unit must be 1")
default:
XCTFail()
}
monaBtcExpectation54.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testHistory() {
// query using 'from' and 'count'. 'from' minus value
let fromQueryExpectation2 = self.expectation(description: "query using 'from' and 'count'")
let query2 = HistoryQuery(from: -1, count: 10)
api.tradeHistory(query2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' zero value
let fromQueryExpectation3 = self.expectation(description: "query using 'from' and 'count'")
let query3 = HistoryQuery(from: 0, count: 10)
api.tradeHistory(query3) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' valid value
let fromQueryExpectation = self.expectation(description: "query using 'from' and 'count'")
let query = HistoryQuery(from: 1, count: 10)
api.tradeHistory(query) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' valid value
let fromQueryExpectation4 = self.expectation(description: "query using 'from' and 'count'")
let query4 = HistoryQuery(from: 10, count: 10)
api.tradeHistory(query4) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'from' not specified
let fromQueryExpectation41 = self.expectation(description: "query using 'from' and 'count'")
let query41 = HistoryQuery(count: 10)
api.tradeHistory(query41) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 10)
fromQueryExpectation41.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' minus value
let fromQueryExpectation5 = self.expectation(description: "query using 'from' and 'count'")
let query5 = HistoryQuery(from: 0, count: -1)
api.tradeHistory(query5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' zero value
let fromQueryExpectation6 = self.expectation(description: "query using 'from' and 'count'")
let query6 = HistoryQuery(from: 0, count: 0)
api.tradeHistory(query6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
fromQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' valid value
let fromQueryExpectation7 = self.expectation(description: "query using 'from' and 'count'")
let query7 = HistoryQuery(from: 1, count: 1)
api.tradeHistory(query7) { (err, res) in
//print(res)
XCTAssertNil(err)
XCTAssertEqual(res!["return"].dictionary?.count, 1)
fromQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' valid value
let fromQueryExpectation8 = self.expectation(description: "query using 'from' and 'count'")
let query8 = HistoryQuery(from: 1, count: 2)
api.tradeHistory(query8) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 2)
fromQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from' and 'count'. 'count' not specified
let fromQueryExpectation9 = self.expectation(description: "query using 'from' and 'count'")
let query9 = HistoryQuery(from: 1, count: 2)
api.tradeHistory(query9) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
fromQueryExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'
let idQueryExpectation = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery = HistoryQuery(fromId: 6915724, endId: 7087911)
api.tradeHistory(idQuery) { (err, res) in
//print(res)
XCTAssertEqual(res!["return"].dictionary?.count, 8)
idQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' minus value
let idQueryExpectation2 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery2 = HistoryQuery(fromId: -1, endId: 7087911)
api.tradeHistory(idQuery2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
idQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' 0 value
let idQueryExpectation3 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery3 = HistoryQuery(fromId: 0, endId: 7087911)
api.tradeHistory(idQuery3) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'from_id' not specified
let idQueryExpectation4 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery4 = HistoryQuery(endId: 7087911)
api.tradeHistory(idQuery4) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' minus value
let idQueryExpectation5 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery5 = HistoryQuery(fromId: 6915724, endId: -1)
api.tradeHistory(idQuery5) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
idQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' zero value
let idQueryExpectation6 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery6 = HistoryQuery(fromId: 6915724, endId: 0)
api.tradeHistory(idQuery6) { (err, res) in
XCTAssertNil(err)
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
idQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' not specified
let idQueryExpectation7 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery7 = HistoryQuery(fromId: 6915724)
api.tradeHistory(idQuery7) { (err, res) in
XCTAssertNil(err)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
idQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'from_id' and 'end_id'. 'end_id' is greater than 'from_id'
let idQueryExpectation8 = self.expectation(description: "query using 'from_id' and 'end_id'")
let idQuery8 = HistoryQuery(fromId: 7087911 , endId: 6915724)
api.tradeHistory(idQuery8) { (err, res) in
XCTAssertNil(err)
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
idQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'
let sinceQueryExpectation = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery = HistoryQuery(since: 1467014263, end: 1467540926)
api.tradeHistory(sinceQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' minus value
let sinceQueryExpectation2 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery2 = HistoryQuery(since: -1, end: 1467540926)
api.tradeHistory(sinceQuery2) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
sinceQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' zero value
let sinceQueryExpectation3 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery3 = HistoryQuery(since: 0, end: 1467540926)
api.tradeHistory(sinceQuery3) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' valid value
let sinceQueryExpectation4 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery4 = HistoryQuery(since: 1, end: 1467540926)
api.tradeHistory(sinceQuery4) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation4.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' not spcified
let sinceQueryExpectation5 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery5 = HistoryQuery(end: 1467540926)
api.tradeHistory(sinceQuery5) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation5.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' minus value
let sinceQueryExpectation6 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery6 = HistoryQuery(since: 1467014263, end: -1)
api.tradeHistory(sinceQuery6) { (err, res) in
XCTAssertNotNil(err)
switch err!.errorType {
case ZSErrorType.PROCESSING_ERROR:
XCTAssertTrue(true)
default:
XCTFail()
}
sinceQueryExpectation6.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' zero value
let sinceQueryExpectation7 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery7 = HistoryQuery(since: 1467014263, end: 0)
api.tradeHistory(sinceQuery7) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation7.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' valid value
let sinceQueryExpectation8 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery8 = HistoryQuery(since: 1467014263, end: 1)
api.tradeHistory(sinceQuery8) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation8.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'end' not specified
let sinceQueryExpectation9 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery9 = HistoryQuery(since: 1467014263)
api.tradeHistory(sinceQuery9) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
sinceQueryExpectation9.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query using 'since' and 'end'. 'since' is greater than 'end'
let sinceQueryExpectation10 = self.expectation(description: "query using 'since' and 'end'")
let sinceQuery10 = HistoryQuery(since: 1467540926, end: 1467014263)
api.tradeHistory(sinceQuery10) { (err, res) in
//print(res)
let noEntry = res!["return"].dictionary?.count == 0
XCTAssertTrue(noEntry)
sinceQueryExpectation10.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for btc_jpy. asc order
let btcQueryExpectation = self.expectation(description: "query for btc_jpy")
let btcQuery = HistoryQuery(order: .ASC, currencyPair: .BTC_JPY)
api.tradeHistory(btcQuery) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for btc_jpy. desc order
let btcQueryExpectation2 = self.expectation(description: "query for btc_jpy")
let btcQuery2 = HistoryQuery(order: .DESC, currencyPair: .BTC_JPY)
api.tradeHistory(btcQuery2) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_jpy. asc order
let monaQueryExpectation = self.expectation(description: "query for mona_jpy")
let monaQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_JPY)
api.tradeHistory(monaQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_jpy. desc order
let monaQueryExpectation2 = self.expectation(description: "query for mona_jpy")
let monaQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_JPY)
api.tradeHistory(monaQuery2) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_btc. asc order
let monaBtcQueryExpectation = self.expectation(description: "query for mona_btc")
let monaBtcQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_BTC)
api.tradeHistory(monaBtcQuery) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcQueryExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// query for mona_btc. desc order
let monaBtcQueryExpectation2 = self.expectation(description: "query for mona_btc")
let monaBtcQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_BTC)
api.tradeHistory(monaBtcQuery2) { (err, res) in
//print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcQueryExpectation2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testActiveOrders() {
// btc_jpy
let btcExpectation = self.expectation(description: "active orders of btc_jpy")
api.activeOrders(.BTC_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "btc_jpy")
btcExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// mona_jpy
let monaExpectation = self.expectation(description: "active orders of mona_jpy")
api.activeOrders(.MONA_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_jpy")
monaExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// mona_btc
let monaBtcExpectation = self.expectation(description: "active orders of mona_btc")
api.activeOrders(.MONA_BTC) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "mona_btc")
monaBtcExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemExpectation = self.expectation(description: "active orders of xem_jpy")
api.activeOrders(.XEM_JPY) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue
XCTAssertEqual(pair, "xem_jpy")
xemExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// all
let allExpectation = self.expectation(description: "active orders of all")
api.activeOrders() { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
allExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testCancelOrder() {
var orderIds: [String] = []
let allExpectation = self.expectation(description: "active orders of all")
api.activeOrders() { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
for (orderId, _) in res!["return"].dictionaryValue {
orderIds.append(orderId)
}
allExpectation.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let cancelExpectation = self.expectation(description: "cancel orders")
var count = orderIds.count
let semaphore = DispatchSemaphore(value: 1)
for orderId in orderIds {
api.cancelOrder(Int(orderId)!) { (err, res) in
print(res)
let hasEntry = (res!["return"].dictionary?.count)! > 0
XCTAssertTrue(hasEntry)
var resOrderId = res!["return"].dictionaryValue["order_id"]
XCTAssertEqual(resOrderId?.stringValue, orderId)
semaphore.wait(timeout: DispatchTime.distantFuture)
count -= 1
if count == 0 {
cancelExpectation.fulfill()
}
semaphore.signal()
}
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let invalid = self.expectation(description: "invalid order id")
api.cancelOrder(-1) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let invalid2 = self.expectation(description: "invalid order id")
api.cancelOrder(0) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid2.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
let invalid3 = self.expectation(description: "invalid order id")
api.cancelOrder(999) { (err, res) in
print(res)
XCTAssertNotNil(err)
invalid3.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testStream() {
// btc_jpy
let streamExpectation = self.expectation(description: "stream of btc_jpy")
let stream = StreamingApi.stream(.BTC_JPY) { _,_ in
print("opened btc_jpy")
}
var count = 10
stream.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation.fulfill()
stream.onData(callback: nil)
}
}
stream.onError() { (err, _) in
print(err)
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let colseExp = self.expectation(description: "")
stream.close() { (_, res) in
print(res)
colseExp.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
// reopen
let streamExpectationRe = self.expectation(description: "stream of btc_jpy")
stream.open() { (_, _) in
print("reopened")
}
count = 10
stream.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectationRe.fulfill()
stream.onData(callback: nil)
}
}
stream.onError() { (err, _) in
print(err)
}
self.waitForExpectations(timeout: 50.0, handler: nil)
let colseExpRe = self.expectation(description: "")
stream.close() { (_, res) in
print(res)
colseExpRe.fulfill()
}
self.waitForExpectations(timeout: 50.0, handler: nil)
// mona_jpy
let streamExpectation2 = self.expectation(description: "stream of mona_jpy")
let stream2 = StreamingApi.stream(.MONA_JPY) { _,_ in
print("opened mona_jpy")
}
count = 1
stream2.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation2.fulfill()
stream2.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp2 = self.expectation(description: "")
stream2.onClose() { (_, res) in
print(res)
colseExp2.fulfill()
}
stream2.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
// mona_btc
let streamExpectation3 = self.expectation(description: "stream of mona_btc")
let stream3 = StreamingApi.stream(.MONA_BTC) { _,_ in
print("opened mona_btc")
}
count = 1
stream3.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation3.fulfill()
stream3.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp3 = self.expectation(description: "")
stream3.onClose() { (_, res) in
print(res)
colseExp3.fulfill()
}
stream3.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
// xem_jpy
let streamExpectation4 = self.expectation(description: "stream of xem_jpy")
let stream4 = StreamingApi.stream(.XEM_JPY) { _,_ in
print("opened xem_jpy")
}
count = 1
stream4.onData() { (_, res) in
print(res)
count -= 1
if count <= 0 {
streamExpectation4.fulfill()
stream4.onData(callback: nil)
}
}
self.waitForExpectations(timeout: 5000.0, handler: nil)
let colseExp4 = self.expectation(description: "")
stream4.onClose() { (_, res) in
print(res)
colseExp4.fulfill()
}
stream4.close()
self.waitForExpectations(timeout: 50.0, handler: nil)
}
func testLastPrice() {
// btc_jpy
let btcLastPrice = self.expectation(description: "last price of btc_jpy")
PublicApi.lastPrice(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
btcLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaLastPrice = self.expectation(description: "last price of mona_jpy")
PublicApi.lastPrice(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
monaLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcLastPrice = self.expectation(description: "last price for mona_btc")
PublicApi.lastPrice(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
monaBtcLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemLastPrice = self.expectation(description: "last price for xem_jpy")
PublicApi.lastPrice(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let price = res?["last_price"].int
XCTAssertNotNil(price)
xemLastPrice.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTicker() {
// btc_jpy
let btcTicker = self.expectation(description: "ticker for btc_jpy")
PublicApi.ticker(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
btcTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaTicker = self.expectation(description: "ticker for mona_jpy")
PublicApi.ticker(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
monaTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcTicker = self.expectation(description: "ticker for mona_btc")
PublicApi.ticker(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
monaBtcTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemTicker = self.expectation(description: "ticker for xem_jpy")
PublicApi.ticker(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
xemTicker.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testTrades() {
// btc_jpy
let btcTrades = self.expectation(description: "trades of btc_jpy")
PublicApi.trades(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "btc_jpy")
btcTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaTrades = self.expectation(description: "trades of mona_jpy")
PublicApi.trades(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "mona_jpy")
monaTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcTrades = self.expectation(description: "trades of mona_btc")
PublicApi.trades(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "mona_btc")
monaBtcTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemTrades = self.expectation(description: "trades of xem_jpy")
PublicApi.trades(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasEntry = (res?.count)! > 0
XCTAssertTrue(hasEntry)
let cp = res?[[0, "currency_pair"]].stringValue
XCTAssertEqual(cp, "xem_jpy")
xemTrades.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testDepth() {
// btc_jpy
let btcDepth = self.expectation(description: "depth of btc_jpy")
PublicApi.depth(.BTC_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
btcDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_jpy
let monaDepth = self.expectation(description: "depth of mona_jpy")
PublicApi.depth(.MONA_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
monaDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
usleep(200)
// mona_btc
let monaBtcDepth = self.expectation(description: "depth of mona_btc")
PublicApi.depth(.MONA_BTC) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
monaBtcDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
// xem_jpy
let xemDepth = self.expectation(description: "depth of xem_jpy")
PublicApi.depth(.XEM_JPY) { (err, res) in
print(res)
XCTAssertNil(err)
XCTAssertNotNil(res)
let hasAsks = (res?["asks"].count)! > 0
XCTAssertTrue(hasAsks)
XCTAssertNotNil(res)
let hasBids = (res?["bids"].count)! > 0
XCTAssertTrue(hasBids)
xemDepth.fulfill()
}
self.waitForExpectations(timeout: 5.0, handler: nil)
}
func testSerialNonce() {
// invalid initial value test
var nonce = SerialNonce(initialValue: -1)
var value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value -1")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value -1, 1 increment")
nonce = SerialNonce(initialValue: 0)
value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value 0")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 0, 1 increment")
// valid initial value test
nonce = SerialNonce(initialValue: 1)
value = try! nonce.getNonce()
XCTAssertEqual(value, "1", "initial value 1")
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 1, 1 increment")
nonce = SerialNonce(initialValue: 2)
value = try! nonce.getNonce()
XCTAssertEqual(value, "2", "initial value 2")
value = try! nonce.getNonce()
XCTAssertEqual(value, "3", "initial value 2, 1 increment")
// max initial value test
nonce = SerialNonce(initialValue: IntMax.max)
value = try! nonce.getNonce()
XCTAssertEqual(value, IntMax.max.description, "initial value max")
XCTAssertThrowsError(try nonce.getNonce()) { (error) in
switch error as! ZSErrorType {
case .NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
}
}
func testTimeNonce() {
let nonce = TimeNonce()
var prev = try! nonce.getNonce()
sleep(1)
var cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second")
prev = cur
sleep(2)
cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second")
prev = cur
var count = 10
while count > 0 {
cur = try! nonce.getNonce()
XCTAssertTrue(Int64(prev)! < Int64(cur)!, "multiple request in a second")
prev = cur
if Int64(cur) == IntMax.max {
break
}
count -= 1
}
/*
XCTAssertThrowsError(try nonce.getNonce()) { (error) in
switch error as! ZSErrorType {
case .NONCE_EXCEED_LIMIT:
XCTAssertTrue(true)
default:
XCTFail()
}
}
*/
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit | b271c88fddf3f228cf54f56cced503c1 | 37.443741 | 111 | 0.566348 | 4.282188 | false | false | false | false |
AndrewShmig/Qtty | Qtty/NAGPhotoOverlayView.swift | 1 | 2557 | //
// NAGPhotoFiltersOverlayView.swift
// Qtty
//
// Created by AndrewShmig on 28/07/14.
// Copyright (c) 2014 Non Atomic Games Inc. All rights reserved.
//
import UIKit
class NAGPhotoOverlayView: UIView {
let kPhotoViewTag: Int = 1
let kControlsViewTag: Int = 2
var photoView: UIImageView!
var originalPhoto: UIImage!
convenience required init(coder aDecoder: NSCoder!) {
self.init(imageInfo: [:], frame: UIScreen.mainScreen().bounds)
}
init(imageInfo: [NSObject : AnyObject]!, frame: CGRect) {
super.init(frame: frame)
originalPhoto = imageInfo[UIImagePickerControllerOriginalImage] as UIImage
photoView = createPhotoLayer(image: originalPhoto)
addSubview(photoView)
let controlsView = createControls()
photoView.addSubview(controlsView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceDidChangeOrientation:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
func deviceDidChangeOrientation(notification: NSNotification) {
rotateImage(toOrientation: UIDevice.currentDevice().orientation)
}
private func rotateImage(toOrientation orientation: UIDeviceOrientation) {
let orientation = UIDevice.currentDevice().orientation
let photoOrientation = originalPhoto.imageOrientation
let isLandscapedPhoto = photoOrientation == .Down || photoOrientation == .Up
if isLandscapedPhoto && (orientation == .LandscapeLeft || orientation == .LandscapeRight) {
photoView.image = UIImage(CGImage: originalPhoto.CGImage, scale: originalPhoto.scale, orientation: orientation == .LandscapeRight ? .Right : .Left)
} else if !isLandscapedPhoto && (orientation == .Portrait || orientation == .PortraitUpsideDown){
photoView.image = UIImage(CGImage: originalPhoto.CGImage, scale: originalPhoto.scale, orientation: orientation == .Portrait ? .Right : .Left)
}
}
private func createPhotoLayer(#image: UIImage!) -> UIImageView {
let layer = UIImageView(frame: frame)
layer.tag = kPhotoViewTag
layer.image = (image.imageOrientation == .Down || image.imageOrientation == .Up) ? UIImage(CGImage: image.CGImage, scale: image.scale, orientation: .Right) : image
return layer
}
private func createControls() -> UIView {
let layer = UIView(frame: frame)
layer.tag = kControlsViewTag
layer.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
return layer
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | e0e0fdefee9355ce7853445d7a3f0bf7 | 35.014085 | 167 | 0.718811 | 4.557932 | false | false | false | false |
neonichu/NBMaterialDialogIOS | Pod/Classes/NBMaterialCircularActivityIndicator.swift | 1 | 7688 | //
// NBMaterialCircularActivityIndicator.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// 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.
@objc public class NBMaterialCircularActivityIndicator : UIView {
// MARK: - Field Vars
private var _progressLayer: CAShapeLayer!
private var _isAnimating: Bool = false
private var _hidesWhenStopped: Bool = false
private var _timingFunction: CAMediaTimingFunction!
// MARK; - Properties
internal var progressLayer: CAShapeLayer {
if _progressLayer == nil {
_progressLayer = CAShapeLayer()
_progressLayer.strokeColor = tintColor.CGColor
_progressLayer.fillColor = nil
_progressLayer.lineWidth = 3.0
}
return _progressLayer
}
public var isAnimating: Bool {
return _isAnimating
}
/**
Defines the thickness of the indicator. Change this to make the circular indicator larger
*/
public var lineWidth: CGFloat {
get {
return progressLayer.lineWidth
}
set {
progressLayer.lineWidth = newValue
updatePath()
}
}
/**
Defines if the indicator should be hidden when its stopped (usually yes).
*/
public var hidesWhenStopped: Bool {
get {
return _hidesWhenStopped
}
set {
_hidesWhenStopped = newValue
hidden = !isAnimating && _hidesWhenStopped
}
}
public var indicatorColor: UIColor {
get {
return tintColor
}
set {
tintColor = newValue
}
}
// MARK: - Constants
internal let kNBCircleStrokeAnimationKey: String = "nbmaterialcircularactivityindicator.stroke"
internal let kNBCircleRotationAnimationKey: String = "nbmaterialcircularactivityindicator.rotation"
// MARK: (de)Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
internal func initialize() {
tintColor = NBConfig.AccentColor
_timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
layer.addSublayer(progressLayer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resetAnimations", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
// MARK: UIView overrides
public override func layoutSubviews() {
super.layoutSubviews()
progressLayer.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
updatePath()
}
public override func tintColorDidChange() {
super.tintColorDidChange()
progressLayer.strokeColor = tintColor.CGColor
}
// MARK: Animation functions
/**
If for some reason you need to reset, call this
*/
public func resetAnimations() {
if isAnimating {
stopAnimating()
startAnimating()
}
}
/**
Start or stop animating the indicator
- parameter animate: BOOL
*/
public func setAnimating(animate: Bool) {
animate ? startAnimating() : stopAnimating()
}
internal func startAnimating() {
if isAnimating {
return
}
let animation: CABasicAnimation = CABasicAnimation()
animation.keyPath = "transform.rotation"
animation.duration = 4.0
animation.fromValue = 0.0
animation.toValue = 2 * M_PI
animation.repeatCount = Float.infinity
animation.timingFunction = _timingFunction
progressLayer.addAnimation(animation, forKey: kNBCircleRotationAnimationKey)
let headAnimation: CABasicAnimation = CABasicAnimation()
headAnimation.keyPath = "strokeStart"
headAnimation.duration = 1.0
headAnimation.fromValue = 0.0
headAnimation.toValue = 0.25
headAnimation.timingFunction = _timingFunction
let tailAnimation: CABasicAnimation = CABasicAnimation()
tailAnimation.keyPath = "strokeEnd"
tailAnimation.duration = 1.0
tailAnimation.fromValue = 0.0
tailAnimation.toValue = 1.0
tailAnimation.timingFunction = _timingFunction
let endHeadAnimation: CABasicAnimation = CABasicAnimation()
endHeadAnimation.keyPath = "strokeStart"
endHeadAnimation.beginTime = 1.0
endHeadAnimation.duration = 0.5
endHeadAnimation.fromValue = 0.25
endHeadAnimation.toValue = 1.0
endHeadAnimation.timingFunction = _timingFunction
let endTailAnimation: CABasicAnimation = CABasicAnimation()
endTailAnimation.keyPath = "strokeEnd"
endTailAnimation.beginTime = 1.0
endTailAnimation.duration = 0.5
endTailAnimation.fromValue = 1.0
endTailAnimation.toValue = 1.0
endTailAnimation.timingFunction = _timingFunction
let animations: CAAnimationGroup = CAAnimationGroup()
animations.duration = 1.5
animations.animations = [headAnimation, tailAnimation, endHeadAnimation, endTailAnimation]
animations.repeatCount = Float.infinity
progressLayer.addAnimation(animations, forKey: kNBCircleStrokeAnimationKey)
_isAnimating = true
if hidesWhenStopped {
hidden = false
}
}
internal func stopAnimating() {
if !isAnimating {
return
}
progressLayer.removeAnimationForKey(kNBCircleRotationAnimationKey)
progressLayer.removeAnimationForKey(kNBCircleStrokeAnimationKey)
_isAnimating = false
if hidesWhenStopped {
hidden = true
}
}
// MARK: - Private methods
private func updatePath() {
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = min(bounds.width / 2, bounds.height / 2) - progressLayer.lineWidth / 2
let startAngle:CGFloat = 0.0
let endAngle:CGFloat = CGFloat(2.0*M_PI)
let path: UIBezierPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
progressLayer.path = path.CGPath
progressLayer.strokeStart = 0.0
progressLayer.strokeEnd = 0.0
}
} | mit | d62cb33b1a765e535cc825f761092b1a | 31.719149 | 152 | 0.666103 | 5.247782 | false | false | false | false |
jovito-royeca/Cineko | Cineko/TMDBManager.swift | 1 | 78324 | //
// TMDBManager.swift
// Cineko
//
// Created by Jovit Royeca on 04/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import Foundation
import KeychainAccess
enum TMDBError: ErrorType {
case NoAPIKey
case NoSessionID
case NoAccount
}
struct TMDBConstants {
static let APIKeyParam = "api_key"
static let SessionID = "session_id"
static let APIURL = "https://api.themoviedb.org/3"
static let SignupURL = "https://www.themoviedb.org/account/signup"
static let AuthenticateURL = "https://www.themoviedb.org/authenticate"
static let AllowURL = "https://www.themoviedb.org/allow"
static let ImageURL = "https://image.tmdb.org/t/p"
static let BackdropSizes = [
"w300",
"w780",
"w1280",
"original"]
static let LogoSizes = [
"w45",
"w92",
"w154",
"w185",
"w300",
"w500",
"original"]
static let PosterSizes = [
"w92",
"w154",
"w185",
"w342",
"w500",
"w780",
"original"]
static let ProfileSizes = [
"w45",
"w92", // not include in TMDB configuration
"w185",
"h632",
"original"]
static let StillSizes = [
"w92",
"w185",
"w300",
"original"]
struct Device {
struct Keys {
static let RequestToken = "request_token"
static let RequestTokenDate = "request_token_date"
static let MoviesNowShowing = "MoviesNowShowing"
static let MoviesPopular = "MoviesPopular"
static let MoviesTopRated = "MoviesTopRated"
static let MoviesComingSoon = "MoviesComingSoon"
static let MoviesDynamic = "MoviesDynamic"
static let TVShowsAiringToday = "TVShowsAiringToday"
static let TVShowsPopular = "TVShowsPopular"
static let TVShowsTopRated = "TVShowsTopRated"
static let TVShowsOnTheAir = "TVShowsOnTheAir"
static let TVShowsDynamic = "TVShowsDymanic"
static let PeoplePopular = "PeoplePopular"
static let FavoriteMovies = "FavoriteMovies"
static let FavoriteTVShows = "FavoriteTVShows"
static let WatchlistMovies = "WatchlistMovies"
static let WatchlistTVShows = "WatchlistTVShows"
static let Lists = "Lists"
}
}
struct Authentication {
struct TokenNew {
static let Path = "/authentication/token/new"
struct Keys {
static let RequestToken = "request_token"
static let ExpiresAt = "expires_at"
}
}
struct SessionNew {
static let Path = "/authentication/session/new"
struct Keys {
static let SessionID = "session_id"
}
}
}
struct Account {
struct Details {
static let Path = "/account"
}
struct Favorite {
static let Path = "/account/{id}/favorite"
}
struct FavoriteMovies {
static let Path = "/account/{id}/favorite/movies"
}
struct FavoriteTVShows {
static let Path = "/account/{id}/favorite/tv"
}
struct Watchlist {
static let Path = "/account/{id}/watchlist"
}
struct WatchlistMovies {
static let Path = "/account/{id}/watchlist/movies"
}
struct WatchlistTVShows {
static let Path = "/account/{id}/watchlist/tv"
}
}
struct Movies {
struct NowPlaying {
static let Path = "/movie/now_playing"
}
struct Upcoming {
static let Path = "/movie/upcoming"
}
struct TopRated {
static let Path = "/movie/top_rated"
}
struct Popular {
static let Path = "/movie/popular"
}
struct ByGenre {
static let Path = "/genre/{id}/movies"
}
struct Details {
static let Path = "/movie/{id}"
}
struct Images {
static let Path = "/movie/{id}/images"
}
struct Credits {
static let Path = "/movie/{id}/credits"
}
struct Videos {
static let Path = "/movie/{id}/videos"
}
}
struct TVShows {
struct OnTheAir {
static let Path = "/tv/on_the_air"
}
struct AiringToday {
static let Path = "/tv/airing_today"
}
struct TopRated {
static let Path = "/tv/top_rated"
}
struct Popular {
static let Path = "/tv/popular"
}
struct Details {
static let Path = "/tv/{id}"
}
struct Images {
static let Path = "/tv/{id}/images"
}
struct Credits {
static let Path = "/tv/{id}/credits"
}
struct Videos {
static let Path = "/tv/{id}/videos"
}
}
struct People {
struct Popular {
static let Path = "/person/popular"
}
struct Details {
static let Path = "/person/{id}"
}
struct Images {
static let Path = "/person/{id}/images"
}
struct Credits {
static let Path = "/person/{id}/combined_credits"
}
}
struct Genres {
struct Movie {
static let Path = "/genre/movie/list"
}
struct TVShow {
static let Path = "/genre/tv/list"
}
}
struct Search {
struct Multi {
static let Path = "/search/multi"
}
struct Movie {
static let Path = "/search/movie"
}
struct TVShow {
static let Path = "/search/tv"
}
struct Person {
static let Path = "/search/person"
}
}
struct Lists {
struct All {
static let Path = "/account/{id}/lists"
}
struct Details {
static let Path = "/list/{id}"
}
struct Create {
static let Path = "/list"
}
struct Delete {
static let Path = "/list/{id}"
}
struct MovieStatus {
static let Path = "/list/{id}/item_status"
}
struct AddMovie {
static let Path = "/list/{id}/add_item"
}
struct RemoveMovie {
static let Path = "/list/{id}/remove_item"
}
}
}
enum ImageType : Int {
case MovieBackdrop
case MoviePoster
case TVShowBackdrop
case TVShowPoster
case PersonProfile
}
enum CreditType : String {
case Cast = "cast",
Crew = "crew",
GuestStar = "guest_star"
}
enum CreditParent : String {
case Job = "Job",
Movie = "Movie",
Person = "Person",
TVEpisode = "TVEpisode",
TVSeason = "TVSeason",
TVShow = "TVShow"
}
enum MediaType : String {
case Movie = "movie",
TVShow = "tv",
Person = "person"
}
let HoursNeededForRefresh = Double(60*60*3) // 3 hours
class TMDBManager: NSObject {
let keychain = Keychain(server: "\(TMDBConstants.APIURL)", protocolType: .HTTPS)
// MARK: Variables
private var apiKey:String?
var account:Account?
// MARK: Setup
func setup(apiKey: String) {
self.apiKey = apiKey
checkFirstRun()
}
// MARK: Device
func checkFirstRun() {
if !NSUserDefaults.standardUserDefaults().boolForKey("FirstRun") {
// remove prior keychain items if this is our first run
keychain[TMDBConstants.SessionID] = nil
keychain[TMDBConstants.Device.Keys.RequestToken] = nil
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.RequestTokenDate)
// then mark this us our first run
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstRun")
}
}
func getAvailableRequestToken() throws -> String? {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
if let requestToken = keychain[TMDBConstants.Device.Keys.RequestToken],
let requestTokenDate = NSUserDefaults.standardUserDefaults().valueForKey(TMDBConstants.Device.Keys.RequestTokenDate) as? NSDate {
// let's calculate the age of the request token
let interval = requestTokenDate.timeIntervalSinceNow
let secondsInAnHour:Double = 3600
let elapsedTime = abs(interval / secondsInAnHour)
// request token's expiration is 1 hour
if elapsedTime <= 60 {
return requestToken
} else {
logout()
}
}
return nil
}
func saveRequestToken(requestToken: String, date: NSDate) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
keychain[TMDBConstants.Device.Keys.RequestToken] = requestToken
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: TMDBConstants.Device.Keys.RequestTokenDate)
}
func removeRequestToken() throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
keychain[TMDBConstants.Device.Keys.RequestToken] = nil
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.RequestTokenDate)
}
func saveSessionID(sessionID: String) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
keychain[TMDBConstants.SessionID] = sessionID
}
func hasSessionID() -> Bool {
return keychain[TMDBConstants.SessionID] != nil
}
func needsRefresh(data: String) -> Bool {
let timeNow = NSDate()
var needsRefresh = false
if let dataTime = NSUserDefaults.standardUserDefaults().valueForKey(data) as? NSDate {
if dataTime.timeIntervalSinceNow >= HoursNeededForRefresh {
needsRefresh = true
}
} else {
needsRefresh = true
}
if needsRefresh {
NSUserDefaults.standardUserDefaults().setObject(timeNow, forKey: data)
}
return needsRefresh
}
func deleteRefreshData(data: String) {
NSUserDefaults.standardUserDefaults().removeObjectForKey(data)
}
func deleteAllRefreshData() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.MoviesNowShowing)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.TVShowsAiringToday)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.PeoplePopular)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.MoviesDynamic)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.MoviesPopular)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.MoviesTopRated)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.MoviesComingSoon)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.FavoriteMovies)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.WatchlistMovies)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.TVShowsPopular)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.TVShowsTopRated)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.TVShowsOnTheAir)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.TVShowsDynamic)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.FavoriteTVShows)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.WatchlistTVShows)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.Lists)
}
func logout() {
account = nil
keychain[TMDBConstants.SessionID] = nil
keychain[TMDBConstants.Device.Keys.RequestToken] = nil
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.RequestTokenDate)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.FavoriteMovies)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.WatchlistMovies)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.FavoriteTVShows)
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.WatchlistTVShows)
NSUserDefaults.standardUserDefaults().synchronize()
}
// MARK: Authentication
func authenticationTokenNew(completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Authentication.TokenNew.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) -> Void in
if let dict = results as? [String: AnyObject] {
if let requestToken = dict[TMDBConstants.Authentication.TokenNew.Keys.RequestToken] as? String,
let expires_at = dict[TMDBConstants.Authentication.TokenNew.Keys.ExpiresAt] as? String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
let expirationDate = formatter.dateFromString(expires_at)
do {
try self.saveRequestToken(requestToken, date: expirationDate!)
} catch {}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func authenticationSessionNew(completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
if let requestToken = try getAvailableRequestToken() {
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Authentication.SessionNew.Path)"
let headers = ["Accept": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.Authentication.TokenNew.Keys.RequestToken: requestToken]
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let sessionID = dict[TMDBConstants.Authentication.SessionNew.Keys.SessionID] as? String {
do {
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.Lists)
try self.saveSessionID(sessionID)
try self.downloadInitialData(completion)
} catch {}
}
}
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
} else {
completion(error: NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey : "No request token available."]))
}
}
// MARK: Account
func downloadInitialData(completion: (error: NSError?) -> Void?) throws {
// download account details, then favorite movies, then favorite TV shows,
// then watchlist movies, then watchlist TV shows,
// then movie genres, then TV show genres
let accountCompletion = { (error: NSError?) in
do {
let fmCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let ftvCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let wmCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let wtvCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let gMCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let gTVCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
completion(error: error)
}
do {
try self.genresTVShow(gTVCompletion)
} catch {}
}
do {
try self.genresMovie(gMCompletion)
} catch {}
}
do {
try self.accountWatchlistTVShows(wtvCompletion)
} catch {}
}
do {
try self.accountWatchlistMovies(wmCompletion)
} catch {}
}
do {
try self.accountFavoriteTVShows(ftvCompletion)
} catch {}
}
try self.accountFavoriteMovies(fmCompletion)
} catch {}
}
do {
try accountDetails(accountCompletion)
} catch {
// down load movie and TV genres even if User did not log in
let gMCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
let gTVCompletion = { (arrayIDs: [AnyObject], error: NSError?) in
completion(error: error)
}
do {
try self.genresTVShow(gTVCompletion)
} catch {}
}
do {
try self.genresMovie(gMCompletion)
} catch {}
}
}
func accountDetails(completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.Details.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
self.account = ObjectManager.sharedInstance.findOrCreateAccount(dict)
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountFavorite(mediaID: NSNumber, mediaType: MediaType, favorite: Bool, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Post
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.Favorite.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["media_type": mediaType.rawValue,
"media_id": "\(mediaID)",
"favorite": favorite]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) -> Void in
switch mediaType {
case .Movie:
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: mediaID])
movie.favorite = NSNumber(bool: favorite)
case .TVShow:
let tvShow = ObjectManager.sharedInstance.findOrCreateTVShow([TVShow.Keys.TVShowID: mediaID])
tvShow.favorite = NSNumber(bool: favorite)
default:
()
}
CoreDataManager.sharedInstance.savePrivateContext()
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountWatchlist(mediaID: NSNumber, mediaType: MediaType, watchlist: Bool, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Post
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.Watchlist.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["media_type": mediaType.rawValue,
"media_id": "\(mediaID)",
"watchlist": watchlist]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) -> Void in
switch mediaType {
case .Movie:
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: mediaID])
movie.watchlist = NSNumber(bool: watchlist)
case .TVShow:
let tvShow = ObjectManager.sharedInstance.findOrCreateTVShow([TVShow.Keys.TVShowID: mediaID])
tvShow.watchlist = NSNumber(bool: watchlist)
default:
()
}
CoreDataManager.sharedInstance.savePrivateContext()
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountFavoriteMovies(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.FavoriteMovies.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
var movieIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for movie in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(movie)
m.favorite = NSNumber(bool: true)
CoreDataManager.sharedInstance.savePrivateContext()
if let movieID = m.movieID {
movieIDs.append(movieID)
}
}
}
}
completion(arrayIDs: movieIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: movieIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountFavoriteTVShows(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.FavoriteTVShows.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
var tvShowIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for tvShow in json {
let m = ObjectManager.sharedInstance.findOrCreateTVShow(tvShow)
m.favorite = NSNumber(bool: true)
CoreDataManager.sharedInstance.savePrivateContext()
if let tvShowID = m.tvShowID {
tvShowIDs.append(tvShowID)
}
}
}
}
completion(arrayIDs: tvShowIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: tvShowIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountWatchlistMovies(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.WatchlistMovies.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
var movieIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for movie in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(movie)
m.watchlist = NSNumber(bool: true)
CoreDataManager.sharedInstance.savePrivateContext()
if let movieID = m.movieID {
movieIDs.append(movieID)
}
}
}
}
completion(arrayIDs: movieIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: movieIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func accountWatchlistTVShows(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Account.WatchlistTVShows.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
var tvShowIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for tvShow in json {
let m = ObjectManager.sharedInstance.findOrCreateTVShow(tvShow)
m.watchlist = NSNumber(bool: true)
CoreDataManager.sharedInstance.savePrivateContext()
if let tvShowID = m.tvShowID {
tvShowIDs.append(tvShowID)
}
}
}
}
completion(arrayIDs: tvShowIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: tvShowIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: Movies
func movies(path: String, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var movieIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for movie in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(movie)
if let movieID = m.movieID {
movieIDs.append(movieID)
}
}
}
}
completion(arrayIDs: movieIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: movieIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func moviesByGenre(genreID: Int, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Movies.ByGenre.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(genreID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var movieIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for movie in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(movie)
if let movieID = m.movieID {
movieIDs.append(movieID)
}
}
}
}
completion(arrayIDs: movieIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: movieIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func movieDetails(movieID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Movies.Details.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(movieID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
ObjectManager.sharedInstance.updateMovie(dict)
completion(error: nil)
}
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func movieImages(movieID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Movies.Images.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(movieID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: movieID])
if let dict = results as? [String: AnyObject] {
if let backdrops = dict["backdrops"] as? [[String: AnyObject]] {
for backdrop in backdrops {
ObjectManager.sharedInstance.findOrCreateImage(backdrop, imageType: .MovieBackdrop, forObject: movie)
}
}
if let posters = dict["posters"] as? [[String: AnyObject]] {
for poster in posters {
ObjectManager.sharedInstance.findOrCreateImage(poster, imageType: .MoviePoster, forObject: movie)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func movieCredits(movieID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Movies.Credits.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(movieID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: movieID])
if let dict = results as? [String: AnyObject] {
if let cast = dict["cast"] as? [[String: AnyObject]] {
for c in cast {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Cast, creditParent: .Movie, forObject: movie)
}
}
if let crew = dict["crew"] as? [[String: AnyObject]] {
for c in crew {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Crew, creditParent: .Movie, forObject: movie)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func movieVideos(movieID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Movies.Videos.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(movieID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: movieID])
if let dict = results as? [String: AnyObject] {
if let videos = dict["results"] as? [[String: AnyObject]] {
for video in videos {
ObjectManager.sharedInstance.findOrCreateVideo(video, forObject: movie)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: TV Shows
func tvShows(path: String, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var tvShowIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for tvShow in json {
let m = ObjectManager.sharedInstance.findOrCreateTVShow(tvShow)
if let tvShowID = m.tvShowID {
tvShowIDs.append(tvShowID)
}
}
}
}
completion(arrayIDs: tvShowIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: tvShowIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func tvShowDetails(tvShowID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.TVShows.Details.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(tvShowID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
ObjectManager.sharedInstance.updateTVShow(dict)
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func tvShowImages(tvShowID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.TVShows.Images.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(tvShowID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let tvShow = ObjectManager.sharedInstance.findOrCreateTVShow([TVShow.Keys.TVShowID: tvShowID])
if let dict = results as? [String: AnyObject] {
if let backdrops = dict["backdrops"] as? [[String: AnyObject]] {
for backdrop in backdrops {
ObjectManager.sharedInstance.findOrCreateImage(backdrop, imageType: .TVShowBackdrop, forObject: tvShow)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func tvShowCredits(tvShowID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.TVShows.Credits.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(tvShowID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let tvShow = ObjectManager.sharedInstance.findOrCreateTVShow([TVShow.Keys.TVShowID: tvShowID])
if let dict = results as? [String: AnyObject] {
if let cast = dict["cast"] as? [[String: AnyObject]] {
for c in cast {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Cast, creditParent: .TVShow, forObject: tvShow)
}
}
if let crew = dict["crew"] as? [[String: AnyObject]] {
for c in crew {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Crew, creditParent: .TVShow, forObject: tvShow)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func tvShowVideos(tvShowID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.TVShows.Videos.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(tvShowID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let tvShow = ObjectManager.sharedInstance.findOrCreateTVShow([TVShow.Keys.TVShowID: tvShowID])
if let dict = results as? [String: AnyObject] {
if let videos = dict["results"] as? [[String: AnyObject]] {
for video in videos {
ObjectManager.sharedInstance.findOrCreateVideo(video, forObject: tvShow)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: People
func peoplePopular(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.People.Popular.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var personIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for person in json {
let m = ObjectManager.sharedInstance.findOrCreatePerson(person)
if let personID = m.personID {
personIDs.append(personID)
}
}
}
}
completion(arrayIDs: personIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: personIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func personDetails(personID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.People.Details.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(personID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
ObjectManager.sharedInstance.updatePerson(dict)
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func personImages(personID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.People.Images.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(personID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let person = ObjectManager.sharedInstance.findOrCreatePerson([Person.Keys.PersonID: personID])
if let dict = results as? [String: AnyObject] {
if let profiles = dict["profiles"] as? [[String: AnyObject]] {
for profile in profiles {
ObjectManager.sharedInstance.findOrCreateImage(profile, imageType: .PersonProfile, forObject: person)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func personCredits(personID: NSNumber, completion: (error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.People.Credits.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(personID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
let success = { (results: AnyObject!) in
let person = ObjectManager.sharedInstance.findOrCreatePerson([Person.Keys.PersonID: personID])
if let dict = results as? [String: AnyObject] {
if let cast = dict["cast"] as? [[String: AnyObject]] {
for c in cast {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Cast, creditParent: .Person, forObject: person)
}
}
if let crew = dict["crew"] as? [[String: AnyObject]] {
for c in crew {
ObjectManager.sharedInstance.findOrCreateCredit(c, creditType: .Crew, creditParent: .Person, forObject: person)
}
}
}
completion(error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: Genre
func genresMovie(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Genres.Movie.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var genreIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["genres"] as? [[String: AnyObject]] {
for genre in json {
let m = ObjectManager.sharedInstance.findOrCreateGenre(genre)
if let genreID = m.genreID {
genreIDs.append(genreID)
}
m.movieGenre = NSNumber(bool: true)
}
}
}
CoreDataManager.sharedInstance.savePrivateContext()
completion(arrayIDs: genreIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: genreIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func genresTVShow(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Genres.Movie.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var genreIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["genres"] as? [[String: AnyObject]] {
for genre in json {
let m = ObjectManager.sharedInstance.findOrCreateGenre(genre)
if let genreID = m.genreID {
genreIDs.append(genreID)
}
m.tvGenre = NSNumber(bool: true)
}
}
}
CoreDataManager.sharedInstance.savePrivateContext()
completion(arrayIDs: genreIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: genreIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: Search
func searchMulti(query: String, completion: (results: [MediaType: [AnyObject]], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Search.Multi.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
"query": query,
"include_adult": "true"]
var media = [MediaType: [AnyObject]]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for dict in json {
if let mediaType = dict["media_type"] as? String {
var ids:[NSNumber]?
if mediaType == "movie" {
let m = ObjectManager.sharedInstance.findOrCreateMovie(dict)
if let movieID = m.movieID {
if let x = media[MediaType.Movie] as? [NSNumber] {
ids = x
} else {
ids = [NSNumber]()
}
ids!.append(movieID)
media[MediaType.Movie] = ids
}
} else if mediaType == "tv" {
let m = ObjectManager.sharedInstance.findOrCreateTVShow(dict)
if let tvShowID = m.tvShowID {
if let x = media[MediaType.TVShow] as? [NSNumber] {
ids = x
} else {
ids = [NSNumber]()
}
ids!.append(tvShowID)
media[MediaType.TVShow] = ids
}
} else if mediaType == "person" {
let m = ObjectManager.sharedInstance.findOrCreatePerson(dict)
if let personID = m.personID {
if let x = media[MediaType.Person] as? [NSNumber] {
ids = x
} else {
ids = [NSNumber]()
}
ids!.append(personID)
media[MediaType.Person] = ids
}
}
}
}
}
}
completion(results: media, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(results: media, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func searchMovie(query: String, releaseYear year: Int, includeAdult: Bool, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Search.Movie.Path)"
var parameters = [TMDBConstants.APIKeyParam: apiKey!,
"query": query,
"include_adult": "\(includeAdult)"]
if year > 0 {
parameters["year"] = "\(year)"
}
var array = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for dict in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(dict)
if let movieID = m.movieID {
array.append(movieID)
}
}
}
}
completion(arrayIDs: array, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: array, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func searchTVShow(query: String, firstAirDate year: Int, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Search.TVShow.Path)"
var parameters = [TMDBConstants.APIKeyParam: apiKey!,
"query": query]
if year > 0 {
parameters["first_air_date_year"] = "\(year)"
}
var array = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for dict in json {
let m = ObjectManager.sharedInstance.findOrCreateTVShow(dict)
if let tvShowID = m.tvShowID {
array.append(tvShowID)
}
}
}
}
completion(arrayIDs: array, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: array, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func searchPeople(query: String, includeAdult: Bool, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Search.Person.Path)"
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
"query": query,
"include_adult": "\(includeAdult)"]
var array = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for dict in json {
let m = ObjectManager.sharedInstance.findOrCreatePerson(dict)
if let personID = m.personID {
array.append(personID)
}
}
}
}
completion(arrayIDs: array, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: array, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: Lists
func lists(completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.All.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(account!.accountID!)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
var listIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["results"] as? [[String: AnyObject]] {
for list in json {
let m = ObjectManager.sharedInstance.findOrCreateList(list)
m.createdBy = self.account
if let listIDInt = m.listIDInt {
listIDs.append(listIDInt)
// pre-download the list details
do {
try self.listDetails(listIDInt, completion: { _,_ -> Void in
})
} catch {}
}
}
}
}
CoreDataManager.sharedInstance.savePrivateContext()
completion(arrayIDs: listIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: listIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func listDetails(listID: NSNumber, completion: (arrayIDs: [AnyObject], error: NSError?) -> Void?) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
let httpMethod:HTTPMethod = .Get
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.Details.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(listID)")
let parameters = [TMDBConstants.APIKeyParam: apiKey!]
var movieIDs = [NSNumber]()
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let json = dict["items"] as? [[String: AnyObject]] {
let list = ObjectManager.sharedInstance.findOrCreateList([List.Keys.ListID: listID])
let set = list.mutableSetValueForKey("movies") as NSMutableSet
for movie in json {
let m = ObjectManager.sharedInstance.findOrCreateMovie(movie)
if let movieID = m.movieID {
movieIDs.append(movieID)
set.addObject(m)
}
}
// update list movies
CoreDataManager.sharedInstance.savePrivateContext()
}
}
completion(arrayIDs: movieIDs, error: nil)
}
let failure = { (error: NSError?) -> Void in
completion(arrayIDs: movieIDs, error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func createList(name: String, description: String, completion: (error: NSError?) -> Void) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Post
let urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.Create.Path)"
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["name": name,
"description": description]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let _ = dict["list_id"] {
// force refresh of Lists
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.Lists)
completion(error: nil)
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error creating list: \(name)."])
completion(error: e)
}
}
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func deleteList(listIDInt: NSNumber, completion: (error: NSError?) -> Void) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Delete
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.Delete.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(listIDInt)")
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["media_id": listIDInt]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
// force refresh of Lists
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.Lists)
ObjectManager.sharedInstance.deleteObject("List", objectKey: "listIDInt", objectValue: listIDInt)
if let statusCode = dict["status_code"] as? Int {
if statusCode == 13 { // 13 200 The item/record was deleted successfully.
completion(error: nil)
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error deleting list: \(listIDInt)."])
completion(error: e)
}
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error deleting list: \(listIDInt)."])
completion(error: e)
}
}
}
let failure = { (error: NSError?) -> Void in
// force refresh of Lists
NSUserDefaults.standardUserDefaults().removeObjectForKey(TMDBConstants.Device.Keys.Lists)
ObjectManager.sharedInstance.deleteObject("List", objectKey: "listIDInt", objectValue: listIDInt)
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func addMovie(movieID: NSNumber, toList listID: NSNumber, completion: (error: NSError?) -> Void) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Post
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.AddMovie.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(listID)")
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["media_id": movieID]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let statusCode = dict["status_code"] as? Int {
if statusCode == 12 { // 12 201 The item/record was updated successfully.
let list = ObjectManager.sharedInstance.findOrCreateList([List.Keys.ListID: listID])
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: movieID])
let movies = list.mutableSetValueForKey("movies")
movies.addObject(movie)
CoreDataManager.sharedInstance.savePrivateContext()
completion(error: nil)
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error adding movie to list"])
completion(error: e)
}
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error adding movie to list"])
completion(error: e)
}
}
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
func removeMovie(movieID: NSNumber, fromList listID: NSNumber, completion: (error: NSError?) -> Void) throws {
guard (apiKey) != nil else {
throw TMDBError.NoAPIKey
}
guard hasSessionID() else {
throw TMDBError.NoSessionID
}
guard account != nil else {
throw TMDBError.NoAccount
}
let httpMethod:HTTPMethod = .Post
var urlString = "\(TMDBConstants.APIURL)\(TMDBConstants.Lists.RemoveMovie.Path)"
urlString = urlString.stringByReplacingOccurrencesOfString("{id}", withString: "\(listID)")
let headers = ["Accept": "application/json",
"Content-Type": "application/json"]
let parameters = [TMDBConstants.APIKeyParam: apiKey!,
TMDBConstants.SessionID: keychain[TMDBConstants.SessionID]!]
let bodyDict = ["media_id": movieID]
let body = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: .PrettyPrinted)
let success = { (results: AnyObject!) in
if let dict = results as? [String: AnyObject] {
if let statusCode = dict["status_code"] as? Int {
if statusCode == 13 { // 13 200 The item/record was deleted successfully.
let list = ObjectManager.sharedInstance.findOrCreateList([List.Keys.ListID: listID])
let movie = ObjectManager.sharedInstance.findOrCreateMovie([Movie.Keys.MovieID: movieID])
let movies = list.mutableSetValueForKey("movies")
movies.removeObject(movie)
CoreDataManager.sharedInstance.savePrivateContext()
completion(error: nil)
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error removing movie to list"])
completion(error: e)
}
} else {
let e = NSError(domain: "exec", code: 1, userInfo: [NSLocalizedDescriptionKey: "Error adding movie to list"])
completion(error: e)
}
}
}
let failure = { (error: NSError?) -> Void in
completion(error: error)
}
NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: headers, parameters: parameters, values: nil, body: body, dataOffset: 0, isJSON: true, success: success, failure: failure)
}
// MARK: Shared Instance
static let sharedInstance = TMDBManager()
}
| apache-2.0 | 0f16ce2dfccba3cd3c1e6ced9bd10b66 | 41.041331 | 211 | 0.545587 | 5.293168 | false | false | false | false |
shralpmeister/shralptide2 | ShralpTide/Shared/Components/ChartView/LocationDateViewModifier.swift | 1 | 1112 | //
// LocationDateViewModifier.swift
// SwiftTides
//
// Created by Michael Parlee on 4/9/21.
//
import SwiftUI
struct LocationDateViewModifier: ViewModifier {
private var location: String?
private var date: Date
private var dateFormatter = DateFormatter()
init(location: String? = nil, date: Date) {
self.location = location
self.date = date
dateFormatter.dateStyle = .full
}
func body(content: Content) -> some View {
return GeometryReader { proxy in
content.overlay(
HStack(alignment: .bottom) {
if location != nil {
Text(location!)
}
Spacer()
Text(dateFormatter.string(from: date))
}
.font(.body)
.minimumScaleFactor(0.2)
.padding(.leading)
.padding(.trailing)
.foregroundColor(.white)
.frame(maxHeight: 30)
.position(x: proxy.size.width / 2.0, y: 50)
)
}
}
}
| gpl-3.0 | f5dcda435bbea7e5f4042ffb9b3fe993 | 25.47619 | 59 | 0.505396 | 4.772532 | false | false | false | false |
belkhadir/Beloved | Beloved/CoreDataStackManager.swift | 1 | 5291 | //
// CoreDataStackManager.swift
// Beloved
//
// Created by Anas Belkhadir on 07/03/2016.
// Copyright © 2016 Anas Belkhadir. All rights reserved.
//
import Foundation
import CoreData
private let SQLITE_FILE_NAME = "Beloved.sqlite"
class CoreDataStackManager {
// MARK: - Shared Instance
/**
* This class variable provides an easy way to get access
* to a shared instance of the CoreDataStackManager class.
*/
class func sharedInstance() -> CoreDataStackManager {
struct Static {
static let instance = CoreDataStackManager()
}
return Static.instance
}
// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory: NSURL = {
print("Instantiating the applicationDocumentsDirectory property")
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
print("Instantiating the managedObjectModel property")
let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
/**
* The Persistent Store Coordinator is an object that the Context uses to interact with the underlying file system. Usually
* the persistent store coordinator object uses an SQLite database file to save the managed objects. But it is possible to
* configure it to use XML or other formats.
*
* Typically you will construct your persistent store manager exactly like this. It needs two pieces of information in order
* to be set up:
*
* - The path to the sqlite file that will be used. Usually in the documents directory
* - A configured Managed Object Model. See the next property for details.
*/
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
print("Instantiating the persistentStoreCoordinator property")
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME)
print("sqlite path: \(url.path!)")
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] = "There was an error creating or loading the application's saved data."
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Left in for development.
// 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.
print("Instantiating the managedObjectContext property")
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 {
// Left in for development.
// 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 | e4f48813dfd502e50287af63c5b978f4 | 43.838983 | 291 | 0.674291 | 5.825991 | false | false | false | false |
kylef/cocoapods-deintegrate | spec/fixtures/Project_Pre_1.0.0/Frameworks/Pods/Quick/Quick/ExampleGroup.swift | 177 | 2921 | /**
Example groups are logical groupings of examples, defined with
the `describe` and `context` functions. Example groups can share
setup and teardown code.
*/
@objc final public class ExampleGroup {
weak internal var parent: ExampleGroup?
internal let hooks = ExampleHooks()
private let description: String
private let flags: FilterFlags
private let isInternalRootExampleGroup: Bool
private var childGroups = [ExampleGroup]()
private var childExamples = [Example]()
internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) {
self.description = description
self.flags = flags
self.isInternalRootExampleGroup = isInternalRootExampleGroup
}
/**
Returns a list of examples that belong to this example group,
or to any of its descendant example groups.
*/
public var examples: [Example] {
var examples = childExamples
for group in childGroups {
examples.extend(group.examples)
}
return examples
}
internal var name: String? {
if let parent = parent {
switch(parent.name) {
case .Some(let name): return "\(name), \(description)"
case .None: return description
}
} else {
return isInternalRootExampleGroup ? nil : description
}
}
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
walkUp() { (group: ExampleGroup) -> () in
for (key, value) in group.flags {
aggregateFlags[key] = value
}
}
return aggregateFlags
}
internal var befores: [BeforeExampleWithMetadataClosure] {
var closures = hooks.befores.reverse()
walkUp() { (group: ExampleGroup) -> () in
closures.extend(group.hooks.befores.reverse())
}
return closures.reverse()
}
internal var afters: [AfterExampleWithMetadataClosure] {
var closures = hooks.afters
walkUp() { (group: ExampleGroup) -> () in
closures.extend(group.hooks.afters)
}
return closures
}
internal func walkDownExamples(callback: (example: Example) -> ()) {
for example in childExamples {
callback(example: example)
}
for group in childGroups {
group.walkDownExamples(callback)
}
}
internal func appendExampleGroup(group: ExampleGroup) {
group.parent = self
childGroups.append(group)
}
internal func appendExample(example: Example) {
example.group = self
childExamples.append(example)
}
private func walkUp(callback: (group: ExampleGroup) -> ()) {
var group = self
while let parent = group.parent {
callback(group: parent)
group = parent
}
}
}
| mit | 7e5c14b98052b176d1e6a42ffe6f7616 | 29.113402 | 102 | 0.608696 | 4.984642 | false | false | false | false |
kidaa/codecombat-ios | CodeCombat/TomeInventoryItemPropertyDocumentationView.swift | 2 | 1268 | //
// TomeInventoryItemPropertyDocumentationView.swift
// CodeCombat
//
// Created by Nick Winter on 10/26/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import Foundation
import WebKit
class TomeInventoryItemPropertyDocumentationView: UIView {
var item: TomeInventoryItem!
var property: TomeInventoryItemProperty!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init?(item: TomeInventoryItem, property: TomeInventoryItemProperty, coder aDecoder: NSCoder!) {
self.item = item
self.property = property
super.init(coder: aDecoder)
buildSubviews()
}
init(item: TomeInventoryItem, property: TomeInventoryItemProperty, frame: CGRect) {
self.item = item
self.property = property
super.init(frame: frame)
buildSubviews()
}
func buildSubviews() {
let docWebView = WKWebView(frame: frame)
let wrappedHTML = "<!DOCTYPE html>\n<html><head><meta name='viewport' content='width=320, height=480, initial-scale=1'><link rel='stylesheet' href='/stylesheets/app.css'></head><body><div class='tome-inventory-property-documentation'>\(property.docHTML)</div></body></html>"
docWebView.loadHTMLString(wrappedHTML, baseURL: rootURL)
addSubview(docWebView)
}
}
| mit | 1cc411b855dbe7861b22fbd163b49805 | 30.7 | 278 | 0.723186 | 4.130293 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Services/Scan/S3Service.swift | 2 | 4851 | //
// S3Service.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 22/09/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import AWSS3
import RxSwift
fileprivate let BUCKET = "smartreceipts"
fileprivate let FOLDER = "ocr/"
fileprivate let AMAZON_PREFIX = "https://s3.amazonaws.com/"
class S3Service {
private var transferManager: AWSS3TransferManager!
private var credentialsProvider: AWSCognitoCredentialsProvider!
private let cognitoService = CognitoService()
private let bag = DisposeBag()
init() {
credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityProvider: cognitoService)
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
transferManager = AWSS3TransferManager.default()
AuthService.shared.loggedInObservable
.filter({ !$0 })
.subscribe(onNext: { [weak self] _ in
self?.credentialsProvider.clearCredentials()
}).disposed(by: bag)
}
func upload(image: UIImage) -> Observable<URL> {
if let imageURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("temp.jpg") {
try? image.jpegData(compressionQuality: 1.0)?.write(to: imageURL)
return upload(file: imageURL)
}
return Observable.error(NSError(domain: "temp.image.url.error", code: 1, userInfo: nil))
}
func upload(file url: URL) -> Observable<URL> {
return Observable<URL>.create { [weak self] observer -> Disposable in
if let sSelf = self {
let key = FOLDER + UUID().uuidString + "_\(url.lastPathComponent)"
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = BUCKET
uploadRequest?.key = key
uploadRequest?.body = url
sSelf.transferManager.cancelAll()
sSelf.transferManager.upload(uploadRequest!)
.continueWith(executor: AWSExecutor.mainThread(), block: { (task: AWSTask<AnyObject>) -> Any? in
if let error = task.error {
printError(error, operation: "Upload")
observer.onError(error)
} else {
Logger.debug("Upload complete for: \(uploadRequest!.key!)")
var resultURL = URL(string: AMAZON_PREFIX + BUCKET)
resultURL = resultURL!.appendingPathComponent(uploadRequest!.key!)
observer.onNext(resultURL!)
observer.onCompleted()
}
return nil
})
}
return Disposables.create()
}
}
func downloadImage(_ url: URL, folder: String = FOLDER) -> Observable<UIImage> {
return Observable<UIImage>.create { [weak self] observer -> Disposable in
if let sSelf = self {
let downloadingFileURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(url.lastPathComponent)
let downloadRequest = AWSS3TransferManagerDownloadRequest()
downloadRequest!.bucket = BUCKET
downloadRequest!.key = folder + url.lastPathComponent
downloadRequest!.downloadingFileURL = downloadingFileURL
sSelf.transferManager.download(downloadRequest!)
.continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
if let error = task.error {
printError(error, operation: "Download")
observer.onError(error)
} else {
Logger.debug("Download complete for: \(downloadRequest!.key!)")
let img = UIImage(data: try! Data(contentsOf: downloadingFileURL))
observer.onNext(img!)
observer.onCompleted()
}
return nil
})
}
return Disposables.create()
}
}
}
fileprivate func printError(_ error: Error, operation: String) {
if error.domain == AWSS3TransferManagerErrorDomain,
let code = AWSS3TransferManagerErrorType(rawValue: error.code) {
switch code {
case .cancelled, .paused:
break
default:
Logger.error(operation + " Error: \(error)")
}
} else {
Logger.error(operation + " Error: \(error)")
}
}
| agpl-3.0 | 13600059762e891eda46591ec3171ce4 | 40.810345 | 116 | 0.575258 | 5.43722 | false | false | false | false |
danielsaidi/iExtra | iExtra/Files/DirectoryFileManagerDefault.swift | 1 | 3034 | //
// DirectoryFileManagerDefault.swift
// iExtra
//
// Created by Daniel Saidi on 2016-12-19.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import UIKit
open class DirectoryFileManagerDefault: DirectoryFileManager {
// MARK: - Initialization
public init?(
fileManager: FileManager = .default,
directory: FileManager.SearchPathDirectory) {
guard let dir = fileManager.urls(for: directory, in: .userDomainMask).last else { return nil }
self.directory = dir
self.fileManager = fileManager
}
public init(
fileManager: FileManager = .default,
directoryUrl: URL) {
self.directory = directoryUrl
self.fileManager = fileManager
}
// MARK: - Properties
public let directory: URL
private let fileManager: FileManager
// MARK: - Public Functions
open func createFile(named name: String, contents: Data?) -> Bool {
let url = directory.appendingPathComponent(name)
return fileManager.createFile(atPath: url.path, contents: contents, attributes: nil)
}
open func fileExists(named name: String) -> Bool {
getUrlForFile(named: name) != nil
}
open func getAttributesForFile(named name: String) -> [FileAttributeKey: Any]? {
guard let url = getUrlForFile(named: name) else { return nil }
return try? fileManager.attributesOfItem(atPath: url.path)
}
open func getExistingFileNames(in collection: [String]) -> [String] {
let fileNames = getFileNames()
return collection.filter { fileNames.contains($0) }
}
open func getFileNames() -> [String] {
guard let urls = try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) else { return [] }
return urls.map { $0.lastPathComponent }
}
open func getFileNames(matching fileNamePatterns: [String]) -> [String] {
let patterns = fileNamePatterns.map { $0.lowercased() }
return getFileNames().filter {
let fileName = $0.lowercased()
return patterns.filter { fileName.contains($0) }.first != nil
}
}
open func getSizeOfAllFiles() -> UInt64 {
getFileNames().reduce(0) { $0 + (getSizeOfFile(named: $1) ?? 0) }
}
open func getSizeOfFile(named name: String) -> UInt64? {
guard let attributes = getAttributesForFile(named: name) else { return nil }
let number = attributes[FileAttributeKey.size] as? NSNumber
return number?.uint64Value
}
open func getUrlForFile(named name: String) -> URL? {
let urls = try? fileManager.contentsOfDirectory(atPath: directory.path)
return urls?.first { $0.lastPathComponent == name }
}
open func removeFile(named name: String) -> Bool {
guard let url = getUrlForFile(named: name) else { return false }
return fileManager.removeFile(at: url)
}
}
| mit | 041968e7392d42b99ab71a3a781c5a95 | 32.32967 | 156 | 0.636334 | 4.637615 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/views/ColorPicker/ColorWheel.swift | 1 | 10331 | //
// ColorWheel.swift
// SwiftHSVColorPicker
//
// Created by johankasperi on 2015-08-20.
//
import UIKit
protocol ColorWheelDelegate: class {
func hueAndSaturationSelected(_ hue: CGFloat, saturation: CGFloat)
}
class ColorWheel: UIView {
var color: UIColor!
// Layer for the Hue and Saturation wheel
var wheelLayer: CALayer!
// Overlay layer for the brightness
var brightnessLayer: CAShapeLayer!
var brightness: CGFloat = 1.0
// Layer for the indicator
var indicatorLayer: CAShapeLayer!
var point: CGPoint!
var indicatorCircleRadius: CGFloat = 12.0
var indicatorColor: CGColor = UIColor.lightGray.cgColor
var indicatorBorderWidth: CGFloat = 2.0
// Retina scaling factor
let scale: CGFloat = UIScreen.main.scale
weak var delegate: ColorWheelDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
init(frame: CGRect, color: UIColor!) {
super.init(frame: frame)
self.color = color
// Layer for the Hue/Saturation wheel
wheelLayer = CALayer()
wheelLayer.frame = CGRect(x: 20, y: 20, width: self.frame.width-40, height: self.frame.height-40)
wheelLayer.contents = createColorWheel(wheelLayer.frame.size)
self.layer.addSublayer(wheelLayer)
// Layer for the brightness
brightnessLayer = CAShapeLayer()
brightnessLayer.path = UIBezierPath(roundedRect: CGRect(x: 20.5, y: 20.5, width: self.frame.width-40.5, height: self.frame.height-40.5), cornerRadius: (self.frame.height-40.5)/2).cgPath
self.layer.addSublayer(brightnessLayer)
// Layer for the indicator
indicatorLayer = CAShapeLayer()
indicatorLayer.strokeColor = indicatorColor
indicatorLayer.lineWidth = indicatorBorderWidth
indicatorLayer.fillColor = nil
self.layer.addSublayer(indicatorLayer)
setViewColor(color);
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
indicatorCircleRadius = 18.0
touchHandler(touches)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touchHandler(touches)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
indicatorCircleRadius = 12.0
touchHandler(touches)
}
func touchHandler(_ touches: Set<UITouch>) {
// Set reference to the location of the touch in member point
if let touch = touches.first {
point = touch.location(in: self)
}
let indicator = getIndicatorCoordinate(point)
point = indicator.point
var color = (hue: CGFloat(0), saturation: CGFloat(0))
if !indicator.isCenter {
color = hueSaturationAtPoint(CGPoint(x: point.x*scale, y: point.y*scale))
}
self.color = UIColor(hue: color.hue, saturation: color.saturation, brightness: self.brightness, alpha: 1.0)
// Notify delegate of the new Hue and Saturation
delegate?.hueAndSaturationSelected(color.hue, saturation: color.saturation)
// Draw the indicator
drawIndicator()
}
func drawIndicator() {
// Draw the indicator
if (point != nil) {
indicatorLayer.path = UIBezierPath(roundedRect: CGRect(x: point.x-indicatorCircleRadius, y: point.y-indicatorCircleRadius, width: indicatorCircleRadius*2, height: indicatorCircleRadius*2), cornerRadius: indicatorCircleRadius).cgPath
indicatorLayer.fillColor = self.color.cgColor
}
}
func getIndicatorCoordinate(_ coord: CGPoint) -> (point: CGPoint, isCenter: Bool) {
// Making sure that the indicator can't get outside the Hue and Saturation wheel
let dimension: CGFloat = min(wheelLayer.frame.width, wheelLayer.frame.height)
let radius: CGFloat = dimension/2
let wheelLayerCenter: CGPoint = CGPoint(x: wheelLayer.frame.origin.x + radius, y: wheelLayer.frame.origin.y + radius)
let dx: CGFloat = coord.x - wheelLayerCenter.x
let dy: CGFloat = coord.y - wheelLayerCenter.y
let distance: CGFloat = sqrt(dx*dx + dy*dy)
var outputCoord: CGPoint = coord
// If the touch coordinate is outside the radius of the wheel, transform it to the edge of the wheel with polar coordinates
if (distance > radius) {
let theta: CGFloat = atan2(dy, dx)
outputCoord.x = radius * cos(theta) + wheelLayerCenter.x
outputCoord.y = radius * sin(theta) + wheelLayerCenter.y
}
// If the touch coordinate is close to center, focus it to the very center at set the color to white
let whiteThreshold: CGFloat = 10
var isCenter = false
if (distance < whiteThreshold) {
outputCoord.x = wheelLayerCenter.x
outputCoord.y = wheelLayerCenter.y
isCenter = true
}
return (outputCoord, isCenter)
}
func createColorWheel(_ size: CGSize) -> CGImage {
// Creates a bitmap of the Hue Saturation wheel
let originalWidth: CGFloat = size.width
let originalHeight: CGFloat = size.height
let dimension: CGFloat = min(originalWidth*scale, originalHeight*scale)
let bufferLength: Int = Int(dimension * dimension * 4)
let bitmapData: CFMutableData = CFDataCreateMutable(nil, 0)
CFDataSetLength(bitmapData, CFIndex(bufferLength))
let bitmap = CFDataGetMutableBytePtr(bitmapData)
for y in stride(from: CGFloat(0), to: dimension, by: CGFloat(1)) {
for x in stride(from: CGFloat(0), to: dimension, by: CGFloat(1)) {
var hsv: HSV = (hue: 0, saturation: 0, brightness: 0, alpha: 0)
var rgb: RGB = (red: 0, green: 0, blue: 0, alpha: 0)
let color = hueSaturationAtPoint(CGPoint(x: x, y: y))
let hue = color.hue
let saturation = color.saturation
var a: CGFloat = 0.0
if (saturation < 1.0) {
// Antialias the edge of the circle.
if (saturation > 0.99) {
a = (1.0 - saturation) * 100
} else {
a = 1.0;
}
hsv.hue = hue
hsv.saturation = saturation
hsv.brightness = 1.0
hsv.alpha = a
rgb = hsv2rgb(hsv)
}
let offset = Int(4 * (x + y * dimension))
bitmap?[offset] = UInt8(rgb.red*255)
bitmap?[offset + 1] = UInt8(rgb.green*255)
bitmap?[offset + 2] = UInt8(rgb.blue*255)
bitmap?[offset + 3] = UInt8(rgb.alpha*255)
}
}
// Convert the bitmap to a CGImage
let colorSpace: CGColorSpace? = CGColorSpaceCreateDeviceRGB()
let dataProvider: CGDataProvider? = CGDataProvider(data: bitmapData)
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.last.rawValue)
let imageRef: CGImage? = CGImage(width: Int(dimension), height: Int(dimension), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(dimension) * 4, space: colorSpace!, bitmapInfo: bitmapInfo, provider: dataProvider!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent)
return imageRef!
}
func hueSaturationAtPoint(_ position: CGPoint) -> (hue: CGFloat, saturation: CGFloat) {
// Get hue and saturation for a given point (x,y) in the wheel
let c = wheelLayer.frame.width * scale / 2
let dx = CGFloat(position.x - c) / c
let dy = CGFloat(position.y - c) / c
let d = sqrt(CGFloat (dx * dx + dy * dy))
let saturation: CGFloat = d
var hue: CGFloat
if (d == 0) {
hue = 0;
} else {
hue = acos(dx/d) / CGFloat(Float.pi) / 2.0
if (dy < 0) {
hue = 1.0 - hue
}
}
return (hue, saturation)
}
func pointAtHueSaturation(_ hue: CGFloat, saturation: CGFloat) -> CGPoint {
// Get a point (x,y) in the wheel for a given hue and saturation
let dimension: CGFloat = min(wheelLayer.frame.width, wheelLayer.frame.height)
let radius: CGFloat = saturation * dimension / 2
let x = dimension / 2 + radius * cos(hue * CGFloat(Float.pi) * 2) + 20;
let y = dimension / 2 + radius * sin(hue * CGFloat(Float.pi) * 2) + 20;
return CGPoint(x: x, y: y)
}
func setViewColor(_ color: UIColor!) {
// Update the entire view with a given color
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
self.color = color
self.brightness = brightness
brightnessLayer.fillColor = UIColor(white: 0, alpha: 1.0-self.brightness).cgColor
point = pointAtHueSaturation(hue, saturation: saturation)
drawIndicator()
}
func setViewBrightness(_ _brightness: CGFloat) {
// Update the brightness of the view
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
self.brightness = _brightness
brightnessLayer.fillColor = UIColor(white: 0, alpha: 1.0-self.brightness).cgColor
self.color = UIColor(hue: hue, saturation: saturation, brightness: _brightness, alpha: 1.0)
drawIndicator()
}
}
| mit | f0a063aff2e76810677e1f78a07da943 | 39.996032 | 313 | 0.603136 | 4.432003 | false | false | false | false |
BitGo/keytool-ios | KeyTool/KeyTool/KeyInfoManager.swift | 1 | 27421 | //
// KeyInfoManager.swift
// KeyTool
//
// Created by Huang Yu on 7/29/15.
// Copyright (c) 2015 BitGo, Inc. All rights reserved.
//
import UIKit
import Alamofire
public let BitGoBlueColor: UIColor = UIColor(red: 9.0/256.0, green: 161.0/256.0, blue: 217.0/256.0, alpha: 1.0)
public let BitGoGreenColor: UIColor = UIColor(red: 60.0/256.0, green: 188.0/256.0, blue: 86.0/256.0, alpha: 1.0)
protocol KeyInfoManagerDelegate {
func didGenerateKeyInfo()
func didResetKeyInfo()
}
enum KeyInfoBaseUrl: String {
case Dev = "webdev"
case Prod = "www"
case Test = "test"
case Staging = "staging"
case Local = "local"
var urlString: String {
if self == .Local {
return "https://webdev.bitgo.com/api/v1/coldkey" // redirect to webdev, since it is sync with local db
}
return "https://\(self.rawValue).bitgo.com/api/v1/coldkey"
}
}
class KeyInfoManager: NSObject {
private(set) var keyInfo: KeyInfo = KeyInfo()
private(set) var publicKeyQRCode: UIImage?
private(set) var privateKeyQRCode: UIImage?
static let qrCodeVersion = 1
var signingKey: NSString?
var baseUrl: KeyInfoBaseUrl = .Dev
var delegate: KeyInfoManagerDelegate?
static let sharedManager = KeyInfoManager()
func generate(mnemonic providedMnemonic: NSString? = nil) {
var width = UIScreen.mainScreen().bounds.width
var scale = UIScreen.mainScreen().scale
var size = CGSizeMake(width, width)
// generate the new key
dispatch_async(dispatch_get_main_queue(), {
if let words = KeyInfoManager.mnemonicArray(providedMnemonic as String?) {
self.keyInfo = KeyInfo(words: words)
} else {
var mnemonic = self.generateMnemonicData(128)
self.keyInfo = KeyInfo(data: mnemonic)
}
// generate public key qr code
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.publicKeyQRCode = BTCQRCode.imageForString(
self.keyInfo.publicKey as String,
size: size,
scale: scale
)
// generate private key qr code
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.privateKeyQRCode = BTCQRCode.imageForString(
self.keyInfo.privateKey as String,
size: size,
scale: scale
)
if let delegate = self.delegate {
delegate.didGenerateKeyInfo()
}
})
})
})
}
func reset() {
if self.keyInfo.mnemonic != nil {
self.keyInfo.mnemonic!.clear()
self.keyInfo.mnemonic = nil
}
self.keyInfo = KeyInfo(mnemonic: BTCMnemonic(), publicKey: "", privateKey: "")
self.publicKeyQRCode = nil
self.privateKeyQRCode = nil
self.signingKey = nil
if let delegate = self.delegate {
delegate.didResetKeyInfo()
}
}
func postRequest(completionHandler: (Bool, AnyObject?, NSError?) -> ()) {
if self.signingKey == nil {
return
}
let parameters = [
"id": self.signingKey,
"xpub": self.keyInfo.publicKey
]
let headers = [
"Content-Type": "application/json; charset=utf-8"
]
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"bitgo.com": .PinCertificates(
certificates: ServerTrustPolicy.certificatesInBundle(),
validateCertificateChain: true,
validateHost: true
)
]
Alamofire.Manager(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
Alamofire.request(
.POST,
baseUrl.urlString,
parameters: parameters,
encoding: .JSON,
headers: headers
).responseJSON { _, _, JSON, err in
// println(JSON)
if let json = JSON as? [String:String] {
completionHandler(true, json, nil)
} else {
completionHandler(false, nil, err)
}
}
}
func generateMnemonicData(strength: Int, language: String = "english") -> NSData {
if strength % 32 != 0 {
NSException(
name: "Strength must be divisible by 32",
reason: "Strength was: \(strength)",
userInfo: nil
)
}
var bytes = UnsafeMutablePointer<UInt8>.alloc(strength / 8)
var status = SecRandomCopyBytes(kSecRandomDefault, strength / 8, bytes)
if status != -1 {
return NSData(bytes: bytes, length: strength / 8)
} else {
return NSData()
}
}
class func safeMnemonicString(string mnString: String?) -> String? {
if let mn = mnString?.lowercaseString {
if let
regEx = NSRegularExpression(
pattern: "[ ]+",
options: NSRegularExpressionOptions.allZeros,
error: nil
),
removeTrailingRegEx = NSRegularExpression(
pattern: "[ ]+$",
options: NSRegularExpressionOptions.AnchorsMatchLines,
error: nil
),
noTrailingString = removeTrailingRegEx.stringByReplacingMatchesInString(
mn,
options: NSMatchingOptions.allZeros,
range: NSMakeRange(0, count(mn)),
withTemplate: ""
) as String?,
cleanString = regEx.stringByReplacingMatchesInString(
noTrailingString,
options: NSMatchingOptions.allZeros,
range: NSMakeRange(0, count(noTrailingString)),
withTemplate: " "
) as String?
{
return cleanString
}
}
return nil
}
class func mnemonicArray(string: String?) -> [String]? {
if let safeString = KeyInfoManager.safeMnemonicString(string: string) {
return safeString.componentsSeparatedByString(" ")
}
return nil
}
static let wordList: [String] = ["abandon", "ability", "able", "about", "above",
"absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve",
"acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add",
"addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid",
"again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol",
"alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always",
"amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry",
"animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart",
"apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed",
"armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork",
"ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend",
"attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado",
"avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon",
"badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain",
"barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef",
"before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray",
"better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter",
"black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse",
"blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border",
"boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave",
"bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze",
"broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk",
"bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer",
"buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can",
"canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car",
"carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat",
"catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement",
"census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter",
"charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child",
"chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle",
"citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click",
"client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club",
"clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect",
"color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct",
"confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy",
"coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin",
"cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream",
"credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd",
"crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup",
"cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage",
"damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade",
"december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree",
"delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth",
"deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect",
"develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ",
"digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease",
"dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor",
"document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove",
"draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive",
"drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager",
"eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit",
"educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant",
"elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty",
"enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance",
"enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode",
"equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence",
"estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess",
"exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist",
"exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye",
"eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous",
"fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite",
"feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever",
"few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger",
"finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash",
"flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly",
"foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork",
"fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh",
"friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace",
"fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden",
"garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle",
"genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad",
"glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat",
"goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain",
"grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow",
"grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer",
"hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head",
"health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high",
"hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home",
"honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub",
"huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband",
"hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image",
"imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income",
"increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit",
"initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect",
"inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island",
"isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel",
"job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just",
"kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit",
"kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder",
"lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law",
"lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal",
"legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar",
"liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid",
"list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long",
"loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch",
"luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal",
"man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine",
"market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum",
"maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member",
"memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method",
"middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror",
"misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment",
"monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion",
"motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum",
"mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow",
"nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve",
"nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee",
"noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear",
"number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious",
"occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive",
"olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option",
"orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich",
"other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster",
"ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper",
"parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern",
"pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil",
"people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano",
"picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch",
"pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem",
"poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position",
"possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict",
"prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority",
"prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote",
"proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse",
"pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle",
"pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon",
"race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range",
"rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild",
"recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region",
"regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove",
"render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble",
"resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review",
"reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring",
"riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance",
"roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug",
"rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon",
"salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale",
"scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap",
"screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security",
"seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service",
"session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff",
"shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove",
"shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk",
"silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate",
"sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide",
"slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack",
"snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier",
"solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source",
"south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere",
"spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray",
"spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs",
"stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still",
"sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong",
"struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such",
"sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply",
"supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow",
"swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom",
"syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task",
"taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text",
"thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive",
"throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired",
"tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato",
"tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado",
"tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic",
"tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe",
"trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust",
"truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty",
"twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle",
"uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown",
"unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban",
"urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid",
"valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor",
"venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious",
"victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual",
"vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait",
"walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave",
"way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome",
"west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife",
"wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish",
"witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap",
"wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra",
"zero", "zone", "zoo"]
}
| apache-2.0 | 61dc009610566c411d68bf38cf39ab8d | 70.971129 | 118 | 0.534627 | 3.224103 | false | false | false | false |
SanctionCo/pilot-ios | pilot/PostsViewController.swift | 1 | 5941 | //
// HistoryViewController.swift
// pilot
//
// Created by Nick Eckert on 11/19/17.
// Copyright © 2017 sanction. All rights reserved.
//
import CoreData
import UIKit
class PostsViewController: UIViewController {
var posts: [Post] = [Post]()
var containerView: UIView = {
let container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = UIColor.white
return container
}()
var postsTableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
var postsEmptyView: UIView = {
let emptyView = UIView()
emptyView.translatesAutoresizingMaskIntoConstraints = false
return emptyView
}()
var postsEmptyImage: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "bulb"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = UIColor.TextGray
return imageView
}()
var postsEmptyMessage: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "There are no posts to show..."
label.textColor = UIColor.TextGray
label.font = label.font?.withSize(15)
label.textAlignment = .center
label.sizeToFit()
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Set the right bar button item to a plus image
let composeButton = UIBarButtonItem(image: #imageLiteral(resourceName: "plus"), style: .plain, target: self, action: #selector(self.compose))
self.navigationItem.rightBarButtonItem = composeButton
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.topItem?.title = "Posts"
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationItem.largeTitleDisplayMode = .never
self.postsTableView.delegate = self
self.postsTableView.dataSource = self
self.postsTableView.rowHeight = 50
self.postsTableView.separatorStyle = .none
self.postsTableView.register(PostsTableViewCell.self, forCellReuseIdentifier: "PostsTableViewCell")
self.view.addSubview(containerView)
setupContainerView()
}
@objc func compose(_ sender: UIBarButtonItem) {
let composeViewController = ComposeViewController()
let composeNavigationController = UINavigationController(rootViewController: composeViewController)
self.present(composeNavigationController, animated: true, completion: nil)
}
func setupContainerView() {
self.containerView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.containerView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.containerView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.containerView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.containerView.addSubview(postsTableView)
self.containerView.addSubview(postsEmptyView)
self.containerView.sendSubview(toBack: postsEmptyView)
setupPostsEmptyView()
setupPostsTableView()
}
func setupPostsTableView() {
postsTableView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
postsTableView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
postsTableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
postsTableView.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
}
func setupPostsEmptyView() {
// Setup the postEmptyView
postsEmptyView.widthAnchor.constraint(equalToConstant: 300).isActive = true
postsEmptyView.heightAnchor.constraint(equalToConstant: 200).isActive = true
postsEmptyView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
postsEmptyView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
postsEmptyView.addSubview(postsEmptyImage)
postsEmptyView.addSubview(postsEmptyMessage)
// Position the history empty image
postsEmptyImage.topAnchor.constraint(equalTo: postsEmptyView.topAnchor).isActive = true
postsEmptyImage.centerXAnchor.constraint(equalTo: postsEmptyView.centerXAnchor).isActive = true
postsEmptyImage.heightAnchor.constraint(equalToConstant: 75).isActive = true
postsEmptyImage.widthAnchor.constraint(equalToConstant: 75).isActive = true
// Position the history empty message
postsEmptyMessage.topAnchor.constraint(equalTo: postsEmptyImage.bottomAnchor, constant: 15).isActive = true
postsEmptyMessage.centerXAnchor.constraint(equalTo: postsEmptyView.centerXAnchor).isActive = true
postsEmptyMessage.widthAnchor.constraint(equalTo: postsEmptyView.widthAnchor).isActive = true
}
}
extension PostsViewController: UITableViewDataSource, UITableViewDelegate {
// MARK: HistoryTableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func numberOfSections(in tableView: UITableView) -> Int {
if posts.count == 0 {
// Hide the tableView to reveal the empty talbeView custom view
tableView.isHidden = true
return 0
}
// Display the tableView to show it's cells and hide the empty tableView custom view
tableView.isHidden = false
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostsTableViewCell") as? PostsTableViewCell else {
fatalError("Wrong cell type dequed!")
}
// Configure cell here
return cell
}
}
| mit | 26c182900b7be285432e7c63c7a64565 | 35.666667 | 145 | 0.764815 | 5.178727 | false | false | false | false |
hxx0215/VPNOn | VPNOn/Theme/LTThemeManager.swift | 1 | 3898 | //
// LTThemeManager.swift
// VPNOn
//
// Created by Lex on 1/15/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
let kLTCurrentThemeIndexKey = "CurrentThemeIndex"
class LTThemeManager
{
var currentTheme : LTTheme? = .None
let themes: [LTTheme] = [LTDarkTheme(), LTLightTheme(), LTHelloKittyTheme(), LTDarkGreenTheme(), LTDarkPurpleTheme()]
class var sharedManager : LTThemeManager
{
struct Static
{
static let sharedInstance = LTThemeManager()
}
return Static.sharedInstance
}
var themeIndex: Int {
get {
if let index = NSUserDefaults.standardUserDefaults().objectForKey(kLTCurrentThemeIndexKey) as? NSNumber {
if index.isKindOfClass(NSNumber.self) {
return min(themes.count - 1, index.integerValue ?? 0)
}
}
return 0
}
set {
let newNumber = NSNumber(integer: newValue)
NSUserDefaults.standardUserDefaults().setObject(newNumber, forKey: kLTCurrentThemeIndexKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func activateTheme() {
activateTheme(themes[themeIndex])
}
func activateTheme(theme : LTTheme)
{
currentTheme = theme
UIWindow.appearance().tintColor = theme.tintColor
LTViewControllerBackground.appearance().backgroundColor = theme.defaultBackgroundColor
// Switch
UISwitch.appearance().tintColor = theme.switchBorderColor
UISwitch.appearance().onTintColor = theme.tintColor
UISwitch.appearance().thumbTintColor = theme.switchBorderColor
// Navigation
UINavigationBar.appearance().barTintColor = theme.navigationBarColor
UINavigationBar.appearance().tintColor = theme.tintColor
UINavigationBar.appearance().backgroundColor = UIColor.clearColor()
UINavigationBar.appearance().titleTextAttributes = NSDictionary(objects: [theme.textColor], forKeys: [NSForegroundColorAttributeName]) as [NSObject : AnyObject]
// TableView
UITableView.appearance().backgroundColor = theme.tableViewBackgroundColor
UITableView.appearance().separatorColor = theme.tableViewLineColor
UITableViewCell.appearance().backgroundColor = theme.tableViewCellColor
UITableViewCell.appearance().tintColor = theme.tintColor
UITableViewCell.appearance().selectionStyle = UITableViewCellSelectionStyle.None
UILabel.lt_appearanceWhenContainedIn(UITableViewHeaderFooterView.self).textColor = theme.textColor
LTTableViewCellTitle.appearance().textColor = theme.textColor
UILabel.lt_appearanceWhenContainedIn(LTTableViewActionCell.self).textColor = theme.tintColor
UILabel.lt_appearanceWhenContainedIn(LTVPNTableViewCell.self).textColor = theme.textColor
UITextView.lt_appearanceWhenContainedIn(UITableViewCell.self).backgroundColor = theme.tableViewCellColor
UITextView.lt_appearanceWhenContainedIn(UITableViewCell.self).textColor = theme.textColor
// TextField
UITextField.appearance().tintColor = theme.tintColor
UITextField.appearance().textColor = theme.textFieldColor
}
func activateNextTheme()
{
var index = themeIndex
index++
if index >= themes.count {
themeIndex = 0
} else {
themeIndex = index
}
activateTheme(themes[themeIndex])
let windows = UIApplication.sharedApplication().windows
for window in windows {
for view in window.subviews {
view.removeFromSuperview()
window.addSubview(view as! UIView)
}
}
}
}
| mit | 5d3fa2e3b217c2654495227463fdedd7 | 35.092593 | 168 | 0.655464 | 5.826607 | false | false | false | false |
wavecos/curso_ios_3 | TestMVC/TestMVC/ViewController.swift | 1 | 1591 | //
// ViewController.swift
// TestMVC
//
// Created by onix on 10/25/14.
// Copyright (c) 2014 tekhne. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var saludoLabel: UILabel!
@IBOutlet weak var okButton: UIButton!
@IBOutlet weak var nombreTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println("Entre al ViewController")
nombreTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func okTapped(sender: AnyObject) {
println("El boton se ha presionado...")
saludar()
}
func saludar() {
saludoLabel.text = "Hola " + nombreTextField.text
//saludoLabel.textColor = UIColor.greenColor()
saludoLabel.textColor = UIColor(red: 0.5, green: 0.3, blue: 0.2, alpha: 1)
// okButton.enabled = false
self.view.backgroundColor = UIColor(red: randomValue(),green: randomValue(), blue:randomValue(), alpha: 1)
}
func randomValue() -> CGFloat {
return CGFloat(rand()) / CGFloat(UINT32_MAX)
}
// Metodos del UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
println("el usuario comenzo a escribir")
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
println("se ha presionado Return")
nombreTextField.resignFirstResponder()
saludar()
return true
}
}
| apache-2.0 | 8c880876764cf1d114da50f43ecc310b | 25.516667 | 110 | 0.69516 | 4.175853 | false | false | false | false |
soapyigu/LeetCode_Swift | Tree/PathSum.swift | 1 | 797 | /**
* Question Link: https://leetcode.com/problems/path-sum/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class PathSum {
func hasPathSum(root: TreeNode?, _ sum: Int) -> Bool {
guard let root = root else {
return false
}
if sum == root.val && root.left == nil && root.right == nil {
return true
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
}
} | mit | c0220f921d89a3e01929d07835094e21 | 25.6 | 94 | 0.548306 | 3.558036 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/LanguageRowItem.swift | 1 | 4868 | //
// LanguageRowItem.swift
// Telegram
//
// Created by keepcoder on 25/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
class LanguageRowItem: GeneralRowItem {
fileprivate let selected:Bool
fileprivate let locale:TextViewLayout
fileprivate let title:TextViewLayout
fileprivate let deleteAction: ()->Void
fileprivate let deletable: Bool
fileprivate let _stableId:AnyHashable
override var stableId: AnyHashable {
return _stableId
}
init(initialSize: NSSize, stableId: AnyHashable, selected: Bool, deletable: Bool, value:LocalizationInfo, viewType: GeneralViewType = .legacy, action:@escaping()->Void, deleteAction: @escaping()->Void = {}, reversed: Bool = false) {
self._stableId = stableId
self.selected = selected
self.title = TextViewLayout(.initialize(string: reversed ? value.localizedTitle : value.title, color: theme.colors.text, font: .normal(.title)), maximumNumberOfLines: 1)
self.locale = TextViewLayout(.initialize(string: reversed ? value.title : value.localizedTitle, color: reversed ? theme.colors.grayText : theme.colors.grayText, font: .normal(.text)), maximumNumberOfLines: 1)
self.deletable = deletable
self.deleteAction = deleteAction
super.init(initialSize, viewType: viewType, action: action)
_ = makeSize(initialSize.width, oldWidth: initialSize.width)
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
locale.measure(width: width - 100)
title.measure(width: width - 100)
return true
}
override var height: CGFloat {
return 48
}
override func viewClass() -> AnyClass {
return LanguageRowView.self
}
}
class LanguageRowView : TableRowView {
private let localeTextView:TextView = TextView()
private let titleTextView:TextView = TextView()
private let selectedImage:ImageView = ImageView()
private let overalay:OverlayControl = OverlayControl()
private let deleteButton = ImageButton()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(titleTextView)
addSubview(localeTextView)
addSubview(selectedImage)
selectedImage.sizeToFit()
localeTextView.isSelectable = false
titleTextView.isSelectable = false
addSubview(overalay)
overalay.set(background: .grayTransparent, for: .Highlight)
addSubview(deleteButton)
overalay.set(handler: { [weak self] _ in
if let item = self?.item as? LanguageRowItem {
item.action()
}
}, for: .Click)
deleteButton.set(handler: { [weak self] _ in
if let item = self?.item as? LanguageRowItem {
item.deleteAction()
}
}, for: .Click)
}
override var backdorColor: NSColor {
return theme.colors.background
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
overalay.setFrameSize(newSize)
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated: animated)
if let item = item as? LanguageRowItem {
titleTextView.update(item.title)
localeTextView.update(item.locale)
deleteButton.set(image: theme.icons.customLocalizationDelete, for: .Normal)
_ = deleteButton.sizeToFit()
selectedImage.image = theme.icons.generalSelect
selectedImage.sizeToFit()
titleTextView.backgroundColor = theme.colors.background
localeTextView.backgroundColor = theme.colors.background
selectedImage.isHidden = !item.selected
deleteButton.isHidden = !item.deletable || item.selected
needsLayout = true
}
}
override func layout() {
super.layout()
selectedImage.centerY(x: frame.width - 25 - selectedImage.frame.width)
deleteButton.centerY(x: frame.width - 18 - deleteButton.frame.width)
if let item = item as? LanguageRowItem {
titleTextView.update(item.title, origin: NSMakePoint(25, 5))
localeTextView.update(item.locale, origin: NSMakePoint(25, frame.height - titleTextView.frame.height - 5))
}
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
ctx.setFillColor(theme.colors.border.cgColor)
ctx.fill(NSMakeRect(25, frame.height - .borderSize, frame.width - 50, .borderSize))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 81aea5cf61a363f51f6b2e70cbfcb103 | 34.786765 | 236 | 0.641463 | 4.837972 | false | false | false | false |
nearspeak/iOS-SDK | NearspeakDemo/DiscoveryTableViewController.swift | 1 | 5911 | //
// DiscoveryTableViewController.swift
// NearspeakKit
//
// Created by Patrick Steiner on 23.04.15.
// Copyright (c) 2015 Mopius. All rights reserved.
//
import UIKit
import NearspeakKit
class DiscoveryTableViewController: UITableViewController {
var nearbyTags = [NSKTag]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Discovery"
let stopMonitoringButton = UIBarButtonItem(title: "Stop Monitoring", style: .Plain, target: self, action: #selector(DiscoveryTableViewController.stopMonitoring))
self.navigationItem.rightBarButtonItem = stopMonitoringButton
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setupNotifications()
// true: show all beacons, also if the beacon has not data set on the server
NSKManager.sharedInstance.startBeaconDiscovery(true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSKManager.sharedInstance.stopBeaconDiscovery()
removeNotifications()
}
// MARK: - Notifications
private func setupNotifications() {
// get notifications for if beacons updates appear
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(DiscoveryTableViewController.onNearbyTagsUpdatedNotification(_:)),
name: NSKConstants.managerNotificationNearbyTagsUpdatedKey,
object: nil)
// get notification if bluetooth state changes
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(DiscoveryTableViewController.onBluetoothErrorNotification(_:)),
name: NSKConstants.managerNotificationBluetoothErrorKey,
object: nil)
// get notifications if location state changes
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(DiscoveryTableViewController.onLocationErrorNotification(_:)),
name: NSKConstants.managerNotificationLocationErrorKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(DiscoveryTableViewController.onLocationOnlyWhenInUseNotification(_:)),
name: NSKConstants.managerNotificationLocationWhenInUseOnKey,
object: nil)
}
private func removeNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(NSKConstants.managerNotificationNearbyTagsUpdatedKey)
NSNotificationCenter.defaultCenter().removeObserver(NSKConstants.managerNotificationBluetoothErrorKey)
NSNotificationCenter.defaultCenter().removeObserver(NSKConstants.managerNotificationLocationErrorKey)
NSNotificationCenter.defaultCenter().removeObserver(NSKConstants.managerNotificationLocationWhenInUseOnKey)
}
func onNearbyTagsUpdatedNotification(notification: NSNotification) {
// refresh the table view
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// copy the nearbyTags from the shared instance
self.nearbyTags = NSKManager.sharedInstance.nearbyTags
self.tableView.reloadData()
})
}
func onBluetoothErrorNotification(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let alertController = UIAlertController(title: "Bluetooth Error", message: "Turn on bluetooth", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
})
}
func onLocationErrorNotification(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let alertController = UIAlertController(title: "Location Error", message: "Turn on location for this app.", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
})
}
func onLocationOnlyWhenInUseNotification(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let alertController = UIAlertController(title: "Location Error", message: "Background scanning disabled.", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
})
}
// MARK: - Beacon Monitoring
func stopMonitoring() {
NSKManager.sharedInstance.stopBeaconMonitoring()
}
}
// MARK: - Table view data source
extension DiscoveryTableViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nearbyTags.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tagCell", forIndexPath: indexPath)
// get the current NSKTag item
let tag = nearbyTags[indexPath.row]
cell.textLabel?.text = tag.titleString()
if let uuidString = tag.hardwareBeacon?.proximityUUID.UUIDString {
cell.detailTextLabel?.text = "UUID: " + uuidString
}
return cell
}
}
| lgpl-3.0 | b363afd7923adc826252782cdb192b45 | 38.939189 | 169 | 0.676535 | 5.645654 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/swift/Swift Standard Library 2.playground/Pages/Indexing and Slicing Strings.xcplaygroundpage/Sources/Message.swift | 6 | 1308 | import Foundation
public struct Message {
public let from: String
public let contents: String
public let date: Date
public init(from: String, contents: String, date: Date) {
self.from = from
self.contents = contents
self.date = date
}
}
extension Message: CustomDebugStringConvertible {
public var debugDescription: String {
return "[\(date) From: \(from)] \(contents)"
}
}
private var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.doesRelativeDateFormatting = true
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
extension Message: CustomStringConvertible {
public var description: String {
return "\(contents)\n \(from) \(dateFormatter.string(from: date))"
}
}
public var messages: [Message] = [
Message(from: "Sandy", contents: "Hey, what's going on tonight?", date: messageDates[0]),
Message(from: "Michelle", contents: "Studying for Friday's exam. You guys aren't?", date: messageDates[1]),
Message(from: "Christian", contents: "Nope. That's what tomorrow is for. Let's get food, I'm hungry!", date: messageDates[2]),
Message(from: "Michelle", contents: "Maybe. What do you want to eat?", date: messageDates[3])
]
| mit | 53364220146e46fc0a127ab3b131b4a0 | 30.902439 | 130 | 0.66896 | 4.139241 | false | false | false | false |
antitypical/Manifold | Manifold/Declaration.swift | 1 | 1196 | // Copyright © 2015 Rob Rix. All rights reserved.
public typealias DefinitionType = (symbol: Name, type: Term, value: Term)
public enum Declaration: CustomStringConvertible {
public init(_ symbol: Name, type: Term, value: Term) {
self = .Definition(symbol, type, value)
}
public init(_ symbol: Name, _ datatype: Manifold.Datatype) {
self = .Datatype(symbol, datatype)
}
public var definitions: [DefinitionType] {
switch self {
case let .Definition(symbol, type, value):
return [ (symbol, type, value) ]
case let .Datatype(symbol, datatype):
return datatype.definitions(symbol)
}
}
public var description: String {
switch self {
case let .Definition(symbol, type, value):
return "\(symbol) : \(type)\n"
+ "\(symbol) = \(value)"
case let .Datatype(symbol, datatype):
let definition = datatype.definitions(symbol)[0]
return "data \(symbol) : \(definition.type) = \(definition.value)"
}
}
case Definition(Name, Term, Term)
case Datatype(Name, Manifold.Datatype)
public var ref: Term {
switch self {
case let .Definition(symbol, _, _):
return .Variable(symbol)
case let .Datatype(symbol, _):
return .Variable(symbol)
}
}
}
| mit | 44cef40dfef5397d679a7f09d48959cb | 23.387755 | 73 | 0.674477 | 3.414286 | false | false | false | false |
russbishop/swift | test/SourceKit/CodeComplete/complete_inner.swift | 1 | 5131 | // XFAIL: broken_std_regex
class Foo {}
class Base {
init() {}
func base() {}
}
class FooBar {
init() {}
init(x: Foo) {}
static func fooBar() {}
static func fooBaz() {}
func method() {}
let prop: FooBar { return FooBar() }
subscript(x: Foo) -> Foo {}
}
func test001() {
#^TOP_LEVEL_0,fo,foo,foob,foobar^#
}
// RUN: %complete-test %s -no-fuzz -group=none -add-inner-results -tok=TOP_LEVEL_0 | FileCheck %s -check-prefix=TOP_LEVEL_0
// TOP_LEVEL_0-LABEL: Results for filterText: fo [
// TOP_LEVEL_0-NEXT: for
// TOP_LEVEL_0-NEXT: Foo
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foo [
// TOP_LEVEL_0-NEXT: Foo
// TOP_LEVEL_0-NEXT: Foo(
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: Foo()
// TOP_LEVEL_0-NEXT: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foob [
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foobar [
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: FooBar.
// TOP_LEVEL_0-NEXT: FooBar(
// TOP_LEVEL_0-NEXT: FooBar()
// TOP_LEVEL_0-NEXT: FooBar(x: Foo)
// TOP_LEVEL_0-NEXT: FooBar.fooBar()
// TOP_LEVEL_0-NEXT: FooBar.fooBaz()
// TOP_LEVEL_0: ]
func test002(abc: FooBar, abd: Base) {
#^TOP_LEVEL_1,ab,abc,abd^#
}
// RUN: %complete-test %s -no-fuzz -group=none -add-inner-results -tok=TOP_LEVEL_1 | FileCheck %s -check-prefix=TOP_LEVEL_1
// TOP_LEVEL_1-LABEL: Results for filterText: ab [
// TOP_LEVEL_1-NEXT: abc
// TOP_LEVEL_1-NEXT: abd
// TOP_LEVEL_1: ]
// TOP_LEVEL_1-LABEL: Results for filterText: abc [
// TOP_LEVEL_1-NEXT: abc
// TOP_LEVEL_1-NEXT: abc.
// TOP_LEVEL_1-NEXT: abc===
// TOP_LEVEL_1-NEXT: abc!==
// TOP_LEVEL_1-NEXT: abc.method()
// TOP_LEVEL_1-NEXT: abc.prop
// TOP_LEVEL_1-NEXT: ]
// TOP_LEVEL_1-LABEL: Results for filterText: abd [
// TOP_LEVEL_1-NEXT: abd
// TOP_LEVEL_1-NEXT: abd.
// TOP_LEVEL_1-NEXT: abd===
// TOP_LEVEL_1-NEXT: abd!==
// TOP_LEVEL_1-NEXT: abd.base()
// TOP_LEVEL_1-NEXT: ]
func test003(x: FooBar) {
x.#^FOOBAR_QUALIFIED,pro,prop,prop.^#
}
// RUN: %complete-test %s -group=none -add-inner-results -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED
// FOOBAR_QUALIFIED-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED-NEXT: prop
// FOOBAR_QUALIFIED-NEXT: ]
// FOOBAR_QUALIFIED-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED-NEXT: prop
// FOOBAR_QUALIFIED-NEXT: prop.
// FOOBAR_QUALIFIED: prop.method()
// FOOBAR_QUALIFIED-NEXT: prop.prop
// FOOBAR_QUALIFIED-NEXT: ]
// Just don't explode. We generally expect to get a new session here.
// FOOBAR_QUALIFIED-LABEL: Results for filterText: prop. [
// FOOBAR_QUALIFIED-NEXT: ]
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_OP
// FOOBAR_QUALIFIED_OP-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED_OP-NEXT: prop
// FOOBAR_QUALIFIED_OP-NEXT: ]
// FOOBAR_QUALIFIED_OP-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_OP-NEXT: prop
// FOOBAR_QUALIFIED_OP-NEXT: prop.
// FOOBAR_QUALIFIED_OP: ]
// RUN: %complete-test %s -group=none -add-inner-results -no-inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_NOOP
// FOOBAR_QUALIFIED_NOOP-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED_NOOP-NEXT: prop
// FOOBAR_QUALIFIED_NOOP-NEXT: ]
// FOOBAR_QUALIFIED_NOOP-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_NOOP-NEXT: prop
// FOOBAR_QUALIFIED_NOOP-NEXT: prop.method()
// FOOBAR_QUALIFIED_NOOP-NEXT: prop.prop
// FOOBAR_QUALIFIED_NOOP-NEXT: ]
// RUN: %complete-test %s -group=none -no-include-exact-match -add-inner-results -no-inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_NOEXACT
// FOOBAR_QUALIFIED_NOEXACT-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_NOEXACT-NEXT: prop.method()
// FOOBAR_QUALIFIED_NOEXACT-NEXT: prop.prop
// FOOBAR_QUALIFIED_NOEXACT-NEXT: ]
func test004() {
FooBar#^FOOBAR_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_POSTFIX | FileCheck %s -check-prefix=FOOBAR_POSTFIX_OP
// FOOBAR_POSTFIX_OP: {{^}}.{{$}}
// FOOBAR_POSTFIX_OP: {{^}}({{$}}
func test005(x: FooBar) {
x#^FOOBAR_INSTANCE_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_INSTANCE_POSTFIX | FileCheck %s -check-prefix=FOOBAR_INSTANCE_POSTFIX_OP
// FOOBAR_INSTANCE_POSTFIX_OP: .
// FIXME: We should probably just have '[' here - rdar://22702955
// FOOBAR_INSTANCE_POSTFIX_OP: [Foo]
func test005(x: Base?) {
x#^OPTIONAL_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=OPTIONAL_POSTFIX | FileCheck %s -check-prefix=OPTIONAL_POSTFIX_OP
// OPTIONAL_POSTFIX_OP: .
// OPTIONAL_POSTFIX_OP: ?.
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=KEYWORD_0 | FileCheck %s -check-prefix=KEYWORD_0
func test006() {
#^KEYWORD_0,for^#
}
// KEYWORD_0-NOT: for_
// KEYWORD_0-NOT: fortest
// KEYWORD_0-NOT: for.
| apache-2.0 | c91f34525bc1f5ad46b0e62570dc2111 | 34.143836 | 176 | 0.67862 | 2.799236 | false | true | false | false |
SonnyBrooks/ProjectEulerSwift | ProjectEulerSwift/IntUtility.swift | 1 | 964 | //
// IntUtility.swift
// ProjectEulerSwift
//
// Created by Andrew Budziszek on 11/6/16.
// Copyright © 2016 Andrew Budziszek. All rights reserved.
//
import Foundation
extension Int {
func squareroot() -> Int {
return Int(sqrt(Double(self)))
}
func isEven() -> Bool {
return self % 2 == 0
}
func isOdd() -> Bool {
return self % 2 != 0
}
/*
Uses the 6k ± 1 Primality Test
Ref: https://en.wikipedia.org/wiki/Primality_test
*/
func isPrime() -> Bool {
if self <= 1{
return false
}else if self <= 3{
return true
}else if self % 2 == 0 || self % 3 == 0 {
return false
}
var i = 5
while i * i <= self {
if self % i == 0 || self % (i + 2) == 0 {
return false
}
i = i + 6
}
return true
}
}
| mit | e6828b8ba70674a81010fbe03d277e15 | 19.041667 | 59 | 0.443867 | 3.879032 | false | false | false | false |
entaq/GoogleMapsAndAppleMaps | GoogleMapsAndAppleMaps/ViewController.swift | 1 | 1576 | import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
@IBOutlet weak var googleMapView: GMSMapView!
@IBOutlet weak var appleMapView: MKMapView!
var manager : CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager?.requestAlwaysAuthorization()
var googleCamera = GMSCameraPosition.cameraWithLatitude(-33.86,
longitude: 151.20, zoom: 12)
googleMapView.camera = googleCamera
googleMapView.myLocationEnabled = true
googleMapView.settings.myLocationButton = true
var marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = googleMapView
appleMapView.setCenterCoordinate(CLLocationCoordinate2DMake(
-33.86, 151.20), animated: true)
var appleCamera = MKMapCamera(lookingAtCenterCoordinate: CLLocationCoordinate2DMake(
-33.86, 151.20), fromEyeCoordinate: CLLocationCoordinate2DMake(
-33.86, 151.20), eyeAltitude: 30000)!
var point = MKPointAnnotation()
point.coordinate = CLLocationCoordinate2DMake(-33.86, 151.20)
point.title = "Sydney";
point.subtitle = "Australia";
appleMapView.showsUserLocation = true
appleMapView.addAnnotation(point)
// appleMapView.setCamera(appleCamera, animated: true)
}
}
| mit | de10d8942bb509baeed79baf43d19ac8 | 33.26087 | 92 | 0.654822 | 5.100324 | false | false | false | false |
jindulys/GithubPilot | Sources/Helpers/Helper.swift | 2 | 1889 | //
// Helper.swift
// Pods
//
// Created by yansong li on 2016-03-25.
//
//
import Foundation
/**
Special URL query escape for `GithubSearch`, this one will not escape `+`, otherwise search could not wokr.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
func githubSearchURLQueryEscape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*,;="
let allowedCharacterSet = (CharacterSet.urlQueryAllowed as NSCharacterSet).mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharacters(in: generalDelimitersToEncode + subDelimitersToEncode)
var escaped = ""
if #available(iOS 10.0, OSX 10.12, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
var endIndex: String.Index
if let batchedEndIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) {
endIndex = batchedEndIndex
} else {
endIndex = string.endIndex
}
let range = (startIndex ..< endIndex)
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
/**
Creates percent-escaped, URL encoded query string components from the given key-value pair.
*/
func githubSearchQueryComponents(_ key: String, _ value: String) -> [(String, String)] {
var components: [(String, String)] = []
components.append((githubSearchURLQueryEscape(key), githubSearchURLQueryEscape(value)))
return components
}
| mit | 99f14d13711d4443a9b643e10a4fee07 | 31.016949 | 120 | 0.687665 | 4.710723 | false | false | false | false |
clarkcb/xsearch | swift/swiftsearch/Sources/swiftsearch/common.swift | 1 | 2338 | //
// common.swift
// swiftsearch
//
// Created by Cary Clark on 5/20/15.
// Copyright (c) 2015 Cary Clark. All rights reserved.
//
import Foundation
public let whitespace = CharacterSet(charactersIn: " \t\r\n")
public func logMsg(_ str: String) {
print(str)
}
public func logError(_ str: String) {
logMsg("ERROR: \(str)")
}
public func setError(_ error: NSErrorPointer, msg: String) {
error?.pointee = NSError(domain: msg, code: 1, userInfo: [:])
}
// from http://ijoshsmith.com/2014/06/18/create-a-swift-dictionary-from-an-array/
func toDictionary<E, K, V>(
_ array: [E],
transformer: (_ element: E) -> (key: K, value: V)?
) -> [K: V] {
array.reduce([:]) { dict, e in
var d = dict
if let (key, value) = transformer(e) {
d[key] = value
}
return d
}
}
func arrayToString(_ arr: [String]) -> String {
var str: String = "["
var count: Int = 0
for elem in arr {
if count > 0 {
str += ", "
}
str += "\"\(elem)\""
count += 1
}
str += "]"
return str
}
func arrayToString(_ arr: [Regex]) -> String {
arrayToString(arr.map(\.pattern))
}
func setToString(_ set: Set<String>) -> String {
arrayToString(Array(set.sorted()))
}
func take<T>(_ seq: [T], num: Int) -> [T] {
var newSeq: [T] = []
var taken = 0
while taken < num, taken < seq.count {
newSeq.append(seq[taken])
taken += 1
}
return newSeq
}
func takeRight<T>(_ seq: [T], num: Int) -> [T] {
var right: [T] = []
var sub = 1
while sub <= num, sub <= seq.count {
right.append(seq[seq.count - sub])
sub += 1
}
return Array(right.reversed())
}
// for printing the borders in multiline search results
extension String {
func `repeat`(_ n: Int) -> String {
var result = self
for _ in 1 ..< n {
result += self
}
return result
}
}
// https://www.avanderlee.com/swift/unique-values-removing-duplicates-array/
public extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var seen: Set<Iterator.Element> = []
return filter { seen.insert($0).inserted }
}
}
// let array: [Int] = [1, 1, 1, 2, 2, 2, 3, 3, 3]
// print(array.unique()) // prints: [1, 2, 3]
| mit | 830fef8f5522d7fb3076c63427136569 | 22.148515 | 81 | 0.553892 | 3.292958 | false | false | false | false |
Rdxer/FFLabel | FFLabel/Source/FFLabel.swift | 3 | 8276 | //
// FFLabel.swift
// FFLabel
//
// Created by 刘凡 on 15/7/18.
// Copyright © 2015年 joyios. All rights reserved.
//
import UIKit
@objc
public protocol FFLabelDelegate: NSObjectProtocol {
optional func labelDidSelectedLinkText(label: FFLabel, text: String)
}
public class FFLabel: UILabel {
public var linkTextColor = UIColor.blueColor()
public var selectedBackgroudColor = UIColor.lightGrayColor()
public weak var labelDelegate: FFLabelDelegate?
// MARK: - override properties
override public var text: String? {
didSet {
updateTextStorage()
}
}
override public var attributedText: NSAttributedString? {
didSet {
updateTextStorage()
}
}
override public var font: UIFont! {
didSet {
updateTextStorage()
}
}
override public var textColor: UIColor! {
didSet {
updateTextStorage()
}
}
// MARK: - upadte text storage and redraw text
private func updateTextStorage() {
if attributedText == nil {
return
}
let attrStringM = addLineBreak(attributedText!)
regexLinkRanges(attrStringM)
addLinkAttribute(attrStringM)
textStorage.setAttributedString(attrStringM)
setNeedsDisplay()
}
/// add link attribute
private func addLinkAttribute(attrStringM: NSMutableAttributedString) {
if attrStringM.length == 0 {
return
}
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range)
attributes[NSFontAttributeName] = font!
attributes[NSForegroundColorAttributeName] = textColor
attrStringM.addAttributes(attributes, range: range)
attributes[NSForegroundColorAttributeName] = linkTextColor
for r in linkRanges {
attrStringM.setAttributes(attributes, range: r)
}
}
/// use regex check all link ranges
private let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"]
private func regexLinkRanges(attrString: NSAttributedString) {
linkRanges.removeAll()
let regexRange = NSRange(location: 0, length: attrString.string.characters.count)
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
let results = regex.matchesInString(attrString.string, options: NSMatchingOptions(rawValue: 0), range: regexRange)
for r in results {
linkRanges.append(r.rangeAtIndex(0))
}
}
}
/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
let attrStringM = NSMutableAttributedString(attributedString: attrString)
if attrStringM.length == 0 {
return attrStringM
}
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range)
var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle
if paragraphStyle != nil {
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
} else {
// iOS 8.0 can not get the paragraphStyle directly
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
attributes[NSParagraphStyleAttributeName] = paragraphStyle
attrStringM.setAttributes(attributes, range: range)
}
return attrStringM
}
public override func drawTextInRect(rect: CGRect) {
let range = glyphsRange()
let offset = glyphsOffset(range)
layoutManager.drawBackgroundForGlyphRange(range, atPoint: offset)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero)
}
private func glyphsRange() -> NSRange {
return NSRange(location: 0, length: textStorage.length)
}
private func glyphsOffset(range: NSRange) -> CGPoint {
let rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: textContainer)
let height = (bounds.height - rect.height) * 0.5
return CGPoint(x: 0, y: height)
}
// MARK: - touch events
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInView(self)
selectedRange = linkRangeAtLocation(location)
modifySelectedAttribute(true)
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInView(self)
if let range = linkRangeAtLocation(location) {
if !(range.location == selectedRange?.location && range.length == selectedRange?.length) {
modifySelectedAttribute(false)
selectedRange = range
modifySelectedAttribute(true)
}
} else {
modifySelectedAttribute(false)
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if selectedRange != nil {
let text = (textStorage.string as NSString).substringWithRange(selectedRange!)
labelDelegate?.labelDidSelectedLinkText!(self, text: text)
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) {
self.modifySelectedAttribute(false)
}
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
modifySelectedAttribute(false)
}
private func modifySelectedAttribute(isSet: Bool) {
if selectedRange == nil {
return
}
var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil)
attributes[NSForegroundColorAttributeName] = linkTextColor
let range = selectedRange!
if isSet {
attributes[NSBackgroundColorAttributeName] = selectedBackgroudColor
} else {
attributes[NSBackgroundColorAttributeName] = UIColor.clearColor()
selectedRange = nil
}
textStorage.addAttributes(attributes, range: range)
setNeedsDisplay()
}
private func linkRangeAtLocation(location: CGPoint) -> NSRange? {
if textStorage.length == 0 {
return nil
}
let offset = glyphsOffset(glyphsRange())
let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y)
let index = layoutManager.glyphIndexForPoint(point, inTextContainer: textContainer)
for r in linkRanges {
if index >= r.location && index <= r.location + r.length {
return r
}
}
return nil
}
// MARK: - init functions
override public init(frame: CGRect) {
super.init(frame: frame)
prepareLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareLabel()
}
public override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
private func prepareLabel() {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0
userInteractionEnabled = true
}
// MARK: lazy properties
private lazy var linkRanges = [NSRange]()
private var selectedRange: NSRange?
private lazy var textStorage = NSTextStorage()
private lazy var layoutManager = NSLayoutManager()
private lazy var textContainer = NSTextContainer()
}
| mit | 9e30ebf70e90cd2643bb554ac8715141 | 31.555118 | 128 | 0.618334 | 5.602304 | false | false | false | false |
firebase/firebase-ios-sdk | Firestore/Swift/Source/Codable/DocumentReference+WriteEncodable.swift | 1 | 4644 | /*
* Copyright 2019 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import FirebaseFirestore
public extension DocumentReference {
/// Encodes an instance of `Encodable` and overwrites the encoded data
/// to the document referred by this `DocumentReference`. If no document exists,
/// it is created. If a document already exists, it is overwritten.
///
/// See `Firestore.Encoder` for more details about the encoding process.
///
/// - Parameters:
/// - value: An instance of `Encodable` to be encoded to a document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This closure will not be called while
/// the client is offline, though local changes will be visible
/// immediately.
func setData<T: Encodable>(from value: T,
encoder: Firestore.Encoder = Firestore.Encoder(),
completion: ((Error?) -> Void)? = nil) throws {
let encoded = try encoder.encode(value)
setData(encoded, completion: completion)
}
/// Encodes an instance of `Encodable` and overwrites the encoded data
/// to the document referred by this `DocumentReference`. If no document exists,
/// it is created. If a document already exists, it is overwritten. If you pass
/// merge:true, the provided `Encodable` will be merged into any existing document.
///
/// See `Firestore.Encoder` for more details about the encoding process.
///
/// - Parameters:
/// - value: An instance of `Encodable` to be encoded to a document.
/// - merge: Whether to merge the provided `Encodable` into any existing
/// document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This closure will not be called while
/// the client is offline, though local changes will be visible
/// immediately.
func setData<T: Encodable>(from value: T,
merge: Bool,
encoder: Firestore.Encoder = Firestore.Encoder(),
completion: ((Error?) -> Void)? = nil) throws {
let encoded = try encoder.encode(value)
setData(encoded, merge: merge, completion: completion)
}
/// Encodes an instance of `Encodable` and writes the encoded data to the document referred
/// by this `DocumentReference` by only replacing the fields specified under `mergeFields`.
/// Any field that is not specified in mergeFields is ignored and remains untouched. If the
/// document doesn’t yet exist, this method creates it and then sets the data.
///
/// It is an error to include a field in `mergeFields` that does not have a corresponding
/// field in the `Encodable`.
///
/// See `Firestore.Encoder` for more details about the encoding process.
///
/// - Parameters:
/// - value: An instance of `Encodable` to be encoded to a document.
/// - mergeFields: Array of `String` or `FieldPath` elements specifying which fields to
/// merge. Fields can contain dots to reference nested fields within the
/// document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This closure will not be called while
/// the client is offline, though local changes will be visible
/// immediately.
func setData<T: Encodable>(from value: T,
mergeFields: [Any],
encoder: Firestore.Encoder = Firestore.Encoder(),
completion: ((Error?) -> Void)? = nil) throws {
let encoded = try encoder.encode(value)
setData(encoded, mergeFields: mergeFields, completion: completion)
}
}
| apache-2.0 | e282d076eec8fd2b8d181d6b0e0a1dc4 | 49.456522 | 93 | 0.646058 | 4.756148 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/UserProfile/Details/ProfileDetailsContentController.swift | 1 | 11852 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
import WireSyncEngine
/**
* An object that receives notifications from a profile details content controller.
*/
protocol ProfileDetailsContentControllerDelegate: AnyObject {
/// Called when the profile details change.
func profileDetailsContentDidChange()
/// Called when the group role change.
func profileGroupRoleDidChange(isAdminRole: Bool)
}
/**
* An object that controls the content to display in the user details screen.
*/
final class ProfileDetailsContentController: NSObject,
UITableViewDataSource,
UITableViewDelegate,
ZMUserObserver {
/**
* The type of content that can be displayed in the profile details.
*/
enum Content: Equatable {
/// Display rich profile data from SCIM.
case richProfile([UserRichProfileField])
/// Display the status of read receipts for a 1:1 conversation.
case readReceiptsStatus(enabled: Bool)
/// Display the status of groud admin enabled for a group conversation.
case groupAdminStatus(enabled: Bool)
/// Display the reason for the forced user block.
case blockingReason
}
/// The user to display the details of.
let user: UserType
/// The user that will see the details.
let viewer: UserType
/// The conversation where the profile details will be displayed.
let conversation: ZMConversation?
/// The current group admin status for UI.
private var isAdminState: Bool
// MARK: - Accessing the Content
/// The contents to display for the current configuration.
private(set) var contents: [Content] = []
/// The object that will receive notifications in case of content change.
weak var delegate: ProfileDetailsContentControllerDelegate?
// MARK: - Properties
private var observerToken: Any?
private let userPropertyCellID = "UserPropertyCell"
// MARK: - Initialization
/**
* Creates the controller to display the profile details for the specified user,
* in the scope of the given conversation.
* - parameter user: The user to display the details of.
* - parameter viewer: The user that will see the details. Most commonly, the self user.
* - parameter conversation: The conversation where the profile details will be displayed.
*/
init(user: UserType,
viewer: UserType,
conversation: ZMConversation?) {
self.user = user
self.viewer = viewer
self.conversation = conversation
isAdminState = conversation.map(user.isGroupAdmin) ?? false
super.init()
configureObservers()
updateContent()
ZMUserSession.shared()?.perform {
user.refreshRichProfile()
}
}
// MARK: - Calculating the Content
/// Whether the viewer can access the rich profile data of the displayed user.
private var viewerCanAccessRichProfile: Bool {
return viewer.canAccessCompanyInformation(of: user)
}
/// Starts observing changes in the user profile.
private func configureObservers() {
if let userSession = ZMUserSession.shared() {
observerToken = UserChangeInfo.add(observer: self, for: user, in: userSession)
}
}
private var richProfileInfoWithEmail: ProfileDetailsContentController.Content? {
var richProfile = user.richProfile
if (!viewerCanAccessRichProfile || richProfile.isEmpty) && user.emailAddress == nil {
return nil
}
guard let email = user.emailAddress else { return .richProfile(richProfile) }
// If viewer can't access rich profile information,
// delete all rich profile info just for displaying purposes.
if !viewerCanAccessRichProfile && richProfile.count > 0 {
richProfile.removeAll()
}
richProfile.insert(UserRichProfileField(type: "email.placeholder".localized, value: email), at: 0)
return .richProfile(richProfile)
}
/// Updates the content for the current configuration.
private func updateContent() {
switch conversation?.conversationType ?? .group {
case .group:
let groupAdminEnabled = conversation.map(user.isGroupAdmin) ?? false
// Do not show group admin toggle for self user or requesting connection user
var items: [ProfileDetailsContentController.Content] = []
if let conversation = conversation {
let viewerCanChangeOtherRoles = viewer.canModifyOtherMember(in: conversation)
let userCanHaveRoleChanged = !user.isWirelessUser && !user.isFederated
if viewerCanChangeOtherRoles && userCanHaveRoleChanged {
items.append(.groupAdminStatus(enabled: groupAdminEnabled))
}
}
if let richProfile = richProfileInfoWithEmail {
// If there is rich profile data and the user is allowed to see it, display it.
items.append(richProfile)
}
if user.isBlocked && user.blockState == .blockedMissingLegalholdConsent {
items.append(.blockingReason)
}
contents = items
case .oneOnOne:
let readReceiptsEnabled = viewer.readReceiptsEnabled
if let richProfile = richProfileInfoWithEmail {
// If there is rich profile data and the user is allowed to see it, display it and the read receipts status.
contents = [richProfile, .readReceiptsStatus(enabled: readReceiptsEnabled)]
} else {
// If there is no rich profile data, show the read receipts.
contents = [.readReceiptsStatus(enabled: readReceiptsEnabled)]
}
default:
contents = []
}
delegate?.profileDetailsContentDidChange()
}
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.readReceiptsEnabledChanged || changeInfo.richProfileChanged else { return }
updateContent()
}
// MARK: - Table View
func numberOfSections(in tableView: UITableView) -> Int {
return contents.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch contents[section] {
case .richProfile(let fields):
return fields.count
case .readReceiptsStatus:
return 0
case .groupAdminStatus:
return 1
case .blockingReason:
return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = SectionTableHeader()
switch contents[section] {
case .groupAdminStatus:
header.titleLabel.text = nil
header.accessibilityIdentifier = nil
case .richProfile:
header.titleLabel.text = "profile.extended_metadata.header".localized(uppercased: true)
header.accessibilityIdentifier = "InformationHeader"
case .readReceiptsStatus(let enabled):
header.accessibilityIdentifier = "ReadReceiptsStatusHeader"
if enabled {
header.titleLabel.text = "profile.read_receipts_enabled_memo.header".localized(uppercased: true)
} else {
header.titleLabel.text = "profile.read_receipts_disabled_memo.header".localized(uppercased: true)
}
case .blockingReason:
header.titleLabel.text = nil
header.accessibilityIdentifier = nil
}
return header
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch contents[indexPath.section] {
case .groupAdminStatus(let groupAdminEnabled):
let cell = tableView.dequeueReusableCell(withIdentifier: IconToggleSubtitleCell.zm_reuseIdentifier, for: indexPath) as! IconToggleSubtitleCell
cell.configure(with: CellConfiguration.groupAdminToogle(get: {
return groupAdminEnabled
}, set: {_, _ in
self.isAdminState.toggle()
self.delegate?.profileGroupRoleDidChange(isAdminRole: self.isAdminState)
self.updateConversationRole()
}), variant: ColorScheme.default.variant)
return cell
case .richProfile(let fields):
let field = fields[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: userPropertyCellID) as? UserPropertyCell ?? UserPropertyCell(style: .default, reuseIdentifier: userPropertyCellID)
cell.propertyName = field.type
cell.propertyValue = field.value
return cell
case .readReceiptsStatus:
fatalError("We do not create cells for the readReceiptsStatus section.")
case .blockingReason:
let cell = tableView.dequeueReusableCell(withIdentifier: UserBlockingReasonCell.zm_reuseIdentifier, for: indexPath) as! UserBlockingReasonCell
return cell
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
switch contents[section] {
case .richProfile:
return nil
case .readReceiptsStatus:
let footer = SectionTableFooter()
footer.titleLabel.text = "profile.read_receipts_memo.body".localized
footer.accessibilityIdentifier = "ReadReceiptsStatusFooter"
return footer
case .groupAdminStatus:
let footer = SectionTableFooter()
footer.titleLabel.text = "profile.group_admin_status_memo.body".localized
footer.accessibilityIdentifier = "GroupAdminStatusFooter"
return footer
case .blockingReason:
return nil
}
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
private func updateConversationRole() {
let groupRoles = self.conversation?.getRoles()
let newParticipantRole = groupRoles?.first {
$0.name == (self.isAdminState ? ZMConversation.defaultAdminRoleName : ZMConversation.defaultMemberRoleName)
}
guard
let role = newParticipantRole,
let user = (user as? ZMUser) ?? (user as? ZMSearchUser)?.user
else {
return
}
conversation?.updateRole(of: user, to: role) { (result) in
if case .failure = result {
self.isAdminState.toggle()
self.updateUI()
}
}
}
private func updateUI() {
self.delegate?.profileGroupRoleDidChange(isAdminRole: self.isAdminState)
self.delegate?.profileDetailsContentDidChange()
}
}
| gpl-3.0 | d60cc123e7c8440494743ba839cda3ca | 35.134146 | 183 | 0.646473 | 5.198246 | false | false | false | false |
banjun/SwiftBeaker | Examples/14. JSON Schema.swift | 1 | 4662 | import Foundation
import APIKit
import URITemplate
protocol URITemplateContextConvertible: Encodable {}
extension URITemplateContextConvertible {
var context: [String: String] {
return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:]
}
}
public enum RequestError: Error {
case encode
}
public enum ResponseError: Error {
case undefined(Int, String?)
case invalidData(Int, String?)
}
struct RawDataParser: DataParser {
var contentType: String? {return nil}
func parse(data: Data) -> Any { return data }
}
struct TextBodyParameters: BodyParameters {
let contentType: String
let content: String
func buildEntity() throws -> RequestBodyEntity {
guard let r = content.data(using: .utf8) else { throw RequestError.encode }
return .data(r)
}
}
public protocol APIBlueprintRequest: Request {}
extension APIBlueprintRequest {
public var dataParser: DataParser {return RawDataParser()}
func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? {
return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces)
}
func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data {
guard let d = object as? Data else {
throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse))
}
return d
}
func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String {
guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else {
throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse))
}
return s
}
func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T {
return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse))
}
public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any {
return object
}
}
protocol URITemplateRequest: Request {
static var pathTemplate: URITemplate { get }
associatedtype PathVars: URITemplateContextConvertible
var pathVars: PathVars { get }
}
extension URITemplateRequest {
// reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query`
public func intercept(urlRequest: URLRequest) throws -> URLRequest {
var req = urlRequest
req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))!
return req
}
}
/// indirect Codable Box-like container for recursive data structure definitions
public class Indirect<V: Codable>: Codable {
public var value: V
public init(_ value: V) {
self.value = value
}
public required init(from decoder: Decoder) throws {
self.value = try V(from: decoder)
}
public func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
// MARK: - Transitions
/// Gets a single note by its unique identifier.
struct Get_a_note: APIBlueprintRequest {
let baseURL: URL
var method: HTTPMethod {return .get}
var path: String {return "/notes/{id}"}
enum Responses {
case http200_application_json(Void)
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses {
let contentType = contentMIMEType(in: urlResponse)
switch (urlResponse.statusCode, contentType) {
case (200, "application/json"?):
return .http200_application_json(try decodeJSON(from: object, urlResponse: urlResponse))
default:
throw ResponseError.undefined(urlResponse.statusCode, contentType)
}
}
}
/// Modify a note's data using its unique identifier. You can edit the `title`,
/// `content`, and `tags`.
struct Update_a_note: APIBlueprintRequest {
let baseURL: URL
var method: HTTPMethod {return .patch}
var path: String {return "/notes/{id}"}
enum Responses {
case http204_(Void)
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses {
let contentType = contentMIMEType(in: urlResponse)
switch (urlResponse.statusCode, contentType) {
case (204, _):
return .http204_(try decodeJSON(from: object, urlResponse: urlResponse))
default:
throw ResponseError.undefined(urlResponse.statusCode, contentType)
}
}
}
// MARK: - Data Structures
| mit | 60e3bd90bc81caf504963ad1a5d114ed | 30.931507 | 145 | 0.682111 | 4.517442 | false | false | false | false |
tmn/swift-http-server | Sources/HTTP/Router.swift | 1 | 477 | public class Router {
private(set) var routers = [Route]()
public init() { }
public func addRoute(route: Route) {
routers.append(route)
}
public func findRoute(path: String, method: HTTPMethod) -> Route? {
for route in routers {
if route.path == path && route.method == method {
print("Route found! \(path)")
return route
}
}
return nil
}
} | bsd-3-clause | b1a637adf629ca6b8e25a67ad0b5f636 | 22.9 | 71 | 0.494759 | 4.5 | false | false | false | false |
loudnate/LoopKit | LoopKit/PumpManagerStatus.swift | 1 | 1823 | //
// PumpManagerStatus.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
public struct PumpManagerStatus: Equatable {
public enum BasalDeliveryState: Equatable {
case active(_ at: Date)
case initiatingTempBasal
case tempBasal(_ dose: DoseEntry)
case cancelingTempBasal
case suspending
case suspended(_ at: Date)
case resuming
public var isSuspended: Bool {
if case .suspended = self {
return true
}
return false
}
}
public enum BolusState: Equatable {
case none
case initiating
case inProgress(_ dose: DoseEntry)
case canceling
}
public let timeZone: TimeZone
public let device: HKDevice
public var pumpBatteryChargeRemaining: Double?
public var basalDeliveryState: BasalDeliveryState
public var bolusState: BolusState
public init(
timeZone: TimeZone,
device: HKDevice,
pumpBatteryChargeRemaining: Double?,
basalDeliveryState: BasalDeliveryState,
bolusState: BolusState
) {
self.timeZone = timeZone
self.device = device
self.pumpBatteryChargeRemaining = pumpBatteryChargeRemaining
self.basalDeliveryState = basalDeliveryState
self.bolusState = bolusState
}
}
extension PumpManagerStatus: CustomDebugStringConvertible {
public var debugDescription: String {
return """
## PumpManagerStatus
* timeZone: \(timeZone)
* device: \(device)
* pumpBatteryChargeRemaining: \(pumpBatteryChargeRemaining as Any)
* basalDeliveryState: \(basalDeliveryState)
* bolusState: \(bolusState)
"""
}
}
| mit | f6edac0cfb4f51ab5c86156576863703 | 25.405797 | 74 | 0.637761 | 5.521212 | false | false | false | false |
toggl/superday | teferi/UI/Common/Views/LoadingView.swift | 1 | 3848 | import UIKit
import SnapKit
class LoadingView: UIView
{
private let backgroundView = UIView()
private let loadingIndicator = LoadingIndicator()
private let label = UILabel()
var text: NSAttributedString? = nil {
didSet {
label.attributedText = text
}
}
init()
{
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
backgroundView.backgroundColor = UIColor(white: 1.0, alpha: 0.9)
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.almostBlack
addSubview(backgroundView)
addSubview(loadingIndicator)
addSubview(label)
backgroundView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
loadingIndicator.snp.makeConstraints { make in
make.width.height.equalTo(16)
make.centerX.centerY.equalToSuperview()
}
label.snp.makeConstraints { make in
make.top.equalTo(loadingIndicator.snp.bottom).offset(16)
make.centerX.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
// MARK: Public Methods
func show()
{
guard let window = UIApplication.shared.windows.first else {
return
}
if superview == nil {
frame = window.bounds
window.addSubview(self)
}
loadingIndicator.animateCircle()
alpha = 0
loadingIndicator.transform = CGAffineTransform(translationX: 0, y: 50)
label.transform = CGAffineTransform(translationX: 0, y: 200)
UIView.animate(
withDuration: 0.6,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.4,
options: [],
animations: { [unowned self] in
self.alpha = 1.0
self.loadingIndicator.transform = CGAffineTransform.identity
self.label.transform = CGAffineTransform.identity
},
completion: nil)
}
func hide()
{
guard let _ = superview else { return }
UIView.animate(
withDuration: 0.3,
animations: { [unowned self] in
self.alpha = 0.0
},
completion: { _ in
self.removeFromSuperview()
})
}
}
extension LoadingView
{
static var locating: LoadingView = {
let loadingView = LoadingView()
let textAttachment = NSTextAttachment()
textAttachment.image = #imageLiteral(resourceName: "icEmojiNerd")
textAttachment.bounds = CGRect(x: 0.0, y: UIFont.systemFont(ofSize: 12).descender, width: textAttachment.image!.size.width, height: textAttachment.image!.size.height)
let text = NSMutableAttributedString(string: "Finding your location... ")
text.append(NSAttributedString(attachment: textAttachment))
loadingView.text = text
return loadingView
}()
static var generating: LoadingView = {
let loadingView = LoadingView()
let textAttachment = NSTextAttachment()
textAttachment.image = #imageLiteral(resourceName: "icEmojiNerd")
textAttachment.bounds = CGRect(x: 0.0, y: UIFont.systemFont(ofSize: 12).descender, width: textAttachment.image!.size.width, height: textAttachment.image!.size.height)
let text = NSMutableAttributedString(string: "Generating your timeline... ")
text.append(NSAttributedString(attachment: textAttachment))
loadingView.text = text
return loadingView
}()
}
| bsd-3-clause | ded8fc9260352b26ca3299e2854f7563 | 29.784 | 174 | 0.584459 | 5.228261 | false | false | false | false |
danpratt/Simply-Zen | SZLesson.swift | 1 | 681 | //
// SZLesson.swift
// Simply Zen
//
// Created by Daniel Pratt on 5/15/17.
// Copyright © 2017 Daniel Pratt. All rights reserved.
//
import Foundation
import UIKit
// MARK: SZLesson Class
/** Conforms to SZLessonProtocol
- Author: Daniel Pratt
*/
class SZLesson: SZLessonProtocol {
var lessonName: String
var lessonFileName: String
var lessonLevel: Int
var durationInSeconds: Double = 0
init(addLesson name: String, withFilename file: String, level: Int, durationInSeconds: Double = 0) {
lessonName = name
lessonFileName = file
lessonLevel = level
self.durationInSeconds = durationInSeconds
}
}
| apache-2.0 | 427b3e12212741595726089600b134db | 20.25 | 104 | 0.669118 | 4.387097 | false | false | false | false |
hawkfalcon/Clients | Clients/FileCreator.swift | 1 | 7614 | import Foundation
import Contacts
import SSZipArchive
class FileCreator {
static let types = ["Clients", "Categories", "Payments", "Mileage", "All"]
class func createFile(clients: [Client], type: String) -> URL {
if type == "All" {
return createZip(clients)
}
guard let path = FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask).first else {
return URL(fileURLWithPath: "")
}
let content = getCSV(clients, type: type)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd_HH_mm_ss"
let date = formatter.string(from: Date())
let file = path.appendingPathComponent("Clients_\(type)_\(date).csv")
do {
try content.write(to: file, atomically: false, encoding: String.Encoding.utf8.rawValue)
} catch let error as NSError {
print(error.localizedDescription)
}
return file
}
class func createZip(_ clients: [Client]) -> URL {
guard let path = FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask).first else {
return URL(fileURLWithPath: "")
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd_HH_mm_ss"
let date = formatter.string(from: Date())
let folder = path.appendingPathComponent("Clients_\(date)")
do {
try FileManager.default.createDirectory(atPath: folder.path, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
for type in types {
if type == "All" {
continue
}
let file = folder.appendingPathComponent("\(type).csv")
let content = getCSV(clients, type: type)
do {
try content.write(to: file, atomically: false, encoding: String.Encoding.utf8.rawValue)
} catch let error as NSError {
print(error.localizedDescription)
}
}
let zip = path.appendingPathComponent("Clients_\(date).zip")
SSZipArchive.createZipFile(atPath: zip.path, withContentsOfDirectory: folder.path)
return zip
}
class func getCSV(_ clients: [Client], type: String) -> NSString {
switch type {
case "Clients": return getClientsCSV(clients)
case "Categories": return getCategoriesCSV(clients)
case "Payments": return getPaymentsCSV(clients)
case "Mileage": return getMileageCSV(clients)
default: return NSString(string: "test")
}
}
private class func getMileageCSV(_ clients: [Client]) -> NSString {
var data = "Last,First,Total Miles,Date,Mileage\n"
for client in clients {
var names = ""
if let last = client.lastName {
names += "\(last)"
}
names += ","
if let first = client.firstName {
names += "\(first)"
}
names += ","
var milesText = ""
var total = 0.0
for miles in client.mileage! {
let miles = miles as! Mileage
total += miles.miles
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
let date = formatter.string(from: miles.date as! Date)
milesText += "\(date),"
milesText += "\(miles.miles),"
}
data += "\(total),"
data += milesText
data += "\n"
}
return NSString(string: data)
}
private class func getPaymentsCSV(_ clients: [Client]) -> NSString {
var data = "Last,First,Category,Name,Type,Amount,Date\n"
for client in clients {
var names = ""
if let last = client.lastName {
names += "\(last)"
}
names += ","
if let first = client.firstName {
names += "\(first)"
}
names += ","
for category in client.categories! {
let category = category as! Category
for payment in category.payments! {
let payment = payment as! Payment
data += "\(names)"
if let name = category.name {
data += "\(name)"
}
data += ","
data += "\(payment.name!),"
data += "\(payment.type!),"
data += "\(payment.value),"
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let date = formatter.string(from: payment.date as! Date)
data += "\(date)"
data += "\n"
}
}
data += "\n"
}
return NSString(string: data)
}
private class func getCategoriesCSV(_ clients: [Client]) -> NSString {
var data = "Last,First,Category,Total\n"
for client in clients {
var names = ""
if let last = client.lastName {
names += "\(last)"
}
names += ","
if let first = client.firstName {
names += "\(first)"
}
names += ","
for category in client.categories! {
let category = category as! Category
data += "\(names)"
if let name = category.name {
data += "\(name)"
}
data += ","
data += "\(category.total)"
data += "\n"
}
data += "\n"
}
return NSString(string: data)
}
private class func getClientsCSV(_ clients: [Client]) -> NSString {
var data = "Last,First,Phone,Email,Notes,Timestamp,Total Paid, Total Owed\n"
for client in clients {
if let last = client.lastName {
data += "\(last)"
}
data += ","
if let first = client.firstName {
data += "\(first)"
}
data += ","
do {
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactEmailAddressesKey, CNContactIdentifierKey]
let contact = try CNContactStore().unifiedContact(withIdentifier: client.contact!, keysToFetch: keysToFetch as [CNKeyDescriptor])
if let phone = contact.phoneNumbers.first {
let phoneNumber = phone.value
data += "\(phoneNumber.stringValue)"
}
data += ","
if let email = contact.emailAddresses.first {
data += "\(email.value)"
}
data += ","
} catch {
print("Invalid contact")
}
if let notes = client.notes {
data += "\(notes)"
}
data += ","
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
let date = formatter.string(from: client.timestamp as! Date)
data += "\(date),"
data += "\(client.paid()),"
data += "\(client.owed())"
data += "\n"
}
return NSString(string: data)
}
}
| mit | b39a3f881619b837cff197031603c17e | 32.104348 | 159 | 0.491594 | 5.059136 | false | false | false | false |
chrishulbert/gondola-appletv | Gondola TVOS/ViewControllers/TVEpisodeViewController.swift | 1 | 5544 | //
// TVEpisodeViewController.swift
// Gondola TVOS
//
// Created by Chris on 13/02/2017.
// Copyright © 2017 Chris Hulbert. All rights reserved.
//
// This shows the details of an episode and lets you play it.
import UIKit
import AVKit
class TVEpisodeViewController: UIViewController {
let episode: TVEpisodeMetadata
let show: TVShowMetadata
let season: TVSeasonMetadata
let episodeImage: UIImage?
let backdrop: UIImage?
init(episode: TVEpisodeMetadata, show: TVShowMetadata, season: TVSeasonMetadata, episodeImage: UIImage?, backdrop: UIImage?) {
self.episode = episode
self.show = show
self.season = season
self.episodeImage = episodeImage
self.backdrop = backdrop
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var rootView = TVEpisodeView()
override func loadView() {
view = rootView
}
override func viewDidLoad() {
super.viewDidLoad()
rootView.title.text = episode.name
rootView.overview.text = episode.overview
rootView.background.image = backdrop
rootView.episodeImage.image = episodeImage
rootView.details.text = season.name + "\nEpisode \(episode.episode)\nAir date: \(episode.airDate)\nVote: \(episode.vote)"
rootView.play.addTarget(self, action: #selector(tapPlay), for: .primaryActionTriggered)
}
@objc func tapPlay() {
pushPlayer(media: episode.media)
}
}
class TVEpisodeView: UIView {
let background = UIImageView()
let dim = UIView()
let title = UILabel()
let overview = UILabel()
let episodeImage = UIImageView()
let details = UILabel()
let play = UIButton(type: .system)
init() {
super.init(frame: CGRect.zero)
background.contentMode = .scaleAspectFill
addSubview(background)
dim.backgroundColor = UIColor(white: 0, alpha: 0.7)
addSubview(dim)
title.textColor = UIColor.white
title.font = UIFont.systemFont(ofSize: 60, weight: .thin)
addSubview(title)
overview.textColor = UIColor.white
overview.font = UIFont.systemFont(ofSize: 30, weight: .light)
overview.numberOfLines = 0
addSubview(overview)
episodeImage.contentMode = .scaleAspectFit
addSubview(episodeImage)
details.textColor = UIColor(white: 1, alpha: 0.7)
details.numberOfLines = 0
details.font = UIFont.systemFont(ofSize: 25, weight: .light)
addSubview(details)
play.setTitle("Play", for: .normal)
addSubview(play)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = bounds.width
let h = bounds.height
background.frame = bounds
dim.frame = bounds
// Top row.
title.frame = CGRect(x: LayoutHelpers.sideMargins,
y: LayoutHelpers.vertMargins,
width: w - 2*LayoutHelpers.sideMargins,
height: ceil(title.font.lineHeight))
// Image under it.
let imageWidth = round(w * 0.35)
let aspect: CGFloat
if let image = episodeImage.image, image.size.width > 0 {
aspect = image.size.height / image.size.width
} else {
aspect = 0
}
let imageHeight = round(imageWidth * aspect)
episodeImage.frame = CGRect(x: LayoutHelpers.sideMargins, y: title.frame.maxY + 40, width: imageWidth, height: imageHeight)
// Details under image.
let detailsTop = episodeImage.frame.maxY + 40
let detailsBottom = h - LayoutHelpers.vertMargins
let detailsWidth = imageWidth
let maxDetailsHeight = detailsBottom - detailsTop
let textDetailsHeight = ceil(details.sizeThatFits(CGSize(width: detailsWidth, height: 999)).height)
let detailsHeight = min(textDetailsHeight, maxDetailsHeight)
details.frame = CGRect(x: episodeImage.frame.minX, y: detailsTop, width: detailsWidth, height: detailsHeight)
let overviewLeft = episodeImage.frame.maxX + LayoutHelpers.sideMargins
let overviewRight = w - LayoutHelpers.sideMargins
let overviewTop = episodeImage.frame.minY
let overviewBottom = h - LayoutHelpers.vertMargins
let overviewWidth = overviewRight - overviewLeft
let maxOverviewHeight = overviewBottom - overviewTop
let textOverviewHeight = ceil(overview.sizeThatFits(CGSize(width: overviewWidth, height: 999)).height)
let overviewHeight = min(textOverviewHeight, maxOverviewHeight)
overview.frame = CGRect(x: overviewLeft,
y: overviewTop,
width: overviewWidth,
height: overviewHeight)
// Center bottom.
let playSize = play.intrinsicContentSize
play.frame = CGRect(origin: CGPoint(x: round(w/2 - playSize.width/2),
y: round(h - LayoutHelpers.vertMargins - playSize.height - 8)), // -8 to compensate for focus growth
size: playSize)
}
}
| mit | 8a252c4b6363be41b1d566b2c4dfc991 | 34.305732 | 144 | 0.614288 | 4.654072 | false | false | false | false |
chrishulbert/gondola-appletv | Gondola TVOS/ViewControllers/TVShowSeasonsViewController.swift | 1 | 6663 | //
// TVShowSeasonsViewController.swift
// Gondola TVOS
//
// Created by Chris on 12/02/2017.
// Copyright © 2017 Chris Hulbert. All rights reserved.
//
// This is the show details with a list of seasons.
import UIKit
class TVShowSeasonsViewController: UIViewController {
let show: TVShowMetadata
init(show: TVShowMetadata) {
self.show = show
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var rootView = TVShowSeasonsView()
override func loadView() {
view = rootView
}
override func viewDidLoad() {
super.viewDidLoad()
rootView.collection.register(PictureCell.self, forCellWithReuseIdentifier: "cell")
rootView.collection.dataSource = self
rootView.collection.delegate = self
rootView.title.text = show.name
rootView.overview.text = show.overview
// Load the backdrop.
ServiceHelpers.imageRequest(path: show.backdrop) { result in
switch result {
case .success(let image):
DispatchQueue.main.async {
self.rootView.background.image = image
UIView.animate(withDuration: 0.3) {
self.rootView.background.alpha = 1
}
}
case .failure(let error):
NSLog("Error loading backdrop: \(error)")
}
}
}
}
extension TVShowSeasonsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return show.seasons.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let season = show.seasons[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PictureCell
cell.label.text = season.name
cell.image.image = nil
cell.imageAspectRatio = 1.5
// TODO use a reusable image view? Or some helper that checks for stale?
cell.imagePath = season.image
ServiceHelpers.imageRequest(path: season.image) { result in
DispatchQueue.main.async {
if cell.imagePath == season.image { // Cell hasn't been recycled?
switch result {
case .success(let image):
cell.image.image = image
case .failure(let error):
NSLog("error: \(error)")
// TODO show sad cloud image.
}
}
}
}
return cell
}
}
extension TVShowSeasonsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let season = show.seasons[indexPath.item]
let vc = TVSeasonEpisodesViewController(show: show, season: season, backdrop: rootView.background.image)
navigationController?.pushViewController(vc, animated: true)
}
}
class TVShowSeasonsView: UIView {
let background = UIImageView()
let dim = UIView()
let title = UILabel()
let overview = UILabel()
let collection: UICollectionView
let layout = UICollectionViewFlowLayout()
init() {
// TODO have a layout helper.
layout.scrollDirection = .horizontal
let itemWidth = PictureCell.width(forHeight: K.itemHeight, imageAspectRatio: 1.5)
layout.itemSize = CGSize(width: itemWidth, height: K.itemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: LayoutHelpers.sideMargins, bottom: LayoutHelpers.vertMargins, right: LayoutHelpers.sideMargins)
collection = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout)
collection.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
super.init(frame: CGRect.zero)
background.contentMode = .scaleAspectFill
background.alpha = 0
addSubview(background)
dim.backgroundColor = UIColor(white: 0, alpha: 0.7)
addSubview(dim)
title.textColor = UIColor.white
title.font = UIFont.systemFont(ofSize: 60, weight: .thin)
addSubview(title)
overview.textColor = UIColor.white
overview.font = UIFont.systemFont(ofSize: 30, weight: .light)
overview.numberOfLines = 0
addSubview(overview)
addSubview(collection)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = bounds.width
let h = bounds.height
background.frame = bounds
let collectionHeight = K.itemHeight + layout.sectionInset.top + layout.sectionInset.bottom
collection.frame = CGRect(x: 0, y: h - collectionHeight, width: w, height: collectionHeight)
dim.frame = CGRect(x: 0, y: 0, width: w, height: collection.frame.minY)
title.frame = CGRect(x: LayoutHelpers.sideMargins, y: LayoutHelpers.vertMargins,
width: w - 2*LayoutHelpers.sideMargins, height: ceil(title.font.lineHeight))
let overviewTop = title.frame.maxY + 40
let overviewBottom = collection.frame.minY - LayoutHelpers.vertMargins
let overviewWidth = (w - LayoutHelpers.sideMargins)/2
let maxOverviewHeight = overviewBottom - overviewTop
let textOverviewHeight = ceil(overview.sizeThatFits(CGSize(width: overviewWidth, height: 999)).height)
let overviewHeight = min(textOverviewHeight, maxOverviewHeight)
overview.frame = CGRect(x: LayoutHelpers.sideMargins,
y: overviewTop,
width: overviewWidth,
height: overviewHeight)
}
struct K {
static let itemUnfocusedHeightToScreenHeightRatio: CGFloat = 0.3
static let itemHeight: CGFloat = {
return round(UIScreen.main.bounds.height * itemUnfocusedHeightToScreenHeightRatio)
}()
}
}
| mit | 7d0d84a480d907ada89ac65b57f777ba | 34.625668 | 152 | 0.609727 | 5.12856 | false | false | false | false |
dsxNiubility/SXSwiftWeibo | 103 - swiftWeibo/103 - swiftWeibo/AppDelegate.swift | 1 | 2952 | //
// AppDelegate.swift
// 103 - swiftWeibo
//
// Created by 董 尚先 on 15/3/2.
// Copyright (c) 2015年 shangxianDante. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
SQLite.sharedSQLite.openDatabase("sxweibo.db")
/// 关于accessToken
if let token = AccessToken.loadAccessToken() {
print(token)
print(token.uid)
showMainInterface()
}else{
// 添加通知监听,监听用户登录成功
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showMainInterface", name: WB_Login_Successed_Notification, object: nil)
}
return true
}
/// 测试两次上拉刷新
func loadTwoRefreshDemo() {
// 加载数据测试代码 - 第一次刷新,都是从服务器加载数据!
StatusesData.loadStatus(0) { (data, error) -> () in
// 第一次加载的数据
if let statuses = data?.statuses {
// 模拟上拉刷新
// 取出最后一条记录中的 id,id -1 -> maxId
let mId = statuses.last!.id
let tId = statuses.first!.id
print("maxId \(mId) ---- topId \(tId)")
// 上拉刷新
StatusesData.loadStatus(maxId: (mId - 1), completion: { (data, error) -> () in
print("第一次上拉刷新结束")
// 再一次加载的数据
if let statuses = data?.statuses {
// 模拟上拉刷新
// 取出最后一条记录中的 id,id -1 -> maxId
let mId = statuses.last!.id
let tId = statuses.first!.id
print("2222 maxId \(mId) ---- topId \(tId)")
// 上拉刷新
StatusesData.loadStatus(maxId: (mId - 1), completion: { (data, error) -> () in
print("第二次上拉刷新结束")
})
}
})
}
}
}
func showMainInterface(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: WB_Login_Successed_Notification, object: nil)
let sb = UIStoryboard(name: "Main", bundle: nil)
window!.rootViewController = (sb.instantiateInitialViewController() as!UIViewController)
/// 添加导航栏主题
setNavAppeareance()
}
func setNavAppeareance(){
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
}
}
| mit | d8f02de6020a1d37b59c7f3e5ca5095e | 30.857143 | 149 | 0.504858 | 4.761566 | false | false | false | false |
albertinopadin/SwiftBreakout | Breakout/GameViewController.swift | 1 | 16599 | //
// GameViewController.swift
// Breakout
//
// Created by Albertino Padin on 10/26/14.
// Copyright (c) 2014 Albertino Padin. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
import AVFoundation
import AudioToolbox
import SpriteKit
class GameViewController: UIViewController, SCNPhysicsContactDelegate, UIGestureRecognizerDelegate
{
var gameRunning = false
var _gameLoop: CADisplayLink? = nil
var walls = SCNNode()
var blocks = SCNNode()
var ball = Ball()
let paddleNode = Paddle(color: UIColor.whiteColor())
var score = 0
var scoreLabel = SKLabelNode(fontNamed: "San Francisco")
var previousContactNodes = Array<SCNNode>()
// Ball bounds
// let maxX = 50.0
// let minX = 0.0
// let maxY = 45.0
let minY = -45.0
// Ball speed
let defaultVectorX = 25.0
let defaultVectorY = 25.0
var vectorX: Double = 25.0
var vectorY: Double = 25.0
let musicURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("MarbleZone", ofType: "mp3")!)
var musicAudioPlayer = AVAudioPlayer()
let soundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("tock", ofType: "caf")!)
var tockSound: SystemSoundID = 0
var initialPaddlePosition: Float = 24.0 // Paddle starts at x = 24
var ballHasFallenOff = false // Use this to let the game loop know to not keep adding velocity vector to regenerated ball
override func viewDidLoad() {
super.viewDidLoad()
// --- TINO ADDED --- //
let scene = SCNScene()
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor(white: 0.67, alpha: 1.0)
scene.rootNode.addChildNode(ambientLightNode)
let omniLightNode = SCNNode()
omniLightNode.light = SCNLight()
omniLightNode.light!.type = SCNLightTypeOmni
omniLightNode.light!.color = UIColor(white: 0.75, alpha: 1.0)
omniLightNode.position = SCNVector3Make(0, 50, 50)
scene.rootNode.addChildNode(omniLightNode)
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3Make(25, 0, 80)
scene.rootNode.addChildNode(cameraNode)
// --- TINO ADDED --- //
// retrieve the SCNView
let scnView = self.view as! SCNView
scoreLabel.fontColor = UIColor.whiteColor()
scoreLabel.text = String(score)
scoreLabel.setScale(1.0)
scoreLabel.position = CGPoint(x: 20, y: 40)
scnView.overlaySKScene = SKScene(size: scnView.bounds.size)
scnView.overlaySKScene?.addChild(scoreLabel)
// set the scene to the view
scnView.scene = scene
//scnView.delegate = self // Implement update method
// Set gravity to zero and create level
scnView.scene!.physicsWorld.gravity = SCNVector3(x: 0, y: 0, z: 0)
// Add blocks and walls
self.instantiateLevel()
// Adding paddle
paddleNode.position = SCNVector3Make(+24, -15, 0)
scnView.scene!.rootNode.addChildNode(paddleNode)
ball.setPositionVector(SCNVector3Make(+8, -4, 0))
scnView.scene!.rootNode.addChildNode(ball.ballNode)
scnView.scene!.physicsWorld.contactDelegate = self;
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.blackColor()
var gestureRecognizers:[UIGestureRecognizer] = []
createAndAddGestureRecognizer(UITapGestureRecognizer.self,
action: #selector(handleTap),
numOfTapsRequired: 1,
recognizerArray: &gestureRecognizers)
createAndAddGestureRecognizer(UIPanGestureRecognizer.self,
action: #selector(handlePan),
numOfTapsRequired: nil,
recognizerArray: &gestureRecognizers)
createAndAddGestureRecognizer(UITapGestureRecognizer.self,
action: #selector(pauseAndResumeGame),
numOfTapsRequired: 2,
recognizerArray: &gestureRecognizers)
// Removing default gesture recognizers
scnView.gestureRecognizers = gestureRecognizers
AudioServicesCreateSystemSoundID(soundURL, &tockSound)
// Start music
startMusicPlayer()
// Game Loop
startGameLoop()
}
func createAndAddGestureRecognizer(recognizerType: UIGestureRecognizer.Type,
action: Selector,
numOfTapsRequired: Int?,
inout recognizerArray: [UIGestureRecognizer])
{
let gestureRecognizer = recognizerType.init(target: self, action: action)
gestureRecognizer.delegate = self
if let gr = gestureRecognizer as? UITapGestureRecognizer
{
gr.numberOfTapsRequired = numOfTapsRequired!
}
recognizerArray.append(gestureRecognizer)
}
func startGameLoop()
{
self.vectorX = defaultVectorX
self.vectorY = defaultVectorY
self._gameLoop = CADisplayLink(target: self, selector: #selector(gameLoop))
self._gameLoop!.frameInterval = 1
self._gameLoop!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.gameRunning = true // Consider placing this inside the game loop perhaps?
// TESTING!
//ball.setVelocityVector(SCNVector3(x: Float(vectorX), y: Float(vectorY), z: 0))
}
func startMusicPlayer()
{
musicAudioPlayer = try! AVAudioPlayer(contentsOfURL: musicURL)
musicAudioPlayer.numberOfLoops = -1 // Infinite loop
musicAudioPlayer.prepareToPlay()
musicAudioPlayer.play()
}
func instantiateLevel()
{
let scnView = view as! SCNView
let levelAndWalls = Level.createLevel()
if walls.childNodes.count == 0
{
walls = levelAndWalls.walls
scnView.scene!.rootNode.addChildNode(walls)
}
blocks = levelAndWalls.blocks
scnView.scene!.rootNode.addChildNode(blocks)
}
func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact)
{
// print("CONTACT!")
// print("ContactNormal: x: \(contact.contactNormal.x), y: \(contact.contactNormal.y)")
if !ballHasFallenOff && (contact.nodeA == ball.ballNode || contact.nodeB == ball.ballNode) &&
!(previousContactNodes.contains(contact.nodeA) && previousContactNodes.contains(contact.nodeB))
{
// didBeginContact can be called multiple times for the same contact, so need to check that the nodes are not the same.
// Storing the current contact nodes to check on next call to didBeginContact:
previousContactNodes.removeAll()
previousContactNodes = [contact.nodeA, contact.nodeB]
// contactNormal is a unitary vector, so when it is at 45 degrees to the horizon (corner contact),
// it will satisfy the equation 1 = x^2 + y^2, with x = y = sqrt(0.5)
if contact.contactNormal.x <= -sqrt(0.5) || contact.contactNormal.x >= sqrt(0.5)
{
vectorX *= -1
}
if contact.contactNormal.y <= -sqrt(0.5) || contact.contactNormal.y >= sqrt(0.5)
{
vectorY *= -1
}
if (contact.nodeA == ball.ballNode && contact.nodeB == paddleNode) ||
(contact.nodeA == paddleNode && contact.nodeB == ball.ballNode)
{
// Change vectorX depending on Paddle movement:
let paddleSpeed = self.paddleNode.physicsBody!.velocity.x
print("Paddle Speed = \(paddleSpeed) m/s")
vectorX += (Double)(0.1 * -paddleSpeed)
// Vibrate (using Pop)!
AudioServicesPlaySystemSound(Taptics.Pop.rawValue)
}
ball.setVelocityVector(SCNVector3(x: Float(vectorX), y: Float(vectorY), z: 0))
AudioServicesPlaySystemSound(tockSound)
if contact.nodeA is Block || contact.nodeB is Block
{
// Is a block
if contact.nodeA is Block
{
contact.nodeA.removeFromParentNode()
}
else
{
contact.nodeB.removeFromParentNode()
}
score += 1
scoreLabel.text = String(score)
print("Score: \(score)")
print("ScoreLabel.text: \(scoreLabel.text)")
}
// Check to see if there are no more blocks:
if blocks.childNodes.count == 0
{
// Add blocks again
instantiateLevel()
}
}
}
func gameLoop()
{
// print("ball.position.x = \(self.ball.getPositionVector().x)")
// print("ball.presentationNode.position.x = \(self.ball.ballNode.presentationNode.position.x)")
// print("ball.position.y = \(self.ball.getPositionVector().y)")
// print("ball.presentationNode.position.y = \(self.ball.ballNode.presentationNode.position.y)")
// print("Ball presentation node Z position: \(self.ball.getPresentationNode().position.z)")
// print("Ball presentation node Z velocity: \(self.ball.getPresentationNode().physicsBody?.velocity.z)")
if self.ball.getPresentationNode().physicsBody != nil &&
(self.ball.getVelocityVector().z != 0 ||
self.ball.getPresentationNode().position.z != 0)
{
print("Ball has aquired Z velocity or position.z != 0!")
self.ball.setVelocityVector(SCNVector3(x: Float(vectorX), y: Float(vectorY), z: 0))
let ballPosVect = self.ball.getPositionVector()
self.ball.setPositionVector(SCNVector3(x: ballPosVect.x, y: ballPosVect.y, z: 0))
}
if !ballHasFallenOff
{
if (self.ball.ballNode.presentationNode.position.y <= Float(minY) && vectorY < 0)
{
// Regenerate ball on top of paddle:
ballHasFallenOff = true
self.ball.ballNode.removeFromParentNode()
self.ball.setPositionVector(SCNVector3Make(paddleNode.position.x + 1, paddleNode.position.y + 2, 0))
self.ball.setVelocityVector(SCNVector3Make(0, 0, 0))
let scnView = self.view as! SCNView
scnView.scene!.rootNode.addChildNode(self.ball.ballNode)
}
// TODO: This won't be necessary once code to control ball angle using paddle motion is implemented.
// To make sure ball doesn't get stuck in an infinite vertical or horizontal movement
if (vectorX < 0.09 && vectorX > -0.09)
{
vectorX += 0.20
}
if (vectorY < 0.09 && vectorY > -0.09)
{
vectorY += 0.20
}
// print("Vector X: \(vectorX)")
// print("Vector Y:\(vectorY)")
// print("Ball node velocity before update: \(ball.getVelocityVector())")
ball.setVelocityVector(SCNVector3(x: Float(vectorX), y: Float(vectorY), z: 0))
// print("Ball node velocity after update: \(ball.getVelocityVector())")
}
else
{
// Set ball on top of paddle
ball.setVelocityVector(SCNVector3Make(0, 0, 0))
ball.setPositionVector(SCNVector3Make(paddleNode.position.x + 1, paddleNode.position.y + 2, 0))
}
}
func pauseAndResumeGame(gestureRecognizer: UIGestureRecognizer) {
if(self.gameRunning)
{
self.musicAudioPlayer.pause()
self._gameLoop!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.ball.setVelocityVector(SCNVector3Make(0, 0, 0))
self.gameRunning = false
}
else
{
self.musicAudioPlayer.prepareToPlay()
self._gameLoop!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.musicAudioPlayer.play()
self.ball.setVelocityVector(SCNVector3Make(Float(self.vectorX), Float(self.vectorY), 0)) // Save the Velocity vector
self.gameRunning = true
}
}
func handleTap(gestureRecognizer: UIGestureRecognizer) {
if ballHasFallenOff
{
if vectorY <= 0
{
vectorY = defaultVectorY
}
ballHasFallenOff = false // Start ball moving again
}
}
// Move Paddle!
func handlePan(gestureRecognizer: UIGestureRecognizer)
{
let scnView = self.view as! SCNView
let panRecognizer = gestureRecognizer as! UIPanGestureRecognizer
let translation = panRecognizer.translationInView(scnView)
//println("Translation.x (raw): \(translation)")
// Using uproject point to go from 2D View coordinated to the actual 3D scene coordinates.
let convertedTranslation = scnView.unprojectPoint(SCNVector3Make(Float(translation.x), Float(translation.y), 1.0))
var xSceneTranslation = convertedTranslation.x
// This discrepancy probably has to do with the different screen scales
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
{
// WTF?
// The converted translation is more negative than it should be
xSceneTranslation += 16.5
}
else // iPhone
{
xSceneTranslation += 7.5
}
// Limits of paddle motion
if self.paddleNode.position.x <= 3 && initialPaddlePosition + xSceneTranslation < 3 // Don't move further to the left
{
self.paddleNode.position.x = 3
}
else if self.paddleNode.position.x >= 47 && initialPaddlePosition + xSceneTranslation > 47 // Don't move further to the right
{
self.paddleNode.position.x = 47
}
else
{
self.paddleNode.position.x = xSceneTranslation + initialPaddlePosition
}
if panRecognizer.state == UIGestureRecognizerState.Ended || panRecognizer.state == UIGestureRecognizerState.Cancelled
{
initialPaddlePosition = self.paddleNode.presentationNode.position.x
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| gpl-2.0 | cfa78110f3e15a453c0f73882b073fa7 | 34.928571 | 170 | 0.575577 | 5.036104 | false | false | false | false |
rwbutler/TypographyKit | TypographyKit/Classes/UIButtonAdditions.swift | 1 | 7205 | //
// UIButtonAdditions.swift
// TypographyKit
//
// Created by Ross Butler on 5/16/17.
//
//
import Foundation
import UIKit
extension UIButton {
public typealias TitleColorApplyMode = ButtonTitleColorApplyMode
@objc public var fontTextStyle: UIFont.TextStyle {
get {
// swiftlint:disable:next force_cast
return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle) as! UIFont.TextStyle
}
set {
objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.fontTextStyle,
newValue, .OBJC_ASSOCIATION_RETAIN)
if let typography = Typography(for: newValue) {
self.typography = typography
}
}
}
@objc public var fontTextStyleName: String {
get {
return fontTextStyle.rawValue
}
set {
fontTextStyle = UIFont.TextStyle(rawValue: newValue)
}
}
public var letterCase: LetterCase {
get {
// swiftlint:disable:next force_cast
return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase) as! LetterCase
}
set {
objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.letterCase,
newValue, .OBJC_ASSOCIATION_RETAIN)
if !isAttributed() {
let title = self.title(for: .normal)?.letterCase(newValue)
self.setTitle(title, for: .normal)
}
}
}
@objc public var titleColorApplyMode: TitleColorApplyMode {
get {
objc_getAssociatedObject(
self,
&TypographyKitPropertyAdditionsKey.titleColorApplyMode
) as? TitleColorApplyMode ?? TypographyKit.buttonTitleColorApplyMode
}
set {
objc_setAssociatedObject(
self,
&TypographyKitPropertyAdditionsKey.titleColorApplyMode,
newValue,
.OBJC_ASSOCIATION_RETAIN
)
}
}
public var typography: Typography {
get {
// swiftlint:disable:next force_cast
return objc_getAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography) as! Typography
}
set {
objc_setAssociatedObject(self, &TypographyKitPropertyAdditionsKey.typography,
newValue, .OBJC_ASSOCIATION_RETAIN)
addObserver()
guard !isAttributed() else {
return
}
if let newFont = newValue.font(UIApplication.shared.preferredContentSizeCategory) {
self.titleLabel?.font = newFont
}
if let textColor = newValue.textColor {
applyTitleColor(textColor, mode: titleColorApplyMode)
}
if let letterCase = newValue.letterCase {
self.letterCase = letterCase
}
}
}
// MARK: Functions
public func attributedText(_ text: NSAttributedString?, style: UIFont.TextStyle,
letterCase: LetterCase? = nil, textColor: UIColor? = nil,
replacingDefaultTextColor: Bool = false) {
// Update text.
if let text = text {
self.setAttributedTitle(text, for: .normal)
}
// Update text color.
if let textColor = textColor {
self.setTitleColor(textColor, for: .normal)
}
guard var typography = Typography(for: style), let attrString = text else {
return
}
// Apply overriding parameters.
typography.textColor = textColor ?? typography.textColor
typography.letterCase = letterCase ?? typography.letterCase
self.fontTextStyle = style
self.typography = typography
let mutableString = NSMutableAttributedString(attributedString: attrString)
let textRange = NSRange(location: 0, length: attrString.string.count)
mutableString.enumerateAttributes(in: textRange, options: [], using: { value, range, _ in
update(attributedString: mutableString, with: value, in: range, and: typography)
})
self.setAttributedTitle(mutableString, for: .normal)
if replacingDefaultTextColor {
let defaultColor = defaultTextColor(in: mutableString)
let replacementString = replaceTextColor(defaultColor, with: typography.textColor, in: mutableString)
self.setAttributedTitle(replacementString, for: .normal)
}
}
public func text(_ text: String?, style: UIFont.TextStyle, letterCase: LetterCase? = nil,
textColor: UIColor? = nil) {
if let text = text {
self.setTitle(text, for: .normal)
}
if var typography = Typography(for: style) {
// Only override letterCase and textColor if explicitly specified
if let textColor = textColor {
typography.textColor = textColor
}
if let letterCase = letterCase {
typography.letterCase = letterCase
}
self.typography = typography
}
}
}
extension UIButton: TypographyKitElement {
func isAttributed() -> Bool {
guard let attributedText = titleLabel?.attributedText else {
return false
}
return isAttributed(attributedText)
}
func contentSizeCategoryDidChange(_ notification: NSNotification) {
if let newValue = notification.userInfo?[UIContentSizeCategory.newValueUserInfoKey] as? UIContentSizeCategory {
if let attributedText = titleLabel?.attributedText, isAttributed(attributedText) {
self.attributedText(attributedText, style: fontTextStyle)
} else {
self.titleLabel?.font = self.typography.font(newValue)
}
}
}
}
extension UIButton {
func applyTitleColor(_ color: UIColor, mode: TitleColorApplyMode) {
switch mode {
case .all:
UIControl.State.allCases.forEach { controlState in
setTitleColor(color, for: controlState)
}
case .none:
return
case .normal:
setTitleColor(color, for: .normal)
case .whereUnspecified:
applyTitleColorWhereNoneSpecified(color)
}
}
private func applyTitleColorWhereNoneSpecified(_ color: UIColor) {
let defaultButton = UIButton(type: buttonType)
let normalStateColor = titleColor(for: .normal)
UIControl.State.allCases.forEach { controlState in
let defaultStateColor = defaultButton.titleColor(for: controlState)
let currentStateColor = titleColor(for: controlState)
if defaultStateColor == currentStateColor
|| (controlState != .normal && currentStateColor == normalStateColor) {
setTitleColor(color, for: controlState)
}
}
}
}
| mit | 616c2a2733efc09753d6790a5bd4a47d | 35.025 | 120 | 0.593199 | 5.736465 | false | false | false | false |
cp3hnu/Bricking | Bricking/Source/NSLayoutDimension+OP.swift | 1 | 4424 | //
// NSLayoutDimension+OP.swift
// Bricking
//
// Created by CP3 on 2017/11/7.
// Copyright © 2017年 CP3. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
public typealias CPLayoutDimension = CPLayoutAnchor<NSLayoutDimension, NSLayoutDimension>
public typealias PriorityDimension = PriorityAnchor<NSLayoutDimension, NSLayoutDimension>
// MARK: - NSLayoutDimension => PriorityDimension
extension NSLayoutDimension {
static public func !! (left: NSLayoutDimension, right: LayoutPriority) -> PriorityDimension {
return PriorityDimension(anchor: CPLayoutDimension(anchor: left), priority: right)
}
}
// MARK: - NSLayoutDimension => CPLayoutDimension
extension NSLayoutDimension {
static public func + (left: NSLayoutDimension, right: CGFloat) -> CPLayoutDimension {
return CPLayoutDimension(anchor: left, multiplier: 1, constant: right)
}
static public func + (left: CGFloat, right: NSLayoutDimension) -> CPLayoutDimension {
return right + left
}
static public func - (left: NSLayoutDimension, right: CGFloat) -> CPLayoutDimension {
return left + (-right)
}
static public func * (left: NSLayoutDimension, right: CGFloat) -> CPLayoutDimension {
return CPLayoutDimension(anchor: left, multiplier: right, constant: 0)
}
static public func * (left: CGFloat, right: NSLayoutDimension) -> CPLayoutDimension {
return right * left
}
static public func / (left: NSLayoutDimension, right: CGFloat) -> CPLayoutDimension {
return left * (1/right)
}
static public func % (left: CGFloat, right: NSLayoutDimension) -> CPLayoutDimension {
return right * (left/100.0)
}
}
// MARK: - NSLayoutDimension ~ Constant
extension NSLayoutDimension {
@discardableResult
static public func == (left: NSLayoutDimension, right: CGFloat) -> NSLayoutConstraint {
let constraint = left.constraint(equalToConstant: right)
constraint.isActive = true
return constraint
}
@discardableResult
static public func >= (left: NSLayoutDimension, right: CGFloat) -> NSLayoutConstraint {
let constraint = left.constraint(greaterThanOrEqualToConstant: right)
constraint.isActive = true
return constraint
}
@discardableResult
static public func <= (left: NSLayoutDimension, right: CGFloat) -> NSLayoutConstraint {
let constraint = left.constraint(lessThanOrEqualToConstant: right)
constraint.isActive = true
return constraint
}
}
// MARK: - NSLayoutDimension ~ NSLayoutDimension
extension NSLayoutDimension {
@discardableResult
static public func == (left: NSLayoutDimension, right: NSLayoutDimension) -> NSLayoutConstraint {
return left == CPLayoutDimension(anchor: right, multiplier: 1.0, constant: 0.0)
}
@discardableResult
static public func >= (left: NSLayoutDimension, right: NSLayoutDimension) -> NSLayoutConstraint {
return left >= CPLayoutDimension(anchor: right, multiplier: 1.0, constant: 0.0)
}
@discardableResult
static public func <= (left: NSLayoutDimension, right: NSLayoutDimension) -> NSLayoutConstraint {
return left <= CPLayoutDimension(anchor: right, multiplier: 1.0, constant: 0.0)
}
}
// MARK: - NSLayoutDimension ~ PriorityConstant
extension NSLayoutDimension {
@discardableResult
static public func == (left: NSLayoutDimension, right: PriorityConstant) -> NSLayoutConstraint {
let constraint = left.constraint(equalToConstant: right.constant)
constraint.priority = right.priority
constraint.isActive = true
return constraint
}
@discardableResult
static public func >= (left: NSLayoutDimension, right: PriorityConstant) -> NSLayoutConstraint {
let constraint = left.constraint(greaterThanOrEqualToConstant: right.constant)
constraint.priority = right.priority
constraint.isActive = true
return constraint
}
@discardableResult
static public func <= (left: NSLayoutDimension, right: PriorityConstant) -> NSLayoutConstraint {
let constraint = left.constraint(lessThanOrEqualToConstant: right.constant)
constraint.priority = right.priority
constraint.isActive = true
return constraint
}
}
| mit | 5f9381559a29cebccd753c56678f3818 | 34.368 | 101 | 0.697354 | 5.081609 | false | false | false | false |
acchou/RxGmail | RxGmail/Classes/RxGmail.swift | 1 | 36713 | import GoogleAPIClientForREST
import RxSwift
import RxSwiftExt
// Protocols used to retroactively model all paged query types in the Gmail API.
public protocol PagedQuery {
var pageToken: String? { get set }
}
public protocol PagedResponse {
var nextPageToken: String? { get }
}
extension RxGmail.MessageListQuery: PagedQuery { }
extension RxGmail.MessageListResponse: PagedResponse { }
extension RxGmail.DraftsListQuery: PagedQuery { }
extension RxGmail.DraftsListResponse: PagedResponse { }
extension RxGmail.HistoryQuery: PagedQuery { }
extension RxGmail.HistoryResponse: PagedResponse { }
extension RxGmail.ThreadListQuery: PagedQuery { }
extension RxGmail.ThreadListResponse: PagedResponse { }
extension Observable where Element: RxGmail.Response {
/**
Override of Observable.debug for GTLRObjects prints a json string.
*/
public func debug(_ identifier: String? = "", trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) -> Observable<E> {
let identifier = identifier ?? ""
let prefix = "\(function) \(identifier) ->"
return self.do (
onNext: { print("\(prefix) next \($0.jsonString())") },
onError: { print("\(prefix) error \($0.localizedDescription)") },
onCompleted: { print("\(prefix) *completed*") },
onSubscribe: { print("\(prefix) *subscribed*") },
onDispose: { print("\(prefix) *disposed*") }
)
}
}
public class RxGmail {
let service: GTLRGmailService
public init(gmailService: GTLRGmailService) {
GTMSessionFetcher.setLoggingEnabled(true)
self.service = gmailService
}
// MARK: - Types
public typealias GmailService = GTLRGmailService
public typealias QueryType = GTLRQueryProtocol
public typealias Query = GTLRQuery
public typealias Response = GTLRObject
public typealias BatchQuery = GTLRBatchQuery
public typealias BatchResult = GTLRBatchResult
public typealias ServiceTicket = GTLRServiceTicket
public typealias UploadParameters = GTLRUploadParameters
public typealias ErrorObject = GTLRErrorObject
public typealias ErrorObjectDetail = GTLRErrorObjectDetail
public typealias ErrorObjectItem = GTLRErrorObjectErrorItem
public typealias Label = GTLRGmail_Label
public typealias LabelsListQuery = GTLRGmailQuery_UsersLabelsList
public typealias LabelsListResponse = GTLRGmail_ListLabelsResponse
public typealias LabelsCreateQuery = GTLRGmailQuery_UsersLabelsCreate
public typealias LabelsDeleteQuery = GTLRGmailQuery_UsersLabelsDelete
public typealias LabelsGetQuery = GTLRGmailQuery_UsersLabelsGet
public typealias LabelsPatchQuery = GTLRGmailQuery_UsersLabelsPatch
public typealias LabelsUpdateQuery = GTLRGmailQuery_UsersLabelsUpdate
public typealias Message = GTLRGmail_Message
public typealias MessagePartBody = GTLRGmail_MessagePartBody
public typealias MessagePart = GTLRGmail_MessagePart
public typealias MessagePartHeader = GTLRGmail_MessagePartHeader
public typealias MessageListQuery = GTLRGmailQuery_UsersMessagesList
public typealias MessageListResponse = GTLRGmail_ListMessagesResponse
public typealias MessageBatchDeleteQuery = GTLRGmailQuery_UsersMessagesBatchDelete
public typealias MessageBatchDeleteRequest = GTLRGmail_BatchDeleteMessagesRequest
public typealias MessageBatchModifyQuery = GTLRGmailQuery_UsersMessagesBatchModify
public typealias MessageBatchModifyRequest = GTLRGmail_BatchModifyMessagesRequest
public typealias MessageDeleteQuery = GTLRGmailQuery_UsersMessagesDelete
public typealias MessageGetQuery = GTLRGmailQuery_UsersMessagesGet
public typealias MessageImportQuery = GTLRGmailQuery_UsersMessagesImport
public typealias MessageInsertQuery = GTLRGmailQuery_UsersMessagesInsert
public typealias MessageModifyQuery = GTLRGmailQuery_UsersMessagesModify
public typealias MessageModifyRequest = GTLRGmail_ModifyMessageRequest
public typealias MessageSendQuery = GTLRGmailQuery_UsersMessagesSend
public typealias MessageTrashQuery = GTLRGmailQuery_UsersMessagesTrash
public typealias MessageUntrashQuery = GTLRGmailQuery_UsersMessagesUntrash
public typealias MessageAttachmentQuery = GTLRGmailQuery_UsersMessagesAttachmentsGet
public typealias Profile = GTLRGmail_Profile
public typealias ProfileQuery = GTLRGmailQuery_UsersGetProfile
public typealias WatchRequest = GTLRGmail_WatchRequest
public typealias WatchResponse = GTLRGmail_WatchResponse
public typealias WatchStartQuery = GTLRGmailQuery_UsersWatch
public typealias WatchStopQuery = GTLRGmailQuery_UsersStop
public typealias Draft = GTLRGmail_Draft
public typealias DraftsCreateQuery = GTLRGmailQuery_UsersDraftsCreate
public typealias DraftsDeleteQuery = GTLRGmailQuery_UsersDraftsDelete
public typealias DraftsGetQuery = GTLRGmailQuery_UsersDraftsGet
public typealias DraftsListQuery = GTLRGmailQuery_UsersDraftsList
public typealias DraftsListResponse = GTLRGmail_ListDraftsResponse
public typealias DraftsSendQuery = GTLRGmailQuery_UsersDraftsSend
public typealias DraftsUpdateQuery = GTLRGmailQuery_UsersDraftsUpdate
public typealias HistoryQuery = GTLRGmailQuery_UsersHistoryList
public typealias HistoryResponse = GTLRGmail_ListHistoryResponse
public typealias SettingsAutoForwardingQuery = GTLRGmailQuery_UsersSettingsGetAutoForwarding
public typealias SettingsAutoForwarding = GTLRGmail_AutoForwarding
public typealias SettingsAutoForwardingUpdateQuery = GTLRGmailQuery_UsersSettingsUpdateAutoForwarding
public typealias SettingsImapQuery = GTLRGmailQuery_UsersSettingsGetImap
public typealias SettingsImapUpdateQuery = GTLRGmailQuery_UsersSettingsUpdateImap
public typealias SettingsImap = GTLRGmail_ImapSettings
public typealias SettingsPopQuery = GTLRGmailQuery_UsersSettingsGetPop
public typealias SettingsPopUpdateQuery = GTLRGmailQuery_UsersSettingsUpdatePop
public typealias SettingsPop = GTLRGmail_PopSettings
public typealias SettingsVacationQuery = GTLRGmailQuery_UsersSettingsGetVacation
public typealias SettingsVacationUpdateQuery = GTLRGmailQuery_UsersSettingsUpdateVacation
public typealias SettingsVacation = GTLRGmail_VacationSettings
public typealias FilterCreateQuery = GTLRGmailQuery_UsersSettingsFiltersCreate
public typealias Filter = GTLRGmail_Filter
public typealias FilterGetQuery = GTLRGmailQuery_UsersSettingsFiltersGet
public typealias FilterDeleteQuery = GTLRGmailQuery_UsersSettingsFiltersDelete
public typealias FilterListQuery = GTLRGmailQuery_UsersSettingsFiltersList
public typealias FilterListResponse = GTLRGmail_ListFiltersResponse
public typealias ForwardingAddress = GTLRGmail_ForwardingAddress
public typealias ForwardingAddressGetQuery = GTLRGmailQuery_UsersSettingsForwardingAddressesGet
public typealias ForwardingAddressDeleteQuery = GTLRGmailQuery_UsersSettingsForwardingAddressesDelete
public typealias ForwardingAddressCreateQuery = GTLRGmailQuery_UsersSettingsForwardingAddressesCreate
public typealias ForwardingAddressListQuery = GTLRGmailQuery_UsersSettingsForwardingAddressesList
public typealias ForwardingAddressListResponse = GTLRGmail_ListForwardingAddressesResponse
public typealias SendAsAlias = GTLRGmail_SendAs
public typealias SendAsListResponse = GTLRGmail_ListSendAsResponse
public typealias SendAsGetQuery = GTLRGmailQuery_UsersSettingsSendAsGet
public typealias SendAsListQuery = GTLRGmailQuery_UsersSettingsSendAsList
public typealias SendAsPatchQuery = GTLRGmailQuery_UsersSettingsSendAsPatch
public typealias SendAsCreateQuery = GTLRGmailQuery_UsersSettingsSendAsCreate
public typealias SendAsDeleteQuery = GTLRGmailQuery_UsersSettingsSendAsDelete
public typealias SendAsUpdateQuery = GTLRGmailQuery_UsersSettingsSendAsUpdate
public typealias SendAsVerifyQuery = GTLRGmailQuery_UsersSettingsSendAsVerify
public typealias ThreadListQuery = GTLRGmailQuery_UsersThreadsList
public typealias ThreadListResponse = GTLRGmail_ListThreadsResponse
public typealias Thread = GTLRGmail_Thread
public typealias ThreadModifyRequest = GTLRGmail_ModifyThreadRequest
public typealias ThreadGetQuery = GTLRGmailQuery_UsersThreadsGet
public typealias ThreadTrashQuery = GTLRGmailQuery_UsersThreadsTrash
public typealias ThreadDeleteQuery = GTLRGmailQuery_UsersThreadsDelete
public typealias ThreadModifyQuery = GTLRGmailQuery_UsersThreadsModify
public typealias ThreadUntrashQuery = GTLRGmailQuery_UsersThreadsUntrash
// MARK: - Generic request helper functions
fileprivate func createRequest(observer: AnyObserver<Any?>, query: QueryType) -> ServiceTicket {
let serviceTicket = service.executeQuery(query) { ticket, object, error in
if let error = error {
observer.onError(error)
} else {
observer.onNext(object)
observer.onCompleted()
}
}
return serviceTicket
}
/**
Execute a query.
- Parameter query: the query to execute.
- Returns: An observable with the fetched response. This variant of `execute` returns an optional, which will be `nil` only for queries that explicitly return `nil` to signal success. Most responses will return an instance of `GTLRObject`.
*/
public func execute<R: Response>(query: QueryType) -> Observable<R?> {
return Observable<Any?>.create { [weak self] observer in
let serviceTicket = self?.createRequest(observer: observer, query: query)
return Disposables.create {
serviceTicket?.cancel()
}
}
.map { $0 as! R? }
}
/**
Execute a query.
- Parameter query: the query to execute.
- Returns: an instance of GTLRObject fetched by the query upon success.
*/
public func execute<R: Response>(query: QueryType) -> Observable<R> {
return execute(query: query).map { $0! }
}
public func execute(query: QueryType) -> Observable<Void> {
let response: Observable<Response?> = execute(query: query)
return response.map { _ in () }
}
/**
Execute a query returning a paged response.
- Parameter query: the query to execute, the result of the query should
be a paged response.
- Returns: an observable that sends one event per page.
*/
public func executePaged<Q, R>(query: Q) -> Observable<R>
where Q: QueryType, Q: PagedQuery, R: Response, R: PagedResponse {
func getRemainingPages(after previousPage: R?) -> Observable<R> {
let nextPageToken = previousPage?.nextPageToken
if previousPage != nil && nextPageToken == nil {
return .empty()
}
var query = query.copy() as! Q
query.pageToken = nextPageToken
let response: Observable<R> = execute(query: query)
return response.flatMap { page -> Observable<R> in
return Observable.just(page).concat(getRemainingPages(after: page))
}
}
return getRemainingPages(after: nil)
}
// MARK: - Users
public func getProfile(forUserId userId: String = "me") -> Observable<Profile> {
let query = ProfileQuery.query(withUserId: userId)
return getProfile(query: query)
}
public func getProfile(query: ProfileQuery) -> Observable<Profile> {
return execute(query: query)
}
public func watchRequest(request: WatchRequest, forUserId userId: String = "me") -> Observable<WatchResponse> {
let query = WatchStartQuery.query(withObject: request, userId: userId)
return watchRequest(query: query)
}
public func watchRequest(query: WatchStartQuery) -> Observable<WatchResponse> {
return execute(query: query)
}
public func stopNotifications(forUserId userId: String = "me") -> Observable<Void> {
let query = WatchStopQuery.query(withUserId: userId)
return stopNotifications(query: query)
}
public func stopNotifications(query: WatchStopQuery) -> Observable<Void> {
return execute(query: query)
}
// MARK: - Drafts
public func createDraft(draft: Draft, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Draft> {
let query = DraftsCreateQuery.query(withObject: draft, userId: userId, uploadParameters: uploadParameters)
return createDraft(query: query)
}
public func createDraft(query: DraftsCreateQuery) -> Observable<Draft> {
return execute(query: query)
}
public func deleteDraft(draftID: String, forUserId userId: String = "me") -> Observable<Void> {
let query = DraftsDeleteQuery.query(withUserId: userId, identifier: draftID)
return deleteDraft(query: query)
}
public func deleteDraft(query: DraftsDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func getDraft(draftID: String, format: String? = nil, forUserId userId: String = "me") -> Observable<Draft> {
let query = DraftsGetQuery.query(withUserId: userId, identifier: draftID)
query.format = format
return getDraft(query: query)
}
public func getDraft(query: DraftsGetQuery) -> Observable<Draft> {
return execute(query: query)
}
public func listDrafts(forUserId userId: String = "me") -> Observable<DraftsListResponse> {
let query = DraftsListQuery.query(withUserId: userId)
return listDrafts(query: query)
}
public func listDrafts(query: DraftsListQuery) -> Observable<DraftsListResponse> {
return executePaged(query: query)
}
public func sendDraft(draft: Draft, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Message> {
let query = DraftsSendQuery.query(withObject: draft, userId: userId, uploadParameters: uploadParameters)
return sendDraft(query: query)
}
public func sendDraft(query: DraftsSendQuery) -> Observable<Message> {
return execute(query: query)
}
public func updateDraft(draftID: String, draft: Draft, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Draft> {
let query = DraftsUpdateQuery.query(withObject: draft, userId: userId, identifier: draftID, uploadParameters: uploadParameters)
return updateDraft(query: query)
}
public func updateDraft(query: DraftsUpdateQuery) -> Observable<Draft> {
return execute(query: query)
}
// MARK: - History
public func history(startHistoryId: UInt64, forUserId userId: String = "me") -> Observable<HistoryResponse> {
let query = HistoryQuery.query(withUserId: userId)
query.startHistoryId = startHistoryId
return history(query: query)
}
public func history(query: HistoryQuery) -> Observable<HistoryResponse> {
return executePaged(query: query)
}
// MARK: - Labels
public func listLabels(forUserId userId: String = "me") -> Observable<LabelsListResponse> {
let query = LabelsListQuery.query(withUserId: userId)
return self.listLabels(query: query)
}
public func listLabels(query: LabelsListQuery) -> Observable<LabelsListResponse> {
return execute(query: query)
}
public func createLabel(label: Label, forUserId userId: String = "me") -> Observable<Label> {
let query = LabelsCreateQuery.query(withObject: label, userId: userId)
return createLabel(query: query)
}
public func createLabel(query: LabelsCreateQuery) -> Observable<Label> {
return execute(query: query)
}
public func deleteLabel(labelId: String, forUserId userId: String = "me") -> Observable<Void> {
let query = LabelsDeleteQuery.query(withUserId: userId, identifier: labelId)
return deleteLabel(query: query)
}
public func deleteLabel(query: LabelsDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func getLabel(labelId: String, forUserId userId: String = "me") -> Observable<Label> {
let query = LabelsGetQuery.query(withUserId: userId, identifier: labelId)
return getLabel(query: query)
}
public func getLabel(query: LabelsGetQuery) -> Observable<Label> {
return execute(query: query)
}
public func patchLabel(labelId: String, updatedLabel: Label, forUserId userId: String = "me") -> Observable<Label> {
let query = LabelsPatchQuery.query(withObject: updatedLabel, userId: userId, identifier: userId)
return patchLabel(query: query)
}
public func patchLabel(query: LabelsPatchQuery) -> Observable<Label> {
return execute(query: query)
}
public func updateLabel(labelId: String, updatedLabel: Label, forUserId userId: String = "me") -> Observable<Label> {
let query = LabelsUpdateQuery.query(withObject: updatedLabel, userId: userId, identifier: labelId)
return updateLabel(query: query)
}
public func updateLabel(query: LabelsUpdateQuery) -> Observable<Label> {
return execute(query: query)
}
// MARK: - Messages
// Each event returns a page of messages.
public func listMessages(forUserId userId: String = "me") -> Observable<MessageListResponse> {
let query = MessageListQuery.query(withUserId: userId)
return listMessages(query: query)
}
public func listMessages(query: MessageListQuery) -> Observable<MessageListResponse> {
return executePaged(query: query)
}
public func batchDeleteMessages(request: MessageBatchDeleteRequest, forUserId userId: String = "me") -> Observable<Void> {
let query = MessageBatchDeleteQuery.query(withObject: request, userId: userId)
return batchDeleteMessages(query: query)
}
public func batchDeleteMessages(query: MessageBatchDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func batchModifyMessages(request: MessageBatchModifyRequest, forUserId userId: String = "me") -> Observable<Void> {
let query = MessageBatchModifyQuery.query(withObject: request, userId: userId)
return batchModifyMessages(query: query)
}
public func batchModifyMessages(query: MessageBatchModifyQuery) -> Observable<Void> {
return execute(query: query)
}
public func deleteMessage(messageId: String, forUserId userId: String = "me") -> Observable<Void> {
let query = MessageDeleteQuery.query(withUserId: userId, identifier: messageId)
return deleteMessage(query: query)
}
public func deleteMessage(query: MessageDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func getMessage(messageId: String, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageGetQuery.query(withUserId: userId, identifier: messageId)
return getMessage(query: query)
}
public func getMessage(query: MessageGetQuery) -> Observable<Message> {
return execute(query: query)
}
public func importMessage(message: Message, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageImportQuery.query(withObject: message, userId: userId, uploadParameters: uploadParameters)
return importMessage(query: query)
}
public func importMessage(query: MessageImportQuery) -> Observable<Message> {
return execute(query: query)
}
public func insertMessage(message: Message, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageInsertQuery.query(withObject: message, userId: userId, uploadParameters: uploadParameters)
return insertMessage(query: query)
}
public func insertMessage(query: MessageInsertQuery) -> Observable<Message> {
return execute(query: query)
}
public func modifyMessage(messageId: String, request: MessageModifyRequest, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageModifyQuery.query(withObject: request, userId: userId, identifier: messageId)
return modifyMessage(query: query)
}
public func modifyMessage(query: MessageModifyQuery) -> Observable<Message> {
return execute(query: query)
}
public func sendMessage(message: Message, uploadParameters: UploadParameters? = nil, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageSendQuery.query(withObject: message, userId: userId, uploadParameters: uploadParameters)
return sendMessage(query: query)
}
public func sendMessage(query: MessageSendQuery) -> Observable<Message> {
return execute(query: query)
}
public func trashMessage(messageId: String, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageTrashQuery.query(withUserId: userId, identifier: messageId)
return trashMessage(query: query)
}
public func trashMessage(query: MessageTrashQuery) -> Observable<Message> {
return execute(query: query)
}
public func untrashMessage(messageId: String, forUserId userId: String = "me") -> Observable<Message> {
let query = MessageUntrashQuery.query(withUserId: userId, identifier: messageId)
return untrashMessage(query: query)
}
public func untrashMessage(query: MessageUntrashQuery) -> Observable<Message> {
return execute(query: query)
}
// MARK: - Attachments
public func getAttachments(messageId: String, attachmentId: String, forUserId userId: String = "me") -> Observable<MessagePartBody> {
let query = MessageAttachmentQuery.query(withUserId: userId, messageId: messageId, identifier: attachmentId)
return getAttachments(query: query)
}
public func getAttachments(query: MessageAttachmentQuery) -> Observable<MessagePartBody> {
return execute(query: query)
}
// Mark: - Settings
public func getAutoForwarding(forUserId userId: String = "me") -> Observable<SettingsAutoForwarding> {
let query = SettingsAutoForwardingQuery.query(withUserId: userId)
return getAutoForwarding(query: query)
}
public func getAutoForwarding(query: SettingsAutoForwardingQuery) -> Observable<SettingsAutoForwarding> {
return execute(query: query)
}
public func updateAutoForwarding(forwardingSettings: SettingsAutoForwarding, forUserId userId: String = "me") -> Observable<SettingsAutoForwarding> {
let query = SettingsAutoForwardingUpdateQuery.query(withObject: forwardingSettings, userId: userId)
return updateAutoForwarding(query: query)
}
public func updateAutoForwarding(query: SettingsAutoForwardingUpdateQuery) -> Observable<SettingsAutoForwarding> {
return execute(query: query)
}
public func getImap(forUserId userId: String = "me") -> Observable<SettingsImap> {
let query = SettingsImapQuery.query(withUserId: userId)
return getImap(query: query)
}
public func getImap(query: SettingsImapQuery) -> Observable<SettingsImap> {
return execute(query: query)
}
public func updateImap(imapSettings: SettingsImap, forUserId userId: String = "me") -> Observable<SettingsImap> {
let query = SettingsImapUpdateQuery.query(withObject: imapSettings, userId: userId)
return updateImap(query: query)
}
public func updateImap(query: SettingsImapUpdateQuery) -> Observable<SettingsImap> {
return execute(query: query)
}
public func getPop(forUserId userId: String = "me") -> Observable<SettingsPop> {
let query = SettingsPopQuery.query(withUserId: userId)
return getPop(query: query)
}
public func getPop(query: SettingsPopQuery) -> Observable<SettingsPop> {
return execute(query: query)
}
public func updatePop(popSettings: SettingsPop, forUserId userId: String = "me") -> Observable<SettingsPop> {
let query = SettingsPopUpdateQuery.query(withObject: popSettings, userId: userId)
return updatePop(query: query)
}
public func updatePop(query: SettingsPopUpdateQuery) -> Observable<SettingsPop> {
return execute(query: query)
}
public func getVacation(forUserId userId: String = "me") -> Observable<SettingsVacation> {
let query = SettingsVacationQuery.query(withUserId: userId)
return getVacation(query: query)
}
public func getVacation(query: SettingsVacationQuery) -> Observable<SettingsVacation> {
return execute(query: query)
}
public func updateVacation(vacationSettings: SettingsVacation, forUserId userId: String = "me") -> Observable<SettingsVacation> {
let query = SettingsVacationUpdateQuery.query(withObject: vacationSettings, userId: userId)
return updateVacation(query: query)
}
public func updateVacation(query: SettingsVacationUpdateQuery) -> Observable<SettingsVacation> {
return execute(query: query)
}
// MARK: - Filters
public func createFilter(filter: Filter, forUserId userId: String = "me") -> Observable<Filter> {
let query = FilterCreateQuery.query(withObject: filter, userId: userId)
return createFilter(query: query)
}
public func createFilter(query: FilterCreateQuery) -> Observable<Filter> {
return execute(query: query)
}
public func getFilter(filterId: String, forUserId userId: String = "me") -> Observable<Filter> {
let query = FilterGetQuery.query(withUserId: userId, identifier: filterId)
return getFilter(query: query)
}
public func getFilter(query: FilterGetQuery) -> Observable<Filter> {
return execute(query: query)
}
public func deleteFilter(filterId: String, forUserId userId: String = "me") -> Observable<Void> {
let query = FilterDeleteQuery.query(withUserId: userId, identifier: filterId)
return deleteFilter(query: query)
}
public func deleteFilter(query: FilterDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func listFilters(forUserId userId: String = "me") -> Observable<FilterListResponse> {
let query = FilterListQuery.query(withUserId: userId)
return listFilters(query: query)
}
public func listFilters(query: FilterListQuery) -> Observable<FilterListResponse> {
return execute(query: query)
}
// MARK: - Forward addresses
public func listForwardingAddresses(forUserId userId: String = "me") -> Observable<ForwardingAddressListResponse> {
let query = ForwardingAddressListQuery.query(withUserId: userId)
return listForwardingAddresses(query: query)
}
public func listForwardingAddresses(query: ForwardingAddressListQuery) -> Observable<ForwardingAddressListResponse> {
return execute(query: query)
}
public func getForwardingAddress(forwardingEmail: String, forUserId userId: String = "me") -> Observable<ForwardingAddress> {
let query = ForwardingAddressGetQuery.query(withUserId: userId, forwardingEmail: forwardingEmail)
return getForwardingAddress(query: query)
}
public func getForwardingAddress(query: ForwardingAddressGetQuery) -> Observable<ForwardingAddress> {
return execute(query: query)
}
public func createForwardingAddress(forwardingAddress: ForwardingAddress, forUserId userId: String = "me") -> Observable<ForwardingAddress> {
let query = ForwardingAddressCreateQuery.query(withObject: forwardingAddress, userId: userId)
return createForwardingAddress(query: query)
}
public func createForwardingAddress(query: ForwardingAddressCreateQuery) -> Observable<ForwardingAddress> {
return execute(query: query)
}
public func deleteForwardingAddress(forwardingEmail: String, forUserId userId: String = "me") -> Observable<Void> {
let query = ForwardingAddressDeleteQuery.query(withUserId: userId, forwardingEmail: forwardingEmail)
return deleteForwardingAddress(query: query)
}
public func deleteForwardingAddress(query: ForwardingAddressDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
// MARK: Send As Aliases
public func createSendAsAlias(sendAsAlias: SendAsAlias, forUserId userId: String = "me") -> Observable<SendAsAlias> {
let query = SendAsCreateQuery.query(withObject: sendAsAlias, userId: userId)
return createSendAsAlias(query: query)
}
public func createSendAsAlias(query: SendAsCreateQuery) -> Observable<SendAsAlias> {
return execute(query: query)
}
public func getSendAsAlias(sendAsEmail: String, forUserId userId: String = "me") -> Observable<SendAsAlias> {
let query = SendAsGetQuery.query(withUserId: userId, sendAsEmail: sendAsEmail)
return getSendAsAlias(query: query)
}
public func getSendAsAlias(query: SendAsGetQuery) -> Observable<SendAsAlias> {
return execute(query: query)
}
public func listSendAsAliases(forUserId userId: String = "me") -> Observable<SendAsListResponse> {
let query = SendAsListQuery.query(withUserId: userId)
return listSendAsAliases(query: query)
}
public func listSendAsAliases(query: SendAsListQuery) -> Observable<SendAsListResponse> {
return execute(query: query)
}
public func patchSendAsAlias(sendAsAlias: SendAsAlias, sendAsEmail: String, forUserId userId: String = "me") -> Observable<SendAsAlias> {
let query = SendAsPatchQuery.query(withObject: sendAsAlias, userId: userId, sendAsEmail: sendAsEmail)
return patchSendAsAlias(query: query)
}
public func patchSendAsAlias(query: SendAsPatchQuery) -> Observable<SendAsAlias> {
return execute(query: query)
}
public func deleteSendAsAlias(sendAsEmail: String, forUserId userId: String = "me") -> Observable<Void> {
let query = SendAsDeleteQuery.query(withUserId: userId, sendAsEmail: sendAsEmail)
return deleteSendAsAlias(query: query)
}
public func deleteSendAsAlias(query: SendAsDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func updateSendAsAlias(sendAsAlias: SendAsAlias, sendAsEmail: String, forUserId userId: String = "me") -> Observable<SendAsAlias> {
let query = SendAsUpdateQuery.query(withObject: sendAsAlias, userId: userId, sendAsEmail: sendAsEmail)
return updateSendAsAlias(query: query)
}
public func updateSendAsAlias(query: SendAsUpdateQuery) -> Observable<SendAsAlias> {
return execute(query: query)
}
public func verifySendAsAlias(sendAsEmail: String, forUserId userId: String = "me") -> Observable<Void> {
let query = SendAsVerifyQuery.query(withUserId: userId, sendAsEmail: sendAsEmail)
return verifySendAsAlias(query: query)
}
public func verifySendAsAlias(query: SendAsVerifyQuery) -> Observable<Void> {
return execute(query: query)
}
public func listThreads(forUserId userId: String = "me") -> Observable<ThreadListResponse> {
let query = ThreadListQuery.query(withUserId: userId)
return listThreads(query: query)
}
public func listThreads(query: ThreadListQuery) -> Observable<ThreadListResponse> {
return executePaged(query: query)
}
public func getThread(threadId: String, forUserId userId: String = "me") -> Observable<Thread> {
let query = ThreadGetQuery.query(withUserId: userId, identifier: threadId)
return getThread(query: query)
}
public func getThread(query: ThreadGetQuery) -> Observable<Thread> {
return execute(query: query)
}
public func trashThread(threadId: String, forUserId userId: String = "me") -> Observable<Thread> {
let query = ThreadTrashQuery.query(withUserId: userId, identifier: threadId)
return trashThread(query: query)
}
public func trashThread(query: ThreadTrashQuery) -> Observable<Thread> {
return execute(query: query)
}
public func deleteThread(threadId: String, forUserId userId: String = "me") -> Observable<Void> {
let query = ThreadDeleteQuery.query(withUserId: userId, identifier: threadId)
return deleteThread(query: query)
}
public func deleteThread(query: ThreadDeleteQuery) -> Observable<Void> {
return execute(query: query)
}
public func modifyThread(modifyThreadRequest: ThreadModifyRequest, threadId: String, forUserId userId: String = "me") -> Observable<Thread> {
let query = ThreadModifyQuery.query(withObject: modifyThreadRequest, userId: userId, identifier: threadId)
return modifyThread(query: query)
}
public func modifyThread(query: ThreadModifyQuery) -> Observable<Thread> {
return execute(query: query)
}
public func untrashThread(threadId: String, forUserId userId: String = "me") -> Observable<Thread> {
let query = ThreadUntrashQuery.query(withUserId: userId, identifier: threadId)
return untrashThread(query: query)
}
public func untrashThread(query: ThreadUntrashQuery) -> Observable<Thread> {
return execute(query: query)
}
// Batch queries
public func batchQuery(queries: [Query]) -> Observable<BatchResult> {
let query = BatchQuery(queries: queries)
return execute(query: query)
}
}
public protocol GetQueryType {
static func query(withUserId userId: String, identifier: String) -> Self
var format: String? { get set }
}
public protocol Identifiable {
associatedtype QueryType: RxGmail.Query, GetQueryType
var identifier: String? { get }
}
extension Identifiable {
func getQuery(forUserId userId: String = "me") -> QueryType {
return QueryType.query(withUserId: userId, identifier: self.identifier!)
}
}
extension RxGmail.MessageGetQuery: GetQueryType { }
extension RxGmail.ThreadGetQuery: GetQueryType { }
extension RxGmail.LabelsGetQuery: GetQueryType {
public var format: String? {
get { return nil }
set { }
}
}
extension RxGmail.Message: Identifiable {
public typealias QueryType = RxGmail.MessageGetQuery
}
extension RxGmail.Label: Identifiable {
public typealias QueryType = RxGmail.LabelsGetQuery
}
extension RxGmail.Thread: Identifiable {
public typealias QueryType = RxGmail.ThreadGetQuery
}
extension RxGmail {
// See https://developers.google.com/gmail/api/v1/reference/users/messages/get
public enum DetailType {
case full
case metadata
case minimal
case raw
func asGmailFormat() -> String {
switch self {
case .full: return kGTLRGmailFormatFull
case .metadata: return kGTLRGmailFormatMetadata
case .minimal: return kGTLRGmailFormatMinimal
case .raw: return kGTLRGmailFormatRaw
}
}
}
/**
Gmail "List" queries return only response objects with identifiers but no details. fetchMetadata uses a batch query to retrieve details for all of the response objects in an array.
- Parameter identifiables: array of response objects with an "identifier" attribute
- Parameter format: Specifies what details to retrieve.
- Returns: An observable of the array of response objects whose metadata were successfully retrieved.
*/
public func fetchDetails<T: Identifiable>(_ identifiables: [T], detailType: DetailType? = nil, forUserId userId: String = "me") -> Observable<[T]>{
let queries: [T.QueryType] = identifiables.map { (identifiable: T) -> T.QueryType in
var query = identifiable.getQuery(forUserId: userId)
query.format = detailType?.asGmailFormat()
return query
}
return self.batchQuery(queries: queries)
.map { $0.successes?.values.map { $0 as! T } }
.unwrap()
}
}
extension RxGmail.Message {
public func parseHeaders() -> [String:String] {
guard let rawHeaders = self.payload?.headers else { return [:] }
var headers = [String:String]()
rawHeaders.forEach {
if let name = $0.name {
headers[name] = $0.value ?? ""
}
}
return headers
}
}
| mit | fc49ba43370329880a73e0952fd77da7 | 41.689535 | 244 | 0.717021 | 4.476649 | false | false | false | false |
pjulien/flatbuffers | tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift | 1 | 9327 | import XCTest
@testable import FlatBuffers
final class FlatBuffersStructsTests: XCTestCase {
func testCreatingStruct() {
let v = createVecWrite(x: 1.0, y: 2.0, z: 3.0)
var b = FlatBufferBuilder(initialSize: 20)
let o = b.create(struct: v, type: Vec.self)
let end = VPointerVec.createVPointer(b: &b, o: o)
b.finish(offset: end)
XCTAssertEqual(b.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 4, 0, 4, 0, 6, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64])
}
func testReadingStruct() {
let v = createVecWrite(x: 1.0, y: 2.0, z: 3.0)
var b = FlatBufferBuilder(initialSize: 20)
let o = b.create(struct: v, type: Vec.self)
let end = VPointerVec.createVPointer(b: &b, o: o)
b.finish(offset: end)
let buffer = b.sizedByteArray
XCTAssertEqual(buffer, [12, 0, 0, 0, 0, 0, 6, 0, 4, 0, 4, 0, 6, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64])
let point = VPointerVec.getRootAsCountry(ByteBuffer(bytes: buffer))
XCTAssertEqual(point.vec?.z, 3.0)
}
func testCreatingVectorStruct() {
var b = FlatBufferBuilder(initialSize: 20)
let path = b.createVector(structs: [createVecWrite(x: 1, y: 2, z: 3), createVecWrite(x: 4.0, y: 5.0, z: 6)], type: Vec.self)
let end = VPointerVectorVec.createVPointer(b: &b, v: path)
b.finish(offset: end)
XCTAssertEqual(b.sizedByteArray, [12, 0, 0, 0, 8, 0, 8, 0, 0, 0, 4, 0, 8, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64])
}
func testCreatingVectorStructWithForcedDefaults() {
var b = FlatBufferBuilder(initialSize: 20, serializeDefaults: true)
let path = b.createVector(structs: [createVecWrite(x: 1, y: 2, z: 3), createVecWrite(x: 4.0, y: 5.0, z: 6)], type: Vec.self)
let end = VPointerVectorVec.createVPointer(b: &b, v: path)
b.finish(offset: end)
XCTAssertEqual(b.sizedByteArray, [12, 0, 0, 0, 8, 0, 12, 0, 4, 0, 8, 0, 8, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64])
}
func testCreatingEnums() {
var b = FlatBufferBuilder(initialSize: 20)
let path = b.createVector(structs: [createVecWrite(x: 1, y: 2, z: 3), createVecWrite(x: 4, y: 5, z: 6)], type: Vec.self)
let end = VPointerVectorVec.createVPointer(b: &b, color: .blue, v: path)
b.finish(offset: end)
XCTAssertEqual(b.sizedByteArray, [12, 0, 0, 0, 8, 0, 12, 0, 4, 0, 8, 0, 8, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64])
}
func testReadingStructWithEnums() {
var b = FlatBufferBuilder(initialSize: 20)
let vec = createVec2(x: 1, y: 2, z: 3, color: .red)
let o = b.create(struct: vec, type: Vec2.self)
let end = VPointerVec2.createVPointer(b: &b, o: o, type: .vec)
b.finish(offset: end)
let buffer = b.sizedByteArray
XCTAssertEqual(buffer, [16, 0, 0, 0, 0, 0, 10, 0, 12, 0, 12, 0, 11, 0, 4, 0, 10, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0])
let point = VPointerVec2.getRootAsCountry(ByteBuffer(bytes: buffer))
XCTAssertEqual(point.vec?.c, Color2.red)
XCTAssertEqual(point.vec?.x, 1.0)
XCTAssertEqual(point.vec?.y, 2.0)
XCTAssertEqual(point.vec?.z, 3.0)
XCTAssertEqual(point.UType, Test1.vec)
}
func testWritingAndMutatingBools() {
var b = FlatBufferBuilder()
let offset = b.create(struct: createProperty(), type: Property.self)
let root = TestMutatingBool.createTestMutatingBool(&b, offsetOfB: offset)
b.finish(offset: root)
let testMutatingBool = TestMutatingBool.getRootAsTestMutatingBool(bb: b.sizedBuffer)
let property = testMutatingBool.b
XCTAssertEqual(property?.property, false)
property?.mutate(property: false)
XCTAssertEqual(property?.property, false)
property?.mutate(property: true)
XCTAssertEqual(property?.property, true)
}
}
func createVecWrite(x: Float32, y: Float32, z: Float32) -> UnsafeMutableRawPointer{
let memory = UnsafeMutableRawPointer.allocate(byteCount: Vec.size, alignment: Vec.alignment)
memory.initializeMemory(as: UInt8.self, repeating: 0, count: Vec.size)
memory.storeBytes(of: x, toByteOffset: 0, as: Float32.self)
memory.storeBytes(of: y, toByteOffset: 4, as: Float32.self)
memory.storeBytes(of: z, toByteOffset: 8, as: Float32.self)
return memory
}
struct Vec: Readable {
var __buffer: ByteBuffer! { __p.bb }
static var size = 12
static var alignment = 4
private var __p: Struct
init(_ fb: ByteBuffer, o: Int32) { __p = Struct(bb: fb, position: o) }
var x: Float32 { return __p.readBuffer(of: Float32.self, at: 0)}
var y: Float32 { return __p.readBuffer(of: Float32.self, at: 4)}
var z: Float32 { return __p.readBuffer(of: Float32.self, at: 8)}
}
struct VPointerVec {
private var __t: Table
private init(_ t: Table) {
__t = t
}
var vec: Vec? { let o = __t.offset(4); return o == 0 ? nil : Vec(__t.bb, o: o + __t.postion) }
@inlinable static func getRootAsCountry(_ bb: ByteBuffer) -> VPointerVec {
return VPointerVec(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
}
static func startVPointer(b: inout FlatBufferBuilder) -> UOffset { b.startTable(with: 1) }
static func finish(b: inout FlatBufferBuilder, s: UOffset) -> Offset<UOffset> { return Offset(offset: b.endTable(at: s)) }
static func createVPointer(b: inout FlatBufferBuilder, o: Offset<UOffset>) -> Offset<UOffset> {
let s = VPointerVec.startVPointer(b: &b)
b.add(structOffset: 4)
return VPointerVec.finish(b: &b, s: s)
}
}
enum Color: UInt32 { case red = 0, green = 1, blue = 2 }
private let VPointerVectorVecOffsets: (color: VOffset, vector: VOffset) = (4, 6)
struct VPointerVectorVec {
static func startVPointer(b: inout FlatBufferBuilder) -> UOffset { b.startTable(with: 2) }
static func addVector(b: inout FlatBufferBuilder, v: Offset<UOffset>) { b.add(offset: v, at: VPointerVectorVecOffsets.vector) }
static func addColor(b: inout FlatBufferBuilder, color: Color) { b.add(element: color.rawValue, def: 1, at: VPointerVectorVecOffsets.color) }
static func finish(b: inout FlatBufferBuilder, s: UOffset) -> Offset<UOffset> { return Offset(offset: b.endTable(at: s)) }
static func createVPointer(b: inout FlatBufferBuilder, color: Color = .green, v: Offset<UOffset>) -> Offset<UOffset> {
let s = VPointerVectorVec.startVPointer(b: &b)
VPointerVectorVec.addVector(b: &b, v: v)
VPointerVectorVec.addColor(b: &b, color: color)
return VPointerVectorVec.finish(b: &b, s: s)
}
}
enum Color2: Int32 { case red = 0, green = 1, blue = 2 }
enum Test1: Byte { case none = 0, vec = 1 }
func createVec2(x: Float32 = 0, y: Float32 = 0, z: Float32 = 0, color: Color2) -> UnsafeMutableRawPointer {
let memory = UnsafeMutableRawPointer.allocate(byteCount: Vec2.size, alignment: Vec2.alignment)
memory.initializeMemory(as: UInt8.self, repeating: 0, count: Vec2.size)
memory.storeBytes(of: x, toByteOffset: 0, as: Float32.self)
memory.storeBytes(of: y, toByteOffset: 4, as: Float32.self)
memory.storeBytes(of: z, toByteOffset: 8, as: Float32.self)
return memory
}
struct Vec2: Readable {
var __buffer: ByteBuffer! { __p.bb }
static var size = 13
static var alignment = 4
private var __p: Struct
init(_ fb: ByteBuffer, o: Int32) { __p = Struct(bb: fb, position: o) }
var c: Color2 { return Color2(rawValue: __p.readBuffer(of: Int32.self, at: 12)) ?? .red }
var x: Float32 { return __p.readBuffer(of: Float32.self, at: 0)}
var y: Float32 { return __p.readBuffer(of: Float32.self, at: 4)}
var z: Float32 { return __p.readBuffer(of: Float32.self, at: 8)}
}
struct VPointerVec2 {
private var __t: Table
private init(_ t: Table) {
__t = t
}
var vec: Vec2? { let o = __t.offset(4); return o == 0 ? nil : Vec2( __t.bb, o: o + __t.postion) }
var UType: Test1? { let o = __t.offset(6); return o == 0 ? Test1.none : Test1(rawValue: __t.readBuffer(of: Byte.self, at: o)) }
@inlinable static func getRootAsCountry(_ bb: ByteBuffer) -> VPointerVec2 {
return VPointerVec2(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
}
static func startVPointer(b: inout FlatBufferBuilder) -> UOffset { b.startTable(with: 3) }
static func finish(b: inout FlatBufferBuilder, s: UOffset) -> Offset<UOffset> { return Offset(offset: b.endTable(at: s)) }
static func createVPointer(b: inout FlatBufferBuilder, o: Offset<UOffset>, type: Test1) -> Offset<UOffset> {
let s = VPointerVec2.startVPointer(b: &b)
b.add(structOffset: 4)
b.add(element: type.rawValue, def: Test1.none.rawValue, at: 6)
b.add(offset: o, at: 8)
return VPointerVec2.finish(b: &b, s: s)
}
}
| apache-2.0 | de8dc583e1704cf7beab71741e3337ef | 45.173267 | 215 | 0.618205 | 3.147823 | false | true | false | false |
maicki/AsyncDisplayKit | examples/CustomCollectionView-Swift/Sample/ViewController.swift | 11 | 3795 | //
// ViewController.swift
// Sample
//
// Created by Rajeev Gupta on 11/9/16.
//
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// 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
// FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import AsyncDisplayKit
class ViewController: UIViewController, MosaicCollectionViewLayoutDelegate, ASCollectionDataSource, ASCollectionDelegate {
var _sections = [[UIImage]]()
let _collectionNode: ASCollectionNode!
let _layoutInspector = MosaicCollectionViewLayoutInspector()
let kNumberOfImages: UInt = 14
required init?(coder aDecoder: NSCoder) {
let layout = MosaicCollectionViewLayout()
layout.numberOfColumns = 3;
layout.headerHeight = 44;
_collectionNode = ASCollectionNode(frame: CGRect.zero, collectionViewLayout: layout)
super.init(coder: aDecoder)
layout.delegate = self
_sections.append([]);
var section = 0
for idx in 0 ..< kNumberOfImages {
let name = String(format: "image_%d.jpg", idx)
_sections[section].append(UIImage(named: name)!)
if ((idx + 1) % 5 == 0 && idx < kNumberOfImages - 1) {
section += 1
_sections.append([])
}
}
_collectionNode.dataSource = self;
_collectionNode.delegate = self;
_collectionNode.view.layoutInspector = _layoutInspector
_collectionNode.backgroundColor = UIColor.white
_collectionNode.view.isScrollEnabled = true
_collectionNode.registerSupplementaryNode(ofKind: UICollectionElementKindSectionHeader)
}
deinit {
_collectionNode.dataSource = nil;
_collectionNode.delegate = nil;
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubnode(_collectionNode!)
}
override func viewWillLayoutSubviews() {
_collectionNode.frame = self.view.bounds;
}
func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {
let image = _sections[indexPath.section][indexPath.item]
return ImageCellNode(with: image)
}
func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode {
let textAttributes : NSDictionary = [
NSFontAttributeName: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline),
NSForegroundColorAttributeName: UIColor.gray
]
let textInsets = UIEdgeInsets(top: 11, left: 0, bottom: 11, right: 0)
let textCellNode = ASTextCellNode(attributes: textAttributes as! [AnyHashable : Any], insets: textInsets)
textCellNode.text = String(format: "Section %zd", indexPath.section + 1)
return textCellNode;
}
func numberOfSections(in collectionNode: ASCollectionNode) -> Int {
return _sections.count
}
func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int {
return _sections[section].count
}
internal func collectionView(_ collectionView: UICollectionView, layout: MosaicCollectionViewLayout, originalItemSizeAtIndexPath: IndexPath) -> CGSize {
return _sections[originalItemSizeAtIndexPath.section][originalItemSizeAtIndexPath.item].size
}
}
| bsd-3-clause | 54d1996cdc2f76331f406907990f509d | 36.574257 | 154 | 0.730435 | 4.667897 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS | DUMessagingUIKit/Constants.swift | 1 | 1274 | //
// Constants.swift
// DUMessagingUI
//
// Created by Pofat Tseng on 2016/5/12.
// Copyright © 2016年 duolC. All rights reserved.
//
import Foundation
/// Global Theme setting
open class GlobalUISettings {
/// Navigation bar tint color
open static var navBarTintColor: UIColor? = nil
/// Navigation bar title text color
static var navBarTitleTextColof: UIColor = UIColor.DUWaterBlueColor()
/// Navigation bar title font
static var navBarTitleFont: UIFont = UIFont.DUNavigationFont()
/// Tint color for whole app
static var tintColor: UIColor = UIColor.DUWaterBlueColor()
static var indicatingStatusColor: UIColor = UIColor.DUWaterBlueColor()
// Message bubble color
open static var outgoingMessageBubbleBackgroundColor: UIColor = UIColor.DUWaterBlueColor()
open static var outgoingMessageTextColor: UIColor = UIColor.white
open static var incomingMessageBubbleBackgroundColor: UIColor = UIColor.DULightgreyColor()
open static var incomingMessageTextColor: UIColor = UIColor.black
}
extension GlobalUISettings {
/// This property can add extra bottom content inset to your message collection view, the default is 0.0
public static var extraMessageCollectionViewBottomInset: CGFloat = 0.0
}
| mit | 9a47a9e5326ae042bc93b5d73b665b73 | 36.382353 | 108 | 0.75059 | 4.672794 | false | false | false | false |
hsubra89/RxStarscream | RxStarscream/RxStarscream.swift | 1 | 5897 | //
// RxStarscream.swift
// RxStarscream
//
// Created by Harish Subramanium on 4/06/2015.
//
//
import RxSwift
import Starscream
public enum WebSocketEvent {
case Connected(socket: WebSocket)
case Disconnected(socket: WebSocket)
case DataMessage(socket: WebSocket, data: NSData)
case TextMessage(socket: WebSocket, message: String)
}
public let RxWebSocketErrorDomain = "RxWebSocketErrorDomain"
/** @hsubra89's approach
* Trying to keep this as a subclass of WebSocket so that the source interface isn't changed.
* The source websocket could also be exposed using @kzaher's approach but that would mean the customizations on them would be lost and would need a minimal amount of code refactoring.
* There are a few reasons why access to the source `WebSocket` object is required.
* 1) Customizing headers on the source WebSocket object. For example, services that are hidden behind a secure layer might need additional headers/cookies attached (in some cases, XSRF-TOKEN's), which can only happen when the source layer is exposed.
* 2) Serve as a drop-in replacement to existing implementations of Starscream. i.e, projects that currently use Starscream can simply change the constructor from `WebSocket` to `RxWebSocket` and then all the original modifications on them continue to work (such as adding additional header's from the above point). It also allows them to call the RxObservable function on the resulting class to start the sequence.
* 3) Allows the websocket to be disconnected when the app goes into the background; ( `ws.disconnect()`) effectively pausing the sequence. When the app comes back to the foreground, calling `ws.connect()` will restore the connection resuming the sequence. This scenario is ideal for most apps.
* Since the source WebSocket needs to be exposed, i've implemented a private delegate class with handling happening within them. I attempted to follow @kzaher's approach by having the handling passed through the Websocket constructor; but those closures are marked as private within starscream and dosen't let me override them, which means the only viable approach was a private delegate class. (Not sure if there's a better way to deal with this)
*/
class RxWebSocket: WebSocket {
private class RxWebSocketDelegate: WebSocketDelegate {
var observable: ObserverOf<WebSocketEvent>
init(observable: ObserverOf<WebSocketEvent>) {
self.observable = observable
}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
sendNext(observable, WebSocketEvent.DataMessage(socket: socket, data: data))
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
sendNext(observable, WebSocketEvent.TextMessage(socket: socket, message: text))
}
func websocketDidConnect(socket: WebSocket) {
sendNext(observable, WebSocketEvent.Connected(socket: socket))
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
// Clean Disconnect
if error?.code == 1000 {
sendNext(observable, WebSocketEvent.Disconnected(socket: socket))
return
}
// Thrown after disconnection. Not sure if this is a bug with starscream.
// Temporarily handling it this way
if error == nil || error?.code == 1 {
return
}
// Websocket Error
sendError(observable, error ?? NSError(domain: RxWebSocketErrorDomain, code: -1, userInfo: nil))
// Remove Delegate
socket.delegate = nil
}
}
// Setting this so that a weak reference for websocket within Starscream is maintained.
// https://github.com/daltoniam/Starscream/issues/35
private var rxDelegate: RxWebSocketDelegate!
func rxObservable() -> Observable<WebSocketEvent> {
return create { observable in
self.rxDelegate = RxWebSocketDelegate(observable: observable)
self.delegate = self.rxDelegate
if !self.isConnected {
self.connect()
}
return AnonymousDisposable {
self.delegate = nil
self.disconnect()
sendCompleted(observable)
}
}
}
}
// @kzaher's approach
// fix for generic Apple compiler message
//public typealias RxWebSocket = RxWebSocket_<Void>
//public class RxWebSocket_<_Void>: Observable<WebSocketEvent> {
//
// let url: NSURL
// let protocols: [String]
//
// init(url: NSURL, protocols: [String]) {
// self.url = url
// self.protocols = protocols
// }
//
// public override func subscribe<O : ObserverType where O.Element == WebSocketEvent>(observer: O) -> Disposable {
// weak var weakWebSocket: WebSocket? = nil
// let webSocket = WebSocket(url: url, protocols: protocols, connect: { () -> Void in
// if let webSocket = weakWebSocket {
// sendNext(observer, .Connected(socket: webSocket))
// }
// }, disconnect: { (error) -> Void in
// println(error)
// sendError(observer, error ?? NSError(domain: RxWebSocketErrorDomain, code: -1, userInfo: nil))
// }, text: { text -> Void in
// sendNext(observer, .TextMessage(message: text))
// }, data: { data -> Void in
// sendNext(observer, .DataMessage(data: data))
// })
//
// weakWebSocket = webSocket
//
// webSocket.connect()
//
// return AnonymousDisposable {
// webSocket.disconnect()
// }
// }
//} | mit | c68538d84696d688249be51e2124f125 | 40.244755 | 448 | 0.640665 | 4.90599 | false | false | false | false |
prine/ROCloudModel | Source/ROCloudModelOperations.swift | 1 | 4843 | //
// CloudModelCRUD.swift
// CloudKitTest
//
// Created by Robin Oster on 02/02/16.
// Copyright © 2016 Prine Development. All rights reserved.
//
import Foundation
import CloudKit
import ROConcurrency
public extension ROCloudModel {
public func save(_ callback:@escaping (_ success:Bool, _ error:Error?, _ record:CKRecord?) -> ()) {
// FIXME: Rewrite that it can handle more than one save at the same time
if let record = self.record {
self.currentDatabase.save(record, completionHandler: { (record, error) in
callback(error == nil, error, record)
})
}
}
public func saveDeep(_ callback:@escaping (_ success:Bool, _ error:NSError?, _ recordID:CKRecordID?) -> ()) {
if let record = record {
self.currentDatabase.save(record, completionHandler: { (record, error) -> Void in
if error == nil {
// Successful
if let recordID = record?.recordID {
callback(true, error as NSError?, recordID)
return
}
callback(false, error as NSError?, nil)
}
})
}
}
public func setReferenceValue<T:ROCloudModel>(_ referenceName:String, value:T?) {
if let givenRecord = value?.record {
self.record?[referenceName] = CKReference(record: givenRecord, action: CKReferenceAction.none)
}
}
public func fetchReferenceSynchronous<T:ROCloudModel>(_ referenceName:String) -> T? {
var retrievedCloudModel:T?
let semaphore = DispatchSemaphore(value: 0)
self.fetchReference(referenceName) { (cloudModel:T) -> () in
retrievedCloudModel = cloudModel
semaphore.signal()
}
let timeout = DispatchTime.now() + Double(1000*1000*5) / Double(NSEC_PER_SEC)
if (semaphore.wait(timeout: timeout) != DispatchTimeoutResult.timedOut) {
SynchronizedLogger.sharedInstance.log("Semaphore time out received")
}
return retrievedCloudModel
}
public func fetchReference<T:ROCloudModel>(_ referenceName:String, callback:@escaping (_ cloudModel:T) -> ()) {
if let reference = self.record?[referenceName] as? CKReference {
self.currentDatabase.fetch(withRecordID: reference.recordID, completionHandler: { (record, error) -> Void in
let cloudModel = T()
cloudModel.record = record
// Store reference locally
self.references.updateValue(reference, forKey: referenceName)
callback(cloudModel)
})
}
}
public func fetchReferenceArray<T:ROCloudModel>(_ referenceName:String, callback:@escaping (_ cloudModels:Array<T>) -> ()) {
if let references = self.record?[referenceName] as? Array<CKReference> {
var recordIDs = Array<CKRecordID>()
for reference in references {
let recordID = reference.recordID
recordIDs.append(recordID)
}
let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDs)
fetchOperation.fetchRecordsCompletionBlock = {
records, error in
if error != nil {
print("\(error)")
} else {
if let records = records {
var cloudModels = Array<T>()
var dict = Dictionary<CKRecordID, T>()
for (recordID, record) in records {
// Generate empty cloud model and set the record
let cloudModel = T()
cloudModel.record = record
dict.updateValue(cloudModel, forKey: recordID)
}
// Fetch records does not return all objects if there are duplicate recordIds
// Therefor we need to loop again over all IDs and use the already fetched records in the lookup dictionary
for recordID in recordIDs {
if let cloudModel = dict[recordID] {
cloudModels.append(cloudModel)
}
}
callback(cloudModels)
}
}
}
self.currentDatabase.add(fetchOperation)
}
}
}
| mit | 00df4cbf90f0c638ee038ae9ce222205 | 36.534884 | 131 | 0.513011 | 5.489796 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.