repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/00176-vtable.swift | mit | 12 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<d-> d { class d:b class b
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
i)
import Foundation
class q<k>: NSObject {
var j: k
e ^(l: m, h) -> h {
f !(l)
}
protocol l {
d g n()
}
class h: l {
class g n() { }
}
(h() o l).p.n()
class l<n : h,
q
var m: Int -> Int = {
n $0
o: Int = { d, l f
n l(d)
}(k, m)
protocol j {
typealias d
typealias n = d
typealias l = d}
class g<q : l, m : l p q.g == m> : j {
}
class g<q, m> {
}
protocol l {
typealias g
d)
func e(h: b) -> <f>(() -> f) -> b {
return { c):h())" }
}
func b<d {
enum b {
func c
var _ = c
}
}
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
func d(b: String-> <c>() -> c)
class A<T : A> {
}
class a {
typealias b = b
}
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func a<d>() -> [c{ enum b {
case c
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
d ""
e}
class d {
func b((Any, d)typealias b = b
func ^(a: BooleanType, Bool) -> Bool {
return !(a)
}
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
j n = a
}
struct n : g {
j n = h
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
let k = a
k()
h
protocol k : h { func h
k
protocol a : a {
}
func b(c) -> <d>(() -> d) {
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
}
protocol l {
class func i()
}
class o: l{ class func i {}
class h: h {
}
class m : C {
}
typealias C = m
func s<S: y, t i o<t> == S.k.b>(r : S) -> t? {
j (u : t?) q r {
l let g = u {
p g
}
}
p v
}
let r : [n?] = [w o = h
typealias h = x<g<h
struct l<e : SequenceType> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
class A<T : A> {
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicl A {
{
typealias b = b
d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
class f<d : d, j : d k d.l == j> {
}
protocol d {
i l
i i
}
struct l<l : d> : d {
i j i() {
l.i()
}
}
protocol f {
}
protocol d : f {
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
(e: o, h:o) -> e
})
}
j(k(m, k(2, 3)))
func l(p: j) -> <n>(() -> n
}
e
protocol h : e { func e
func r(d: t, k: t) -> (((t, t) -> t) -i g {
p m
func e(m)
}
struct e<j> : g {
func e(
h s: n -> n = {
return $u
}
l o: n = { (d: n, o: n -> n) -> n q
return o(d)
}
class A: A {
}
class B : C {
}
typealias C = B
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m<o {
r m {
func n
n _ = n
}
}
class k<l : k
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
struct c<d: SequenceType, b where Optional<b> == d.Generator.Element>
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
({})
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
struct c<d : SequenceType> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
func a(b: Int = 0) {
}
let c = a
c()
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
}func h(c: j) -> <i>(() -> i) -> b {
f j = e
func j<i k i.l == j>(d: B<i>)
f g
}
struct d<i : b> : b {
typealias b = i
typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
func b<e>(e : e) -> c { e
)
func t<v>() -> (v, v -> v) -> v {
var d: ((v, v -> v) -> v)!
q d
}
protocol t {
}
protocol d : t {
}
protocol g : t {
}
s
q l
})
}
d(t(u, t(w, y)))
protocol e {
r j
}
struct m<v : e> {
k x: v
k x: v.j
}
protocol n {
g == o>(n: m<v>) {
}
}
struct e<v> {
k t: [(v, () -> ())] = [](m)
}
struct d<x> : e {
func d(d: d.p) {
}
}
class e<v : e> {
}
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
)
var d = b
=b as c=b
func d() -> String {
return 1
k f {
typealias c
}
class g<i{
}
d(j i)
class h {
typealias i = i
}
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.y) -> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
func a<T>() {
enum b {
case c
}
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
class k<g>: d {
var f: g
init(f: g) {
self.f = f
l. d {
typealias i = l
typealias j = j<i<l>, i>
}
class j {
typealias d = d
func f() {
({})
}
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
func g<h>() -> (h, h -> h) -> h {
f f: ((h, h -> h) -> h)!
j f
}
protocol f {
class func j()
}
struct i {
f d: f.i
func j() {
d.j()
}
}
class g {
typealias f = f
}
func g(f: Int = k) {
}
let i = g
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
struct A<T> {
let a: [(T, () -> ())] = []
}
func f<r>() -> (r, r -> r) -> r {
f r f.j = {
}
{
r) {
s }
}
protocol f {
class func j()
}
class f: f{ class func j {}
protocol j {
class func m()
}
class r: j {
class func m() { }
}
(r() n j).p.m()
j=k n j=k
protocol r {
class func q()
}
s m {
m f: r.q
func q() {
f.q()
}
(l, () -> ())
}
func f<l : o>(r: l)
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
}
class d {
func l<j where j: h, j: d>(l: j) {
l.k()
}
func i(k: b) -> <j>(() -> j) -> b {
f { m m "\(k): \(m())" }
}
protocol h
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
struct c<d : SequenceType> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h.f == c> (c: h) {
}
i(e())
class a<f : g, g alias g = g
| ba6c141fbca65db2bdb9b730568b3409 | 11.980808 | 87 | 0.407206 | false | false | false | false |
germc/IBM-Ready-App-for-Retail | refs/heads/master | iOS/ReadyAppRetail/Summit WatchKit Extension/Controllers/ListOverviewInterfaceController.swift | epl-1.0 | 2 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import WatchKit
import Foundation
import Realm
class ListOverviewInterfaceController: WKInterfaceController {
@IBOutlet weak var listsTable: WKInterfaceTable!
@IBOutlet weak var loadingImage: WKInterfaceImage!
@IBOutlet weak var centeringLabelView: WKInterfaceLabel!
@IBOutlet weak var loginLabel: WKInterfaceLabel!
@IBOutlet weak var addListsLabel: WKInterfaceLabel!
@IBOutlet weak var retryButton: WKInterfaceButton!
var realmLists: RLMResults?
var defaults: NSUserDefaults?
var wormhole: MMWormhole?
// -------------------
// LIFECYCLE
// -------------------
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.checkForFirstRun()
self.setUpWormhole()
self.setUpRealm()
// Not yet logged in
// NSUserDefaults.standardUserDefaults().setBool(false, forKey: "userID")
self.beginLoading()
}
override func willActivate() {
super.willActivate()
self.setTitle("Summit")
// Do handoff and attempt to auth
self.updateUserActivity(HandoffListsID, userInfo: [:], webpageURL:nil)
self.refresh()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
// Deactivate handoff
self.invalidateUserActivity()
}
override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
if segueIdentifier == "listSegue" {
var listData: AnyObject = self.realmLists!.objectAtIndex(UInt(rowIndex))
return listData
}
return nil
}
// ------------------
// NETWORKING
// ------------------
private func authenticate() {
var usr : String? = KeychainWrapper.stringForKey("summit_username")
var pswd : String? = KeychainWrapper.stringForKey("summit_password")
var shouldBeAbleToLogin = false
if (usr != nil && pswd != nil) {
LoginDataManager.sharedInstance.login(usr!, password: pswd!, callback: { (success: Bool, errorMessage: String?) in
if success {
// NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userID")
self.fetchLists()
}
else {
self.failedToAuth()
println("Keychain credentials were stale... not authenticiated")
}
})
}
else {
self.failedToAuth()
println("No keychain data was found... not authenticiated")
}
}
private func fetchLists() {
ListDataManager.sharedInstance.getDefaultList({ done in
var usr : String? = KeychainWrapper.stringForKey("summit_username")
var pswd : String? = KeychainWrapper.stringForKey("summit_password")
if done {
self.realmLists = List.allObjects().sortedResultsUsingProperty("name", ascending: true)
self.createTable()
self.presentLists()
} else {
println("Failed to fetch the lists... Perhaps the authentication is dead? Reattempting auth...")
// Reattempt an authenticiation
if (!self.isLoggedIn()) {
self.authenticate()
}
}
})
}
private func createTable() {
dispatch_async(dispatch_get_main_queue(),{
var font = UIFont.systemFontOfSize(14)
var attributeData = [NSFontAttributeName : font]
var count = 0
var imgNames: [String] = ["List_Background_A", "List_Background_B", "List_Background_C", "List_Background_D"]
let numRows = Int(self.realmLists!.count > 20 ? 20 : self.realmLists!.count)
self.listsTable.setNumberOfRows(numRows, withRowType: "ListRow")
for (var i = 0 ; i < numRows ; i++) {
if let row = self.listsTable.rowControllerAtIndex(i) as? ListRow {
let list : List? = self.realmLists!.objectAtIndex(UInt(i)) as? List
var labelText = NSAttributedString(string: list!.name as String, attributes: attributeData)
row.titleLabel.setAttributedText(labelText)
// Set background image
row.listItemGroup.setBackgroundImageNamed(imgNames[i % 4])
}
}
if (numRows <= 0) {
self.addListsLabel.setHidden(false)
}
})
}
@IBAction private func retryListFetch() {
self.beginLoading()
self.fetchLists()
}
private func setUpWormhole() {
self.wormhole = MMWormhole(applicationGroupIdentifier: GroupDataAccess.sharedInstance.groupAppID, optionalDirectory: nil)
self.wormhole!.listenForMessageWithIdentifier("loginNotification", listener: { (messageObject) -> Void in
if let message: Dictionary<String, AnyObject> = messageObject as? Dictionary<String, AnyObject> {
if let username = message["username"] as? String {
KeychainWrapper.setString(username, forKey: "summit_username")
}
if let password = message["password"] as? String {
KeychainWrapper.setString(password, forKey: "summit_password")
}
self.beginLoading()
self.authenticate()
}
})
self.wormhole!.listenForMessageWithIdentifier("refreshLists", listener: { (messageObject) -> Void in
self.refresh()
})
}
private func setUpRealm() {
// Tell Realm to install in the app group
let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(GroupDataAccess.sharedInstance.groupAppID)!
let realmPath = directory.path!.stringByAppendingPathComponent("db.realm")
RLMRealm.setDefaultRealmPath(realmPath)
// Do Realm migration
RLMRealm.setSchemaVersion(1, forRealmAtPath: RLMRealm.defaultRealmPath(), withMigrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerateObjects(Product.className()) { oldObject, newObject in
newObject["checkedOff"] = ""
}
}
})
}
// ------------------
// HELPERS
// ------------------
private func beginLoading() {
self.loadingImage.setHidden(false)
self.centeringLabelView.setHidden(false)
self.loginLabel.setHidden(true)
self.listsTable.setHidden(true)
self.retryButton.setHidden(true)
self.addListsLabel.setHidden(true)
self.loadingImage.setImageNamed("Activity")
self.loadingImage.startAnimatingWithImagesInRange(NSMakeRange(0, 15), duration: 1.0, repeatCount: 0)
}
private func failedToAuth() {
self.loginLabel.setHidden(false)
self.loadingImage.setHidden(true)
self.centeringLabelView.setHidden(true)
self.listsTable.setHidden(true)
self.retryButton.setHidden(true)
self.addListsLabel.setHidden(true)
self.loadingImage.stopAnimating()
KeychainWrapper.removeObjectForKey("summit_username")
KeychainWrapper.removeObjectForKey("summit_password")
}
private func presentLists() {
self.listsTable.setHidden(false)
self.loginLabel.setHidden(true)
self.loadingImage.setHidden(true)
self.centeringLabelView.setHidden(true)
self.retryButton.setHidden(true)
self.addListsLabel.setHidden(true)
self.loadingImage.stopAnimating()
}
private func showRetryButton() {
self.retryButton.setHidden(false)
self.centeringLabelView.setHidden(false)
self.listsTable.setHidden(true)
self.loadingImage.setHidden(true)
self.loginLabel.setHidden(true)
self.addListsLabel.setHidden(true)
self.loadingImage.stopAnimating()
}
private func checkForFirstRun() {
if (NSUserDefaults.standardUserDefaults().objectForKey("summitFirstRun") == nil) {
KeychainWrapper.removeObjectForKey("summit_username")
KeychainWrapper.removeObjectForKey("summit_password")
NSUserDefaults(suiteName: GroupDataAccess.sharedInstance.groupAppID)!.removeObjectForKey("userID")
NSUserDefaults(suiteName: GroupDataAccess.sharedInstance.groupAppID)!.synchronize()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "summitFirstRun")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
private func isLoggedIn() -> Bool {
if let name = NSUserDefaults(suiteName: GroupDataAccess.sharedInstance.groupAppID)!.stringForKey("userID") {
if(count(name) > 0) {
return true
} else {
return false
}
} else {
return false
}
}
private func refresh() {
if (!self.isLoggedIn()) {
self.authenticate()
} else {
self.fetchLists()
}
}
}
| c65fb5e05b978a61692bcad5819263db | 34.352313 | 155 | 0.580834 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/TextLayerModel.swift | mit | 1 | //
// TextLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
/// A layer that holds text.
final class TextLayerModel: LayerModel {
/// The text for the layer
let text: KeyframeGroup<TextDocument>
/// Text animators
let animators: [TextAnimator]
private enum CodingKeys : String, CodingKey {
case textGroup = "t"
}
private enum TextCodingKeys : String, CodingKey {
case text = "d"
case animators = "a"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TextLayerModel.CodingKeys.self)
let textContainer = try container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup)
self.text = try textContainer.decode(KeyframeGroup<TextDocument>.self, forKey: .text)
self.animators = try textContainer.decode([TextAnimator].self, forKey: .animators)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
var textContainer = container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup)
try textContainer.encode(text, forKey: .text)
try textContainer.encode(animators, forKey: .animators)
}
}
| 3d561c7ccc887f2239fed93bc96e3901 | 28.863636 | 103 | 0.715373 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Library/UIPress-Extensions.swift | apache-2.0 | 1 | import UIKit
public extension UIPress.Phase {
var isStartingPhase: Bool {
return self == .began
}
var isTerminatingPhase: Bool {
return self == .cancelled || self == .ended
}
}
| 2b6b4002e7b95c5556713a989b86e178 | 16.727273 | 47 | 0.65641 | false | false | false | false |
CoderST/DYZB | refs/heads/master | DYZB/DYZB/Class/Room/ViewModel/RoomAnchorVM.swift | mit | 1 | //
// RoomAnchorVM.swift
// DYZB
//
// Created by xiudou on 16/10/30.
// Copyright © 2016年 xiudo. All rights reserved.
//
import UIKit
class RoomAnchorVM: NSObject {
fileprivate let urlS = "http://live.9158.com/Fans/GetHotLive?page="
// lazy var roomAnchor : RoomAnchorModel = RoomAnchorModel()
lazy var roomYKModelArray : [RoomYKModel] = [RoomYKModel]()
func getRoomAnchorData(_ page : Int,finishCallBack : @escaping ()->(),noDataCallBack:@escaping ()->()){
// 此处用的是YK/MB的链接
let urlString = urlS + String(page)
print(urlString)
NetworkTools.requestData(.get ,URLString: urlString, parameters: nil) { (result) -> () in
// print("page==\(page)",result)
guard let resultDict = result as? [String : NSObject] else {return}
guard let dict = resultDict["data"] as? [String : NSObject] else { return }
guard let dictArray = dict["list"] as? [[String : NSObject]] else { return }
if dictArray.count == 0{
noDataCallBack()
return
}
if page == 1{
self.roomYKModelArray.removeAll()
}
for dic in dictArray{
let roomYkM = RoomYKModel(dic: dic)
// print(roomYkM.myname)
self.roomYKModelArray.append(roomYkM)
}
// let roomModel = RoomAnchorModel(dict: dict)
// self.roomAnchor = roomModel
finishCallBack()
}
}
}
| 1bbff71ad7d09a85ea3f480a28a1f387 | 29.415094 | 107 | 0.533499 | false | false | false | false |
scoremedia/Fisticuffs | refs/heads/master | Sources/Fisticuffs/UIKit/NSLayoutConstraint+Binding.swift | mit | 1 | //
// NSLayoutConstraint+Binding.swift
// Fisticuffs
//
// Created by Albert Le on 2019-08-28.
// Copyright © 2019 theScore. All rights reserved.
//
import UIKit
private var b_layout_constraint_active_key = 0 //swiftlint:disable:this identifier_name
private var b_layout_constraint_constant_key = 0 //swiftlint:disable:this identifier_name
extension NSLayoutConstraint {
//(consistency with fisticuffs)
//swiftlint:disable:next identifier_name
public var b_active: BindableProperty<NSLayoutConstraint, Bool> {
var bindable = objc_getAssociatedObject(self, &b_layout_constraint_active_key) as? BindableProperty<NSLayoutConstraint, Bool>
if bindable == nil {
bindable = BindableProperty(self) { this, isActive in
this.isActive = isActive
}
objc_setAssociatedObject(self, &b_layout_constraint_active_key, bindable, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
return bindable! //swiftlint:disable:this force_unwrapping
}
//(consistency with fisticuffs)
//swiftlint:disable:next identifier_name
public var b_constant: BindableProperty<NSLayoutConstraint, CGFloat> {
var bindable = objc_getAssociatedObject(self, &b_layout_constraint_constant_key) as? BindableProperty<NSLayoutConstraint, CGFloat>
if bindable == nil {
bindable = BindableProperty(self) { this, constant in
this.constant = constant
}
objc_setAssociatedObject(self, &b_layout_constraint_constant_key, bindable, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
return bindable! //swiftlint:disable:this force_unwrapping
}
}
| c8206e475ee93691daaf84de04c75238 | 39.452381 | 138 | 0.698646 | false | false | false | false |
openHPI/xikolo-ios | refs/heads/dev | Common/Data/Model/VisitProgress.swift | gpl-3.0 | 1 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Foundation
import Stockpile
public class VisitProgress: NSObject, NSSecureCoding, IncludedPullable {
public static var supportsSecureCoding: Bool { return true }
public var itemsAvailable: Int?
public var itemsVisited: Int?
public var visitsPercentage: Double?
public var percentage: Double? {
guard let scored = itemsVisited else { return nil }
guard let possible = itemsAvailable, possible > 0 else { return nil }
return Double(scored) / Double(possible)
}
public required init(object: ResourceData) throws {
self.itemsAvailable = try object.value(for: "items_available")
self.itemsVisited = try object.value(for: "items_visited")
self.visitsPercentage = try object.value(for: "visits_percentage")
}
public required init(coder decoder: NSCoder) {
self.itemsAvailable = decoder.decodeObject(of: NSNumber.self, forKey: "items_available")?.intValue
self.itemsVisited = decoder.decodeObject(of: NSNumber.self, forKey: "items_visited")?.intValue
self.visitsPercentage = decoder.decodeObject(of: NSNumber.self, forKey: "visits_percentage")?.doubleValue
}
public func encode(with coder: NSCoder) {
coder.encode(self.itemsAvailable.map(NSNumber.init(value:)), forKey: "items_available")
coder.encode(self.itemsVisited.map(NSNumber.init(value:)), forKey: "items_visited")
coder.encode(self.visitsPercentage.map(NSNumber.init(value:)), forKey: "visits_percentage")
}
}
| e15ba30cab9ba12698774c1f171c0628 | 38.487805 | 113 | 0.704756 | false | false | false | false |
jiamao130/DouYuSwift | refs/heads/master | DouYuBroad/DouYuBroad/Home/Views/AmuseMenuView.swift | mit | 1 | //
// AmuseMenuView.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/14.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
private var kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
var groups : [AnchorGroup]?{
didSet{
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
//
collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseMenuView{
class func amuseMenuView() -> AmuseMenuView{
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil{return 0}
let pageNum = ((groups?.count)! - 1)/8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell: AmuseMenuViewCell,indexPath: IndexPath){
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
print(startIndex,endIndex)
// 2.判断越界问题
if groups?.count == 0 {return}
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
cell.clipsToBounds = true
cell.groups = Array(groups![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| ddd085542fccb07e26449c21d52cd2cf | 28.211765 | 125 | 0.653242 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | refs/heads/develop | Aztec/Classes/Libxml2/Converters/Out/HTMLSerializer.swift | gpl-2.0 | 2 | import Foundation
import libxml2
protocol HTMLSerializerCustomizer {
func converter(for element: ElementNode) -> ElementToTagConverter?
}
/// Composes the provided nodes into its HTML representation.
///
public class HTMLSerializer {
/// Indentation Spaces to be applied
///
let indentationSpaces: Int
/// Converters
private let genericElementConverter = GenericElementToTagConverter()
private let customizer: HTMLSerializerCustomizer?
/// Default Initializer
///
/// - Parameters:
/// - indentationSpaces: Indicates the number of indentation spaces to be applied, per level.
///
public init(indentationSpaces: Int = 2) {
self.customizer = nil
self.indentationSpaces = indentationSpaces
}
init(indentationSpaces: Int = 2, customizer: HTMLSerializerCustomizer? = nil) {
self.customizer = customizer
self.indentationSpaces = indentationSpaces
}
/// Serializes a node into its HTML representation
///
public func serialize(_ node: Node, prettify: Bool = false) -> String {
return serialize(node: node, prettify: prettify).trimmingCharacters(in: CharacterSet.newlines)
}
func serialize(_ nodes: [Node], prettify: Bool, level: Int = 0) -> String {
return nodes.reduce("") { (previous, child) in
return previous + serialize(node: child, prettify: prettify, level: level)
}
}
}
// MARK: - Nodes: Composition
//
private extension HTMLSerializer {
/// Serializes a node into its HTML representation
///
func serialize(node: Node, prettify: Bool, level: Int = 0) -> String {
switch node {
case let node as RootNode:
return serialize(node, prettify: prettify)
case let node as CommentNode:
return serialize(node)
case let node as ElementNode:
return serialize(node, prettify: prettify, level: level)
case let node as TextNode:
return serialize(text: node)
default:
fatalError("We're missing support for a node type. This should not happen.")
}
}
/// Serializes a `RootNode` into its HTML representation
///
private func serialize(_ rootNode: RootNode, prettify: Bool) -> String {
return rootNode.children.reduce("") { (result, node) in
return result + serialize(node: node, prettify: prettify)
}
}
/// Serializes a `CommentNode` into its HTML representation
///
private func serialize(_ commentNode: CommentNode) -> String {
return "<!--" + commentNode.comment + "-->"
}
/// Serializes an `ElementNode` into its HTML representation
///
private func serialize(_ elementNode: ElementNode, prettify: Bool, level: Int) -> String {
let tag = converter(for: elementNode).convert(elementNode)
let openingTagPrefix = self.openingTagPrefix(for: elementNode, prettify: prettify, level: level)
let opening = openingTagPrefix + tag.opening
let children = serialize(elementNode.children, prettify: prettify, level: level + 1)
let closing: String
if let closingTag = tag.closing {
let prefix = self.closingTagPrefix(for: elementNode, prettify: prettify, withSpacesForIndentationLevel: level)
let suffix = self.closingTagSuffix(for: elementNode, prettify: prettify)
closing = prefix + closingTag + suffix
} else {
closing = ""
}
return opening + children + closing
}
/// Serializes an `TextNode` into its HTML representation
///
private func serialize(text node: TextNode) -> String {
return node.text().escapeHtmlNamedEntities()
}
}
// MARK: - Indentation & newlines
private extension HTMLSerializer {
/// Returns the Tag Prefix String at the specified level
///
private func prefix(for level: Int) -> String {
let indentation = level > 0 ? String(repeating: String(.space), count: level * indentationSpaces) : ""
return String(.lineFeed) + indentation
}
}
// MARK: - Opening Tag Affixes
private extension HTMLSerializer {
private func openingTagPrefix(for elementNode: ElementNode, prettify: Bool, level: Int) -> String {
guard requiresOpeningTagPrefix(elementNode, prettify: prettify) else {
return ""
}
return prefix(for: level)
}
/// Required whenever the node is a blocklevel element
///
private func requiresOpeningTagPrefix(_ node: ElementNode, prettify: Bool) -> Bool {
return node.isBlockLevel() && prettify
}
}
// MARK: - Closing Tag Affixes
private extension HTMLSerializer {
private func closingTagPrefix(for elementNode: ElementNode, prettify: Bool, withSpacesForIndentationLevel level: Int) -> String {
guard requiresClosingTagPrefix(elementNode, prettify: prettify) else {
return ""
}
return prefix(for: level)
}
private func closingTagSuffix(for elementNode: ElementNode, prettify: Bool) -> String {
guard prettify,
requiresClosingTagSuffix(elementNode, prettify: prettify) else {
return ""
}
return String(.lineFeed)
}
/// ClosingTag Prefix: Required whenever one of the children is a blocklevel element
///
private func requiresClosingTagPrefix(_ node: ElementNode, prettify: Bool) -> Bool {
guard prettify else {
return false
}
return node.children.contains { child in
let elementChild = child as? ElementNode
return elementChild?.isBlockLevel() == true
}
}
/// ClosingTag Suffix: Required whenever the node is blocklevel, and the right sibling is not
///
private func requiresClosingTagSuffix(_ node: ElementNode, prettify: Bool) -> Bool {
guard prettify,
let rightSibling = node.rightSibling() else {
return false
}
let rightElementNode = rightSibling as? ElementNode
let isRightNodeRegularElement = rightElementNode == nil || rightElementNode?.isBlockLevel() == false
return isRightNodeRegularElement && node.isBlockLevel()
}
}
// MARK: - Element Conversion Logic
extension HTMLSerializer {
private func converter(for elementNode: ElementNode) -> ElementToTagConverter {
return customizer?.converter(for: elementNode) ?? genericElementConverter
}
}
| 239720a0f0fefe0de4807f2c8f8e4d9c | 31.609756 | 133 | 0.633957 | false | false | false | false |
PerfectServers/APIDocumentationServer | refs/heads/master | Sources/APIDocumentationServer/Handlers/home.swift | apache-2.0 | 1 | //
// home.swift
// APIDocumentationServer
//
// Created by Jonathan Guthrie on 2017-05-09.
//
//
import PerfectHTTP
import StORM
extension WebHandlers {
static func home(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let contextAccountID = request.session?.userid ?? ""
let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
var context: [String : Any] = ["title": "Perfect API Doc Server"]
context["csrfToken"] = request.session?.data["csrf"] as? String ?? ""
context["accountID"] = contextAccountID
context["authenticated"] = contextAuthenticated
if contextAuthenticated {
for i in WebHandlers.extras(request) {
context[i.0] = i.1
}
}
// add app config vars
for i in WebHandlers.appExtras(request) {
context[i.0] = i.1
}
// gather list of groups and api docs to display
let groups = APIGroup.list()
context["groups"] = groups
response.render(template: "views/index", context: context)
}
}
}
| c6c4001e8eeb8e509ae0e3b31d03e99f | 20.765957 | 72 | 0.663734 | false | false | false | false |
Instagram/IGListKit | refs/heads/main | Examples/Examples-iOS/IGListKitExamples/Views/CenterLabelCell.swift | mit | 1 | /*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import UIKit
final class CenterLabelCell: UICollectionViewCell {
lazy private var label: UILabel = {
let view = UILabel()
view.backgroundColor = .clear
view.textAlignment = .center
view.textColor = .white
view.font = .boldSystemFont(ofSize: 18)
self.contentView.addSubview(view)
return view
}()
var text: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = contentView.bounds
}
}
| d3298c48baaa38cad091f72a25256ece | 21.722222 | 66 | 0.601467 | false | false | false | false |
MenloHacks/ios-app | refs/heads/master | Menlo Hacks/Pods/PusherSwift/Sources/PusherConnection.swift | mit | 1 | import Foundation
import Reachability
import Starscream
import CryptoSwift
public typealias PusherEventJSON = [String: AnyObject]
@objcMembers
@objc open class PusherConnection: NSObject {
open let url: String
open let key: String
open var options: PusherClientOptions
open var globalChannel: GlobalChannel!
open var socketId: String?
open var connectionState = ConnectionState.disconnected
open var channels = PusherChannels()
open var socket: WebSocket!
open var URLSession: Foundation.URLSession
open var userDataFetcher: (() -> PusherPresenceChannelMember)?
open var reconnectAttemptsMax: Int? = nil
open var reconnectAttempts: Int = 0
open var maxReconnectGapInSeconds: Double? = 120
open weak var delegate: PusherDelegate?
open var pongResponseTimeoutInterval: TimeInterval = 30
open var activityTimeoutInterval: TimeInterval
var reconnectTimer: Timer? = nil
var pongResponseTimeoutTimer: Timer? = nil
var activityTimeoutTimer: Timer? = nil
var intentionalDisconnect: Bool = false
var socketConnected: Bool = false {
didSet {
setConnectionStateToConnectedAndAttemptSubscriptions()
}
}
var connectionEstablishedMessageReceived: Bool = false {
didSet {
setConnectionStateToConnectedAndAttemptSubscriptions()
}
}
open lazy var reachability: Reachability? = {
let reachability = Reachability.init()
reachability?.whenReachable = { [weak self] reachability in
guard self != nil else {
print("Your Pusher instance has probably become deallocated. See https://github.com/pusher/pusher-websocket-swift/issues/109 for more information")
return
}
self!.delegate?.debugLog?(message: "[PUSHER DEBUG] Network reachable")
switch self!.connectionState {
case .disconnecting, .connecting, .reconnecting:
// If in one of these states then part of the connection, reconnection, or explicit
// disconnection process is underway, so do nothing
return
case .disconnected:
// If already disconnected then reset connection and try to reconnect, provided the
// state isn't disconnected because of an intentional disconnection
if !self!.intentionalDisconnect { self!.resetConnectionAndAttemptReconnect() }
return
case .connected:
// If already connected then we assume that there was a missed network event that
// led to a bad connection so we move to the disconnected state and then attempt
// reconnection
self!.delegate?.debugLog?(
message: "[PUSHER DEBUG] Connection state is \(self!.connectionState.stringValue()) but received network reachability change so going to call attemptReconnect"
)
self!.resetConnectionAndAttemptReconnect()
return
}
}
reachability?.whenUnreachable = { [weak self] reachability in
guard self != nil else {
print("Your Pusher instance has probably become deallocated. See https://github.com/pusher/pusher-websocket-swift/issues/109 for more information")
return
}
self!.delegate?.debugLog?(message: "[PUSHER DEBUG] Network unreachable")
self!.resetConnectionAndAttemptReconnect()
}
return reachability
}()
/**
Initializes a new PusherConnection with an app key, websocket, URL, options and URLSession
- parameter key: The Pusher app key
- parameter socket: The websocket object
- parameter url: The URL the connection is made to
- parameter options: A PusherClientOptions instance containing all of the user-speficied
client options
- parameter URLSession: An NSURLSession instance for the connection to use for making
authentication requests
- returns: A new PusherConnection instance
*/
public init(
key: String,
socket: WebSocket,
url: String,
options: PusherClientOptions,
URLSession: Foundation.URLSession = Foundation.URLSession.shared
) {
self.url = url
self.key = key
self.options = options
self.URLSession = URLSession
self.socket = socket
self.activityTimeoutInterval = options.activityTimeout ?? 60
super.init()
self.socket.delegate = self
self.socket.pongDelegate = self
}
deinit {
self.reconnectTimer?.invalidate()
self.activityTimeoutTimer?.invalidate()
self.pongResponseTimeoutTimer?.invalidate()
}
/**
Initializes a new PusherChannel with a given name
- parameter channelName: The name of the channel
- parameter auth: A PusherAuth value if subscription is being made to an
authenticated channel without using the default auth methods
- parameter onMemberAdded: A function that will be called with information about the
member who has just joined the presence channel
- parameter onMemberRemoved: A function that will be called with information about the
member who has just left the presence channel
- returns: A new PusherChannel instance
*/
internal func subscribe(
channelName: String,
auth: PusherAuth? = nil,
onMemberAdded: ((PusherPresenceChannelMember) -> ())? = nil,
onMemberRemoved: ((PusherPresenceChannelMember) -> ())? = nil
) -> PusherChannel {
let newChannel = channels.add(
name: channelName,
connection: self,
auth: auth,
onMemberAdded: onMemberAdded,
onMemberRemoved: onMemberRemoved
)
guard self.connectionState == .connected else { return newChannel }
if !self.authorize(newChannel, auth: auth) {
print("Unable to subscribe to channel: \(newChannel.name)")
}
return newChannel
}
/**
Initializes a new PusherChannel with a given name
- parameter channelName: The name of the channel
- parameter auth: A PusherAuth value if subscription is being made to an
authenticated channel without using the default auth methods
- parameter onMemberAdded: A function that will be called with information about the
member who has just joined the presence channel
- parameter onMemberRemoved: A function that will be called with information about the
member who has just left the presence channel
- returns: A new PusherChannel instance
*/
internal func subscribeToPresenceChannel(
channelName: String,
auth: PusherAuth? = nil,
onMemberAdded: ((PusherPresenceChannelMember) -> ())? = nil,
onMemberRemoved: ((PusherPresenceChannelMember) -> ())? = nil
) -> PusherPresenceChannel {
let newChannel = channels.addPresence(
channelName: channelName,
connection: self,
auth: auth,
onMemberAdded: onMemberAdded,
onMemberRemoved: onMemberRemoved
)
guard self.connectionState == .connected else { return newChannel }
if !self.authorize(newChannel, auth: auth) {
print("Unable to subscribe to channel: \(newChannel.name)")
}
return newChannel
}
/**
Unsubscribes from a PusherChannel with a given name
- parameter channelName: The name of the channel
*/
internal func unsubscribe(channelName: String) {
if let chan = self.channels.find(name: channelName), chan.subscribed {
self.sendEvent(event: "pusher:unsubscribe",
data: [
"channel": channelName
] as [String : Any]
)
self.channels.remove(name: channelName)
}
}
/**
Unsubscribes from all PusherChannels
*/
internal func unsubscribeAll() {
for (_, channel) in channels.channels {
unsubscribe(channelName: channel.name)
}
}
/**
Either writes a string directly to the websocket with the given event name
and data, or calls a client event to be sent if the event is prefixed with
"client"
- parameter event: The name of the event
- parameter data: The data to be stringified and sent
- parameter channelName: The name of the channel
*/
open func sendEvent(event: String, data: Any, channel: PusherChannel? = nil) {
if event.components(separatedBy: "-")[0] == "client" {
sendClientEvent(event: event, data: data, channel: channel)
} else {
let dataString = JSONStringify(["event": event, "data": data])
self.delegate?.debugLog?(message: "[PUSHER DEBUG] sendEvent \(dataString)")
self.socket.write(string: dataString)
}
}
/**
Sends a client event with the given event, data, and channel name
- parameter event: The name of the event
- parameter data: The data to be stringified and sent
- parameter channelName: The name of the channel
*/
fileprivate func sendClientEvent(event: String, data: Any, channel: PusherChannel?) {
if let channel = channel {
if channel.type == .presence || channel.type == .private {
let dataString = JSONStringify(["event": event, "data": data, "channel": channel.name] as [String : Any])
self.delegate?.debugLog?(message: "[PUSHER DEBUG] sendClientEvent \(dataString)")
self.socket.write(string: dataString)
} else {
print("You must be subscribed to a private or presence channel to send client events")
}
}
}
/**
JSON stringifies an object
- parameter value: The value to be JSON stringified
- returns: A JSON-stringified version of the value
*/
fileprivate func JSONStringify(_ value: Any) -> String {
if JSONSerialization.isValidJSONObject(value) {
do {
let data = try JSONSerialization.data(withJSONObject: value, options: [])
let string = String(data: data, encoding: .utf8)
if string != nil {
return string!
}
} catch _ {
}
}
return ""
}
/**
Disconnects the websocket
*/
open func disconnect() {
if self.connectionState == .connected {
intentionalDisconnect = true
self.reachability?.stopNotifier()
updateConnectionState(to: .disconnecting)
self.socket.disconnect()
}
}
/**
Establish a websocket connection
*/
@objc open func connect() {
// reset the intentional disconnect state
intentionalDisconnect = false
if self.connectionState == .connected {
return
} else {
updateConnectionState(to: .connecting)
self.socket.connect()
if self.options.autoReconnect {
// can call this multiple times and only one notifier will be started
_ = try? reachability?.startNotifier()
}
}
}
/**
Instantiate a new GloblalChannel instance for the connection
*/
internal func createGlobalChannel() {
self.globalChannel = GlobalChannel(connection: self)
}
/**
Add callback to the connection's global channel
- parameter callback: The callback to be stored
- returns: A callbackId that can be used to remove the callback from the connection
*/
internal func addCallbackToGlobalChannel(_ callback: @escaping (Any?) -> Void) -> String {
return globalChannel.bind(callback)
}
/**
Remove the callback with id of callbackId from the connection's global channel
- parameter callbackId: The unique string representing the callback to be removed
*/
internal func removeCallbackFromGlobalChannel(callbackId: String) {
globalChannel.unbind(callbackId: callbackId)
}
/**
Remove all callbacks from the connection's global channel
*/
internal func removeAllCallbacksFromGlobalChannel() {
globalChannel.unbindAll()
}
/**
Set the connection state and call the stateChangeDelegate, if set
- parameter newState: The new ConnectionState value
*/
internal func updateConnectionState(to newState: ConnectionState) {
let oldState = self.connectionState
self.connectionState = newState
self.delegate?.changedConnectionState?(from: oldState, to: newState)
}
/**
Update connection state and attempt subscriptions to unsubscribed channels
*/
fileprivate func setConnectionStateToConnectedAndAttemptSubscriptions() {
if self.connectionEstablishedMessageReceived &&
self.socketConnected &&
self.connectionState != .connected
{
updateConnectionState(to: .connected)
attemptSubscriptionsToUnsubscribedChannels()
}
}
/**
Set the connection state to disconnected, mark channels as unsubscribed,
reset connection-related state to initial state, and initiate reconnect
process
*/
fileprivate func resetConnectionAndAttemptReconnect() {
if connectionState != .disconnected {
updateConnectionState(to: .disconnected)
}
for (_, channel) in self.channels.channels {
channel.subscribed = false
}
cleanUpActivityAndPongResponseTimeoutTimers()
socketConnected = false
connectionEstablishedMessageReceived = false
socketId = nil
attemptReconnect()
}
/**
Reset the activity timeout timer
*/
func resetActivityTimeoutTimer() {
cleanUpActivityAndPongResponseTimeoutTimers()
establishActivityTimeoutTimer()
}
/**
Clean up the activity timeout and pong response timers
*/
func cleanUpActivityAndPongResponseTimeoutTimers() {
activityTimeoutTimer?.invalidate()
activityTimeoutTimer = nil
pongResponseTimeoutTimer?.invalidate()
pongResponseTimeoutTimer = nil
}
/**
Schedule a timer to be fired if no activity occurs over the socket within
the activityTimeoutInterval
*/
fileprivate func establishActivityTimeoutTimer() {
self.activityTimeoutTimer = Timer.scheduledTimer(
timeInterval: self.activityTimeoutInterval,
target: self,
selector: #selector(self.sendPing),
userInfo: nil,
repeats: false
)
}
/**
Send a ping to the server
*/
@objc fileprivate func sendPing() {
socket.write(ping: Data()) {
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Ping sent")
self.setupPongResponseTimeoutTimer()
}
}
/**
Schedule a timer that will fire if no pong response is received within the
pongResponseTImeoutInterval
*/
fileprivate func setupPongResponseTimeoutTimer() {
pongResponseTimeoutTimer = Timer.scheduledTimer(
timeInterval: pongResponseTimeoutInterval,
target: self,
selector: #selector(cleanupAfterNoPongResponse),
userInfo: nil,
repeats: false
)
}
/**
Invalidate the pongResponseTimeoutTimer and set connection state to disconnected
as well as marking channels as unsubscribed
*/
@objc fileprivate func cleanupAfterNoPongResponse() {
pongResponseTimeoutTimer?.invalidate()
pongResponseTimeoutTimer = nil
resetConnectionAndAttemptReconnect()
}
/**
Handle setting channel state and triggering unsent client events, if applicable,
upon receiving a successful subscription event
- parameter json: The PusherEventJSON containing successful subscription data
*/
fileprivate func handleSubscriptionSucceededEvent(json: PusherEventJSON) {
if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) {
chan.subscribed = true
guard let eventData = json["data"] as? String else {
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Subscription succeeded event received without data key in payload")
return
}
if PusherChannelType.isPresenceChannel(name: channelName) {
if let presChan = self.channels.find(name: channelName) as? PusherPresenceChannel {
if let dataJSON = getPusherEventJSON(from: eventData) {
if let presenceData = dataJSON["presence"] as? [String : AnyObject],
let presenceHash = presenceData["hash"] as? [String : AnyObject]
{
presChan.addExistingMembers(memberHash: presenceHash)
}
}
}
}
callGlobalCallbacks(forEvent: "pusher:subscription_succeeded", jsonObject: json)
chan.handleEvent(name: "pusher:subscription_succeeded", data: eventData)
self.delegate?.subscribedToChannel?(name: channelName)
chan.auth = nil
while chan.unsentEvents.count > 0 {
if let pusherEvent = chan.unsentEvents.popLast() {
chan.trigger(eventName: pusherEvent.name, data: pusherEvent.data)
}
}
}
}
/**
Handle setting connection state and making subscriptions that couldn't be
attempted while the connection was not in a connected state
- parameter json: The PusherEventJSON containing connection established data
*/
fileprivate func handleConnectionEstablishedEvent(json: PusherEventJSON) {
if let data = json["data"] as? String {
if let connectionData = getPusherEventJSON(from: data),
let socketId = connectionData["socket_id"] as? String
{
self.socketId = socketId
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Socket established with socket ID: \(socketId)")
self.reconnectAttempts = 0
self.reconnectTimer?.invalidate()
if options.activityTimeout == nil, let activityTimeoutFromServer = connectionData["activity_timeout"] as? TimeInterval {
self.activityTimeoutInterval = activityTimeoutFromServer
}
self.connectionEstablishedMessageReceived = true
}
}
}
/**
Attempts to make subscriptions that couldn't be attempted while the
connection was not in a connected state
*/
fileprivate func attemptSubscriptionsToUnsubscribedChannels() {
for (_, channel) in self.channels.channels {
if !self.authorize(channel, auth: channel.auth) {
print("Unable to subscribe to channel: \(channel.name)")
}
}
}
/**
Handle a new member subscribing to a presence channel
- parameter json: The PusherEventJSON containing the member data
*/
fileprivate func handleMemberAddedEvent(json: PusherEventJSON) {
if let data = json["data"] as? String {
if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) as? PusherPresenceChannel {
if let memberJSON = getPusherEventJSON(from: data) {
chan.addMember(memberJSON: memberJSON)
} else {
print("Unable to add member")
}
}
}
}
/**
Handle a member unsubscribing from a presence channel
- parameter json: The PusherEventJSON containing the member data
*/
fileprivate func handleMemberRemovedEvent(json: PusherEventJSON) {
if let data = json["data"] as? String {
if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) as? PusherPresenceChannel {
if let memberJSON = getPusherEventJSON(from: data) {
chan.removeMember(memberJSON: memberJSON)
} else {
print("Unable to remove member")
}
}
}
}
/**
Handle failure of our auth endpoint
- parameter channelName: The name of channel for which authorization failed
- parameter data: The error returned by the auth endpoint
*/
fileprivate func handleAuthorizationError(forChannel channelName: String, response: URLResponse?, data: String?, error: NSError?) {
let eventName = "pusher:subscription_error"
let json = [
"event": eventName,
"channel": channelName,
"data": data ?? ""
]
DispatchQueue.main.async {
// TODO: Consider removing in favour of exclusively using delegate
self.handleEvent(eventName: eventName, jsonObject: json as [String : AnyObject])
}
self.delegate?.failedToSubscribeToChannel?(name: channelName, response: response, data: data, error: error)
}
/**
Parse a string to extract Pusher event information from it
- parameter string: The string received over the websocket connection containing
Pusher event information
- returns: A dictionary of Pusher-relevant event data
*/
open func getPusherEventJSON(from string: String) -> [String : AnyObject]? {
let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)
do {
if let jsonData = data, let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String : AnyObject] {
return jsonObject
} else {
print("Unable to parse string from WebSocket: \(string)")
}
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
return nil
}
/**
Parse a string to extract Pusher event data from it
- parameter string: The data string received as part of a Pusher message
- returns: The object sent as the payload part of the Pusher message
*/
open func getEventDataJSON(from string: String) -> Any {
let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)
do {
if let jsonData = data, let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
return jsonObject
} else {
print("Returning data string instead because unable to parse string as JSON - check that your JSON is valid.")
}
}
return string
}
/**
Handles incoming events and passes them on to be handled by the appropriate function
- parameter eventName: The name of the incoming event
- parameter jsonObject: The event-specific data related to the incoming event
*/
open func handleEvent(eventName: String, jsonObject: [String : AnyObject]) {
resetActivityTimeoutTimer()
switch eventName {
case "pusher_internal:subscription_succeeded":
handleSubscriptionSucceededEvent(json: jsonObject)
case "pusher:connection_established":
handleConnectionEstablishedEvent(json: jsonObject)
case "pusher_internal:member_added":
handleMemberAddedEvent(json: jsonObject)
case "pusher_internal:member_removed":
handleMemberRemovedEvent(json: jsonObject)
default:
callGlobalCallbacks(forEvent: eventName, jsonObject: jsonObject)
if let channelName = jsonObject["channel"] as? String, let internalChannel = self.channels.find(name: channelName) {
if let eName = jsonObject["event"] as? String, let eData = jsonObject["data"] as? String {
internalChannel.handleEvent(name: eName, data: eData)
}
}
}
}
/**
Call any global callbacks
- parameter eventName: The name of the incoming event
- parameter jsonObject: The event-specific data related to the incoming event
*/
fileprivate func callGlobalCallbacks(forEvent eventName: String, jsonObject: [String : AnyObject]) {
if let globalChannel = self.globalChannel {
if let eData = jsonObject["data"] as? String {
let channelName = jsonObject["channel"] as! String?
globalChannel.handleEvent(name: eventName, data: eData, channelName: channelName)
} else if let eData = jsonObject["data"] as? [String: AnyObject] {
globalChannel.handleErrorEvent(name: eventName, data: eData)
}
}
}
/**
Uses the appropriate authentication method to authenticate subscriptions to private and
presence channels
- parameter channel: The PusherChannel to authenticate
- parameter auth: A PusherAuth value if subscription is being made to an
authenticated channel without using the default auth methods
- returns: A Bool indicating whether or not the authentication request was made
successfully
*/
fileprivate func authorize(_ channel: PusherChannel, auth: PusherAuth? = nil) -> Bool {
if channel.type != .presence && channel.type != .private {
subscribeToNormalChannel(channel)
return true
} else if let auth = auth {
// Don't go through normal auth flow if auth value provided
if channel.type == .private {
self.handlePrivateChannelAuth(authValue: auth.auth, channel: channel)
} else if let channelData = auth.channelData {
self.handlePresenceChannelAuth(authValue: auth.auth, channel: channel, channelData: channelData)
} else {
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Attempting to subscribe to presence channel but no channelData value provided")
return false
}
return true
} else {
guard let socketId = self.socketId else {
print("socketId value not found. You may not be connected.")
return false
}
switch self.options.authMethod {
case .noMethod:
let errorMessage = "Authentication method required for private / presence channels but none provided."
let error = NSError(domain: "com.pusher.PusherSwift", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: errorMessage])
print(errorMessage)
handleAuthorizationError(forChannel: channel.name, response: nil, data: nil, error: error)
return false
case .endpoint(authEndpoint: let authEndpoint):
let request = requestForAuthValue(from: authEndpoint, socketId: socketId, channelName: channel.name)
sendAuthorisationRequest(request: request, channel: channel)
return true
case .authRequestBuilder(authRequestBuilder: let builder):
if let request = builder.requestFor?(socketID: socketId, channelName: channel.name) {
sendAuthorisationRequest(request: request, channel: channel)
return true
} else {
let errorMessage = "Authentication request could not be built"
let error = NSError(domain: "com.pusher.PusherSwift", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: errorMessage])
handleAuthorizationError(forChannel: channel.name, response: nil, data: nil, error: error)
return false
}
case .authorizer(authorizer: let authorizer):
authorizer.fetchAuthValue(socketID: socketId, channelName: channel.name) { authInfo in
guard let authInfo = authInfo else {
print("Auth info passed to authorizer completionHandler was nil so channel subscription failed")
return
}
self.handleAuthInfo(authString: authInfo.auth, channelData: authInfo.channelData, channel: channel)
}
return true
case .inline(secret: let secret):
var msg = ""
var channelData = ""
if channel.type == .presence {
channelData = getUserDataJSON()
msg = "\(self.socketId!):\(channel.name):\(channelData)"
} else {
msg = "\(self.socketId!):\(channel.name)"
}
let secretBuff: [UInt8] = Array(secret.utf8)
let msgBuff: [UInt8] = Array(msg.utf8)
if let hmac = try? HMAC(key: secretBuff, variant: .sha256).authenticate(msgBuff) {
let signature = Data(bytes: hmac).toHexString()
let auth = "\(self.key):\(signature)".lowercased()
if channel.type == .private {
self.handlePrivateChannelAuth(authValue: auth, channel: channel)
} else {
self.handlePresenceChannelAuth(authValue: auth, channel: channel, channelData: channelData)
}
}
return true
}
}
}
/**
Calls the provided userDataFetcher function, if provided, otherwise will
use the socketId as the user_id and return that stringified
- returns: A JSON stringified user data object
*/
fileprivate func getUserDataJSON() -> String {
if let userDataFetcher = self.userDataFetcher {
let userData = userDataFetcher()
if let userInfo: Any = userData.userInfo {
return JSONStringify(["user_id": userData.userId, "user_info": userInfo])
} else {
return JSONStringify(["user_id": userData.userId])
}
} else {
if let socketId = self.socketId {
return JSONStringify(["user_id": socketId])
} else {
print("Authentication failed. You may not be connected")
return ""
}
}
}
/**
Send subscription event for subscribing to a public channel
- parameter channel: The PusherChannel to subscribe to
*/
fileprivate func subscribeToNormalChannel(_ channel: PusherChannel) {
self.sendEvent(
event: "pusher:subscribe",
data: [
"channel": channel.name
]
)
}
/**
Creates an authentication request for the given authEndpoint
- parameter endpoint: The authEndpoint to which the request will be made
- parameter socketId: The socketId of the connection's websocket
- parameter channel: The PusherChannel to authenticate subsciption for
- returns: URLRequest object to be used by the function making the auth request
*/
fileprivate func requestForAuthValue(from endpoint: String, socketId: String, channelName: String) -> URLRequest {
let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted
let encodedChannelName = channelName.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? channelName
var request = URLRequest(url: URL(string: endpoint)!)
request.httpMethod = "POST"
request.httpBody = "socket_id=\(socketId)&channel_name=\(encodedChannelName)".data(using: String.Encoding.utf8)
return request
}
/**
Send authentication request to the authEndpoint specified
- parameter request: The request to send
- parameter channel: The PusherChannel to authenticate subsciption for
*/
fileprivate func sendAuthorisationRequest(request: URLRequest, channel: PusherChannel) {
let task = URLSession.dataTask(with: request, completionHandler: { data, response, sessionError in
if let error = sessionError {
print("Error authorizing channel [\(channel.name)]: \(error)")
self.handleAuthorizationError(forChannel: channel.name, response: response, data: nil, error: error as NSError?)
return
}
guard let data = data else {
print("Error authorizing channel [\(channel.name)]")
self.handleAuthorizationError(forChannel: channel.name, response: response, data: nil, error: nil)
return
}
guard let httpResponse = response as? HTTPURLResponse, (httpResponse.statusCode == 200 || httpResponse.statusCode == 201) else {
let dataString = String(data: data, encoding: String.Encoding.utf8)
print ("Error authorizing channel [\(channel.name)]: \(String(describing: dataString))")
self.handleAuthorizationError(forChannel: channel.name, response: response, data: dataString, error: nil)
return
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), let json = jsonObject as? [String: AnyObject] else {
print("Error authorizing channel [\(channel.name)]")
self.handleAuthorizationError(forChannel: channel.name, response: httpResponse, data: nil, error: nil)
return
}
self.handleAuthResponse(json: json, channel: channel)
})
task.resume()
}
/**
Handle authorizer request response and call appropriate handle function
- parameter json: The auth response as a dictionary
- parameter channel: The PusherChannel to authorize subsciption for
*/
fileprivate func handleAuthResponse(
json: [String: AnyObject],
channel: PusherChannel
) {
if let auth = json["auth"] as? String {
handleAuthInfo(
authString: auth,
channelData: json["channel_data"] as? String,
channel: channel
)
}
}
/**
Handle authorizer info and call appropriate handle function
- parameter authString: The auth response as a dictionary
- parameter channelData: The channelData to send along with the auth request
- parameter channel: The PusherChannel to authorize the subsciption for
*/
fileprivate func handleAuthInfo(authString: String, channelData: String?, channel: PusherChannel) {
if let channelData = channelData {
handlePresenceChannelAuth(authValue: authString, channel: channel, channelData: channelData)
} else {
handlePrivateChannelAuth(authValue: authString, channel: channel)
}
}
/**
Handle presence channel auth response and send subscribe message to Pusher API
- parameter auth: The auth string
- parameter channel: The PusherChannel to authorize subsciption for
- parameter channelData: The channelData to send along with the auth request
*/
fileprivate func handlePresenceChannelAuth(
authValue: String,
channel: PusherChannel,
channelData: String
) {
(channel as? PusherPresenceChannel)?.setMyUserId(channelData: channelData)
self.sendEvent(
event: "pusher:subscribe",
data: [
"channel": channel.name,
"auth": authValue,
"channel_data": channelData
]
)
}
/**
Handle private channel auth response and send subscribe message to Pusher API
- parameter auth: The auth string
- parameter channel: The PusherChannel to authenticate subsciption for
*/
fileprivate func handlePrivateChannelAuth(authValue auth: String, channel: PusherChannel) {
self.sendEvent(
event: "pusher:subscribe",
data: [
"channel": channel.name,
"auth": auth
]
)
}
}
@objc public class PusherAuth: NSObject {
public let auth: String
public let channelData: String?
public init(auth: String, channelData: String? = nil) {
self.auth = auth
self.channelData = channelData
}
}
@objc public enum ConnectionState: Int {
case connecting
case connected
case disconnecting
case disconnected
case reconnecting
static let connectionStates = [
connecting: "connecting",
connected: "connected",
disconnecting: "disconnecting",
disconnected: "disconnected",
reconnecting: "reconnecting",
]
public func stringValue() -> String {
return ConnectionState.connectionStates[self]!
}
}
| b185ab97495bc18816e9c202a8f88566 | 37.840328 | 179 | 0.611748 | false | false | false | false |
giftbott/HandyExtensions | refs/heads/master | Sources/UIColorExtensions.swift | mit | 1 | //
// UIColorExtensions.swift
// HandyExtensions
//
// Created by giftbot on 2017. 4. 29..
// Copyright © 2017년 giftbot. All rights reserved.
//
extension UIColor {
/// let color = UIColor(r: 200, g: 100, b: 0)
/// let color = UIColor(r: 200, g: 100, b: 0, a: 200)
public convenience init(r: Int, g: Int, b: Int, a: Int = 255) {
self.init(red: r.f / 255.0, green: g.f / 255.0, blue: b.f / 255.0, alpha: a.f / 255.0)
}
/// let color = UIColor(hex: 0x00FF00)
public convenience init(hex: Int, alpha: CGFloat = 1) {
let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let g = CGFloat((hex & 0x00FF00) >> 8) / 255.0
let b = CGFloat((hex & 0x0000FF) >> 0) / 255.0
self.init(red: r, green: g, blue: b, alpha: alpha)
}
/// Extract RGB values from UIColor
///
/// let rgb = someColor.getRGB()
/// print(rgb.red, rgb.blue)
public func getRGB() -> (red: Int, green: Int, blue: Int, alpha: Int)? {
var red = CGFloat(0)
var green = CGFloat(0)
var blue = CGFloat(0)
var alpha = CGFloat(0)
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return nil }
return (
red: Int(red * 255.0),
green: Int(green * 255.0),
blue: Int(blue * 255.0),
alpha: Int(alpha * 255.0)
)
}
/// Convert UIColor to UIImage
///
/// let image = UIColor.red.image
public var toImage: UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(self.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 25a779d87f847af56170dd186443e8c9 | 29.982143 | 90 | 0.599424 | false | false | false | false |
alessiobrozzi/firefox-ios | refs/heads/master | Storage/SQL/SQLiteLogins.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let IndexLoginsOverrideHostname = "idx_loginsM_is_overridden_hostname"
let IndexLoginsDeletedHostname = "idx_loginsL_is_deleted_hostname"
let AllLoginTables: [String] = [TableLoginsMirror, TableLoginsLocal]
private let OverriddenHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsOverrideHostname) ON \(TableLoginsMirror) (is_overridden, hostname)"
private let DeletedHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsDeletedHostname) ON \(TableLoginsLocal) (is_deleted, hostname)"
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 3 }
func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(_ db: SQLiteDBConnection) -> Bool {
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local, OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
let to = self.version
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from < 3 && to >= 3 {
log.debug("Updating logins tables to include version 3 indices")
return self.run(db, queries: [OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db)
}
func exists(_ db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(_ db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)")
return err == nil
}
}
open class SQLiteLogins: BrowserLogins {
fileprivate let db: BrowserDB
fileprivate static let MainColumns: String = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
fileprivate static let MainWithLastUsedColumns: String = MainColumns + ", timeLastUsed, timesUsed"
fileprivate static let LoginColumns: String = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
let _ = db.createOrUpdate(LoginsTable())
}
fileprivate class func populateLogin(_ login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
fileprivate class func constructLogin<T: Login>(_ row: SDRow, c: T.Type) -> T {
let credential = URLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: URLCredential.Persistence.none)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = URLProtectionSpace(host: host,
port: port,
protocol: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(_ row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(_ row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
fileprivate class func LoginFactory(_ row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
fileprivate class func LoginDataFactory(_ row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
fileprivate class func LoginUsageDataFactory(_ row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
NotificationCenter.default.post(name: NotificationDataLoginDidChange, object: nil)
}
open func getUsageDataForLoginByGUID(_ guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
open func getLoginDataForGUID(_ guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login: \(username), \(args[0])")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
open func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
open func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query, !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append("username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ?")
}
let whereSearchClause = searchClauses.count > 0 ? "AND (" + searchClauses.joined(separator: "OR") + ") " : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
open func addLogin(_ login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.new.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
fileprivate func cloneMirrorToOverlay(whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
fileprivate func ensureLocalOverlayExistsForGUID(_ guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { _ in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
fileprivate func cloneMirrorToOverlay(_ guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
fileprivate func markMirrorAsOverridden(_ guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
open func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
open func addUseOfLoginByGUID(_ guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [nowMicro, nowMilli, guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
open func removeLoginByGUID(_ guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
fileprivate func getDeletionStatementsForGUIDs(_ guids: ArraySlice<GUID>, nowMillis: Timestamp) -> [(sql: String, args: Args?)] {
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.new.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 }
return [ (delete, args), (update, args), (markMirrorAsOverridden, args), (insert, args)]
}
open func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success {
let timestamp = Date.now()
return db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap {
self.getDeletionStatementsForGUIDs($0, nowMillis: timestamp)
}) >>> effect(self.notifyLoginDidChange)
}
open func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.new.rawValue)"
let nowMillis = Date.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(_ guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(_ guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
fileprivate func storeReconciledLogin(_ login: Login) -> Success {
let dateMilli = Date.now()
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timeLastUsed,
login.timePasswordChanged,
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(_ upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
fileprivate func applyChangedLogin(_ upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
fileprivate func mirrorArgs(_ login: ServerLogin) -> Args {
let args: Args = [
login.serverModified,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
login.timeLastUsed,
login.timePasswordChanged,
login.timeCreated,
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
fileprivate func updateMirrorToLogin(_ login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
fileprivate func insertNewMirror(_ login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
fileprivate func findLocalRecordByContent(_ login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch cursor.count {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
fileprivate func resolveConflictBetween(local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
fileprivate func resolveConflictWithoutParentBetween(local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized<T: Collection>(_ guids: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> where T.Iterator.Element == GUID {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.flatMap { $0 }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.new.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.new.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
| 425bcc3b1df7ecc6c80b556980426479 | 42.141129 | 204 | 0.609052 | false | false | false | false |
Ramotion/reel-search | refs/heads/master | RAMReel/Framework/CollectionViewCell.swift | mit | 1 | //
// RAMCell.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/10/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import UIKit
// MARK: - Collection view cells
/**
Type that implements this protocol allows configuration.
As type name hints this protocol primarily targeted to UITableView and UICollectionView cells
*/
public protocol ConfigurableCell {
associatedtype DataType: Equatable
/**
Implementing type should use data to fill own data fields
- parameter data: Data to present in the cell
*/
func configureCell(_ data: DataType)
/// Visual appearance theme
var theme: Theme { get set }
}
/**
RAMCell
--
Example configurable cell
*/
open class RAMCell: UICollectionViewCell, ConfigurableCell {
/**
Proxy call to superclass init.
- parameter coder: `NSCoder` instance proxied to superview.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Proxy call to superclass init.
- parameter frame: Rect of cell, proxied to superview.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
var textLabel: UILabel!
/// Visual appearance theme
open var theme: Theme = RAMTheme.sharedTheme {
didSet {
if theme.font != oldValue.font || theme.textColor != oldValue.textColor {
updateFont()
}
}
}
func updateFont() {
let theme = self.theme
textLabel.font = theme.font
textLabel.textColor = theme.textColor.withAlphaComponent(0.3)
}
fileprivate func setup() {
let labelFrame = self.contentView.bounds
textLabel = UILabel(frame: labelFrame)
textLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(textLabel)
let attributes: [NSLayoutConstraint.Attribute] = [.left, .right, .top, .bottom]
let constraints: [NSLayoutConstraint] = attributes.map {
let const: CGFloat = ($0 == .left || $0 == .right) ? -20 : 0
return NSLayoutConstraint(item: self,
attribute: $0,
relatedBy: .equal,
toItem: textLabel,
attribute: $0,
multiplier: 1,
constant: const)
}
addConstraints(constraints)
updateFont()
}
/**
Applies string data to the label text property
- parameter string: String to show in the cell
*/
open func configureCell(_ string: String) {
self.textLabel.text = string
}
}
| 07c2a2ad310f84ec2281c69c7efdafa3 | 24.738739 | 97 | 0.571229 | false | true | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/scripts/Colosseum/CMScriptCompiler.swift | gpl-2.0 | 1 | //
// CMScriptCompiler.swift
// GoD Tool
//
// Created by The Steez on 01/11/2018.
//
import Foundation
// just a placeholder
class XDSScriptCompiler: NSObject {
typealias CMSCode = [UInt32]
// special variables
static var scriptTypeID = 0
static var baseStringID = 0
static var cmsversion : Float = 0.9
static var writeDisassembly = false
static var decompileXDS = false
static var updateStringIDs = false
static var increaseMSGSize = false
static var createBackup = true
static var scriptFile : XGFiles?
static var error = ""
class func setFlags(disassemble: Bool, decompile: Bool, updateStrings: Bool, increaseMSG: Bool) { }
class func clearCompilerFlags() { }
// MARK: - specify file or text to compile
class func compile(textFile file: XGFiles) -> Bool {
return false
}
class func compile(textFile file: XGFiles, toFile target: XGFiles) -> Bool {
return false
}
class func compile(text: String, toFile file: XGFiles) -> Bool {
return false
}
}
| b2e9d5bcaf7aa4b7e740b0f1d876d45f | 22.139535 | 100 | 0.718593 | false | false | false | false |
alitaso345/swift-annict-client | refs/heads/master | AnnictAPIClient/User.swift | mit | 1 | struct User :JSONDecodable {
let id: Int
let username: String
let name: String
let description: String
let url: String?
let avatarURL: String
let backgroundImageURL: String
let recordsCount: Int
let createdAt: String
init(json: Any) throws {
guard let dictionary = json as? [String: Any] else {
throw JSONDecodeError.invalidFormat(json: json)
}
guard let id = dictionary["id"] as? Int else {
throw JSONDecodeError.missingValue(key: "id", actualValue: dictionary["id"])
}
guard let username = dictionary["username"] as? String else {
throw JSONDecodeError.missingValue(key: "username", actualValue: dictionary["username"])
}
guard let name = dictionary["name"] as? String else {
throw JSONDecodeError.missingValue(key: "name", actualValue: dictionary["name"])
}
guard let description = dictionary["description"] as? String else {
throw JSONDecodeError.missingValue(key: "description", actualValue: dictionary["description"])
}
if let url = dictionary["user"] as? String {
self.url = url
} else {
self.url = nil
}
guard let avatarURL = dictionary["avatar_url"] as? String else {
throw JSONDecodeError.missingValue(key: "avatar_url", actualValue: dictionary["avatar_url"])
}
guard let backgroundImageURL = dictionary["background_image_url"] as? String else {
throw JSONDecodeError.missingValue(key: "background_image_url", actualValue: dictionary["background_image_url"])
}
guard let recordsCount = dictionary["records_count"] as? Int else {
throw JSONDecodeError.missingValue(key: "records_count", actualValue: dictionary["records_count"])
}
guard let createdAt = dictionary["created_at"] as? String else {
throw JSONDecodeError.missingValue(key: "created_at", actualValue: dictionary["created_at"])
}
self.id = id
self.username = username
self.name = name
self.description = description
self.avatarURL = avatarURL
self.backgroundImageURL = backgroundImageURL
self.recordsCount = recordsCount
self.createdAt = createdAt
}
}
| 26c52be42f43780e7a8f62cbd3836e98 | 35.609375 | 124 | 0.629535 | false | false | false | false |
SandcastleApps/partyup | refs/heads/master | PartyUP/TutorialOverlayManager.swift | mit | 1 | //
// TutorialOverlayManager.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2016-04-06.
// Copyright © 2016 Sandcastle Application Development. All rights reserved.
//
import Instructions
import Foundation
struct TutorialMark {
let identifier: Int
let hint: String
var view: UIView?
init(identifier: Int, hint: String, view: UIView? = nil){
self.identifier = identifier
self.hint = hint
self.view = view
}
}
class TutorialOverlayManager: CoachMarksControllerDataSource, CoachMarksControllerDelegate {
var marks: [TutorialMark]? {
didSet {
filterMarks()
}
}
var tutoring: Bool {
get {
return coach.flatMap { $0.flow.started } ?? false
}
}
var completion: ((Bool) -> Void)?
private var coach: CoachMarksController?
private let skip: CoachMarkSkipDefaultView = {
let skip = CoachMarkSkipDefaultView()
skip.setTitle(NSLocalizedString("Skip", comment: "Tutorial skip button label"), forState: .Normal)
return skip
}()
private let defaults = NSUserDefaults.standardUserDefaults()
private var unseen = [TutorialMark]()
private weak var target: UIViewController?
init(marks: [TutorialMark]) {
self.marks = marks
filterMarks()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TutorialOverlayManager.filterMarks), name: NSUserDefaultsDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc
private func filterMarks() {
if let marks = marks where !marks.isEmpty{
if let seen = defaults.arrayForKey(PartyUpPreferences.TutorialViewed) as? [Int] {
unseen = marks.filter { !seen.contains($0.identifier) }
}
} else {
unseen.removeAll()
}
}
private func create() -> CoachMarksController {
let coach = CoachMarksController()
coach.dataSource = self
coach.delegate = self
coach.overlay.color = UIColor.darkGrayColor().colorWithAlphaComponent(0.4)
coach.overlay.allowTap = true
coach.overlay.allowTouchInsideCutoutPath = false
return coach
}
func start(target: UIViewController) {
if !unseen.isEmpty {
if coach == nil {
coach = create()
coach?.skipView = unseen.count > 1 ? skip : nil
coach?.startOn(target)
self.target = target
}
} else {
completion?(false)
}
}
func stop() {
coach?.stop()
}
func pause() {
coach?.pause()
}
func resume() {
coach?.resume()
}
func numberOfCoachMarksForCoachMarksController(coachMarksController: CoachMarksController) -> Int {
return unseen.count
}
func coachMarksController(coachMarksController: CoachMarksController, coachMarkForIndex index: Int) -> CoachMark {
if unseen[index].view == nil {
unseen[index].view = UIApplication.sharedApplication().keyWindow?.viewWithTag(unseen[index].identifier)
}
return coachMarksController.helper.coachMarkForView(unseen[index].view)
}
func coachMarksController(coachMarksController: CoachMarksController, coachMarkViewsForIndex index: Int, coachMark: CoachMark) -> (bodyView: CoachMarkBodyView, arrowView: CoachMarkArrowView?) {
let hint = NSLocalizedString(unseen[index].hint, comment: "Tutorial Mark \(unseen[index].identifier)")
let next = NSLocalizedString("ok", comment: "Tutorial next label")
var coachViews = coachMarksController.helper.defaultCoachViewsWithArrow(true, arrowOrientation: coachMark.arrowOrientation, hintText: hint, nextText: next)
coachViews.bodyView.hintLabel.textAlignment = .Center
if unseen[index].identifier < 0 {
coachViews.arrowView = nil
}
return (bodyView: coachViews.bodyView, arrowView: coachViews.arrowView)
}
func coachMarksController(coachMarksController: CoachMarksController, didFinishShowingAndWasSkipped skipped: Bool) {
if var seen = defaults.arrayForKey(PartyUpPreferences.TutorialViewed) as? [Int] {
seen.appendContentsOf(unseen.map { $0.identifier})
defaults.setObject(seen, forKey: PartyUpPreferences.TutorialViewed)
}
unseen.removeAll()
coach = nil
completion?(skipped)
}
func coachMarksController(coachMarksController: CoachMarksController, constraintsForSkipView skipView: UIView, inParentView parentView: UIView) -> [NSLayoutConstraint]? {
var constraints: [NSLayoutConstraint] = []
constraints.append(NSLayoutConstraint(item: skipView, attribute: .CenterX, relatedBy: .Equal, toItem: parentView, attribute: .CenterX, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: skipView, attribute: .Bottom, relatedBy: .Equal, toItem: parentView, attribute: .BottomMargin, multiplier: 1.0, constant: 0))
return constraints
}
}
| 696c532a22675dc9b6d49e924e370d33 | 29.68 | 194 | 0.741851 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationsViewController.swift | gpl-2.0 | 1 | import Foundation
import Combine
import CoreData
import CocoaLumberjack
import WordPressShared
import WordPressAuthenticator
import Gridicons
import UIKit
/// The purpose of this class is to render the collection of Notifications, associated to the main
/// WordPress.com account.
///
/// Plus, we provide a simple mechanism to render the details for a specific Notification,
/// given its remote identifier.
///
class NotificationsViewController: UIViewController, UIViewControllerRestoration, UITableViewDataSource, UITableViewDelegate {
@objc static let selectedNotificationRestorationIdentifier = "NotificationsSelectedNotificationKey"
@objc static let selectedSegmentIndexRestorationIdentifier = "NotificationsSelectedSegmentIndexKey"
// MARK: - Properties
let formatter = FormattableContentFormatter()
/// Table View
///
@IBOutlet weak var tableView: UITableView!
/// TableHeader
///
@IBOutlet var tableHeaderView: UIView!
/// Filtering Tab Bar
///
@IBOutlet weak var filterTabBar: FilterTabBar!
/// Jetpack Banner View
/// Only visible in WordPress
///
@IBOutlet weak var jetpackBannerView: JetpackBannerView!
/// Inline Prompt Header View
///
@IBOutlet var inlinePromptView: AppFeedbackPromptView!
/// TableView Handler: Our commander in chief!
///
fileprivate var tableViewHandler: WPTableViewHandler!
/// NoResults View
///
private let noResultsViewController = NoResultsViewController.controller()
/// All of the data will be fetched during the FetchedResultsController init. Prevent overfetching
///
fileprivate var lastReloadDate = Date()
/// Indicates whether the view is required to reload results on viewWillAppear, or not
///
var needsReloadResults = false
/// Cached values used for returning the estimated row heights of autosizing cells.
///
fileprivate let estimatedRowHeightsCache = NSCache<AnyObject, AnyObject>()
/// Notifications that must be deleted display an "Undo" button, which simply cancels the deletion task.
///
fileprivate var notificationDeletionRequests: [NSManagedObjectID: NotificationDeletionRequest] = [:]
/// Notifications being deleted are proactively filtered from the list.
///
fileprivate var notificationIdsBeingDeleted = Set<NSManagedObjectID>()
/// Notifications that were unread when the list was loaded.
///
fileprivate var unreadNotificationIds = Set<NSManagedObjectID>()
/// Used to store (and restore) the currently selected filter segment.
///
fileprivate var restorableSelectedSegmentIndex: Int = 0
/// Used to keep track of the currently selected notification,
/// to restore it between table view reloads and state restoration.
///
fileprivate var selectedNotification: Notification? = nil
/// JetpackLoginVC being presented.
///
internal var jetpackLoginViewController: JetpackLoginViewController? = nil
/// Timestamp of the most recent note before updates
/// Used to count notifications to show the second notifications prompt
///
private var timestampBeforeUpdatesForSecondAlert: String?
private lazy var notificationCommentDetailCoordinator: NotificationCommentDetailCoordinator = {
return NotificationCommentDetailCoordinator(notificationsNavigationDataSource: self)
}()
/// Activity Indicator to be shown when refreshing a Jetpack site status.
///
let activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .medium)
indicator.hidesWhenStopped = true
return indicator
}()
/// Notification Settings button
private lazy var settingsBarButtonItem: UIBarButtonItem = {
let settingsButton = UIBarButtonItem(
image: .gridicon(.cog),
style: .plain,
target: self,
action: #selector(showNotificationSettings)
)
settingsButton.accessibilityLabel = NSLocalizedString(
"Notification Settings",
comment: "Link to Notification Settings section"
)
return settingsButton
}()
/// Mark All As Read button
private lazy var markAllAsReadBarButtonItem: UIBarButtonItem = {
let markButton = UIBarButtonItem(
image: .gridicon(.checkmark),
style: .plain,
target: self,
action: #selector(showMarkAllAsReadConfirmation)
)
markButton.accessibilityLabel = NSLocalizedString(
"Mark All As Read",
comment: "Marks all notifications under the filter as read"
)
return markButton
}()
/// Used by JPScrollViewDelegate to send scroll position
internal let scrollViewTranslationPublisher = PassthroughSubject<Bool, Never>()
/// The last time when user seen notifications
var lastSeenTime: String? {
get {
return userDefaults.string(forKey: Settings.lastSeenTime)
}
set {
userDefaults.set(newValue, forKey: Settings.lastSeenTime)
}
}
// MARK: - View Lifecycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
restorationClass = NotificationsViewController.self
startListeningToAccountNotifications()
startListeningToTimeChangeNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupTableHandler()
setupTableView()
setupTableFooterView()
setupRefreshControl()
setupNoResultsView()
setupFilterBar()
tableView.tableHeaderView = tableHeaderView
setupConstraints()
configureJetpackBanner()
reloadTableViewPreservingSelection()
startListeningToCommentDeletedNotifications()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
JetpackFeaturesRemovalCoordinator.presentOverlayIfNeeded(from: .notifications, in: self)
syncNotificationsWithModeratedComments()
setupInlinePrompt()
// Manually deselect the selected row.
if splitViewControllerIsHorizontallyCompact {
// This is required due to a bug in iOS7 / iOS8
tableView.deselectSelectedRowWithAnimation(true)
selectedNotification = nil
}
// While we're onscreen, please, update rows with animations
tableViewHandler.updateRowAnimation = .fade
// Tracking
WPAnalytics.track(WPAnalyticsStat.openedNotificationsList)
// Notifications
startListeningToNotifications()
resetApplicationBadge()
updateLastSeenTime()
// Refresh the UI
reloadResultsControllerIfNeeded()
updateMarkAllAsReadButton()
if !splitViewControllerIsHorizontallyCompact {
reloadTableViewPreservingSelection()
}
if shouldDisplayJetpackPrompt {
promptForJetpackCredentials()
} else {
jetpackLoginViewController?.remove()
}
showNoResultsViewIfNeeded()
selectFirstNotificationIfAppropriate()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
defer {
if AppConfiguration.showsWhatIsNew {
WPTabBarController.sharedInstance()?.presentWhatIsNew(on: self)
}
}
syncNewNotifications()
markSelectedNotificationAsRead()
registerUserActivity()
markWelcomeNotificationAsSeenIfNeeded()
if userDefaults.notificationsTabAccessCount < Constants.inlineTabAccessCount {
userDefaults.notificationsTabAccessCount += 1
}
// Don't show the notification primers if we already asked during onboarding
if userDefaults.onboardingNotificationsPromptDisplayed, userDefaults.notificationsTabAccessCount == 1 {
return
}
if shouldShowPrimeForPush {
setupNotificationPrompt()
} else if AppRatingUtility.shared.shouldPromptForAppReview(section: InlinePrompt.section) {
setupAppRatings()
self.showInlinePrompt()
}
showNotificationPrimerAlertIfNeeded()
showSecondNotificationsAlertIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopListeningToNotifications()
dismissNoNetworkAlert()
// If we're not onscreen, don't use row animations. Otherwise the fade animation might get animated incrementally
tableViewHandler.updateRowAnimation = .none
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.layoutHeaderView()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
DispatchQueue.main.async {
self.showNoResultsViewIfNeeded()
}
if splitViewControllerIsHorizontallyCompact {
tableView.deselectSelectedRowWithAnimation(true)
} else {
if let selectedNotification = selectedNotification {
selectRow(for: selectedNotification, animated: true, scrollPosition: .middle)
} else {
selectFirstNotificationIfAppropriate()
}
}
tableView.tableHeaderView = tableHeaderView
}
// MARK: - State Restoration
static func viewController(withRestorationIdentifierPath identifierComponents: [String],
coder: NSCoder) -> UIViewController? {
return WPTabBarController.sharedInstance().notificationsViewController
}
override func encodeRestorableState(with coder: NSCoder) {
if let uriRepresentation = selectedNotification?.objectID.uriRepresentation() {
coder.encode(uriRepresentation, forKey: type(of: self).selectedNotificationRestorationIdentifier)
}
// If the filter's 'Unread', we won't save it because the notification
// that's selected won't be unread any more once we come back to it.
let index: Filter = (filter != .unread) ? filter : .none
coder.encode(index.rawValue, forKey: type(of: self).selectedSegmentIndexRestorationIdentifier)
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
decodeSelectedSegmentIndex(with: coder)
decodeSelectedNotification(with: coder)
reloadResultsController()
super.decodeRestorableState(with: coder)
}
fileprivate func decodeSelectedNotification(with coder: NSCoder) {
if let uriRepresentation = coder.decodeObject(forKey: type(of: self).selectedNotificationRestorationIdentifier) as? URL {
let context = ContextManager.sharedInstance().mainContext
if let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: uriRepresentation),
let object = try? context.existingObject(with: objectID),
let notification = object as? Notification {
selectedNotification = notification
}
}
}
fileprivate func decodeSelectedSegmentIndex(with coder: NSCoder) {
restorableSelectedSegmentIndex = coder.decodeInteger(forKey: type(of: self).selectedSegmentIndexRestorationIdentifier)
if let filterTabBar = filterTabBar, filterTabBar.selectedIndex != restorableSelectedSegmentIndex {
filterTabBar.setSelectedIndex(restorableSelectedSegmentIndex, animated: false)
}
}
override func applicationFinishedRestoringState() {
super.applicationFinishedRestoringState()
guard let navigationControllers = navigationController?.children else {
return
}
// TODO: add check for CommentDetailViewController
for case let detailVC as NotificationDetailsViewController in navigationControllers {
if detailVC.onDeletionRequestCallback == nil, let note = detailVC.note {
configureDetailsViewController(detailVC, withNote: note)
}
}
}
// MARK: - UITableViewDataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableViewHandler.tableView(tableView, numberOfRowsInSection: section)
}
func numberOfSections(in tableView: UITableView) -> Int {
tableViewHandler.numberOfSections(in: tableView)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ListTableViewCell.defaultReuseID, for: indexPath)
configureCell(cell, at: indexPath)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sectionInfo = tableViewHandler.resultsController.sections?[section],
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ListTableHeaderView.defaultReuseID) as? ListTableHeaderView else {
return nil
}
headerView.title = Notification.descriptionForSectionIdentifier(sectionInfo.name)
return headerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Make sure no SectionFooter is rendered
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// Make sure no SectionFooter is rendered
return nil
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
estimatedRowHeightsCache.setObject(cell.frame.height as AnyObject, forKey: indexPath as AnyObject)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = estimatedRowHeightsCache.object(forKey: indexPath as AnyObject) as? CGFloat {
return height
}
return Settings.estimatedRowHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Failsafe: Make sure that the Notification (still) exists
guard let note = tableViewHandler.resultsController.managedObject(atUnsafe: indexPath) as? Notification else {
tableView.deselectSelectedRowWithAnimation(true)
return
}
// Push the Details: Unless the note has a pending deletion!
guard deletionRequestForNoteWithID(note.objectID) == nil else {
return
}
selectedNotification = note
showDetails(for: note)
if !splitViewControllerIsHorizontallyCompact {
syncNotificationsWithModeratedComments()
}
}
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// skip when the notification is marked for deletion.
guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification,
deletionRequestForNoteWithID(note.objectID) == nil else {
return nil
}
let isRead = note.read
let title = isRead ? NSLocalizedString("Mark Unread", comment: "Marks a notification as unread") :
NSLocalizedString("Mark Read", comment: "Marks a notification as unread")
let action = UIContextualAction(style: .normal, title: title, handler: { (action, view, completionHandler) in
if isRead {
WPAnalytics.track(.notificationMarkAsUnreadTapped)
self.markAsUnread(note: note)
} else {
WPAnalytics.track(.notificationMarkAsReadTapped)
self.markAsRead(note: note)
}
completionHandler(true)
})
action.backgroundColor = .neutral(.shade50)
return UISwipeActionsConfiguration(actions: [action])
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// skip when the notification is marked for deletion.
guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification,
let block: FormattableCommentContent = note.contentGroup(ofKind: .comment)?.blockOfKind(.comment),
deletionRequestForNoteWithID(note.objectID) == nil else {
return nil
}
// Approve comment
guard let approveEnabled = block.action(id: ApproveCommentAction.actionIdentifier())?.enabled,
approveEnabled == true,
let approveAction = block.action(id: ApproveCommentAction.actionIdentifier()),
let actionTitle = approveAction.command?.actionTitle else {
return nil
}
let action = UIContextualAction(style: .normal, title: actionTitle, handler: { (_, _, completionHandler) in
WPAppAnalytics.track(approveAction.on ? .notificationsCommentUnapproved : .notificationsCommentApproved,
withProperties: [Stats.sourceKey: Stats.sourceValue],
withBlogID: block.metaSiteID)
let actionContext = ActionContext(block: block)
approveAction.execute(context: actionContext)
completionHandler(true)
})
action.backgroundColor = approveAction.command?.actionColor
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let note = sender as? Notification else {
return
}
guard let detailsViewController = segue.destination as? NotificationDetailsViewController else {
return
}
configureDetailsViewController(detailsViewController, withNote: note)
}
fileprivate func configureDetailsViewController(_ detailsViewController: NotificationDetailsViewController, withNote note: Notification) {
detailsViewController.navigationItem.largeTitleDisplayMode = .never
detailsViewController.dataSource = self
detailsViewController.notificationCommentDetailCoordinator = notificationCommentDetailCoordinator
detailsViewController.note = note
detailsViewController.onDeletionRequestCallback = { request in
self.showUndeleteForNoteWithID(note.objectID, request: request)
}
detailsViewController.onSelectedNoteChange = { note in
self.selectRow(for: note)
}
}
}
// MARK: - User Interface Initialization
//
private extension NotificationsViewController {
func setupNavigationBar() {
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always
// Don't show 'Notifications' in the next-view back button
// we are using a space character because we need a non-empty string to ensure a smooth
// transition back, with large titles enabled.
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
navigationItem.title = NSLocalizedString("Notifications", comment: "Notifications View Controller title")
}
func updateNavigationItems() {
var barItems: [UIBarButtonItem] = []
if shouldDisplaySettingsButton {
barItems.append(settingsBarButtonItem)
}
barItems.append(markAllAsReadBarButtonItem)
navigationItem.setRightBarButtonItems(barItems, animated: false)
}
@objc func closeNotificationSettings() {
dismiss(animated: true, completion: nil)
}
func setupConstraints() {
// Inline prompt is initially hidden!
inlinePromptView.translatesAutoresizingMaskIntoConstraints = false
filterTabBar.tabBarHeightConstraintPriority = 999
let leading = tableHeaderView.safeLeadingAnchor.constraint(equalTo: tableView.safeLeadingAnchor)
let trailing = tableHeaderView.safeTrailingAnchor.constraint(equalTo: tableView.safeTrailingAnchor)
leading.priority = UILayoutPriority(999)
trailing.priority = UILayoutPriority(999)
NSLayoutConstraint.activate([
tableHeaderView.topAnchor.constraint(equalTo: tableView.topAnchor),
leading,
trailing
])
}
func setupTableView() {
// Register the cells
tableView.register(ListTableHeaderView.defaultNib, forHeaderFooterViewReuseIdentifier: ListTableHeaderView.defaultReuseID)
tableView.register(ListTableViewCell.defaultNib, forCellReuseIdentifier: ListTableViewCell.defaultReuseID)
// UITableView
tableView.accessibilityIdentifier = "Notifications Table"
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.estimatedSectionHeaderHeight = UITableView.automaticDimension
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
WPStyleGuide.configureColors(view: view, tableView: tableView)
}
func setupTableFooterView() {
// Fix: Hide the cellSeparators, when the table is empty
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 1))
}
func setupTableHandler() {
let handler = WPTableViewHandler(tableView: tableView)
handler.cacheRowHeights = false
handler.delegate = self
tableViewHandler = handler
}
func setupInlinePrompt() {
precondition(inlinePromptView != nil)
inlinePromptView.alpha = WPAlphaZero
inlinePromptView.isHidden = true
}
func setupRefreshControl() {
let control = UIRefreshControl()
control.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.refreshControl = control
}
func setupNoResultsView() {
noResultsViewController.delegate = self
}
func setupFilterBar() {
WPStyleGuide.configureFilterTabBar(filterTabBar)
filterTabBar.superview?.backgroundColor = .filterBarBackground
filterTabBar.items = Filter.allCases
filterTabBar.addTarget(self, action: #selector(selectedFilterDidChange(_:)), for: .valueChanged)
}
}
// MARK: - Jetpack banner UI Initialization
//
extension NotificationsViewController {
/// Called on view load to determine whether the Jetpack banner should be shown on the view
/// Also called in the completion block of the JetpackLoginViewController to show the banner once the user connects to a .com account
func configureJetpackBanner() {
guard JetpackBrandingVisibility.all.enabled else {
return
}
jetpackBannerView.buttonAction = { [unowned self] in
JetpackBrandingCoordinator.presentOverlay(from: self)
JetpackBrandingAnalyticsHelper.trackJetpackPoweredBannerTapped(screen: .notifications)
}
jetpackBannerView.isHidden = false
addTranslationObserver(jetpackBannerView)
}
}
// MARK: - Notifications
//
private extension NotificationsViewController {
func startListeningToNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
nc.addObserver(self, selector: #selector(notificationsWereUpdated), name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil)
nc.addObserver(self, selector: #selector(dynamicTypeDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil)
}
func startListeningToAccountNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(defaultAccountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil)
}
func startListeningToTimeChangeNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(significantTimeChange),
name: UIApplication.significantTimeChangeNotification,
object: nil)
}
func startListeningToCommentDeletedNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(removeDeletedNotification),
name: .NotificationCommentDeletedNotification,
object: nil)
}
func stopListeningToNotifications() {
let nc = NotificationCenter.default
nc.removeObserver(self,
name: UIApplication.didBecomeActiveNotification,
object: nil)
nc.removeObserver(self,
name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications),
object: nil)
}
@objc func applicationDidBecomeActive(_ note: Foundation.Notification) {
// Let's reset the badge, whenever the app comes back to FG, and this view was upfront!
guard isViewLoaded == true && view.window != nil else {
return
}
resetApplicationBadge()
updateLastSeenTime()
reloadResultsControllerIfNeeded()
}
@objc func defaultAccountDidChange(_ note: Foundation.Notification) {
resetNotifications()
resetLastSeenTime()
resetApplicationBadge()
guard isViewLoaded == true && view.window != nil else {
needsReloadResults = true
return
}
reloadResultsController()
syncNewNotifications()
}
@objc func notificationsWereUpdated(_ note: Foundation.Notification) {
// If we're onscreen, don't leave the badge updated behind
guard UIApplication.shared.applicationState == .active else {
return
}
resetApplicationBadge()
updateLastSeenTime()
}
@objc func significantTimeChange(_ note: Foundation.Notification) {
needsReloadResults = true
if UIApplication.shared.applicationState == .active
&& isViewLoaded == true
&& view.window != nil {
reloadResultsControllerIfNeeded()
}
}
@objc func dynamicTypeDidChange() {
tableViewHandler.resultsController.fetchedObjects?.forEach {
($0 as? Notification)?.resetCachedAttributes()
}
}
}
// MARK: - Public Methods
//
extension NotificationsViewController {
/// Pushes the Details for a given notificationID, immediately, if the notification is already available.
/// Otherwise, will attempt to Sync the Notification. If this cannot be achieved before the timeout defined
/// by `Syncing.pushMaxWait` kicks in, we'll just do nothing (in order not to disrupt the UX!).
///
/// - Parameter notificationID: The ID of the Notification that should be rendered onscreen.
///
@objc
func showDetailsForNotificationWithID(_ noteId: String) {
if let note = loadNotification(with: noteId) {
showDetails(for: note)
return
}
syncNotification(with: noteId, timeout: Syncing.pushMaxWait) { note in
self.showDetails(for: note)
}
}
/// Pushes the details for a given Notification Instance.
///
private func showDetails(for note: Notification) {
DDLogInfo("Pushing Notification Details for: [\(note.notificationId)]")
// Before trying to show the details of a notification, we need to make sure the view is loaded.
//
// Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/12669#issuecomment-561579415
// Ref: https://sentry.io/organizations/a8c/issues/1329631657/
//
loadViewIfNeeded()
/// Note: markAsRead should be the *first* thing we do. This triggers a context save, and may have many side effects that
/// could affect the OP's that go below!!!.
///
/// YES figuring that out took me +90 minutes of debugger time!!!
///
markAsRead(note: note)
trackWillPushDetails(for: note)
ensureNotificationsListIsOnscreen()
ensureNoteIsNotBeingFiltered(note)
selectRow(for: note, animated: false, scrollPosition: .top)
// Display Details
//
if let postID = note.metaPostID,
let siteID = note.metaSiteID,
note.kind == .matcher || note.kind == .newPost {
let readerViewController = ReaderDetailViewController.controllerWithPostID(postID, siteID: siteID)
readerViewController.navigationItem.largeTitleDisplayMode = .never
showDetailViewController(readerViewController, sender: nil)
return
}
presentDetails(for: note)
}
private func presentDetails(for note: Notification) {
// This dispatch avoids a bug that was occurring occasionally where navigation (nav bar and tab bar)
// would be missing entirely when launching the app from the background and presenting a notification.
// The issue seems tied to performing a `pop` in `prepareToShowDetails` and presenting
// the new detail view controller at the same time. More info: https://github.com/wordpress-mobile/WordPress-iOS/issues/6976
//
// Plus: Avoid pushing multiple DetailsViewController's, upon quick & repeated touch events.
view.isUserInteractionEnabled = false
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
self.view.isUserInteractionEnabled = true
if FeatureFlag.notificationCommentDetails.enabled,
note.kind == .comment {
guard let commentDetailViewController = self.notificationCommentDetailCoordinator.createViewController(with: note) else {
DDLogError("Notifications: failed creating Comment Detail view.")
return
}
self.notificationCommentDetailCoordinator.onSelectedNoteChange = { [weak self] note in
self?.selectRow(for: note)
}
commentDetailViewController.navigationItem.largeTitleDisplayMode = .never
self.showDetailViewController(commentDetailViewController, sender: nil)
return
}
self.performSegue(withIdentifier: NotificationDetailsViewController.classNameWithoutNamespaces(), sender: note)
}
}
/// Tracks: Details Event!
///
private func trackWillPushDetails(for note: Notification) {
// Ensure we don't track if the app has been launched by a push notification in the background
if UIApplication.shared.applicationState != .background {
let properties = [Stats.noteTypeKey: note.type ?? Stats.noteTypeUnknown]
WPAnalytics.track(.openedNotificationDetails, withProperties: properties)
}
}
/// Failsafe: Make sure the Notifications List is onscreen!
///
private func ensureNotificationsListIsOnscreen() {
guard navigationController?.visibleViewController != self else {
return
}
_ = navigationController?.popViewController(animated: false)
}
/// This method will make sure the Notification that's about to be displayed is not currently being filtered.
///
private func ensureNoteIsNotBeingFiltered(_ note: Notification) {
guard filter != .none else {
return
}
let noteIndexPath = tableView.indexPathsForVisibleRows?.first { indexPath in
return note == tableViewHandler.resultsController.object(at: indexPath) as? Notification
}
guard noteIndexPath == nil else {
return
}
filter = .none
}
/// Will display an Undelete button on top of a given notification.
/// On timeout, the destructive action (received via parameter) will be executed, and the notification
/// will (supposedly) get deleted.
///
/// - Parameters:
/// - noteObjectID: The Core Data ObjectID associated to a given notification.
/// - request: A DeletionRequest Struct
///
private func showUndeleteForNoteWithID(_ noteObjectID: NSManagedObjectID, request: NotificationDeletionRequest) {
// Mark this note as Pending Deletion and Reload
notificationDeletionRequests[noteObjectID] = request
reloadRowForNotificationWithID(noteObjectID)
// Dispatch the Action block
perform(#selector(deleteNoteWithID), with: noteObjectID, afterDelay: Syncing.undoTimeout)
}
/// Presents the Notifications Settings screen.
///
@objc func showNotificationSettings() {
let controller = NotificationSettingsViewController()
controller.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(closeNotificationSettings))
let navigationController = UINavigationController(rootViewController: controller)
navigationController.modalPresentationStyle = .formSheet
navigationController.modalTransitionStyle = .coverVertical
present(navigationController, animated: true, completion: nil)
}
}
// MARK: - Notifications Deletion Mechanism
//
private extension NotificationsViewController {
@objc func deleteNoteWithID(_ noteObjectID: NSManagedObjectID) {
// Was the Deletion Canceled?
guard let request = deletionRequestForNoteWithID(noteObjectID) else {
return
}
// Hide the Notification
notificationIdsBeingDeleted.insert(noteObjectID)
reloadResultsController()
// Hit the Deletion Action
request.action { success in
self.notificationDeletionRequests.removeValue(forKey: noteObjectID)
self.notificationIdsBeingDeleted.remove(noteObjectID)
// Error: let's unhide the row
if success == false {
self.reloadResultsController()
}
}
}
func cancelDeletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) {
notificationDeletionRequests.removeValue(forKey: noteObjectID)
reloadRowForNotificationWithID(noteObjectID)
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(deleteNoteWithID), object: noteObjectID)
}
func deletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) -> NotificationDeletionRequest? {
return notificationDeletionRequests[noteObjectID]
}
// MARK: - Notifications Deletion from CommentDetailViewController
// With the `notificationCommentDetails` feature, Comment moderation is handled by the view.
// To avoid updating the Notifications here prematurely, affecting the previous/next buttons,
// the Notifications are tracked in NotificationCommentDetailCoordinator when their comments are moderated.
// Those Notifications are updated here when the view is shown to update the list accordingly.
func syncNotificationsWithModeratedComments() {
selectNextAvailableNotification(ignoring: notificationCommentDetailCoordinator.notificationsCommentModerated)
notificationCommentDetailCoordinator.notificationsCommentModerated.forEach {
syncNotification(with: $0.notificationId, timeout: Syncing.pushMaxWait, success: {_ in })
}
notificationCommentDetailCoordinator.notificationsCommentModerated = []
}
@objc func removeDeletedNotification(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let deletedCommentID = userInfo[userInfoCommentIdKey] as? Int32,
let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification] else {
return
}
let notification = notifications.first(where: { notification -> Bool in
guard let commentID = notification.metaCommentID else {
return false
}
return commentID.intValue == deletedCommentID
})
syncDeletedNotification(notification)
}
func syncDeletedNotification(_ notification: Notification?) {
guard let notification = notification else {
return
}
selectNextAvailableNotification(ignoring: [notification])
syncNotification(with: notification.notificationId, timeout: Syncing.pushMaxWait, success: { [weak self] notification in
self?.notificationCommentDetailCoordinator.notificationsCommentModerated.removeAll(where: { $0.notificationId == notification.notificationId })
})
}
func selectNextAvailableNotification(ignoring: [Notification]) {
// If the currently selected notification is about to be removed, find the next available and select it.
// This is only necessary for split view to prevent the details from showing for removed notifications.
if !splitViewControllerIsHorizontallyCompact,
let selectedNotification = selectedNotification,
ignoring.contains(selectedNotification) {
guard let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification],
let nextAvailable = notifications.first(where: { !ignoring.contains($0) }),
let indexPath = tableViewHandler.resultsController.indexPath(forObject: nextAvailable) else {
self.selectedNotification = nil
return
}
self.selectedNotification = nextAvailable
tableView(tableView, didSelectRowAt: indexPath)
}
}
}
// MARK: - Marking as Read
//
private extension NotificationsViewController {
private enum Localization {
static let markAllAsReadNoticeSuccess = NSLocalizedString(
"Notifications marked as read",
comment: "Title for mark all as read success notice"
)
static let markAllAsReadNoticeFailure = NSLocalizedString(
"Failed marking Notifications as read",
comment: "Message for mark all as read success notice"
)
}
func markSelectedNotificationAsRead() {
guard let note = selectedNotification else {
return
}
markAsRead(note: note)
}
func markAsRead(note: Notification) {
guard !note.read else {
return
}
NotificationSyncMediator()?.markAsRead(note)
}
/// Marks all messages as read under the selected filter.
///
@objc func markAllAsRead() {
guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else {
return
}
WPAnalytics.track(.notificationsMarkAllReadTapped)
let unreadNotifications = notes.filter {
!$0.read
}
NotificationSyncMediator()?.markAsRead(unreadNotifications, completion: { [weak self] error in
let notice = Notice(
title: error != nil ? Localization.markAllAsReadNoticeFailure : Localization.markAllAsReadNoticeSuccess
)
ActionDispatcherFacade().dispatch(NoticeAction.post(notice))
self?.updateMarkAllAsReadButton()
})
}
/// Presents a confirmation action sheet for mark all as read action.
@objc func showMarkAllAsReadConfirmation() {
let title: String
switch filter {
case .none:
title = NSLocalizedString(
"Mark all notifications as read?",
comment: "Confirmation title for marking all notifications as read."
)
default:
title = NSLocalizedString(
"Mark all %1$@ notifications as read?",
comment: "Confirmation title for marking all notifications under a filter as read. %1$@ is replaced by the filter name."
)
}
let cancelTitle = NSLocalizedString(
"Cancel",
comment: "Cancels the mark all as read action."
)
let markAllTitle = NSLocalizedString(
"OK",
comment: "Marks all notifications as read."
)
let alertController = UIAlertController(
title: String.localizedStringWithFormat(title, filter.confirmationMessageTitle),
message: nil,
preferredStyle: .alert
)
alertController.view.accessibilityIdentifier = "mark-all-as-read-alert"
alertController.addCancelActionWithTitle(cancelTitle)
alertController.addActionWithTitle(markAllTitle, style: .default) { [weak self] _ in
self?.markAllAsRead()
}
present(alertController, animated: true, completion: nil)
}
func markAsUnread(note: Notification) {
guard note.read else {
return
}
NotificationSyncMediator()?.markAsUnread(note)
updateMarkAllAsReadButton()
}
func markWelcomeNotificationAsSeenIfNeeded() {
let welcomeNotificationSeenKey = userDefaults.welcomeNotificationSeenKey
if !userDefaults.bool(forKey: welcomeNotificationSeenKey) {
userDefaults.set(true, forKey: welcomeNotificationSeenKey)
resetApplicationBadge()
}
}
func updateMarkAllAsReadButton() {
guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else {
return
}
let isEnabled = notes.first { !$0.read } != nil
markAllAsReadBarButtonItem.tintColor = isEnabled ? .primary : .textTertiary
markAllAsReadBarButtonItem.isEnabled = isEnabled
}
}
// MARK: - Unread notifications caching
//
private extension NotificationsViewController {
/// Updates the cached list of unread notifications, and optionally reloads the results controller.
///
func refreshUnreadNotifications(reloadingResultsController: Bool = true) {
guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else {
return
}
let previous = unreadNotificationIds
// This is additive because we don't want to remove anything
// from the list unless we explicitly call
// clearUnreadNotifications()
notes.lazy.filter({ !$0.read }).forEach { note in
unreadNotificationIds.insert(note.objectID)
}
if previous != unreadNotificationIds && reloadingResultsController {
reloadResultsController()
}
}
/// Empties the cached list of unread notifications.
///
func clearUnreadNotifications() {
let shouldReload = !unreadNotificationIds.isEmpty
unreadNotificationIds.removeAll()
if shouldReload {
reloadResultsController()
}
}
}
// MARK: - WPTableViewHandler Helpers
//
private extension NotificationsViewController {
func reloadResultsControllerIfNeeded() {
// NSFetchedResultsController groups notifications based on a transient property ("sectionIdentifier").
// Simply calling reloadData doesn't make the FRC recalculate the sections.
// For that reason, let's force a reload, only when 1 day has elapsed, and sections would have changed.
//
let daysElapsed = Calendar.current.daysElapsedSinceDate(lastReloadDate)
guard daysElapsed != 0 || needsReloadResults else {
return
}
reloadResultsController()
}
func reloadResultsController() {
// Update the Predicate: We can't replace the previous fetchRequest, since it's readonly!
let fetchRequest = tableViewHandler.resultsController.fetchRequest
fetchRequest.predicate = predicateForFetchRequest()
/// Refetch + Reload
_ = try? tableViewHandler.resultsController.performFetch()
reloadTableViewPreservingSelection()
// Empty State?
showNoResultsViewIfNeeded()
// Don't overwork!
lastReloadDate = Date()
needsReloadResults = false
updateMarkAllAsReadButton()
}
func reloadRowForNotificationWithID(_ noteObjectID: NSManagedObjectID) {
do {
let note = try mainContext.existingObject(with: noteObjectID)
if let indexPath = tableViewHandler.resultsController.indexPath(forObject: note) {
tableView.reloadRows(at: [indexPath], with: .fade)
}
} catch {
DDLogError("Error refreshing Notification Row \(error)")
}
}
func selectRow(for notification: Notification, animated: Bool = true,
scrollPosition: UITableView.ScrollPosition = .none) {
selectedNotification = notification
// also ensure that the index path returned from results controller does not have negative row index.
// ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/15370
guard let indexPath = tableViewHandler.resultsController.indexPath(forObject: notification),
indexPath != tableView.indexPathForSelectedRow,
0..<tableView.numberOfRows(inSection: indexPath.section) ~= indexPath.row else {
return
}
DDLogInfo("\(self) \(#function) Selecting row at \(indexPath) for Notification: \(notification.notificationId) (\(notification.type ?? "Unknown type")) - \(notification.title ?? "No title")")
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
func reloadTableViewPreservingSelection() {
tableView.reloadData()
// Show the current selection if our split view isn't collapsed
if !splitViewControllerIsHorizontallyCompact, let notification = selectedNotification {
selectRow(for: notification, animated: false, scrollPosition: .none)
}
}
}
// MARK: - UIRefreshControl Methods
//
extension NotificationsViewController {
@objc func refresh() {
guard let mediator = NotificationSyncMediator() else {
tableView.refreshControl?.endRefreshing()
return
}
let start = Date()
mediator.sync { [weak self] (error, _) in
let delta = max(Syncing.minimumPullToRefreshDelay + start.timeIntervalSinceNow, 0)
let delay = DispatchTime.now() + Double(Int64(delta * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delay) {
self?.tableView.refreshControl?.endRefreshing()
self?.clearUnreadNotifications()
if let _ = error {
self?.handleConnectionError()
}
}
}
}
}
extension NotificationsViewController: NetworkAwareUI {
func contentIsEmpty() -> Bool {
return tableViewHandler.resultsController.isEmpty()
}
func noConnectionMessage() -> String {
return NSLocalizedString("No internet connection. Some content may be unavailable while offline.",
comment: "Error message shown when the user is browsing Notifications without an internet connection.")
}
}
extension NotificationsViewController: NetworkStatusDelegate {
func networkStatusDidChange(active: Bool) {
reloadResultsControllerIfNeeded()
}
}
// MARK: - FilterTabBar Methods
//
extension NotificationsViewController {
@objc func selectedFilterDidChange(_ filterBar: FilterTabBar) {
selectedNotification = nil
let properties = [Stats.selectedFilter: filter.analyticsTitle]
WPAnalytics.track(.notificationsTappedSegmentedControl, withProperties: properties)
updateUnreadNotificationsForFilterTabChange()
reloadResultsController()
selectFirstNotificationIfAppropriate()
}
@objc func selectFirstNotificationIfAppropriate() {
guard !splitViewControllerIsHorizontallyCompact && selectedNotification == nil else {
return
}
// If we don't currently have a selected notification and there is a notification in the list, then select it.
if let firstNotification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification,
let indexPath = tableViewHandler.resultsController.indexPath(forObject: firstNotification) {
selectRow(for: firstNotification, animated: false, scrollPosition: .none)
self.tableView(tableView, didSelectRowAt: indexPath)
return
}
// If we're not showing the Jetpack prompt or the fullscreen No Results View,
// then clear any detail view controller that may be present.
// (i.e. don't add an empty detail VC if the primary is full width)
if let splitViewController = splitViewController as? WPSplitViewController,
splitViewController.wpPrimaryColumnWidth != WPSplitViewControllerPrimaryColumnWidth.full {
let controller = UIViewController()
controller.navigationItem.largeTitleDisplayMode = .never
showDetailViewController(controller, sender: nil)
}
}
@objc func updateUnreadNotificationsForFilterTabChange() {
if filter == .unread {
refreshUnreadNotifications(reloadingResultsController: false)
} else {
clearUnreadNotifications()
}
}
}
// MARK: - WPTableViewHandlerDelegate Methods
//
extension NotificationsViewController: WPTableViewHandlerDelegate {
func managedObjectContext() -> NSManagedObjectContext {
return ContextManager.sharedInstance().mainContext
}
func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName())
request.sortDescriptors = [NSSortDescriptor(key: Filter.sortKey, ascending: false)]
request.predicate = predicateForFetchRequest()
return request
}
@objc func predicateForFetchRequest() -> NSPredicate {
let deletedIdsPredicate = NSPredicate(format: "NOT (SELF IN %@)", Array(notificationIdsBeingDeleted))
let selectedFilterPredicate = predicateForSelectedFilters()
return NSCompoundPredicate(andPredicateWithSubpredicates: [deletedIdsPredicate, selectedFilterPredicate])
}
@objc func predicateForSelectedFilters() -> NSPredicate {
guard let condition = filter.condition else {
return NSPredicate(value: true)
}
var subpredicates: [NSPredicate] = [NSPredicate(format: condition)]
if filter == .unread {
subpredicates.append(NSPredicate(format: "SELF IN %@", Array(unreadNotificationIds)))
}
return NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates)
}
func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification,
let cell = cell as? ListTableViewCell else {
return
}
cell.configureWithNotification(note)
// handle undo overlays
let deletionRequest = deletionRequestForNoteWithID(note.objectID)
cell.configureUndeleteOverlay(with: deletionRequest?.kind.legendText) { [weak self] in
self?.cancelDeletionRequestForNoteWithID(note.objectID)
}
// additional configurations
cell.accessibilityHint = Self.accessibilityHint(for: note)
}
func sectionNameKeyPath() -> String {
return "sectionIdentifier"
}
@objc func entityName() -> String {
return Notification.classNameWithoutNamespaces()
}
private var shouldCountNotificationsForSecondAlert: Bool {
userDefaults.notificationPrimerInlineWasAcknowledged &&
userDefaults.secondNotificationsAlertCount != Constants.secondNotificationsAlertDisabled
}
func tableViewWillChangeContent(_ tableView: UITableView) {
guard shouldCountNotificationsForSecondAlert,
let notification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification,
let timestamp = notification.timestamp else {
timestampBeforeUpdatesForSecondAlert = nil
return
}
timestampBeforeUpdatesForSecondAlert = timestamp
}
func tableViewDidChangeContent(_ tableView: UITableView) {
refreshUnreadNotifications()
// Update NoResults View
showNoResultsViewIfNeeded()
if let selectedNotification = selectedNotification {
selectRow(for: selectedNotification, animated: false, scrollPosition: .none)
} else {
selectFirstNotificationIfAppropriate()
}
// count new notifications for second alert
guard shouldCountNotificationsForSecondAlert else {
return
}
userDefaults.secondNotificationsAlertCount += newNotificationsForSecondAlert
if isViewOnScreen() {
showSecondNotificationsAlertIfNeeded()
}
}
// counts the new notifications for the second alert
private var newNotificationsForSecondAlert: Int {
guard let previousTimestamp = timestampBeforeUpdatesForSecondAlert,
let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification] else {
return 0
}
for notification in notifications.enumerated() {
if let timestamp = notification.element.timestamp, timestamp <= previousTimestamp {
return notification.offset
}
}
return 0
}
private static func accessibilityHint(for note: Notification) -> String? {
switch note.kind {
case .comment:
return NSLocalizedString("Shows details and moderation actions.",
comment: "Accessibility hint for a comment notification.")
case .commentLike, .like:
return NSLocalizedString("Shows all likes.",
comment: "Accessibility hint for a post or comment “like” notification.")
case .follow:
return NSLocalizedString("Shows all followers",
comment: "Accessibility hint for a follow notification.")
case .matcher, .newPost:
return NSLocalizedString("Shows the post",
comment: "Accessibility hint for a match/mention on a post notification.")
default:
return nil
}
}
}
// MARK: - Filter Helpers
//
private extension NotificationsViewController {
func showFiltersSegmentedControlIfApplicable() {
guard filterTabBar.isHidden == true && shouldDisplayFilters == true else {
return
}
UIView.animate(withDuration: WPAnimationDurationDefault, animations: {
self.filterTabBar.isHidden = false
})
}
func hideFiltersSegmentedControlIfApplicable() {
if filterTabBar.isHidden == false && shouldDisplayFilters == false {
self.filterTabBar.isHidden = true
}
}
var shouldDisplayFilters: Bool {
// Filters should only be hidden whenever there are no Notifications in the bucket (contrary to the FRC's
// results, which are filtered by the active predicate!).
//
return mainContext.countObjects(ofType: Notification.self) > 0 && !shouldDisplayJetpackPrompt
}
}
// MARK: - NoResults Helpers
//
private extension NotificationsViewController {
func showNoResultsViewIfNeeded() {
noResultsViewController.removeFromView()
updateSplitViewAppearanceForNoResultsView()
updateNavigationItems()
// Hide the filter header if we're showing the Jetpack prompt
hideFiltersSegmentedControlIfApplicable()
// Show Filters if needed
guard shouldDisplayNoResultsView == true else {
showFiltersSegmentedControlIfApplicable()
return
}
guard connectionAvailable() else {
showNoConnectionView()
return
}
// Refresh its properties: The user may have signed into WordPress.com
noResultsViewController.configure(title: noResultsTitleText, buttonTitle: noResultsButtonText, subtitle: noResultsMessageText, image: "wp-illustration-notifications")
addNoResultsToView()
}
func showNoConnectionView() {
noResultsViewController.configure(title: noConnectionTitleText, subtitle: noConnectionMessage())
addNoResultsToView()
}
func addNoResultsToView() {
addChild(noResultsViewController)
tableView.insertSubview(noResultsViewController.view, belowSubview: tableHeaderView)
noResultsViewController.view.frame = tableView.frame
setupNoResultsViewConstraints()
noResultsViewController.didMove(toParent: self)
}
func setupNoResultsViewConstraints() {
guard let nrv = noResultsViewController.view else {
return
}
tableHeaderView.translatesAutoresizingMaskIntoConstraints = false
nrv.translatesAutoresizingMaskIntoConstraints = false
nrv.setContentHuggingPriority(.defaultLow, for: .horizontal)
NSLayoutConstraint.activate([
nrv.widthAnchor.constraint(equalTo: view.widthAnchor),
nrv.centerXAnchor.constraint(equalTo: view.centerXAnchor),
nrv.topAnchor.constraint(equalTo: tableHeaderView.bottomAnchor),
nrv.bottomAnchor.constraint(equalTo: view.safeBottomAnchor)
])
}
func updateSplitViewAppearanceForNoResultsView() {
guard let splitViewController = splitViewController as? WPSplitViewController else {
return
}
// Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/14547
// Don't attempt to resize the columns for full width.
let columnWidth: WPSplitViewControllerPrimaryColumnWidth = .default
// The above line should be replace with the following line when the full width issue is resolved.
// let columnWidth: WPSplitViewControllerPrimaryColumnWidth = (shouldDisplayFullscreenNoResultsView || shouldDisplayJetpackPrompt) ? .full : .default
if splitViewController.wpPrimaryColumnWidth != columnWidth {
splitViewController.wpPrimaryColumnWidth = columnWidth
}
if columnWidth == .default {
splitViewController.dimDetailViewController(shouldDimDetailViewController, withAlpha: WPAlphaZero)
}
}
var noConnectionTitleText: String {
return NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.")
}
var noResultsTitleText: String {
return filter.noResultsTitle
}
var noResultsMessageText: String? {
guard AppConfiguration.showsReader else {
return nil
}
return filter.noResultsMessage
}
var noResultsButtonText: String? {
guard AppConfiguration.showsReader else {
return nil
}
return filter.noResultsButtonTitle
}
var shouldDisplayJetpackPrompt: Bool {
return AccountHelper.isDotcomAvailable() == false && blogForJetpackPrompt != nil
}
var shouldDisplaySettingsButton: Bool {
return AccountHelper.isDotcomAvailable()
}
var shouldDisplayNoResultsView: Bool {
return tableViewHandler.resultsController.fetchedObjects?.count == 0 && !shouldDisplayJetpackPrompt
}
var shouldDisplayFullscreenNoResultsView: Bool {
return shouldDisplayNoResultsView && filter == .none
}
var shouldDimDetailViewController: Bool {
return shouldDisplayNoResultsView && filter != .none
}
}
// MARK: - NoResultsViewControllerDelegate
extension NotificationsViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
let properties = [Stats.sourceKey: Stats.sourceValue]
switch filter {
case .none,
.comment,
.follow,
.like:
WPAnalytics.track(.notificationsTappedViewReader, withProperties: properties)
WPTabBarController.sharedInstance().showReaderTab()
case .unread:
WPAnalytics.track(.notificationsTappedNewPost, withProperties: properties)
WPTabBarController.sharedInstance().showPostTab()
}
}
}
// MARK: - Inline Prompt Helpers
//
internal extension NotificationsViewController {
func showInlinePrompt() {
guard inlinePromptView.alpha != WPAlphaFull,
userDefaults.notificationPrimerAlertWasDisplayed,
userDefaults.notificationsTabAccessCount >= Constants.inlineTabAccessCount else {
return
}
UIView.animate(withDuration: WPAnimationDurationDefault, delay: 0, options: .curveEaseIn, animations: {
self.inlinePromptView.isHidden = false
})
UIView.animate(withDuration: WPAnimationDurationDefault * 0.5, delay: WPAnimationDurationDefault * 0.75, options: .curveEaseIn, animations: {
self.inlinePromptView.alpha = WPAlphaFull
})
WPAnalytics.track(.appReviewsSawPrompt)
}
func hideInlinePrompt(delay: TimeInterval) {
UIView.animate(withDuration: WPAnimationDurationDefault * 0.75, delay: delay, animations: {
self.inlinePromptView.alpha = WPAlphaZero
})
UIView.animate(withDuration: WPAnimationDurationDefault, delay: delay + WPAnimationDurationDefault * 0.5, animations: {
self.inlinePromptView.isHidden = true
})
}
}
// MARK: - Sync'ing Helpers
//
private extension NotificationsViewController {
func syncNewNotifications() {
guard connectionAvailable() else {
return
}
let mediator = NotificationSyncMediator()
mediator?.sync()
}
func syncNotification(with noteId: String, timeout: TimeInterval, success: @escaping (_ note: Notification) -> Void) {
let mediator = NotificationSyncMediator()
let startDate = Date()
DDLogInfo("Sync'ing Notification [\(noteId)]")
mediator?.syncNote(with: noteId) { error, note in
guard abs(startDate.timeIntervalSinceNow) <= timeout else {
DDLogError("Error: Timeout while trying to load Notification [\(noteId)]")
return
}
guard let note = note else {
DDLogError("Error: Couldn't load Notification [\(noteId)]")
return
}
DDLogInfo("Notification Sync'ed in \(startDate.timeIntervalSinceNow) seconds")
success(note)
}
}
func updateLastSeenTime() {
guard let note = tableViewHandler.resultsController.fetchedObjects?.first as? Notification else {
return
}
guard let timestamp = note.timestamp, timestamp != lastSeenTime else {
return
}
let mediator = NotificationSyncMediator()
mediator?.updateLastSeen(timestamp) { error in
guard error == nil else {
return
}
self.lastSeenTime = timestamp
}
}
func loadNotification(with noteId: String) -> Notification? {
let predicate = NSPredicate(format: "(notificationId == %@)", noteId)
return mainContext.firstObject(ofType: Notification.self, matching: predicate)
}
func loadNotification(near note: Notification, withIndexDelta delta: Int) -> Notification? {
guard let notifications = tableViewHandler?.resultsController.fetchedObjects as? [Notification] else {
return nil
}
guard let noteIndex = notifications.firstIndex(of: note) else {
return nil
}
let targetIndex = noteIndex + delta
guard targetIndex >= 0 && targetIndex < notifications.count else {
return nil
}
func notMatcher(_ note: Notification) -> Bool {
return note.kind != .matcher
}
if delta > 0 {
return notifications
.suffix(from: targetIndex)
.first(where: notMatcher)
} else {
return notifications
.prefix(through: targetIndex)
.reversed()
.first(where: notMatcher)
}
}
func resetNotifications() {
do {
selectedNotification = nil
mainContext.deleteAllObjects(ofType: Notification.self)
try mainContext.save()
} catch {
DDLogError("Error while trying to nuke Notifications Collection: [\(error)]")
}
}
func resetLastSeenTime() {
lastSeenTime = nil
}
func resetApplicationBadge() {
// These notifications are cleared, so we just need to take Zendesk unread notifications
// into account when setting the app icon count.
UIApplication.shared.applicationIconBadgeNumber = ZendeskUtils.unreadNotificationsCount
}
}
// MARK: - WPSplitViewControllerDetailProvider
//
extension NotificationsViewController: WPSplitViewControllerDetailProvider {
func initialDetailViewControllerForSplitView(_ splitView: WPSplitViewController) -> UIViewController? {
// The first notification view will be populated by `selectFirstNotificationIfAppropriate`
// on viewWillAppear, so we'll just return an empty view here.
let controller = UIViewController()
controller.view.backgroundColor = .basicBackground
return controller
}
private func fetchFirstNotification() -> Notification? {
let context = managedObjectContext()
let fetchRequest = self.fetchRequest()
fetchRequest.fetchLimit = 1
if let results = try? context.fetch(fetchRequest) as? [Notification] {
return results.first
}
return nil
}
}
// MARK: - Details Navigation Datasource
//
extension NotificationsViewController: NotificationsNavigationDataSource {
@objc func notification(succeeding note: Notification) -> Notification? {
return loadNotification(near: note, withIndexDelta: -1)
}
@objc func notification(preceding note: Notification) -> Notification? {
return loadNotification(near: note, withIndexDelta: +1)
}
}
// MARK: - SearchableActivity Conformance
//
extension NotificationsViewController: SearchableActivityConvertable {
var activityType: String {
return WPActivityType.notifications.rawValue
}
var activityTitle: String {
return NSLocalizedString("Notifications", comment: "Title of the 'Notifications' tab - used for spotlight indexing on iOS.")
}
var activityKeywords: Set<String>? {
let keyWordString = NSLocalizedString("wordpress, notifications, alerts, updates",
comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Notifications' tab.")
let keywordArray = keyWordString.arrayOfTags()
guard !keywordArray.isEmpty else {
return nil
}
return Set(keywordArray)
}
}
// MARK: - Private Properties
//
private extension NotificationsViewController {
var mainContext: NSManagedObjectContext {
return ContextManager.sharedInstance().mainContext
}
var actionsService: NotificationActionsService {
return NotificationActionsService(managedObjectContext: mainContext)
}
var userDefaults: UserPersistentRepository {
return UserPersistentStoreFactory.instance()
}
var filter: Filter {
get {
let selectedIndex = filterTabBar?.selectedIndex ?? Filter.none.rawValue
return Filter(rawValue: selectedIndex) ?? .none
}
set {
filterTabBar?.setSelectedIndex(newValue.rawValue)
reloadResultsController()
}
}
enum Filter: Int, FilterTabBarItem, CaseIterable {
case none = 0
case unread = 1
case comment = 2
case follow = 3
case like = 4
var condition: String? {
switch self {
case .none: return nil
case .unread: return "read = NO"
case .comment: return "type = '\(NotificationKind.comment.rawValue)'"
case .follow: return "type = '\(NotificationKind.follow.rawValue)'"
case .like: return "type = '\(NotificationKind.like.rawValue)' OR type = '\(NotificationKind.commentLike.rawValue)'"
}
}
var title: String {
switch self {
case .none: return NSLocalizedString("All", comment: "Displays all of the Notifications, unfiltered")
case .unread: return NSLocalizedString("Unread", comment: "Filters Unread Notifications")
case .comment: return NSLocalizedString("Comments", comment: "Filters Comments Notifications")
case .follow: return NSLocalizedString("Follows", comment: "Filters Follows Notifications")
case .like: return NSLocalizedString("Likes", comment: "Filters Likes Notifications")
}
}
var analyticsTitle: String {
switch self {
case .none: return "All"
case .unread: return "Unread"
case .comment: return "Comments"
case .follow: return "Follows"
case .like: return "Likes"
}
}
var confirmationMessageTitle: String {
switch self {
case .none: return ""
case .unread: return NSLocalizedString("unread", comment: "Displayed in the confirmation alert when marking unread notifications as read.")
case .comment: return NSLocalizedString("comment", comment: "Displayed in the confirmation alert when marking comment notifications as read.")
case .follow: return NSLocalizedString("follow", comment: "Displayed in the confirmation alert when marking follow notifications as read.")
case .like: return NSLocalizedString("like", comment: "Displayed in the confirmation alert when marking like notifications as read.")
}
}
var noResultsTitle: String {
switch self {
case .none: return NSLocalizedString("No notifications yet",
comment: "Displayed in the Notifications Tab as a title, when there are no notifications")
case .unread: return NSLocalizedString("You're all up to date!",
comment: "Displayed in the Notifications Tab as a title, when the Unread Filter shows no unread notifications as a title")
case .comment: return NSLocalizedString("No comments yet",
comment: "Displayed in the Notifications Tab as a title, when the Comments Filter shows no notifications")
case .follow: return NSLocalizedString("No followers yet",
comment: "Displayed in the Notifications Tab as a title, when the Follow Filter shows no notifications")
case .like: return NSLocalizedString("No likes yet",
comment: "Displayed in the Notifications Tab as a title, when the Likes Filter shows no notifications")
}
}
var noResultsMessage: String {
switch self {
case .none: return NSLocalizedString("Get active! Comment on posts from blogs you follow.",
comment: "Displayed in the Notifications Tab as a message, when there are no notifications")
case .unread: return NSLocalizedString("Reignite the conversation: write a new post.",
comment: "Displayed in the Notifications Tab as a message, when the Unread Filter shows no notifications")
case .comment: return NSLocalizedString("Join a conversation: comment on posts from blogs you follow.",
comment: "Displayed in the Notifications Tab as a message, when the Comments Filter shows no notifications")
case .follow,
.like: return NSLocalizedString("Get noticed: comment on posts you've read.",
comment: "Displayed in the Notifications Tab as a message, when the Follow Filter shows no notifications")
}
}
var noResultsButtonTitle: String {
switch self {
case .none,
.comment,
.follow,
.like: return NSLocalizedString("Go to Reader",
comment: "Displayed in the Notifications Tab as a button title, when there are no notifications")
case .unread: return NSLocalizedString("Create a Post",
comment: "Displayed in the Notifications Tab as a button title, when the Unread Filter shows no notifications")
}
}
static let sortKey = "timestamp"
}
enum Settings {
static let estimatedRowHeight = CGFloat(70)
static let lastSeenTime = "notifications_last_seen_time"
}
enum Stats {
static let networkStatusKey = "network_status"
static let noteTypeKey = "notification_type"
static let noteTypeUnknown = "unknown"
static let sourceKey = "source"
static let sourceValue = "notifications"
static let selectedFilter = "selected_filter"
}
enum Syncing {
static let minimumPullToRefreshDelay = TimeInterval(1.5)
static let pushMaxWait = TimeInterval(1.5)
static let syncTimeout = TimeInterval(10)
static let undoTimeout = TimeInterval(4)
}
enum InlinePrompt {
static let section = "notifications"
}
}
// MARK: - Push Notifications Permission Alert
extension NotificationsViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
guard let fancyAlertController = presented as? FancyAlertViewController else {
return nil
}
return FancyAlertPresentationController(presentedViewController: fancyAlertController, presenting: presenting)
}
private func showNotificationPrimerAlertIfNeeded() {
guard shouldShowPrimeForPush, !userDefaults.notificationPrimerAlertWasDisplayed else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + Constants.displayAlertDelay) {
self.showNotificationPrimerAlert()
}
}
private func notificationAlertApproveAction(_ controller: FancyAlertViewController) {
InteractiveNotificationsManager.shared.requestAuthorization { _ in
DispatchQueue.main.async {
controller.dismiss(animated: true)
}
}
}
private func showNotificationPrimerAlert() {
let alertController = FancyAlertViewController.makeNotificationPrimerAlertController(approveAction: notificationAlertApproveAction(_:))
showNotificationAlert(alertController)
}
private func showSecondNotificationAlert() {
let alertController = FancyAlertViewController.makeNotificationSecondAlertController(approveAction: notificationAlertApproveAction(_:))
showNotificationAlert(alertController)
}
private func showNotificationAlert(_ alertController: FancyAlertViewController) {
let mainContext = ContextManager.shared.mainContext
guard (try? WPAccount.lookupDefaultWordPressComAccount(in: mainContext)) != nil else {
return
}
PushNotificationsManager.shared.loadAuthorizationStatus { [weak self] (enabled) in
guard enabled == .notDetermined else {
return
}
UserPersistentStoreFactory.instance().notificationPrimerAlertWasDisplayed = true
let alert = alertController
alert.modalPresentationStyle = .custom
alert.transitioningDelegate = self
self?.tabBarController?.present(alert, animated: true)
}
}
private func showSecondNotificationsAlertIfNeeded() {
guard userDefaults.secondNotificationsAlertCount >= Constants.secondNotificationsAlertThreshold else {
return
}
showSecondNotificationAlert()
userDefaults.secondNotificationsAlertCount = Constants.secondNotificationsAlertDisabled
}
private enum Constants {
static let inlineTabAccessCount = 6
static let displayAlertDelay = 0.2
// number of notifications after which the second alert will show up
static let secondNotificationsAlertThreshold = 10
static let secondNotificationsAlertDisabled = -1
}
}
// MARK: - Scrolling
//
extension NotificationsViewController: WPScrollableViewController {
// Used to scroll view to top when tapping on tab bar item when VC is already visible.
func scrollViewToTop() {
tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
}
}
// MARK: - Jetpack banner delegate
//
extension NotificationsViewController: JPScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
processJetpackBannerVisibility(scrollView)
}
}
// MARK: - StoryboardLoadable
extension NotificationsViewController: StoryboardLoadable {
static var defaultStoryboardName: String {
return "Notifications"
}
}
| 6d69c74f02e225fb9d0b997ad4903114 | 36.891595 | 199 | 0.667251 | false | false | false | false |
ChenJian345/realm-cocoa | refs/heads/master | Realm/Tests/Swift2.0/SwiftArrayTests.swift | apache-2.0 | 7 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
import Foundation
class SwiftArrayTests: SwiftTestCase {
// Swift models
func testFastEnumeration() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let dateMinInput = NSDate()
let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000)
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
realm.commitWriteTransaction()
let result = SwiftAggregateObject.objectsInRealm(realm, "intCol < %d", 100)
XCTAssertEqual(result.count, UInt(10), "10 objects added")
var totalSum = 0
for obj in result {
if let ao = obj as? SwiftAggregateObject {
totalSum += ao.intCol
}
}
XCTAssertEqual(totalSum, 100, "total sum should be 100")
}
func testObjectAggregate() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let dateMinInput = NSDate()
let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000)
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
SwiftAggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
realm.commitWriteTransaction()
let noArray = SwiftAggregateObject.objectsInRealm(realm, "boolCol == NO")
let yesArray = SwiftAggregateObject.objectsInRealm(realm, "boolCol == YES")
// SUM ::::::::::::::::::::::::::::::::::::::::::::::
// Test int sum
XCTAssertEqual(noArray.sumOfProperty("intCol").integerValue, 4, "Sum should be 4")
XCTAssertEqual(yesArray.sumOfProperty("intCol").integerValue, 0, "Sum should be 0")
// Test float sum
XCTAssertEqualWithAccuracy(noArray.sumOfProperty("floatCol").floatValue, Float(0), accuracy: 0.1, "Sum should be 0.0")
XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("floatCol").floatValue, Float(7.2), accuracy: 0.1, "Sum should be 7.2")
// Test double sum
XCTAssertEqualWithAccuracy(noArray.sumOfProperty("doubleCol").doubleValue, Double(10), accuracy: 0.1, "Sum should be 10.0")
XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("doubleCol").doubleValue, Double(0), accuracy: 0.1, "Sum should be 0.0")
// Average ::::::::::::::::::::::::::::::::::::::::::::::
// Test int average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("intCol")!.doubleValue, Double(1), accuracy: 0.1, "Average should be 1.0")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("intCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
// Test float average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("floatCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("floatCol")!.doubleValue, Double(1.2), accuracy: 0.1, "Average should be 1.2")
// Test double average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("doubleCol")!.doubleValue, Double(2.5), accuracy: 0.1, "Average should be 2.5")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("doubleCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
// MIN ::::::::::::::::::::::::::::::::::::::::::::::
// Test int min
var min = noArray.minOfProperty("intCol") as! NSNumber
XCTAssertEqual(min.intValue, Int32(1), "Minimum should be 1")
min = yesArray.minOfProperty("intCol") as! NSNumber
XCTAssertEqual(min.intValue, Int32(0), "Minimum should be 0")
// Test float min
min = noArray.minOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.floatValue, Float(0), accuracy: 0.1, "Minimum should be 0.0f")
min = yesArray.minOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.floatValue, Float(1.2), accuracy: 0.1, "Minimum should be 1.2f")
// Test double min
min = noArray.minOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.doubleValue, Double(2.5), accuracy: 0.1, "Minimum should be 1.5")
min = yesArray.minOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.doubleValue, Double(0), accuracy: 0.1, "Minimum should be 0.0")
// Test date min
var dateMinOutput = noArray.minOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, accuracy: 1, "Minimum should be dateMaxInput")
dateMinOutput = yesArray.minOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, accuracy: 1, "Minimum should be dateMinInput")
// MAX ::::::::::::::::::::::::::::::::::::::::::::::
// Test int max
var max = noArray.maxOfProperty("intCol") as! NSNumber
XCTAssertEqual(max.integerValue, 1, "Maximum should be 8")
max = yesArray.maxOfProperty("intCol") as! NSNumber
XCTAssertEqual(max.integerValue, 0, "Maximum should be 10")
// Test float max
max = noArray.maxOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.floatValue, Float(0), accuracy: 0.1, "Maximum should be 0.0f")
max = yesArray.maxOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.floatValue, Float(1.2), accuracy: 0.1, "Maximum should be 1.2f")
// Test double max
max = noArray.maxOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.doubleValue, Double(2.5), accuracy: 0.1, "Maximum should be 3.5")
max = yesArray.maxOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.doubleValue, Double(0), accuracy: 0.1, "Maximum should be 0.0")
// Test date max
var dateMaxOutput = noArray.maxOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, accuracy: 1, "Maximum should be dateMaxInput")
dateMaxOutput = yesArray.maxOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, accuracy: 1, "Maximum should be dateMinInput")
}
func testArrayDescription() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
for _ in 0..<1012 {
let person = SwiftEmployeeObject()
person.name = "Mary"
person.age = 24
person.hired = true
realm.addObject(person)
}
realm.commitWriteTransaction()
let description = SwiftEmployeeObject.allObjectsInRealm(realm).description
XCTAssertTrue((description as NSString).rangeOfString("name").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("Mary").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("age").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("24").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("12 objects skipped").location != Foundation.NSNotFound, "'12 objects skipped' should be displayed when calling \"description\" on RLMArray")
}
func testDeleteLinksAndObjectsInArray() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let po1 = SwiftEmployeeObject()
po1.age = 40
po1.name = "Joe"
po1.hired = true
let po2 = SwiftEmployeeObject()
po2.age = 30
po2.name = "John"
po2.hired = false
let po3 = SwiftEmployeeObject()
po3.age = 25
po3.name = "Jill"
po3.hired = true
realm.addObject(po1)
realm.addObject(po2)
realm.addObject(po3)
let company = SwiftCompanyObject()
realm.addObject(company)
company.employees.addObjects(SwiftEmployeeObject.allObjectsInRealm(realm))
realm.commitWriteTransaction()
let peopleInCompany = company.employees
XCTAssertEqual(peopleInCompany.count, UInt(3), "No links should have been deleted")
realm.beginWriteTransaction()
peopleInCompany.removeObjectAtIndex(1) // Should delete link to employee
realm.commitWriteTransaction()
XCTAssertEqual(peopleInCompany.count, UInt(2), "link deleted when accessing via links")
var test = peopleInCompany[0] as! SwiftEmployeeObject
XCTAssertEqual(test.age, po1.age, "Should be equal")
XCTAssertEqual(test.name, po1.name, "Should be equal")
XCTAssertEqual(test.hired, po1.hired, "Should be equal")
// XCTAssertEqual(test, po1, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568
test = peopleInCompany[1] as! SwiftEmployeeObject
XCTAssertEqual(test.age, po3.age, "Should be equal")
XCTAssertEqual(test.name, po3.name, "Should be equal")
XCTAssertEqual(test.hired, po3.hired, "Should be equal")
// XCTAssertEqual(test, po3, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568
realm.beginWriteTransaction()
peopleInCompany.removeLastObject()
XCTAssertEqual(peopleInCompany.count, UInt(1), "1 remaining link")
peopleInCompany.replaceObjectAtIndex(0, withObject: po2)
XCTAssertEqual(peopleInCompany.count, UInt(1), "1 link replaced")
peopleInCompany.insertObject(po1, atIndex: 0)
XCTAssertEqual(peopleInCompany.count, UInt(2), "2 links")
peopleInCompany.removeAllObjects()
XCTAssertEqual(peopleInCompany.count, UInt(0), "0 remaining links")
realm.commitWriteTransaction()
}
// Objective-C models
func testFastEnumeration_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let dateMinInput = NSDate()
let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000)
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])
realm.commitWriteTransaction()
let result = AggregateObject.objectsInRealm(realm, "intCol < %d", 100)
XCTAssertEqual(result.count, UInt(10), "10 objects added")
var totalSum: CInt = 0
for obj in result {
if let ao = obj as? AggregateObject {
totalSum += ao.intCol
}
}
XCTAssertEqual(totalSum, CInt(100), "total sum should be 100")
}
func testObjectAggregate_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let dateMinInput = NSDate()
let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000)
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [1, 0 as Float, 2.5 as Double, false, dateMaxInput])
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
AggregateObject.createInRealm(realm, withValue: [0, 1.2 as Float, 0 as Double, true, dateMinInput])
realm.commitWriteTransaction()
let noArray = AggregateObject.objectsInRealm(realm, "boolCol == NO")
let yesArray = AggregateObject.objectsInRealm(realm, "boolCol == YES")
// SUM ::::::::::::::::::::::::::::::::::::::::::::::
// Test int sum
XCTAssertEqual(noArray.sumOfProperty("intCol").integerValue, 4, "Sum should be 4")
XCTAssertEqual(yesArray.sumOfProperty("intCol").integerValue, 0, "Sum should be 0")
// Test float sum
XCTAssertEqualWithAccuracy(noArray.sumOfProperty("floatCol").floatValue, Float(0), accuracy: 0.1, "Sum should be 0.0")
XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("floatCol").floatValue, Float(7.2), accuracy: 0.1, "Sum should be 7.2")
// Test double sum
XCTAssertEqualWithAccuracy(noArray.sumOfProperty("doubleCol").doubleValue, Double(10), accuracy: 0.1, "Sum should be 10.0")
XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("doubleCol").doubleValue, Double(0), accuracy: 0.1, "Sum should be 0.0")
// Average ::::::::::::::::::::::::::::::::::::::::::::::
// Test int average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("intCol")!.doubleValue, Double(1), accuracy: 0.1, "Average should be 1.0")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("intCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
// Test float average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("floatCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("floatCol")!.doubleValue, Double(1.2), accuracy: 0.1, "Average should be 1.2")
// Test double average
XCTAssertEqualWithAccuracy(noArray.averageOfProperty("doubleCol")!.doubleValue, Double(2.5), accuracy: 0.1, "Average should be 2.5")
XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("doubleCol")!.doubleValue, Double(0), accuracy: 0.1, "Average should be 0.0")
// MIN ::::::::::::::::::::::::::::::::::::::::::::::
// Test int min
var min = noArray.minOfProperty("intCol") as! NSNumber
XCTAssertEqual(min.intValue, Int32(1), "Minimum should be 1")
min = yesArray.minOfProperty("intCol") as! NSNumber
XCTAssertEqual(min.intValue, Int32(0), "Minimum should be 0")
// Test float min
min = noArray.minOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.floatValue, Float(0), accuracy: 0.1, "Minimum should be 0.0f")
min = yesArray.minOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.floatValue, Float(1.2), accuracy: 0.1, "Minimum should be 1.2f")
// Test double min
min = noArray.minOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.doubleValue, Double(2.5), accuracy: 0.1, "Minimum should be 1.5")
min = yesArray.minOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(min.doubleValue, Double(0), accuracy: 0.1, "Minimum should be 0.0")
// Test date min
var dateMinOutput = noArray.minOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, accuracy: 1, "Minimum should be dateMaxInput")
dateMinOutput = yesArray.minOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, accuracy: 1, "Minimum should be dateMinInput")
// MAX ::::::::::::::::::::::::::::::::::::::::::::::
// Test int max
var max = noArray.maxOfProperty("intCol") as! NSNumber
XCTAssertEqual(max.integerValue, 1, "Maximum should be 8")
max = yesArray.maxOfProperty("intCol") as! NSNumber
XCTAssertEqual(max.integerValue, 0, "Maximum should be 10")
// Test float max
max = noArray.maxOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.floatValue, Float(0), accuracy: 0.1, "Maximum should be 0.0f")
max = yesArray.maxOfProperty("floatCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.floatValue, Float(1.2), accuracy: 0.1, "Maximum should be 1.2f")
// Test double max
max = noArray.maxOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.doubleValue, Double(2.5), accuracy: 0.1, "Maximum should be 3.5")
max = yesArray.maxOfProperty("doubleCol") as! NSNumber
XCTAssertEqualWithAccuracy(max.doubleValue, Double(0), accuracy: 0.1, "Maximum should be 0.0")
// Test date max
var dateMaxOutput = noArray.maxOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, accuracy: 1, "Maximum should be dateMaxInput")
dateMaxOutput = yesArray.maxOfProperty("dateCol") as! NSDate
XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, accuracy: 1, "Maximum should be dateMinInput")
}
func testArrayDescription_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
for _ in 0..<1012 {
let person = EmployeeObject()
person.name = "Mary"
person.age = 24
person.hired = true
realm.addObject(person)
}
realm.commitWriteTransaction()
let description = EmployeeObject.allObjectsInRealm(realm).description
XCTAssertTrue((description as NSString).rangeOfString("name").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("Mary").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("age").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("24").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray")
XCTAssertTrue((description as NSString).rangeOfString("912 objects skipped").location != Foundation.NSNotFound, "'912 objects skipped' should be displayed when calling \"description\" on RLMArray")
}
func makeEmployee(realm: RLMRealm, _ age: Int32, _ name: String, _ hired: Bool) -> EmployeeObject {
let employee = EmployeeObject()
employee.age = age
employee.name = name
employee.hired = hired
realm.addObject(employee)
return employee
}
func testDeleteLinksAndObjectsInArray_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let po1 = makeEmployee(realm, 40, "Joe", true)
_ = makeEmployee(realm, 30, "John", false)
let po3 = makeEmployee(realm, 25, "Jill", true)
let company = CompanyObject()
company.name = "name"
realm.addObject(company)
company.employees.addObjects(EmployeeObject.allObjectsInRealm(realm))
realm.commitWriteTransaction()
let peopleInCompany = company.employees
XCTAssertEqual(peopleInCompany.count, UInt(3), "No links should have been deleted")
realm.beginWriteTransaction()
peopleInCompany.removeObjectAtIndex(1) // Should delete link to employee
realm.commitWriteTransaction()
XCTAssertEqual(peopleInCompany.count, UInt(2), "link deleted when accessing via links")
var test = peopleInCompany[0] as! EmployeeObject
XCTAssertEqual(test.age, po1.age, "Should be equal")
XCTAssertEqual(test.name!, po1.name!, "Should be equal")
XCTAssertEqual(test.hired, po1.hired, "Should be equal")
// XCTAssertEqual(test, po1, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568
test = peopleInCompany[1] as! EmployeeObject
XCTAssertEqual(test.age, po3.age, "Should be equal")
XCTAssertEqual(test.name!, po3.name!, "Should be equal")
XCTAssertEqual(test.hired, po3.hired, "Should be equal")
// XCTAssertEqual(test, po3, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568
let allPeople = EmployeeObject.allObjectsInRealm(realm)
XCTAssertEqual(allPeople.count, UInt(3), "Only links should have been deleted, not the employees")
}
func testIndexOfObject_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let po1 = makeEmployee(realm, 40, "Joe", true)
let po2 = makeEmployee(realm, 30, "John", false)
let po3 = makeEmployee(realm, 25, "Jill", true)
realm.commitWriteTransaction()
let results = EmployeeObject.objectsInRealm(realm, "hired = YES")
XCTAssertEqual(UInt(2), results.count)
XCTAssertEqual(UInt(0), results.indexOfObject(po1));
XCTAssertEqual(UInt(1), results.indexOfObject(po3));
XCTAssertEqual(NSNotFound, Int(results.indexOfObject(po2)));
}
func testIndexOfObjectWhere_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
makeEmployee(realm, 40, "Joe", true)
makeEmployee(realm, 30, "John", false)
makeEmployee(realm, 25, "Jill", true)
realm.commitWriteTransaction()
let results = EmployeeObject.objectsInRealm(realm, "hired = YES")
XCTAssertEqual(UInt(2), results.count)
XCTAssertEqual(UInt(0), results.indexOfObjectWhere("age = %d", 40))
XCTAssertEqual(UInt(1), results.indexOfObjectWhere("age = %d", 25))
XCTAssertEqual(NSNotFound, Int(results.indexOfObjectWhere("age = %d", 30)))
}
func testSortingExistingQuery_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
makeEmployee(realm, 20, "A", true)
makeEmployee(realm, 30, "B", false)
makeEmployee(realm, 40, "C", true)
realm.commitWriteTransaction()
let sortedByAge = EmployeeObject.allObjectsInRealm(realm).sortedResultsUsingProperty("age", ascending: true)
let sortedByName = sortedByAge.sortedResultsUsingProperty("name", ascending: false)
XCTAssertEqual(Int32(20), (sortedByAge[0] as! EmployeeObject).age)
XCTAssertEqual(Int32(40), (sortedByName[0] as! EmployeeObject).age)
}
}
| 0fdc80eba6f5d468b378480d82813d5f | 51.3125 | 205 | 0.677755 | false | true | false | false |
cnkaptan/SwiftLessons | refs/heads/master | Properties.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
class Legs {
var count: Int = 0
}
//default olarak strong
class Animal {
var name: String = ""
var legs: Legs = Legs()
// Bu yapiya computed proporty denir disardan bir property gibi gorunur ve davranir ama icerde hicbirseyi depolamaz
var upperCaseName: String {
return name.uppercaseString
}
var lowerCaseName: String{
get{
return name.lowercaseString
}
set{
name = newValue
}
}
}
class LegVet{
weak var legs: Legs? = nil
}
var dog: Animal? = Animal()
let vel = LegVet()
//dog objesi nil olursa vel.legs te nil olur , Veldeki Legs weak referans oldugu icin , eger strong type olsaydi Legleri nil olmayacakti cunku o objeye sahip olcakti
vel.legs = dog?.legs
dog = nil
vel.legs
| 6247d345eb32950eab6a345b842fa8c2 | 19.186047 | 165 | 0.640553 | false | false | false | false |
malaonline/iOS | refs/heads/master | mala-ios/Model/StudyReport/SingleAbilityData.swift | mit | 1 | //
// SingleAbilityData.swift
// mala-ios
//
// Created by 王新宇 on 16/5/31.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class SingleAbilityData: NSObject {
// MARK: - Property
/// 能力名称(简略)
var key: String = ""
/// 数值
var val: Int = 0 {
didSet {
if val == 0 {
val = 1
}
}
}
/// 能力
var ability: MalaStudyReportAbility {
get {
return MalaStudyReportAbility(rawValue: key) ?? .unkown
}
}
/// 能力字符串
var abilityString: String {
get {
switch ability {
case .abstract:
return "抽象概括"
case .reason:
return "推理论证"
case .appl:
return "实际应用"
case .spatial:
return "空间想象"
case .calc:
return "运算求解"
case .data:
return "数据分析"
case .unkown:
return ""
}
}
}
// MARK: - Constructed
override init() {
super.init()
}
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
convenience init(key: String, value: Int) {
self.init()
self.key = key
self.val = value
}
}
| 2201e4d17b1f1dc5d9a81fc3ec02a8c7 | 18.573333 | 67 | 0.405995 | false | false | false | false |
18775134221/SwiftBase | refs/heads/master | Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Sources/Mapper.swift | apache-2.0 | 16 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum MappingType {
case fromJSON
case toJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: BaseMappable> {
public var context: MapContext?
public init(context: MapContext? = nil){
self.context = context
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSONObject: Any?, toObject object: N) -> N {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSON: [String: Any], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context)
mutableObject.mapping(map: map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSONObject: Any?) -> N? {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSON: [String: Any]) -> N? {
let map = Map(mappingType: .fromJSON, JSON: JSON, context: context)
if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable
if var object = klass.objectForMapping(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? Mappable.Type { // Check if object is Mappable
if var object = klass.init(map: map) as? N {
object.mapping(map: map)
return object
}
} else {
// Ensure BaseMappable is not implemented directly
assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable")
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return [object]
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSONObject: Any?) -> [N]? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapArray(JSONArray: JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String: Any]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String: N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return mapDictionary(JSONObject: parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?) -> [String: N]? {
if let JSON = JSONObject as? [String: [String: Any]] {
return mapDictionary(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? {
// map every value in dictionary to type N
let result = JSON.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] {
if let JSON = JSONObject as? [String : [String : Any]] {
return mapDictionary(JSON: JSON, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in JSON {
if let object = dictionary[key] {
_ = map(JSON: value, toObject: object)
} else {
mutableDictionary[key] = map(JSON: value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? {
if let JSON = JSONObject as? [String: [[String: Any]]] {
return mapDictionaryOfArrays(JSON: JSON)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = JSON.filterMap {
mapArray(JSONArray: $0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? {
if let JSONArray = JSONObject as? [[[String: Any]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(JSONArray: innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization
public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return parsedJSON as? [String: Any]
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSONString: String) -> Any? {
let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let data = data {
let parsedJSON: Any?
do {
parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String, Any>
public func toJSON(_ object: N) -> [String: Any] {
var mutableObject = object
let map = Map(mappingType: .toJSON, JSON: [:], context: context)
mutableObject.mapping(map: map)
return map.JSON
}
///Maps an array of Objects to an array of JSON dictionaries [[String: Any]]
public func toJSONArray(_ array: [N]) -> [[String: Any]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? {
let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: String.Encoding.utf8)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? {
if JSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: Data?
do {
JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSONObject: Any?) -> Set<N>? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapSet(JSONArray: JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String: Any]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]]
public func toJSONSet(_ set: Set<N>) -> [[String: Any]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] {
var mapped = [K: V]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] {
var mapped = [K: [V]]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] {
var mapped = [Key: U]()
for (key, value) in self {
if let newValue = try f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
| ebcab7ff3fb3bead8f99635db63380fb | 31.074592 | 131 | 0.694259 | false | false | false | false |
AndyWoJ/DouYuLive | refs/heads/master | DouYuLive/DouYuLive/Classes/Tools/Common.swift | mit | 1 | //
// Common.swift
// DouYuLive
//
// Created by wujian on 2017/1/5.
// Copyright © 2017年 wujian. All rights reserved.
//
import UIKit
let kStatusBarH = 20.0
let kNavigationBarH = 44.0
let kTabBarH = 44.0
let kScreenH:Double = Double(UIScreen.main.bounds.height)
let kScreenW:Double = Double(UIScreen.main.bounds.width)
| 1571d621cf3b806a42fa470468b7ab52 | 19.4375 | 57 | 0.721713 | false | false | false | false |
hooman/swift | refs/heads/main | test/attr/attr_concurrent.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -typecheck -verify %s -enable-experimental-flow-sensitive-concurrent-captures
// REQUIRES: concurrency
// Concurrent attribute on a function type.
func f(_ fn: @Sendable (Int) -> Int) { }
// Okay to overload @Sendable vs. not concurrent
func f(_ fn: (Int) -> Int) { }
// Concurrent attribute with other function attributes.
func onEscaping(_ fn: @escaping @Sendable (Int) -> Int) { }
func onEscaping2(_ fn: @Sendable @escaping (Int) -> Int) { }
func onAutoclosure(_ fn: @autoclosure @Sendable () -> Int) { }
func onAutoclosure2(_ fn: @Sendable @autoclosure () -> Int) { }
func onEscapingAutoclosure(_ fn: @Sendable @autoclosure @escaping () -> Int) { }
func onEscapingAutoclosure2(_ fn: @escaping @autoclosure @Sendable () -> Int) { }
func acceptsConcurrent(_ fn: @Sendable (Int) -> Int) { }
func acceptsNonConcurrent(_ fn: (Int) -> Int) { }
@Sendable func negate(_ x: Int) -> Int { -x }
func passingConcurrentOrNot(
_ cfn: @Sendable (Int) -> Int,
ncfn: (Int) -> Int // expected-note{{parameter 'ncfn' is implicitly non-concurrent}}{{9-9=@Sendable }}
) {
// Okay due to overloading
f(cfn)
f(ncfn)
acceptsConcurrent(cfn) // okay
acceptsConcurrent(ncfn) // expected-error{{passing non-concurrent parameter 'ncfn' to function expecting a @Sendable closure}}
acceptsNonConcurrent(cfn) // okay
acceptsNonConcurrent(ncfn) // okay
acceptsConcurrent(negate)
acceptsNonConcurrent(negate)
let _: Int = negate // expected-error{{cannot convert value of type '@Sendable (Int) -> Int' to specified type 'Int'}}
}
func closures() {
// Okay, inferring @Sendable
acceptsConcurrent { $0 }
acceptsConcurrent({ $0 })
acceptsConcurrent({ i in i })
acceptsConcurrent({ (i: Int) -> Int in
print(i)
return i
})
let closure1 = { $0 + 1 } // inferred to be non-concurrent
acceptsConcurrent(closure1) // expected-error{{converting non-concurrent function value to '@Sendable (Int) -> Int' may introduce data races}}
}
// Mutation of captured locals from within @Sendable functions.
extension Int {
mutating func makeNegative() {
self = -self
}
func printMe() {
print(self)
}
}
func mutationOfLocal() {
var localInt = 17
acceptsConcurrent { i in
// Non-mutating accesses are okay
print(localInt + 17)
localInt.printMe()
// Mutations of locally-defined variables are fine.
var localResult = localInt + 1
print(localResult)
_ = {
localResult = localResult + 1
}()
// Mutations of captured variables executing concurrently are bad.
localInt = 17 // expected-error{{mutation of captured var 'localInt' in concurrently-executing code}}
localInt += 1 // expected-error{{mutation of captured var 'localInt' in concurrently-executing code}}
localInt.makeNegative() // expected-error{{mutation of captured var 'localInt' in concurrently-executing code}}
_ = {
localInt = localInt + 12 // expected-error{{mutation of captured var 'localInt' in concurrently-executing code}}
}()
return i + localInt
}
localInt = 20
}
struct NonTrivialValueType {
var int: Int = 0
var array: [Int] = []
var optArray: [Int]? = nil
}
func testCaseNonTrivialValue() {
var i = NonTrivialValueType()
var j = 0
acceptsConcurrent { value in
print(i.int)
print(i.array[0])
print(i.array[j])
print(i.optArray?[j] ?? 0)
print(i.optArray![j])
i.int = 5 // expected-error{{mutation of captured var 'i' in concurrently-executing code}}
i.array[0] = 5 // expected-error{{mutation of captured var 'i' in concurrently-executing code}}
return value
}
j = 17
}
func testExplicitConcurrentClosure() {
let fn = { @Sendable in
17
}
let _: String = fn // expected-error{{cannot convert value of type '@Sendable () -> Int' to specified type 'String'}}
}
| b2d5c0a74e7fee8948067da6c31427b3 | 29.23622 | 144 | 0.672917 | false | false | false | false |
cuappdev/podcast-ios | refs/heads/master | old/Podcast/UILabel+.swift | mit | 1 | //
// Label+.swift
// Podcast
//
// Created by Natasha Armbrust on 9/11/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
extension UILabel {
//@param: label with text,font,and width
// Changes height of label to fit text with current font and width
//@return: None
static func adjustHeightToFit(label: UILabel, numberOfLines: Int? = nil) {
let newLabel = UILabel(frame: .zero)
let size = CGSize(width: label.frame.width, height: CGFloat.greatestFiniteMagnitude)
newLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
newLabel.font = label.font
newLabel.text = label.text
newLabel.numberOfLines = numberOfLines ?? label.numberOfLines
let newSize = newLabel.sizeThatFits(size)
label.frame.size = newSize
label.numberOfLines = numberOfLines ?? label.numberOfLines
}
// taken from https://stackoverflow.com/questions/32309247/add-read-more-to-the-end-of-uilabel
static func addTrailing(to label: UILabel, with trailingText: String, moreText: String, moreTextFont: UIFont, moreTextColor: UIColor, numberOfLinesAllowed: Int) -> NSAttributedString {
guard let text = label.text else { return NSAttributedString() }
if label.numberOfVisibleLines < numberOfLinesAllowed {
return NSAttributedString(string: text, attributes: [NSAttributedStringKey.font: label.font])
}
let readMoreText = trailingText + moreText
let lengthForVisibleString = label.vissibleTextLength
let mutableString = text
let trimmedString = (mutableString as NSString).replacingCharacters(in: NSRange(location: lengthForVisibleString, length: (text.count - lengthForVisibleString)), with: "")
let readMoreLength = readMoreText.count
let trimmedForReadMore: String = (trimmedString as NSString).replacingCharacters(in: NSRange(location: ((trimmedString.count) - readMoreLength), length: readMoreLength), with: "") + trailingText
let answerAttributed = NSMutableAttributedString(string: trimmedForReadMore, attributes: [NSAttributedStringKey.font: label.font])
let readMoreAttributed = NSMutableAttributedString(string: moreText, attributes: [NSAttributedStringKey.font: moreTextFont, NSAttributedStringKey.foregroundColor: moreTextColor])
answerAttributed.append(readMoreAttributed)
return answerAttributed
}
var numberOfVisibleLines: Int {
let textSize = CGSize(width: CGFloat(self.frame.size.width), height: CGFloat(MAXFLOAT))
let rHeight: Int = lroundf(Float(self.sizeThatFits(textSize).height))
let charSize: Int = lroundf(Float(self.font.pointSize))
return rHeight / charSize
}
// taken from https://stackoverflow.com/questions/32309247/add-read-more-to-the-end-of-uilabel
var vissibleTextLength: Int {
guard let _ = self.text else { return 0 }
let font: UIFont = self.font
let mode: NSLineBreakMode = self.lineBreakMode
let labelWidth: CGFloat = self.frame.size.width
let labelHeight: CGFloat = self.frame.size.height
let sizeConstraint = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)
let attributes: [AnyHashable: Any] = [NSAttributedStringKey.font: font]
let attributedText = NSAttributedString(string: self.text!, attributes: attributes as? [NSAttributedStringKey : Any])
let boundingRect: CGRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil)
if boundingRect.size.height > labelHeight {
var index: Int = 0
var prev: Int = 0
let characterSet = CharacterSet.whitespacesAndNewlines
repeat {
prev = index
if mode == NSLineBreakMode.byCharWrapping {
index += 1
} else {
index = (self.text! as NSString).rangeOfCharacter(from: characterSet, options: [], range: NSRange(location: index + 1, length: self.text!.count - index - 1)).location
}
} while index != NSNotFound && index < self.text!.count && (self.text! as NSString).substring(to: index).boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, attributes: attributes as? [NSAttributedStringKey : Any], context: nil).size.height <= labelHeight
return prev
}
return self.text!.count
}
}
| 24caa4a92f35d8d2d8d5c708a86d0908 | 54.37037 | 284 | 0.690747 | false | false | false | false |
007HelloWorld/DouYuZhiBo | refs/heads/master | DYZB/DYZB/Main/View/CollectionBaseCell.swift | mit | 1 | //
// CollectionBaseCell.swift
// DYZB
//
// Created by MacMini on 2017/8/8.
// Copyright © 2017年 MacMini. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
// MARK: - 控件属性
@IBOutlet var iconImageView: UIImageView!
@IBOutlet var onlineBtn: UIButton!
@IBOutlet var nickNameLabel: UILabel!
// MARK: - 定义模型属性
var anchor : AnchorModel?{
didSet{
//0.校验模型属性
guard let anchor = anchor else { return }
//1.取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
}else {
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
//2.显示昵称
nickNameLabel.text = anchor.nickname
//3.设置封面图片,下载图片
iconImageView.kf.setImage(with: URL.init(string: anchor.vertical_src))
}
}
}
| 455e81cc2476f95ff6a1ad71b5f63a20 | 19.982143 | 82 | 0.480851 | false | false | false | false |
ZamzamInc/SwiftPrayTimes | refs/heads/master | SwiftPrayTimes iOSExample/MonthlyController.swift | mit | 1 | //
// ViewController.swift
// SwiftPrayTimes
//
// Created by Basem Emara on 06/12/2015.
// Copyright (c) 06/12/2015 Basem Emara. All rights reserved.
//
import UIKit
class MonthlyController: UITableViewController {
var prayerSeries: [PrayTimes.PrayerResultSeries] = []
let method = "ISNA"
let juristic = "Standard"
let coords = [43.7, -79.4] // Toronto
let timeZone = -5.0 // Toronto
//let coords = [33.9733, -118.2487] // Los Angeles
//let timeZone = -8.0 // Los Angeles
let dst = true
let startDate = Date(fromString: "2016/05/15 14:00")!
let endDate = Date(fromString: "2016/06/15 14:00")!
override func viewDidLoad() {
super.viewDidLoad()
let customMethod = PrayTimes.PrayerMethod("Custom", [
PrayTimes.AdjustmentParam(time: .fajr, type: .degree, value: 15.0),
PrayTimes.AdjustmentParam(time: .isha, type: .degree, value: 15.0)
])
// Create instance
var prayTimes = PrayTimes(
method: customMethod,
juristic: PrayTimes.AdjustmentMethod(rawValue: juristic)
)
// Get prayer times for date range and reload table
prayTimes.getTimeSeries(for: coords,
endDate: endDate,
startDate: startDate,
timeZone: timeZone,
dst: dst,
onlyEssentials: true) { series in
self.prayerSeries = series
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return prayerSeries.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
let data = prayerSeries[indexPath.row]
let formatter = DateFormatter()
var output = ""
for item in data.prayers {
let time = item.formattedTime.components(separatedBy: " ")[0]
// Display current and next indicators
let status = item.isCurrent ? "c" : item.isNext ? "n" : ""
// Place date of prayer next to time
formatter.dateFormat = "dd"
output += "\(time)-\(formatter.string(from: item.date))\(status), "
}
formatter.dateFormat = "MMMM dd, yyyy h:mm a"
cell.textLabel?.text = formatter.string(from: data.date)
cell.detailTextLabel?.text = output
return cell
}
}
| 1b226368f6d28199734d8a4e053a586d | 31.641975 | 109 | 0.580938 | false | false | false | false |
dduan/swift | refs/heads/master | test/DebugInfo/generic_arg2.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// CHECK: define hidden void @_TFC12generic_arg25Class3foo{{.*}}, %swift.type* %U
// CHECK: [[Y:%.*]] = getelementptr inbounds %C12generic_arg25Class, %C12generic_arg25Class* %2, i32 0, i32 0, i32 0
// store %swift.opaque* %[[Y]], %swift.opaque** %[[Y_SHADOW:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %y.addr, metadata ![[U:.*]], metadata !{{[0-9]+}})
// Make sure there is no conflicting dbg.value for this variable.x
// CHECK-NOT: dbg.value{{.*}}metadata ![[U]]
class Class <T> {
// CHECK: ![[U]] = !DILocalVariable(name: "y", arg: 2{{.*}} line: [[@LINE+1]],
func foo<U>(x: T, y: U) {}
func bar(x: String, y: Int64) {}
init() {}
}
func main() {
var object: Class<String> = Class()
var x = "hello"
var y : Int64 = 1234
object.bar(x, y: y)
object.foo(x, y: y)
}
main()
| 3d7e65ada765b038cfd4a546e001aeae | 33.192308 | 116 | 0.600675 | false | false | false | false |
novastorm/Udacity-On-The-Map | refs/heads/master | On the Map/UdacityParseClient.swift | mit | 1 | //
// UdacityParseClient.swift
// On the Map
//
// Created by Adland Lee on 3/24/16.
// Copyright © 2016 Adland Lee. All rights reserved.
//
import Foundation
// MARK: UdacityParseClient
class UdacityParseClient {
// MARK: Shared Instance
static let sharedInstance = UdacityParseClient()
fileprivate init() {} // Disable default initializer
// MARK: Properties
var session = URLSession.shared
// MARK: GET
func taskForGETMethod(_ resource: String, parameters inputParameters: [String:AnyObject], completionHandlerForGet: @escaping (_ results: Any?, _ error: NSError?) -> Void) ->URLSessionDataTask {
// (1) Set Parameters
var parameters = inputParameters
// (2) Build URL, (3) Configure Request
var request = URLRequest(url: URLFromParameters(parameters, withPathExtension: resource))
request.addValue(Constants.ApplicationId, forHTTPHeaderField: RequestKeys.ApplicationIdHeader)
request.addValue(Constants.APIKey, forHTTPHeaderField: RequestKeys.RESTAPIKey)
// (4) Make request
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
// Custom error function
func sendError(_ code: Int, errorString:String) {
var userInfo = [String: Any]()
userInfo[NSLocalizedDescriptionKey] = errorString
userInfo[NSUnderlyingErrorKey] = error
userInfo["http_response"] = response
completionHandlerForGet(nil, NSError(domain: "taskForGetMethod", code: code, userInfo: userInfo))
}
// GUARD: Was there an error?
if let error = error as? NSError {
sendError(error.code, errorString: error.localizedDescription)
return
}
// GUARD: Was a successul 2XX response received?
guard let statusCode = (response as? HTTPURLResponse)?.statusCode , 200...299 ~= statusCode else {
sendError(ErrorCodes.httpUnsucessful.rawValue, errorString: ErrorCodes.httpUnsucessful.description)
return
}
// GUARD: Was any data returned?
guard let data = data else {
sendError(ErrorCodes.noData.rawValue, errorString: ErrorCodes.noData.description)
return
}
// (5) Parse and (6) use data with completion handler
self.convertDataWithCompletionHandler(data, completionHandlerForConvertData: completionHandlerForGet)
})
// (7) Start request
task.resume()
return task
}
// MARK: POST
func taskForPOSTMethod(_ resource: String, parameters inputParameters: [String:AnyObject], JSONBody inputJSONBody: [String:AnyObject], completionHandlerForPost: @escaping (_ results: Any?, _ error: NSError?) -> Void) -> URLSessionDataTask {
// (1) Set Parameters
var parameters = inputParameters
// (2) Build URL, (3) Configure Request
var request = URLRequest(url: URLFromParameters(parameters, withPathExtension: resource))
request.httpMethod = "POST"
request.addValue(Constants.ApplicationId, forHTTPHeaderField: RequestKeys.ApplicationIdHeader)
request.addValue(Constants.APIKey, forHTTPHeaderField: RequestKeys.RESTAPIKey)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = convertObjectToJSONData(inputJSONBody as AnyObject)
// (4) Make request
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
// Custom error function
func sendError(_ code: Int, errorString:String) {
var userInfo = [String: Any]()
userInfo[NSLocalizedDescriptionKey] = errorString
userInfo[NSUnderlyingErrorKey] = error
userInfo["http_response"] = response
completionHandlerForPost(nil, NSError(domain: "taskForPostMethod", code: code, userInfo: userInfo))
}
// GUARD: Was there an error?
if let error = error as? NSError {
sendError(error.code, errorString: error.localizedDescription)
return
}
// GUARD: Was a successul 2XX response received?
guard let statusCode = (response as? HTTPURLResponse)?.statusCode , 200...299 ~= statusCode else {
sendError(ErrorCodes.httpUnsucessful.rawValue, errorString: ErrorCodes.httpUnsucessful.description)
return
}
// GUARD: Was any data returned?
guard let data = data else {
sendError(ErrorCodes.noData.rawValue, errorString: ErrorCodes.noData.description)
return
}
// (5) Parse and (6) use data with completion handler
self.convertDataWithCompletionHandler(data, completionHandlerForConvertData: completionHandlerForPost)
})
// (7) Start request
task.resume()
return task
}
// MARK: PUT
func taskForPUTMethod(_ resource: String, parameters inputParameters: [String:AnyObject], JSONBody inputJSONBody: [String:AnyObject], completionHandlerForPost: @escaping (_ results: Any?, _ error: NSError?) -> Void) -> URLSessionDataTask {
// (1) Set Parameters
var parameters = inputParameters
// (2) Build URL, (3) Configure Request
var request = URLRequest(url: URLFromParameters(parameters, withPathExtension: resource))
request.httpMethod = "PUT"
request.addValue(Constants.ApplicationId, forHTTPHeaderField: RequestKeys.ApplicationIdHeader)
request.addValue(Constants.APIKey, forHTTPHeaderField: RequestKeys.RESTAPIKey)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = convertObjectToJSONData(inputJSONBody as AnyObject)
// (4) Make request
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
// Custom error function
func sendError(_ code: Int, errorString:String) {
var userInfo = [String: Any]()
userInfo[NSLocalizedDescriptionKey] = errorString
userInfo[NSUnderlyingErrorKey] = error
userInfo["http_response"] = response
completionHandlerForPost(nil, NSError(domain: "taskForPostMethod", code: code, userInfo: userInfo))
}
// GUARD: Was there an error?
if let error = error as? NSError{
sendError(error.code, errorString: error.localizedDescription)
return
}
// GUARD: Was a successul 2XX response received?
guard let statusCode = (response as? HTTPURLResponse)?.statusCode , 200...299 ~= statusCode else {
sendError(ErrorCodes.httpUnsucessful.rawValue, errorString: ErrorCodes.httpUnsucessful.description)
return
}
// GUARD: Was any data returned?
guard let data = data else {
sendError(ErrorCodes.noData.rawValue, errorString: ErrorCodes.noData.description)
return
}
// (5) Parse and (6) use data with completion handler
self.convertDataWithCompletionHandler(data, completionHandlerForConvertData: completionHandlerForPost)
})
// (7) Start request
task.resume()
return task
}
// MARK: Helpers
// substitute the key for the value that is contained within the method name
func subtituteKeyInMethod(_ method: String, key: String, value: String) -> String? {
if method.range(of: "{\(key)}") != nil {
return method.replacingOccurrences(of: "{\(key)}", with: value)
} else {
return nil
}
}
// given a Dictionary, return a JSON String
fileprivate func convertObjectToJSONData(_ object: AnyObject) -> Data{
var parsedResult: AnyObject!
do {
parsedResult = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions(rawValue: 0)) as AnyObject!
}
catch {
return Data()
}
return parsedResult as! Data
}
// given raw JSON, return a usable Foundation object
fileprivate func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: Any?, _ error: NSError?) -> Void) {
var parsedResult: Any!
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the parse client data as JSON: '\(data)'"]
completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
}
completionHandlerForConvertData(parsedResult, nil)
}
// create a URL from parameters
fileprivate func URLFromParameters(_ parameters: [String:AnyObject], withPathExtension: String? = nil) -> URL {
var components = URLComponents()
components.scheme = Constants.APIScheme
components.host = Constants.APIHost
components.path = Constants.APIPath + (withPathExtension ?? "")
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
return components.url!
}
static func logout () {
StudentInformation.list.removeAll()
}
}
| 253fa548ae3a5eb78176ac16a0b5e4c0 | 40.845528 | 244 | 0.60443 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/StaticString.swift | apache-2.0 | 10 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implementation Note: Because StaticString is used in the
// implementation of _precondition(), _fatalErrorMessage(), etc., we
// keep it extremely close to the bare metal. In particular, because
// we store only Builtin types, we are guaranteed that no assertions
// are involved in its construction. This feature is crucial for
// preventing infinite recursion even in non-asserting cases.
//
//===----------------------------------------------------------------------===//
/// A string type designed to represent text that is known at compile time.
///
/// Instances of the `StaticString` type are immutable.
///
/// `StaticString` provides only low-level access to its contents, unlike
/// Swift's more commonly used `String` type. A static string can use
/// either of the following as its storage:
///
/// * a pointer to a null-terminated sequence of UTF-8 code units:
///
/// let emoji: StaticString = "\u{1F600}"
/// emoji.hasPointerRepresentation //-> true
/// emoji.isASCII //-> false
/// emoji.unicodeScalar //-> Fatal error!
/// emoji.utf8CodeUnitCount //-> 4
/// emoji.utf8Start[0] //-> 0xF0
/// emoji.utf8Start[1] //-> 0x9F
/// emoji.utf8Start[2] //-> 0x98
/// emoji.utf8Start[3] //-> 0x80
/// emoji.utf8Start[4] //-> 0x00
///
/// * a single Unicode scalar value, under very limited circumstances:
///
/// struct MyStaticScalar: ExpressibleByUnicodeScalarLiteral {
/// typealias UnicodeScalarLiteralType = StaticString
/// let value: StaticString
/// init(unicodeScalarLiteral value: StaticString) {
/// self.value = value
/// }
/// }
///
/// let emoji: StaticString = MyStaticScalar("\u{1F600}").value
/// emoji.hasPointerRepresentation //-> false
/// emoji.isASCII //-> false
/// emoji.unicodeScalar.value //-> 0x1F600
/// emoji.utf8CodeUnitCount //-> Fatal error!
/// emoji.utf8Start //-> Fatal error!
///
/// You can use the `withUTF8Buffer(_:)` method to access a static string's
/// contents, regardless of which representation the static string uses.
///
/// emoji.withUTF8Buffer { utf8 in
/// utf8.count //-> 4
/// utf8[0] //-> 0xF0
/// utf8[1] //-> 0x9F
/// utf8[2] //-> 0x98
/// utf8[3] //-> 0x80
/// utf8[4] //-> Fatal error!
/// }
@frozen
public struct StaticString: Sendable {
/// Either a pointer to the start of UTF-8 data, represented as an integer,
/// or an integer representation of a single Unicode scalar.
@usableFromInline
internal var _startPtrOrData: Builtin.Word
/// If `_startPtrOrData` is a pointer, contains the length of the UTF-8 data
/// in bytes (excluding the null terminator).
@usableFromInline
internal var _utf8CodeUnitCount: Builtin.Word
/// Extra flags:
///
/// - bit 0: set to 0 if `_startPtrOrData` is a pointer, or to 1 if it is a
/// Unicode scalar.
///
/// - bit 1: set to 1 if `_startPtrOrData` either points to an ASCII code unit
/// sequence, or stores an ASCII scalar value.
@usableFromInline
internal var _flags: Builtin.Int8
/// Creates an empty static string.
@_transparent
public init() {
self = ""
}
@usableFromInline @_transparent
internal init(
_start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
// We don't go through UnsafePointer here to make things simpler for alias
// analysis. A higher-level algorithm may be trying to make sure an
// unrelated buffer is not accessed or freed.
self._startPtrOrData = Builtin.ptrtoint_Word(_start)
self._utf8CodeUnitCount = utf8CodeUnitCount
self._flags = Bool(isASCII)
? (0x2 as UInt8)._value
: (0x0 as UInt8)._value
}
@usableFromInline @_transparent
internal init(
unicodeScalar: Builtin.Int32
) {
self._startPtrOrData = UInt(UInt32(unicodeScalar))._builtinWordValue
self._utf8CodeUnitCount = 0._builtinWordValue
self._flags = Unicode.Scalar(_builtinUnicodeScalarLiteral: unicodeScalar).isASCII
? (0x3 as UInt8)._value
: (0x1 as UInt8)._value
}
/// A pointer to a null-terminated sequence of UTF-8 code units.
///
/// - Important: Accessing this property when `hasPointerRepresentation` is
/// `false` triggers a runtime error.
@_transparent
public var utf8Start: UnsafePointer<UInt8> {
_precondition(
hasPointerRepresentation,
"StaticString should have pointer representation")
return UnsafePointer(bitPattern: UInt(_startPtrOrData))!
}
/// A single Unicode scalar value.
///
/// - Important: Accessing this property when `hasPointerRepresentation` is
/// `true` triggers a runtime error.
@_transparent
public var unicodeScalar: Unicode.Scalar {
_precondition(
!hasPointerRepresentation,
"StaticString should have Unicode scalar representation")
return Unicode.Scalar(UInt32(UInt(_startPtrOrData)))!
}
/// The number of UTF-8 code units (excluding the null terminator).
///
/// - Important: Accessing this property when `hasPointerRepresentation` is
/// `false` triggers a runtime error.
@_transparent
public var utf8CodeUnitCount: Int {
_precondition(
hasPointerRepresentation,
"StaticString should have pointer representation")
return Int(_utf8CodeUnitCount)
}
@_alwaysEmitIntoClient @_transparent
internal var unsafeRawPointer: Builtin.RawPointer {
return Builtin.inttoptr_Word(_startPtrOrData)
}
/// A Boolean value that indicates whether the static string stores a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// If `hasPointerRepresentation` is `false`, the static string stores a
/// single Unicode scalar value.
@_transparent
public var hasPointerRepresentation: Bool {
return (UInt8(_flags) & 0x1) == 0
}
/// A Boolean value that indicates whether the static string represents only
/// ASCII code units (or an ASCII scalar value).
@_transparent
public var isASCII: Bool {
return (UInt8(_flags) & 0x2) != 0
}
/// Invokes the given closure with a buffer containing the static string's
/// UTF-8 code unit sequence (excluding the null terminator).
///
/// This method works regardless of whether the static string stores a
/// pointer or a single Unicode scalar value.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUTF8Buffer(_:)`. Do not store or return the pointer for later use.
///
/// - Parameter body: A closure that takes a buffer pointer to the static
/// string's UTF-8 code unit sequence as its sole argument. If the closure
/// has a return value, that value is also used as the return value of the
/// `withUTF8Buffer(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure.
@_transparent
public func withUTF8Buffer<R>(
_ body: (UnsafeBufferPointer<UInt8>) -> R
) -> R {
if hasPointerRepresentation {
return body(UnsafeBufferPointer(
start: utf8Start, count: utf8CodeUnitCount))
} else {
return unicodeScalar.withUTF8CodeUnits { body($0) }
}
}
}
extension StaticString: _ExpressibleByBuiltinUnicodeScalarLiteral {
@_effects(readonly)
@_transparent
public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = StaticString(unicodeScalar: value)
}
}
extension StaticString: ExpressibleByUnicodeScalarLiteral {
/// Creates an instance initialized to a single Unicode scalar.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string with a Unicode scalar.
@_effects(readonly)
@_transparent
public init(unicodeScalarLiteral value: StaticString) {
self = value
}
}
extension StaticString: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
@_effects(readonly)
@_transparent
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
self = StaticString(
_builtinStringLiteral: start,
utf8CodeUnitCount: utf8CodeUnitCount,
isASCII: isASCII
)
}
}
extension StaticString: ExpressibleByExtendedGraphemeClusterLiteral {
/// Creates an instance initialized to a single character that is made up of
/// one or more Unicode scalar values.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string using an extended grapheme cluster.
@_effects(readonly)
@_transparent
public init(extendedGraphemeClusterLiteral value: StaticString) {
self = value
}
}
extension StaticString: _ExpressibleByBuiltinStringLiteral {
@_effects(readonly)
@_transparent
public init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
self = StaticString(
_start: start,
utf8CodeUnitCount: utf8CodeUnitCount,
isASCII: isASCII)
}
}
extension StaticString: ExpressibleByStringLiteral {
/// Creates an instance initialized to the value of a string literal.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string using a string literal.
@_effects(readonly)
@_transparent
public init(stringLiteral value: StaticString) {
self = value
}
}
extension StaticString: CustomStringConvertible {
/// A textual representation of the static string.
public var description: String {
return withUTF8Buffer { String._uncheckedFromUTF8($0) }
}
}
extension StaticString: CustomDebugStringConvertible {
/// A textual representation of the static string, suitable for debugging.
public var debugDescription: String {
return self.description.debugDescription
}
}
#if SWIFT_ENABLE_REFLECTION
extension StaticString: CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: description)
}
}
#endif
| c63438799c62e9c133f3b0fde81ff9a8 | 33.091195 | 85 | 0.665437 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/SteviaLayout/Source/Stevia+LayoutAnchors.swift | mit | 2 | //
// Stevia+LayoutAnchors.swift
// Stevia
//
// Created by Sacha DSO on 09/10/2017.
// Copyright © 2017 Sacha Durand Saint Omer. All rights reserved.
//
#if canImport(UIKit)
import UIKit
@available(iOS 9.0, *)
public struct SteviaLayoutYAxisAnchor {
let anchor: NSLayoutYAxisAnchor
let constant: CGFloat
init(anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) {
self.anchor = anchor
self.constant = constant
}
}
@available(iOS 9.0, *)
public struct SteviaLayoutXAxisAnchor {
let anchor: NSLayoutXAxisAnchor
let constant: CGFloat
init(anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) {
self.anchor = anchor
self.constant = constant
}
}
@available(iOS 9.0, *)
public extension UILayoutGuide {
var Top: SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: topAnchor)
}
var Bottom: SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: bottomAnchor)
}
var Left: SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: leftAnchor)
}
var Right: SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: rightAnchor)
}
var Leading: SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: leadingAnchor)
}
var Trailing: SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: trailingAnchor)
}
var CenterX: SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: centerXAnchor)
}
var CenterY: SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: centerYAnchor)
}
}
@available(iOS 9.0, *)
@discardableResult
public func == (left: SteviaAttribute, right: SteviaLayoutYAxisAnchor) -> NSLayoutConstraint {
var constraint = NSLayoutConstraint()
if left.attribute == .top {
constraint = left.view.topAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .bottom {
constraint = left.view.bottomAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .centerY {
constraint = left.view.centerYAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
constraint.isActive = true
return constraint
}
@available(iOS 9.0, *)
@discardableResult
public func == (left: SteviaAttribute, right: SteviaLayoutXAxisAnchor) -> NSLayoutConstraint {
var constraint = NSLayoutConstraint()
if left.attribute == .left {
constraint = left.view.leftAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .right {
constraint = left.view.rightAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .leading {
constraint = left.view.leadingAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .trailing {
constraint = left.view.trailingAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
if left.attribute == .centerX {
constraint = left.view.centerXAnchor.constraint(equalTo: right.anchor, constant: right.constant)
}
constraint.isActive = true
return constraint
}
// SteviaLayoutYAxisAnchor
@available(iOS 9.0, *)
@discardableResult
public func + (left: SteviaLayoutYAxisAnchor, right: CGFloat) -> SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: left.anchor, constant: right)
}
@available(iOS 9.0, *)
@discardableResult
public func - (left: SteviaLayoutYAxisAnchor, right: CGFloat) -> SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: left.anchor, constant: -right)
}
@available(iOS 9.0, *)
@discardableResult
public func + (left: SteviaLayoutXAxisAnchor, right: CGFloat) -> SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: left.anchor, constant: right)
}
@available(iOS 9.0, *)
@discardableResult
public func - (left: SteviaLayoutXAxisAnchor, right: CGFloat) -> SteviaLayoutXAxisAnchor {
return SteviaLayoutXAxisAnchor(anchor: left.anchor, constant: -right)
}
// UILayoutSupport
@available(iOS 9.0, *)
public extension UILayoutSupport {
var Top: SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: topAnchor)
}
var Bottom: SteviaLayoutYAxisAnchor {
return SteviaLayoutYAxisAnchor(anchor: bottomAnchor)
}
}
#endif
| c7c0a4c77baa4ccb9c690e5ce6d3491c | 27.21118 | 105 | 0.702114 | false | false | false | false |
bellots/usefulExtensions | refs/heads/master | UsefulExtensions/UIColorExtensions.swift | mit | 1 | //
// UIColorExtensions.swift
// JoeBee
//
// Created by Andrea Bellotto on 14/11/16.
// Copyright © 2016 JoeBee Srl. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
// simplify initialization for UIColors
public convenience init(r: Int, g:Int , b:Int) {
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1.0)
}
public convenience init(netHex:Int) {
self.init(r:(netHex >> 16) & 0xff, g:(netHex >> 8) & 0xff, b:netHex & 0xff)
}
public convenience init(hexString:String) {
let scanner = Scanner(string: hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
private func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
| 018be02ff64ff3981606f20528fc77d7 | 26.241379 | 109 | 0.546203 | false | false | false | false |
loudnate/LoopKit | refs/heads/master | LoopKitUI/Views/SettingsTableViewCell.swift | mit | 1 | //
// SettingsTableViewCell.swift
// Loop
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
public class SettingsTableViewCell: UITableViewCell {
public static let EnabledString = LocalizedString("Enabled", comment: "The detail text describing an enabled setting")
public static let NoValueString = LocalizedString("—", comment: "The detail text representing no value")
public static let TapToSetString = LocalizedString("Tap to set", comment: "The empty-state text for a configuration value")
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
textLabel?.adjustsFontForContentSizeCategory = true
textLabel?.font = UIFont.preferredFont(forTextStyle: .body)
detailTextLabel?.adjustsFontForContentSizeCategory = true
detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body)
}
override public func prepareForReuse() {
super.prepareForReuse()
accessoryType = .none
textLabel?.text = nil
detailTextLabel?.text = nil
}
}
| 89318dd301c5125238caa70d74cc1f58 | 31.097561 | 127 | 0.699088 | false | false | false | false |
laszlokorte/reform-swift | refs/heads/master | ReformApplication/ReformApplication/ProcedureViewModel.swift | mit | 1 | //
// ProcedureViewModel.swift
// ReformApplication
//
// Created by Laszlo Korte on 26.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformCore
import ReformExpression
import ReformTools
final class ProcedureViewModel {
let analyzer : DefaultAnalyzer
let instructionFocus : InstructionFocus
let snapshotCollector : SnapshotCollector
let instructionFocusChanger : InstructionFocusChanger
let instructionChanger : () -> ()
let formSelection : FormSelection
let formIdSequence : IdentifierSequence<FormIdentifier>
let nameAllocator : NameAllocator
let lexer : Lexer<ShuntingYardTokenType>
let parser : ShuntingYardParser<ExpressionParserDelegate>
init(analyzer: DefaultAnalyzer, instructionFocus : InstructionFocus, snapshotCollector : SnapshotCollector, instructionFocusChanger : InstructionFocusChanger, formSelection: FormSelection, formIdSequence: IdentifierSequence<FormIdentifier>, nameAllocator: NameAllocator,
lexer : Lexer<ShuntingYardTokenType>,
parser: ShuntingYardParser<ExpressionParserDelegate>,
instructionChanger : @escaping () -> ()) {
self.analyzer = analyzer
self.instructionFocus = instructionFocus
self.snapshotCollector = snapshotCollector
self.instructionFocusChanger = instructionFocusChanger
self.instructionChanger = instructionChanger
self.formSelection = formSelection
self.nameAllocator = nameAllocator
self.formIdSequence = formIdSequence
self.lexer = lexer
self.parser = parser
}
}
| 14d5a642c65fdccb6ee177777cf45f04 | 38.9 | 274 | 0.75188 | false | false | false | false |
gautesolheim/SnapOnboarding-iOS | refs/heads/master | SnapOnboarding-iOS/Unit_tests/SnapOnboardingDelegateTests.swift | bsd-3-clause | 2 | import XCTest
@testable import SnapOnboarding_iOS
class SnapOnboardingDelegateTests: XCTestCase {
var vc: SnapOnboardingViewController!
fileprivate var isOnboardingWillAppearCalled = false
fileprivate var isTermsAndConditionsTapped = false
fileprivate var isPrivacyPolicyTapped = false
fileprivate var isEnableLocationServicesTapped = false
fileprivate var isLocationServicesInstructionsTapped = false
fileprivate var isFacebookSignupTapped = false
fileprivate var isInstagramSignupTapped = false
fileprivate var isSkipLoginTapped = false
fileprivate var isContinueAsLoggedInUserTapped = false
fileprivate var isLogoutFromCurrentAccountTapped = false
override func setUp() {
super.setUp()
let delegate = self as SnapOnboardingDelegate
let viewModel = mockSnapOnboardingViewModelNorwegian()
vc = getSnapOnboardingViewController()
vc.applyConfiguration(SnapOnboardingConfiguration(delegate: delegate, viewModel: viewModel))
_ = vc.view // Force loading of the view
}
override func tearDown() {
super.tearDown()
isOnboardingWillAppearCalled = false
isTermsAndConditionsTapped = false
isPrivacyPolicyTapped = false
isEnableLocationServicesTapped = false
isLocationServicesInstructionsTapped = false
isFacebookSignupTapped = false
isInstagramSignupTapped = false
isSkipLoginTapped = false
isContinueAsLoggedInUserTapped = false
isLogoutFromCurrentAccountTapped = false
vc.childViewControllers.forEach { child in
(child as? HasSparklingStars)?.sparklingStars?.forEach { $0.layer.removeAllAnimations() }
}
}
func testIsOnboardingWillAppearCalled() {
XCTAssertFalse(isOnboardingWillAppearCalled)
vc.viewWillAppear(false)
XCTAssertTrue(isOnboardingWillAppearCalled)
}
func testTermsAndConditionsTapped() {
vc.attributedLabel(vc.termsAndConditionsLabel, didSelectLinkWith: URL(string: "terms"))
XCTAssertTrue(isTermsAndConditionsTapped)
}
func testPrivacyPolicyTapped() {
vc.attributedLabel(vc.termsAndConditionsLabel, didSelectLinkWith: URL(string: "privacy"))
XCTAssertTrue(isPrivacyPolicyTapped)
}
func testEnableLocationServicesButtonTapped() {
let locationVC: LocationViewController = getChildVCOfType()!
locationVC.enableLocationServicesButtonTapped(locationVC.enableLocationServicesButton!)
XCTAssertTrue(isEnableLocationServicesTapped)
}
func testLocationServicesInstructionsTapped() {
let locationVC: LocationViewController = getChildVCOfType()!
locationVC.willAskLaterLabelWithLocationServicesInstructionsTapped()
XCTAssertTrue(isLocationServicesInstructionsTapped)
}
func testFacebookSignupTapped() {
let loginVC: LoginViewController = getChildVCOfType()!
loginVC.continueWithFacebookButtonTapped(loginVC.continueWithFacebookButton!)
XCTAssertTrue(isFacebookSignupTapped)
}
func testInstagramSignupTapped() {
let loginVC: LoginViewController = getChildVCOfType()!
loginVC.continueWithInstagramButtonTapped(loginVC.continueWithInstagramButton!)
XCTAssertTrue(isInstagramSignupTapped)
}
func testSkipLoginTapped() {
let loginVC: LoginViewController = getChildVCOfType()!
loginVC.skipLoginButtonTapped(loginVC.skipLoginButton!)
XCTAssertTrue(isSkipLoginTapped)
}
func testContinueAsLoggedInUserTapped() {
let loginVC: LoginViewController = getChildVCOfType()!
loginVC.continueAsLoggedInUserButtonTapped(loginVC.continueAsLoggedInUserButton!)
XCTAssertTrue(isContinueAsLoggedInUserTapped)
}
func testLogoutFromCurrentAccountTapped() {
let loginVC: LoginViewController = getChildVCOfType()!
loginVC.changeAccountButtonTapped(loginVC.changeAccountButton!)
XCTAssertTrue(isLogoutFromCurrentAccountTapped)
}
func testStarsBeginSparklingOnViewWillAppear() {
applyExpressionOnAllSparklingStars { XCTAssertEqual($0.layer.animationKeys()?.count, nil) }
vc.viewWillAppear(false)
applyExpressionOnAllSparklingStars { XCTAssertEqual($0.layer.animationKeys()?.count, 1) }
}
func testStarsStopSparklingOnViewDidDisappear() {
vc.viewWillAppear(false)
applyExpressionOnAllSparklingStars { XCTAssertEqual($0.layer.animationKeys()?.count, 1) }
vc.viewDidDisappear(false)
applyExpressionOnAllSparklingStars { XCTAssertEqual($0.layer.animationKeys()?.count, nil) }
}
// MARK: Helpers
func getChildVCOfType<T>() -> T? {
for child in vc.childViewControllers {
if let child = child as? T {
return child
}
}
return nil
}
func applyExpressionOnAllSparklingStars(_ expression: @escaping (UIImageView) -> Void) {
vc.childViewControllers.forEach { child in
(child as! HasSparklingStars).sparklingStars!.forEach { star in
expression(star)
}
}
}
}
// MARK: - SnapOnboardingDelegate
extension SnapOnboardingDelegateTests: SnapOnboardingDelegate {
func onboardingWillAppear() {
isOnboardingWillAppearCalled = true
}
func termsAndConditionsTapped() {
isTermsAndConditionsTapped = true
}
func privacyPolicyTapped() {
isPrivacyPolicyTapped = true
}
func enableLocationServicesTapped() {
isEnableLocationServicesTapped = true
}
func locationServicesInstructionsTapped() {
isLocationServicesInstructionsTapped = true
}
func facebookSignupTapped() {
isFacebookSignupTapped = true
}
func instagramSignupTapped() {
isInstagramSignupTapped = true
}
func skipLoginTapped() {
isSkipLoginTapped = true
}
func continueAsLoggedInUserTapped() {
isContinueAsLoggedInUserTapped = true
}
func logoutFromCurrentAccountTapped() {
isLogoutFromCurrentAccountTapped = true
}
}
| aea636af098f9f901a376f7ea76869ae | 31.533333 | 101 | 0.696091 | false | true | false | false |
Ben21hao/edx-app-ios-new | refs/heads/master | Source/EnrolledCoursesViewController.swift | apache-2.0 | 1 | //
// EnrolledCoursesViewController.swift
// edX
//
// Created by Akiva Leffert on 12/21/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
var isActionTakenOnUpgradeSnackBar: Bool = false
class EnrolledCoursesViewController : OfflineSupportViewController, CoursesTableViewControllerDelegate, PullRefreshControllerDelegate, LoadStateViewReloadSupport {
typealias Environment = protocol<OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, NetworkManagerProvider, ReachabilityProvider, OEXRouterProvider>
private let environment : Environment
private let tableController : CoursesTableViewController
private let loadController = LoadStateViewController()
private let refreshController = PullRefreshController()
private let insetsController = ContentInsetsController()
private let enrollmentFeed: Feed<[UserCourseEnrollment]?>
private let userPreferencesFeed: Feed<UserPreference?>
init(environment: Environment) {
self.tableController = CoursesTableViewController(environment: environment, context: .EnrollmentList)
self.enrollmentFeed = environment.dataManager.enrollmentManager.feed
self.userPreferencesFeed = environment.dataManager.userPreferenceManager.feed
self.environment = environment
super.init(env: environment)
self.titleViewLabel.text = Strings.myCourses
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.accessibilityIdentifier = "enrolled-courses-screen"
setviewConfig()
self.enrollmentFeed.refresh()
self.userPreferencesFeed.refresh()
let currentUser = OEXRouter.sharedRouter().environment.session.currentUser
if (currentUser != nil) {//登陆状态
refreshController.setupInScrollView(self.tableController.tableView)
refreshController.delegate = self
setupListener()
} else {
self.tableController.tableView.reloadData()
self.loadController.state = .Loaded
}
setupFooter()
setupObservers()
if !environment.reachability.isReachable() {
self.loadController.state = .Loaded
}
}
override func viewWillAppear(animated: Bool) {
environment.analytics.trackScreenWithName(OEXAnalyticsScreenMyCourses)
showVersionUpgradeSnackBarIfNecessary()
super.viewWillAppear(animated)
hideSnackBarForFullScreenError()
}
override func reloadViewData() {
refreshIfNecessary()
}
private func setupListener() {//数据
enrollmentFeed.output.listen(self) {[weak self] result in
if !(self?.enrollmentFeed.output.active ?? false) {
self?.refreshController.endRefreshing()
}
switch result {
case let .Success(enrollments):
if let enrollments = enrollments {
self?.tableController.courses = enrollments.flatMap { $0.course } ?? [] //flatMap去掉nil项的数组 -- 数据
self?.tableController.tableView.reloadData()
self?.loadController.state = .Loaded
} else {
self?.loadController.state = .Initial
}
case let .Failure(error):
self?.loadController.state = LoadState.failed(error)
if error.errorIsThisType(NSError.oex_outdatedVersionError()) {
self?.hideSnackBar()
}
}
}
}
private func setviewConfig() {
self.view.backgroundColor = OEXStyles.sharedStyles().baseColor5()
tableController.delegate = self
addChildViewController(tableController)
tableController.didMoveToParentViewController(self)
self.loadController.setupInController(self, contentView: tableController.view)
self.view.addSubview(tableController.view)
tableController.view.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
insetsController.setupInController(self, scrollView: tableController.tableView)
insetsController.addSource(self.refreshController)
// We visually separate each course card so we also need a little padding
// at the bottom to match
insetsController.addSource(
ConstantInsetsSource(insets: UIEdgeInsets(top: 0, left: 0, bottom: StandardVerticalMargin, right: 0), affectsScrollIndicators: false)
)
}
private func setupFooter() { //底部视图
if environment.config.courseEnrollmentConfig.isCourseDiscoveryEnabled() {
let footer = EnrolledCoursesFooterView()
footer.findCoursesAction = {[weak self] in
self?.environment.router?.showCourseCatalog(nil)
}
footer.sizeToFit()
self.tableController.tableView.tableFooterView = footer
} else {
tableController.tableView.tableFooterView = UIView()
}
}
private func enrollmentsEmptyState() {
if !environment.config.courseEnrollmentConfig.isCourseDiscoveryEnabled() {
let error = NSError.oex_errorWithCode(.Unknown, message: Strings.EnrollmentList.noEnrollment)
loadController.state = LoadState.failed(error, icon: Icon.UnknownError)
}
}
private func setupObservers() {
let config = environment.config
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: OEXExternalRegistrationWithExistingAccountNotification) { (notification, observer, _) -> Void in
let platform = config.platformName()
let service = notification.object as? String ?? ""
let message = Strings.externalRegistrationBecameLogin(platformName: platform, service: service)
observer.showOverlayMessage(message)
}
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: AppNewVersionAvailableNotification) { (notification, observer, _) -> Void in
observer.showVersionUpgradeSnackBarIfNecessary()
}
}
func refreshIfNecessary() {
if environment.reachability.isReachable() && !enrollmentFeed.output.active {
enrollmentFeed.refresh()
if loadController.state.isError {
loadController.state = .Initial
}
}
}
private func showVersionUpgradeSnackBarIfNecessary() {
if let _ = VersionUpgradeInfoController.sharedController.latestVersion {
var infoString = Strings.VersionUpgrade.newVersionAvailable
if let _ = VersionUpgradeInfoController.sharedController.lastSupportedDateString {
infoString = Strings.VersionUpgrade.deprecatedMessage
}
if !isActionTakenOnUpgradeSnackBar {
showVersionUpgradeSnackBar(infoString)
}
}
else {
hideSnackBar()
}
}
private func hideSnackBarForFullScreenError() {
if tableController.courses.count <= 0 {
hideSnackBar()
}
}
func coursesTableChoseCourse(course: OEXCourse) {
if let course_id = course.course_id {
self.environment.router?.showCourseWithID(course_id, fromController: self, animated: true)
}
else {
preconditionFailure("course without a course id")
}
}
func refreshControllerActivated(controller: PullRefreshController) {
self.enrollmentFeed.refresh()
self.userPreferencesFeed.refresh()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableController.tableView.autolayoutFooter()
}
//MARK:- LoadStateViewReloadSupport method
func loadStateViewReload() {
refreshIfNecessary()
}
}
// For testing use only
extension EnrolledCoursesViewController {
var t_loaded: Stream<()> {
return self.enrollmentFeed.output.map {_ in
return ()
}
}
}
| d78d516d70868bfb166884630ade1dae | 35.274678 | 169 | 0.638665 | false | false | false | false |
glwithu06/ReTodo | refs/heads/master | ReTodo/Reducer/TodoReducer.swift | mit | 1 | //
// TodoReducer.swift
// ReTodo
//
// Created by Nate Kim on 07/07/2017.
// Copyright © 2017 NateKim. All rights reserved.
//
import ReSwift
var counter = 0
extension Int {
mutating func increment() -> Int {
self += 1
return self
}
}
func todoReducer(action: Action, state: AppState?) -> AppState {
var state:AppState = state ?? AppState()
switch action {
case let addAction as AddTaskAction:
state.taskState.appendTask(task: Task(id: counter.increment(), title: addAction.title, note: addAction.note, dueDate: addAction.dueDate))
case let editAction as EditTaskAction:
if let task = state.taskState.task(taskID: editAction.id) {
var task = task
task.title = editAction.title
task.dueDate = editAction.dueDate
task.note = editAction.note
state.taskState.update(task: task)
}
case let toggleAction as ToggleTaskAction:
if let task = state.taskState.task(taskID: toggleAction.id) {
var task = task
task.complete = !task.complete
state.taskState.update(task: task)
}
case let deleteAction as DeleteTaskAction:
state.taskState.deleteTask(taskID: deleteAction.id)
case let deleteTasksAction as DeleteTasksAction:
for id in deleteTasksAction.ids {
state.taskState.deleteTask(taskID: id)
}
case _ as ToggleAllTaskAction:
for i in 0..<state.taskState.numberOfTasks() {
if let task = state.taskState.task(at: i) {
var task = task
task.complete = !task.complete
state.taskState.update(task: task)
}
}
default:
break
}
return state
}
| cdf82fac27dc5bf4d3ddfb290db4c13b | 29.586207 | 145 | 0.611612 | false | false | false | false |
sschiau/swift-package-manager | refs/heads/master | Sources/TestSupport/MockDependencyGraph.swift | apache-2.0 | 1 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import PackageLoading
import PackageModel
import PackageGraph
import SourceControl
import Utility
/// Represents a mock package.
public struct MockPackage {
/// The name of the package.
public let name: String
/// The current available version of the package.
public let version: Utility.Version?
/// The dependencies of the package.
public let dependencies: [MockDependency]
public init(_ name: String, version: Utility.Version?, dependencies: [MockDependency] = []) {
self.name = name
self.version = version
self.dependencies = dependencies
}
}
/// Represents a mock package dependency.
public struct MockDependency {
/// The name of the dependency.
public let name: String
/// The allowed version range of this dependency.
public let version: Range<Utility.Version>
public init(_ name: String, version: Range<Utility.Version>) {
self.name = name
self.version = version
}
public init(_ name: String, version: Utility.Version) {
self.name = name
self.version = version..<Version(version.major, version.minor, version.patch + 1)
}
}
/// A mock manifest graph creator. It takes in a path where it creates empty repositories for mock packages.
/// For each mock package, it creates a manifest and maps it to the url and that version in mock manifest loader.
/// It provides basic functionality of getting the repo paths and manifests which can be later modified in tests.
public struct MockManifestGraph {
/// The map of repositories created by this class where the key is name of the package.
public let repos: [String: RepositorySpecifier]
/// The generated mock manifest loader.
public let manifestLoader: MockManifestLoader
/// The generated root manifest.
public let rootManifest: Manifest
/// The map of external manifests created.
public let manifests: [MockManifestLoader.Key: Manifest]
/// Present if file system used is in inmemory.
public let repoProvider: InMemoryGitRepositoryProvider?
/// Convinience accessor for repository specifiers.
public func repo(_ package: String) -> RepositorySpecifier {
return repos[package]!
}
/// Convinience accessor for external manifests.
public func manifest(_ package: String, version: Utility.Version) -> Manifest {
return manifests[MockManifestLoader.Key(url: repo(package).url, version: version)]!
}
/// Create instance with mocking on in memory file system.
public init(
at path: AbsolutePath,
rootDeps: [MockDependency],
packages: [MockPackage],
fs: InMemoryFileSystem
) throws {
try self.init(at: path, rootDeps: rootDeps, packages: packages, inMemory: (fs, InMemoryGitRepositoryProvider()))
}
public init(
at path: AbsolutePath,
rootDeps: [MockDependency],
packages: [MockPackage],
inMemory: (fs: InMemoryFileSystem, provider: InMemoryGitRepositoryProvider)? = nil
) throws {
repoProvider = inMemory?.provider
// Create the test repositories, we don't need them to have actual
// contents (the manifests are mocked).
let repos = Dictionary(items: try packages.map({ package -> (String, RepositorySpecifier) in
let repoPath = path.appending(component: package.name)
let tag = package.version?.description ?? "initial"
let specifier = RepositorySpecifier(url: repoPath.asString)
// If this is in memory mocked graph.
if let inMemory = inMemory {
if !inMemory.fs.exists(repoPath) {
let repo = InMemoryGitRepository(path: repoPath, fs: inMemory.fs)
try repo.createDirectory(repoPath, recursive: true)
let filePath = repoPath.appending(component: "source.swift")
try repo.writeFileContents(filePath, bytes: "foo")
repo.commit()
try repo.tag(name: tag)
inMemory.provider.add(specifier: specifier, repository: repo)
}
} else {
// Don't recreate repo if it is already there.
if !exists(repoPath) {
try makeDirectories(repoPath)
initGitRepo(repoPath, tag: package.version?.description ?? "initial")
}
}
return (package.name, specifier)
}))
let src = path.appending(component: "Sources")
if let fs = inMemory?.fs {
try fs.createDirectory(src, recursive: true)
try fs.writeFileContents(src.appending(component: "foo.swift"), bytes: "")
} else {
// Make a sources folder for our root package.
try makeDirectories(src)
try systemQuietly(["touch", src.appending(component: "foo.swift").asString])
}
// Create the root manifest.
rootManifest = Manifest(
name: "Root",
platforms: [.all],
path: path.appending(component: Manifest.filename),
url: path.asString,
version: nil,
manifestVersion: .v4,
dependencies: MockManifestGraph.createDependencies(repos: repos, dependencies: rootDeps)
)
// Create the manifests from mock packages.
var manifests = Dictionary(items: packages.map({ package -> (MockManifestLoader.Key, Manifest) in
let url = repos[package.name]!.url
let manifest = Manifest(
name: package.name,
platforms: [.all],
path: AbsolutePath(url).appending(component: Manifest.filename),
url: url,
version: package.version,
manifestVersion: .v4,
dependencies: MockManifestGraph.createDependencies(repos: repos, dependencies: package.dependencies)
)
return (MockManifestLoader.Key(url: url, version: package.version), manifest)
}))
// Add the root manifest.
manifests[MockManifestLoader.Key(url: path.asString, version: nil)] = rootManifest
manifestLoader = MockManifestLoader(manifests: manifests)
self.manifests = manifests
self.repos = repos
}
/// Maps MockDependencies into PackageDescription's Dependency array.
private static func createDependencies(
repos: [String: RepositorySpecifier],
dependencies: [MockDependency]
) -> [PackageDependencyDescription] {
return dependencies.map({ dependency in
return PackageDependencyDescription(
url: repos[dependency.name]?.url ?? "//\(dependency.name)",
requirement: .range(dependency.version.lowerBound ..< dependency.version.upperBound))
})
}
}
| fd9b64565438c8e5e727f10440318e63 | 38.118919 | 120 | 0.640873 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Observers/AnonymousObserver.swift | mit | 12 | //
// AnonymousObserver.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
typealias Element = ElementType
typealias EventHandler = (Event<Element>) -> Void
private let _eventHandler : EventHandler
init(_ eventHandler: @escaping EventHandler) {
#if TRACE_RESOURCES
let _ = AtomicIncrement(&resourceCount)
#endif
_eventHandler = eventHandler
}
override func onCore(_ event: Event<Element>) {
return _eventHandler(event)
}
#if TRACE_RESOURCES
deinit {
let _ = AtomicDecrement(&resourceCount)
}
#endif
}
| dc99a38b012dac22037f42c2f218df70 | 20.970588 | 66 | 0.662651 | false | false | false | false |
AHuaner/Gank | refs/heads/master | Gank/Utility/AHTimeButton.swift | mit | 2 | //
// AHTimeButton.swift
// Gank
//
// Created by CoderAhuan on 2016/12/8.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
class AHTimeButton: UIButton {
fileprivate var time: Int
fileprivate var clickClouse: (() -> Void)
fileprivate var timer: Timer?
init(frame: CGRect, time: Int, clickAction: @escaping () -> Void) {
self.time = time
self.clickClouse = clickAction
super.init(frame: frame)
self.frame = frame
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
setTitle("\(self.time)s跳过", for: .normal)
titleLabel?.font = UIFont.systemFont(ofSize: 12)
backgroundColor = UIColor.orange
layer.cornerRadius = self.Height * 0.4
addTarget(self, action: #selector(skipAction), for: .touchUpInside)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
func skipAction() {
timer?.invalidate()
timer = nil
clickClouse()
}
func timerAction() {
time = time - 1
setTitle("\(self.time)s跳过", for: .normal)
if time <= 0 {
skipAction()
}
}
}
| 5c372e4c9637cb7fca3874ed9894a727 | 25.490196 | 133 | 0.586232 | false | false | false | false |
rhx/gir2swift | refs/heads/main | Plugins/gir2swift-plugin/plugin.swift | bsd-2-clause | 1 | import PackagePlugin
import Foundation
/// Type representing a plugin error
enum Gir2SwiftError: LocalizedError {
case failedToGetGirNameFromManifest
case failedToGetGirDirectory(containing: [String])
}
func getGirName(for manifest: Path) throws -> String {
let lines = try String(contentsOf: URL(fileURLWithPath: manifest.string)).split(separator: "\n")
var girName: String? = nil
for line in lines {
if line.hasPrefix("gir-name: ") {
girName = line.dropFirst(10).trimmingCharacters(in: .whitespacesAndNewlines)
}
}
if let girName = girName {
return girName
} else {
throw Gir2SwiftError.failedToGetGirNameFromManifest
}
}
func girManifestName(for target: Target, in targetPackageDirectory: Path) -> Path {
let gir2swiftManifestYaml = "gir2swift-manifest.yaml"
let gir2swiftTargetDirectoryManifest = target.directory.appending(gir2swiftManifestYaml)
return FileManager.default.fileExists(atPath: gir2swiftTargetDirectoryManifest.string) ?
gir2swiftTargetDirectoryManifest : targetPackageDirectory.appending(gir2swiftManifestYaml)
}
func getGirDirectory(containing girFiles: [String]) throws -> Path {
let possibleDirectories = ["/opt/homebrew/share/gir-1.0", "/usr/local/share/gir-1.0", "/usr/share/gir-1.0"].map(Path.init(_:))
for directory in possibleDirectories {
let directoryContainsAllGirs = girFiles.allSatisfy { file in
let path = directory.appending(file).string
return FileManager.default.fileExists(atPath: path)
}
if directoryContainsAllGirs {
return directory
}
}
throw Gir2SwiftError.failedToGetGirDirectory(containing: girFiles)
}
/// The gir2swift build plugin
@main struct Gir2SwiftPlugin: BuildToolPlugin {
/// A Plugin that generates Swift code from a `.gir` FILE
/// - Parameters:
/// - context: information about the package for which the plugin is provided
/// - target: the target defined in the package
/// - Returns: the commands to run during the build
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
let targetPackageDirectory = context.package.directory
let gir2swiftManifest = girManifestName(for: target, in: targetPackageDirectory)
let outputDir = context.pluginWorkDirectory.appending("gir2swift-generated").appending(target.name)
let fileManager = FileManager.default
try fileManager.createDirectory(atPath: outputDir.string, withIntermediateDirectories: true)
let girName = try getGirName(for: gir2swiftManifest)
// Determine the list of output files
let atChar = Character("@").utf8.first!
let suffixes = ["aliases", "bitfields", "callbacks", "constants", "enumerations", "functions", "unions"] +
(0...26).map { String(Character(UnicodeScalar(atChar + UInt8($0)))) }
var outputFiles = suffixes.map { suffix in
outputDir.appending("\(girName)-\(suffix).swift")
}
outputFiles.append(outputDir.appending("\(girName).swift"))
// Determine the list of input files
let targetDir = URL(fileURLWithPath: target.directory.string)
let contents = try fileManager.contentsOfDirectory(at: targetDir, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants])
let inputFiles = contents.filter { file in
file.lastPathComponent.hasPrefix(girName)
}.map { file in
Path(file.path)
} + [gir2swiftManifest]
// Find all girs that this library depends on
let girFiles = target.recursiveTargetDependencies.compactMap {
let manifest = girManifestName(for: $0, in: targetPackageDirectory)
return try? getGirName(for: manifest)
}.filter {
$0 != girName
}.map {
$0 + ".gir"
}
let girDirectory = try getGirDirectory(containing: girFiles)
// Construct the arguments
var arguments = [
"--alpha-names",
"-w", targetPackageDirectory.string,
"-t", target.directory.string,
"-o", outputDir.string,
]
arguments.append(contentsOf: girFiles.flatMap { girFile in
["-p", girDirectory.appending(girFile).string]
})
return [.buildCommand(
displayName: "Converting \(target.directory.lastComponent) \(girName).gir",
executable: try context.tool(named: "gir2swift").path,
arguments: arguments,
inputFiles: inputFiles,
outputFiles: outputFiles
)]
}
}
| 4a3649f3620c7fd0d202b1770ccbadcd | 40.421053 | 162 | 0.664972 | false | false | false | false |
crossroadlabs/Regex | refs/heads/master | Sources/Regex/Match.swift | apache-2.0 | 1 | //===--- Match.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
/**
* Represents groups of pattern match. Supports subscripts.
*/
public protocol MatchGroupsProtocol {
/**
* Takes a subgroup match substring by index.
- parameter index: Index of subgroup to match to. Zero represents the whole match.
- returns: A substring or nil if the supplied subgroup does not exist.
*/
subscript(index: Int) -> String? {get}
/**
* Takes a subgroup match substring by name. This will work if you supplied subgroup names while creating Regex.
- parameter name: Name of subgroup to match to.
- returns: A substring or nil if the supplied subgroup does not exist.
*/
subscript(name: String) -> String? {get}
}
//Make this one public when we add a second implementation
protocol MatchProtocol {
var source:String {get}
var range:StringRange {get}
var ranges:[StringRange?] {get}
func range(at index:Int) -> StringRange?
func range(named name:String) -> StringRange?
var matched:String {get}
var subgroups:[String?] {get}
var groups: MatchGroupsProtocol {get}
func group(at index:Int) -> String?
func group(named name:String) -> String?
}
struct MatchGroups : MatchGroupsProtocol {
private let match: MatchProtocol
init(match: MatchProtocol) {
self.match = match
}
subscript(index: Int) -> String? {
return match.group(at: index)
}
subscript(name: String) -> String? {
return match.group(named: name)
}
}
/**
* Represents a pattern match
*/
public class Match : MatchProtocol {
/**
* The original string supplied to Regex for matching
*/
public let source:String
let match:CompiledPatternMatch
let groupNames:[String]
let nameMap:Dictionary<String, Int>
init(source:String, match:CompiledPatternMatch, groupNames:[String]) {
self.source = source
self.match = match
self.groupNames = groupNames
self.nameMap = groupNames.indexHash
}
func index(of group:String) -> Int? {
guard let groupIndex = nameMap[group] else { return nil }
return groupIndex + 1
}
/**
* The matching range
*/
public var range:StringRange {
get {
//here it never throws, because otherwise it will not match
return try! match.range.asRange(ofString: source)
}
}
/**
* The matching ranges of subgroups
*/
public var ranges:[StringRange?] {
get {
var result = Array<StringRange?>()
for i in 0..<match.numberOfRanges {
//subrange can be empty
let stringRange = try? match.range(at: i).asRange(ofString: source)
result.append(stringRange)
}
return result
}
}
/**
* Takes a subgroup match by index.
- parameter index: Number of subgroup to match to. Zero represents the whole match.
- returns: A range or nil if the supplied subgroup does not exist.
*/
public func range(at index:Int) -> StringRange? {
guard match.numberOfRanges > index else { return nil }
return try? match.range(at: index).asRange(ofString: source)
}
/**
* Takes a subgroup match range by name. This will work if you supplied subgroup names while creating Regex.
- parameter name: Name of subgroup to match to.
- returns: A range or nil if the supplied subgroup does not exist.
*/
public func range(named name:String) -> StringRange? {
guard let groupIndex = index(of: name) else { return nil }
//subrange can be empty
return try? match.range(at: groupIndex).asRange(ofString: source)
}
/**
* The whole matched substring.
*/
public var matched:String {
get {
//zero group is always there, otherwise there is no match
return group(at: 0)!
}
}
/**
* Matched subgroups' substrings.
*/
public var subgroups:[String?] {
get {
let subRanges = ranges.suffix(from: 1)
return subRanges.map { range in
range.map { range in
String(source[range])
}
}
}
}
/**
* Returns groups object with subscript support. Zero index represents the whole match.
*/
public var groups: MatchGroupsProtocol {
get {
return MatchGroups(match: self)
}
}
/**
* Takes a subgroup match substring by index.
- parameter name: Index of subgroup to match to. Zero represents the whole match.
- returns: A substring or nil if the supplied subgroup does not exist.
*/
public func group(at index:Int) -> String? {
let range = self.range(at: index)
return range.map { range in
String(source[range])
}
}
/**
* Takes a subgroup match substring by name. This will work if you supplied subgroup names while creating Regex.
- parameter name: Name of subgroup to match to.
- returns: A substring or nil if the supplied subgroup does not exist.
*/
public func group(named name:String) -> String? {
guard let groupIndex = index(of: name) else { return nil }
return self.group(at: groupIndex)
}
}
| 558e57bcf1d13d351a6c7f5a93fb1ea3 | 29.490196 | 116 | 0.600322 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/UITestsFoundation/Screens/Login/LoginSiteAddressScreen.swift | gpl-2.0 | 1 | import ScreenObject
import XCTest
private struct ElementStringIDs {
static let nextButton = "Site Address Next Button"
// TODO: clean up comments when unifiedSiteAddress is permanently enabled.
// For original Site Address. This matches accessibilityIdentifier in Login.storyboard.
// Leaving here for now in case unifiedSiteAddress is disabled.
// static let siteAddressTextField = "usernameField"
// For unified Site Address. This matches TextFieldTableViewCell.accessibilityIdentifier.
static let siteAddressTextField = "Site address"
}
public class LoginSiteAddressScreen: ScreenObject {
let siteAddressTextFieldGetter: (XCUIApplication) -> XCUIElement = {
$0.textFields["Site address"]
}
var siteAddressTextField: XCUIElement { siteAddressTextFieldGetter(app) }
var nextButton: XCUIElement { app.buttons[ElementStringIDs.nextButton] }
init(app: XCUIApplication = XCUIApplication()) throws {
try super.init(
expectedElementGetters: [siteAddressTextFieldGetter],
app: app,
waitTimeout: 7
)
}
public func proceedWith(siteUrl: String) throws -> LoginUsernamePasswordScreen {
siteAddressTextField.tap()
siteAddressTextField.typeText(siteUrl)
nextButton.tap()
return try LoginUsernamePasswordScreen()
}
public func proceedWithWP(siteUrl: String) throws -> GetStartedScreen {
siteAddressTextField.tap()
siteAddressTextField.typeText(siteUrl)
nextButton.tap()
return try GetStartedScreen()
}
public static func isLoaded() -> Bool {
(try? LoginSiteAddressScreen().isLoaded) ?? false
}
}
| 65be179335d8682b19703b67c0b80571 | 31.150943 | 93 | 0.705986 | false | false | false | false |
BelowTheHorizon/Mocaccino | refs/heads/master | Mocaccino/CardAddViewController.swift | mit | 1 | //
// CardAddViewController.swift
// Mocaccino
//
// Created by Cirno MainasuK on 2016-2-11.
// Copyright © 2016年 Cirno MainasuK. All rights reserved.
//
import UIKit
private let kCardAddViewHeight: CGFloat = 200
private let kCardAddViewWidth: CGFloat = 300
private let kCardAddViewOffset: CGFloat = kCardAddViewHeight/2 + 64
class CardAddViewController: UIViewController {
let fromView: UIView
let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
var animator: UIDynamicAnimator!
var attachmentBehavior: UIAttachmentBehavior!
var snapBehavior: UISnapBehavior!
var panBehavior: UIAttachmentBehavior!
var cardAddView: CardAddView!
// MARK: - View life cycle
init(fromView: UIView) {
self.fromView = fromView
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .OverFullScreen
modalTransitionStyle = .CrossDissolve
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
blurredView.frame = view.bounds
view.addSubview(blurredView)
cardAddView = creatCardAddView()
cardAddView.center = fromView.center
cardAddView.center.y = kCardAddViewOffset
view.addSubview(cardAddView)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
// setupAnimator()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupAnimator() {
animator = UIDynamicAnimator(referenceView: view)
var center = CGPoint(x: CGRectGetWidth(view.bounds)/2, y: CGRectGetHeight(view.bounds)/2)
cardAddView = creatCardAddView()
view.addSubview(cardAddView)
snapBehavior = UISnapBehavior(item: cardAddView, snapToPoint: center)
center.y += kCardAddViewOffset
attachmentBehavior = UIAttachmentBehavior(item: cardAddView, offsetFromCenter: UIOffset(horizontal: 0, vertical: kCardAddViewOffset), attachedToAnchor: center)
// setupTipView(tipView, index: 0)
// resetTipView(tipView, position: .RotatedRight)
// let pan = UIPanGestureRecognizer(target: self, action: "panTipView:")
// view.addGestureRecognizer(pan)
}
private func creatCardAddView() -> CardAddView? {
if let view = UINib(nibName: "CardAddView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! CardAddView? {
view.frame = CGRect(x: 0, y: 0, width: kCardAddViewWidth, height: kCardAddViewHeight)
return view
}
return nil
}
}
| 33841ce1dd85504f4cab06e2d3287b2b | 29.623762 | 167 | 0.657937 | false | false | false | false |
iqingchen/DouYuZhiBo | refs/heads/master | DY/DY/Classes/Main/Controller/BaseAnchorViewController.swift | mit | 1 | //
// BaseAnchorViewController.swift
// DY
//
// Created by zhang on 16/12/6.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
//MARK: - 定义常量
private let kItemSpace : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 3 * kItemSpace) * 0.5
private let kNormalItemH : CGFloat = kItemW * 3 / 4
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID : String = "kNormalCellID"
private let kPrettyCellID : String = "kPrettyCellID"
private let kReusableViewHeadID : String = "kReusableViewHeadID"
class BaseAnchorViewController: BaseViewController {
//MARK: - 懒加载
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.sectionInset = UIEdgeInsetsMake(0, kItemSpace, 0, kItemSpace)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemSpace
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kReusableViewHeadID)
return collectionView
}()
//MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置ui
setupUI()
//请求数据
loadData()
}
}
//MARK: - 设置UI
extension BaseAnchorViewController {
override func setupUI() {
contentView = collectionView
//1.添加collectionView
view.addSubview(collectionView)
//执行父类方法
super.setupUI()
}
}
//MARK: - 请求娱乐数据
extension BaseAnchorViewController {
func loadData() {
}
}
//MARK: - 实现collectionView的数据源协议
extension BaseAnchorViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kReusableViewHeadID, for: indexPath) as! CollectionHeaderView
header.group = baseVM.anchorGroups[indexPath.section]
return header
}
}
//MARK: - 实现collectionView的delegate协议
extension BaseAnchorViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc(){
let show = RoomShowViewController()
self.present(show, animated: true, completion: nil)
}
private func pushNormalRoomVc(){
let normal = RoomNormalViewController()
navigationController?.pushViewController(normal, animated: true)
}
}
| 3965a251a81ae36cd32f130676ab3af3 | 38 | 192 | 0.720047 | false | false | false | false |
KaiCode2/swift-corelibs-foundation | refs/heads/master | Foundation/NSAttributedString.swift | apache-2.0 | 3 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public class NSAttributedString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
private let _cfinfo = _CFInfo(typeID: CFAttributedStringGetTypeID())
private let _string: NSString
private let _attributeArray: CFRunArrayRef
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func encodeWithCoder(_ aCoder: NSCoder) {
NSUnimplemented()
}
static public func supportsSecureCoding() -> Bool {
return true
}
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public override func mutableCopy() -> AnyObject {
return mutableCopyWithZone(nil)
}
public func mutableCopyWithZone(_ zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public var string: String {
return _string._swiftObject
}
public func attributesAtIndex(_ location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
var cfRange = CFRange()
return withUnsafeMutablePointer(&cfRange) { (rangePointer: UnsafeMutablePointer<CFRange>) -> [String : AnyObject] in
// Get attributes value using CoreFoundation function
let value = CFAttributedStringGetAttributes(_cfObject, location, rangePointer)
// Convert the value to [String : AnyObject]
let dictionary = unsafeBitCast(value, to: NSDictionary.self)
var results = [String : AnyObject]()
for (key, value) in dictionary {
guard let stringKey = (key as? NSString)?._swiftObject else {
continue
}
results[stringKey] = value
}
// Update effective range
let hasAttrs = results.count > 0
range.pointee.location = hasAttrs ? rangePointer.pointee.location : NSNotFound
range.pointee.length = hasAttrs ? rangePointer.pointee.length : 0
return results
}
}
public var length: Int {
return CFAttributedStringGetLength(_cfObject)
}
public func attribute(_ attrName: String, atIndex location: Int, effectiveRange range: NSRangePointer) -> AnyObject? {
var cfRange = CFRange()
return withUnsafeMutablePointer(&cfRange) { (rangePointer: UnsafeMutablePointer<CFRange>) -> AnyObject? in
// Get attribute value using CoreFoundation function
let attribute = CFAttributedStringGetAttribute(_cfObject, location, attrName._cfObject, rangePointer)
// Update effective range and return the result
if let attribute = attribute {
range.pointee.location = rangePointer.pointee.location
range.pointee.length = rangePointer.pointee.length
return attribute
} else {
range.pointee.location = NSNotFound
range.pointee.length = 0
return nil
}
}
}
public func attributedSubstringFromRange(_ range: NSRange) -> NSAttributedString { NSUnimplemented() }
public func attributesAtIndex(_ location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> [String : AnyObject] { NSUnimplemented() }
public func attribute(_ attrName: String, atIndex location: Int, longestEffectiveRange range: NSRangePointer, inRange rangeLimit: NSRange) -> AnyObject? { NSUnimplemented() }
public func isEqualToAttributedString(_ other: NSAttributedString) -> Bool { NSUnimplemented() }
public init(string str: String) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: nil)
}
public init(string str: String, attributes attrs: [String : AnyObject]?) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: attrs)
}
public init(attributedString attrStr: NSAttributedString) { NSUnimplemented() }
private func addAttributesToAttributeArray(attrs: [String : AnyObject]?) {
guard _string.length > 0 else {
return
}
let range = CFRange(location: 0, length: _string.length)
if let attrs = attrs {
CFRunArrayInsert(_attributeArray, range, attrs._cfObject)
} else {
let emptyAttrs = [String : AnyObject]()
CFRunArrayInsert(_attributeArray, range, emptyAttrs._cfObject)
}
}
public func enumerateAttributesInRange(_ enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: ([String : AnyObject], NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() }
public func enumerateAttribute(_ attrName: String, inRange enumerationRange: NSRange, options opts: NSAttributedStringEnumerationOptions, usingBlock block: (AnyObject?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() }
}
extension NSAttributedString: _CFBridgable {
internal var _cfObject: CFAttributedString { return unsafeBitCast(self, to: CFAttributedString.self) }
}
public struct NSAttributedStringEnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let Reverse = NSAttributedStringEnumerationOptions(rawValue: 1 << 1)
public static let LongestEffectiveRangeNotRequired = NSAttributedStringEnumerationOptions(rawValue: 1 << 20)
}
public class NSMutableAttributedString : NSAttributedString {
public func replaceCharactersInRange(_ range: NSRange, withString str: String) { NSUnimplemented() }
public func setAttributes(_ attrs: [String : AnyObject]?, range: NSRange) { NSUnimplemented() }
public var mutableString: NSMutableString { NSUnimplemented() }
public func addAttribute(_ name: String, value: AnyObject, range: NSRange) { NSUnimplemented() }
public func addAttributes(_ attrs: [String : AnyObject], range: NSRange) { NSUnimplemented() }
public func removeAttribute(_ name: String, range: NSRange) { NSUnimplemented() }
public func replaceCharactersInRange(_ range: NSRange, withAttributedString attrString: NSAttributedString) { NSUnimplemented() }
public func insertAttributedString(_ attrString: NSAttributedString, atIndex loc: Int) { NSUnimplemented() }
public func appendAttributedString(_ attrString: NSAttributedString) { NSUnimplemented() }
public func deleteCharactersInRange(_ range: NSRange) { NSUnimplemented() }
public func setAttributedString(_ attrString: NSAttributedString) { NSUnimplemented() }
public func beginEditing() { NSUnimplemented() }
public func endEditing() { NSUnimplemented() }
}
| 707d82f91d7497e791c7d0b860cb8293 | 41.594286 | 244 | 0.673598 | false | false | false | false |
Pomme2Poule/CSVExport | refs/heads/master | CSVExport/CSVExport/CSVTableCoordinate.swift | mit | 1 | //
// CSVTableCoordinate.swift
// CSVExport
//
// Created by Clément Cardonnel on 06/01/2017.
// Copyright (c) 2017 Clément Cardonnel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
struct CSVTableCoordinate {
let x: Int
let y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
// MARK: - Hashable conformance
extension CSVTableCoordinate: Hashable {
var hashValue: Int {
return x.hashValue ^ y.hashValue
}
static func == (lhs: CSVTableCoordinate, rhs: CSVTableCoordinate) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
// MARK: - Comparable
extension CSVTableCoordinate: Comparable {
static func < (lhs: CSVTableCoordinate, rhs: CSVTableCoordinate) -> Bool {
if lhs.y < rhs.y {
return true
} else if lhs.y == rhs.y {
if lhs.x < rhs.x {
return true
} else {
return false
}
} else {
return false
}
}
static func > (lhs: CSVTableCoordinate, rhs: CSVTableCoordinate) -> Bool {
if lhs.y > rhs.y {
return true
} else if lhs.y == rhs.y {
if lhs.x > rhs.x {
return true
} else {
return false
}
} else {
return false
}
}
}
| 74b1a7e9645ebbefe0d1651ab59a7d8c | 27.835294 | 82 | 0.615667 | false | false | false | false |
harungunaydin/Agenda-Master | refs/heads/master | FoldingCell/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// AgendaMaster
//
// Created by Harun Gunaydin on 4/26/16.
// Copyright © 2016 Harun Gunaydin. All rights reserved.
//
import UIKit
import CoreData
var allEvents = [Event]()
var filteredEvents = [Event]()
var sources = [EventSource]()
var eventTable = EventTableViewController()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
sources.append( EventSource(name: "Agenda Master", logo: UIImage(named: "Agenda_Master_Logo.png")! ) )
sources.append( EventSource(name: "Google", logo: UIImage(named: "Google_Logo.png" )! ) )
sources.append( EventSource(name: "Apple", logo: UIImage(named: "Apple_Logo.png" )! ) )
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("firstTimeCheck") == nil {
print("First Time")
defaults.setObject(false, forKey: "firstTimeCheck")
defaults.setObject(false, forKey: "isSignedInAgendaMaster")
defaults.setObject(false, forKey: "isSignedInGoogle")
defaults.setObject(false, forKey: "isSignedInApple")
defaults.setObject(true, forKey: "Agenda Master_filtered")
defaults.setObject(true, forKey: "Google_filtered")
defaults.setObject(true, forKey: "Apple_filtered")
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "harungunaydin.AgendaMaster" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("AgendaMaster", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 6a0cbed6d907c26a38763c413ee8f5b5 | 51.393939 | 291 | 0.700839 | false | false | false | false |
Purdue-iOS-Dev-Club/Fall-2015-Tutorials | refs/heads/master | BoilerMenu/BoilerMenu/RestaurantViewController.swift | mit | 1 | //
// RestaurantViewController.swift
// BoilerMenu
//
// Created by George Lo on 9/21/15.
// Copyright © 2015 Purdue iOS Dev Club. All rights reserved.
//
import UIKit
class RestaurantViewController: UITableViewController {
// MARK: - Global vars
var restaurantDictionary: [NSDictionary] = []
var selectedRow = 0
// MARK: - View controller cycles
override func viewDidLoad() {
super.viewDidLoad()
// Retrieve the data from the URL and get it into the data variable
let data = NSData(contentsOfURL: NSURL(string: "http://api.hfs.purdue.edu/menus/v2/retail")!)
// Convert those data from the web into the format of NSDictionary
let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
// Get the value of "Location" key, and set that value to restaurantDictionary
restaurantDictionary = dict["Location"] as! [NSDictionary]
self.tableView.rowHeight = 70
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return restaurantDictionary.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RestaurantCell", forIndexPath: indexPath) as! RestaurantTableViewCell
let fileName = restaurantDictionary[indexPath.row]["Logo"] as! String
cell.restaurantIV.sd_setImageWithURL(NSURL(string: "http://api.hfs.purdue.edu/menus/v2/file/\(fileName)")!, placeholderImage: UIImage(named: "placeholder"))
//cell.restaurantIV.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://api.hfs.purdue.edu/menus/v2/file/\(fileName)")!)!)
cell.restaurantLabel.text = restaurantDictionary[indexPath.row]["Name"] as? String
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedRow = indexPath.row
self.performSegueWithIdentifier("toRestaurantDetail", sender: self)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toRestaurantDetail" {
let viewController = segue.destinationViewController as! RestaurantDetailViewController
viewController.restaurantDict = restaurantDictionary[selectedRow]
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| c3924e9cdf28f9c9ee4add3b67d2813f | 38.096774 | 164 | 0.682962 | false | false | false | false |
Flinesoft/BartyCrouch | refs/heads/main | Tests/BartyCrouchKitTests/CommandLine/CommandLineActorTests.swift | mit | 1 | //@testable import BartyCrouchKit
//import XCTest
//
//// swiftlint:disable force_try
//
//class CommandLineActorTests: XCTestCase {
// // MARK: - Stored Properties
// static let stringsFilesDirPath: String = "\(BASE_DIR)/Tests/Resources/StringsFiles"
//
// let codeFilesDirPath: String = "\(BASE_DIR)/Tests/Resources/CodeFiles/UnsortedKeys"
// let unsortedKeysStringsFilePath: String = "\(stringsFilesDirPath)/UnsortedKeys/Base.lproj/Localizable.strings"
// let unsortedKeysDirPath: String = "\(stringsFilesDirPath)/UnsortedKeys"
//
// // MARK: - Test Callbacks
// override func setUp() {
// super.setUp()
//
// if FileManager.default.fileExists(atPath: unsortedKeysStringsFilePath + ".backup") {
// try! FileManager.default.removeItem(atPath: unsortedKeysStringsFilePath + ".backup")
// }
//
// try! FileManager.default.copyItem(atPath: unsortedKeysStringsFilePath, toPath: unsortedKeysStringsFilePath + ".backup")
// }
//
// override func tearDown() {
// super.tearDown()
//
// try! FileManager.default.removeItem(atPath: unsortedKeysStringsFilePath)
// try! FileManager.default.copyItem(atPath: unsortedKeysStringsFilePath + ".backup", toPath: unsortedKeysStringsFilePath)
// try! FileManager.default.removeItem(atPath: unsortedKeysStringsFilePath + ".backup")
// }
//
// // MARK: - Test Methods
// func testActOnCode() {
// let args = ["bartycrouch", "code", "-p", codeFilesDirPath, "-l", unsortedKeysDirPath, "-a"]
//
// CommandLineParser(arguments: args).parse { commonOptions, subCommandOptions in
// CommandLineActor().act(commonOptions: commonOptions, subCommandOptions: subCommandOptions)
//
// guard let updater = StringsFileUpdater(path: self.unsortedKeysStringsFilePath) else {
// XCTFail("Updater could not be initialized. Is the file missing? Path: \(self.unsortedKeysStringsFilePath)")
// return
// }
//
// let resultingKeys = updater.findTranslations(inString: updater.oldContentString).map { $0.key }
// let expectedKeys = ["DDD", "ggg", "BBB", "aaa", "FFF", "eee", "ccc"]
//
// XCTAssertEqual(resultingKeys, expectedKeys)
// }
// }
//
// func testActOnCodeWithSortedOption() {
// let args = ["bartycrouch", "code", "-p", codeFilesDirPath, "-l", unsortedKeysDirPath, "-a", "-s"]
//
// CommandLineParser(arguments: args).parse { commonOptions, subCommandOptions in
// CommandLineActor().act(commonOptions: commonOptions, subCommandOptions: subCommandOptions)
//
// guard let updater = StringsFileUpdater(path: self.unsortedKeysStringsFilePath) else {
// XCTFail("Updater could not be initialized. Is the file missing? Path: \(self.unsortedKeysStringsFilePath)")
// return
// }
//
// let resultingKeys = updater.findTranslations(inString: updater.oldContentString).map { $0.key }
// let expectedKeys = ["aaa", "BBB", "eee", "FFF", "ggg", "ccc", "DDD"]
//
// XCTAssertEqual(resultingKeys, expectedKeys)
// }
// }
//}
//
//// swiftlint:enable force_try
| 3d5b5756461b3cf0909b38e9c64f9f1f | 44.267606 | 129 | 0.650902 | false | true | false | false |
timothybowers/PersistenceEngine | refs/heads/master | PersistenceEngine/Classes/PersistenceEngine.swift | mit | 1 | //
// PersistenceEngine.swift
// Pods
//
// Created by Timothy S Bowers on 19/8/17.
// Copyright © 2017 Timothy Bowers. All rights reserved.
//
//
import CoreData
/**
PersistenceEngine uses this name to store your dictionaries in Core Data.
You have to create an **attribute** with this name for each *entity* you add to your *Data Mode*.
*/
let DictionaryAttribute = "coredictionary"
/**
**Data Model**
You have to create this file, *Data Model (Core Data)* in your application folder (Main Bundle)
*/
let CoreDataSQLiteFileName = "PersistenceEngineDB" // Do not include the .xcdatamodeld extension
/**
Manage Core Data for Dictionaries
- Author:
Timothy S Bowers
**Description:**
Making life easier to save and manage Dictionaries into Core Data for persistence.
**Requirements:**
*STEP1:*
Create a new file, *Data Model (Core Data)* in your application folder (Main Bundle) and save it with the name 'PersistenceEngineDB.xcdatamodeld'
*STEP2:*
Open this new file and create a new entity with any name you like (Starting with a capital), e.g. 'AirportsEntity'
*STEP3:*
Create an **attribute** with the name 'coredictionary' (all small letters) for each *entity* you add. Type must be 'Transformable'
*/
public class PersistenceEngine {
/// Array of Core Data Objects
private var entityArray: [NSManagedObject] = []
public init() {
print("PersistenceEngine version 0.2.6")
print()
print("Entity list in DB: \(self.entityNames())")
print()
self.loadStores()
}
lazy var persistentContainer: NSPersistentContainer = {
return NSPersistentContainer(name: CoreDataSQLiteFileName)
}()
private func loadCoreDataEntityTransformable(entity: NSManagedObject, field: String) -> [String: Any] {
guard let loadedEntity = entity.value(forKeyPath: field) as? [String : Any] else {
print("'",field, "' not found")
return ["":"" as Any]
}
return loadedEntity
}
public func entityNames() -> [String] {
let names = persistentContainer.managedObjectModel.entities.map({ (entity) -> String in
return entity.name ?? "nil entity name"
})
return names
}
public func printCoreData(entity: String) {
self.reload(entity: entity)
print()
print("------[ printDebug output start ]-----[ \(entity) ]----");
print("amount of core data objects stored = ", self.entityArray.count)
for (index, item) in entityArray.enumerated() {
print("index = ", index)
let coredictionary = self.loadCoreDataEntityTransformable(entity: item, field: DictionaryAttribute)
print("coredictionary = ", coredictionary)
}
print("------[ printDebug output stop ]-----[ \(entity) ]----");
print()
}
public func dictionaryFrom(entity: String) -> [[String: Any]] {
self.reload(entity: entity)
var coreDictionaryArray = [[String: Any]]()
for item in entityArray {
let coreDictionary = self.loadCoreDataEntityTransformable(entity: item, field: DictionaryAttribute)
coreDictionaryArray.append(coreDictionary)
}
print("\(coreDictionaryArray.count) dictionaries read from entity \(entity)")
return coreDictionaryArray
}
public func insert(dictionary: [String : Any], intoEntity: String) {
guard let entity = NSEntityDescription.entity(forEntityName: intoEntity, in: self.persistentContainer.viewContext) else {
print(#function,"failed. Could not find entity (table) named '",intoEntity,"'")
print("Make sure you have added an entity named '\(intoEntity)' to your \(CoreDataSQLiteFileName).xcdatamodeld file")
return
}
let newObject = NSManagedObject(entity: entity, insertInto: persistentContainer.viewContext)
newObject.setValue(dictionary, forKeyPath: DictionaryAttribute)
do {
try persistentContainer.viewContext.save()
print("inserted dictionary into \(intoEntity)")
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
private func reload(entity: String) {
guard let _ = NSEntityDescription.entity(forEntityName: entity, in: self.persistentContainer.viewContext) else {
print(#function,"failed. Could not find entity named '",entity,"'")
print("Make sure you have added an entity named '\(entity)' to your \(CoreDataSQLiteFileName).xcdatamodeld file")
return
}
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
do {
self.entityArray = try persistentContainer.viewContext.fetch(fetchRequest)
} catch let error as NSError {
print(#function,"failed. Could not fetch. \(error), \(error.userInfo)")
}
}
public func clear(entity: String) {
guard let _ = NSEntityDescription.entity(forEntityName: entity, in: self.persistentContainer.viewContext) else {
print(#function,"failed. Could not find entity named '",entity,"'")
print("Make sure you have added an entity named '\(entity)' to your \(CoreDataSQLiteFileName).xcdatamodeld file")
return
}
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try persistentContainer.viewContext.execute(deleteRequest)
try persistentContainer.viewContext.save()
self.entityArray.removeAll()
print("cleared '\(entity)' of all data")
} catch let error as NSError {
print(#function,"failed. Could not clear entity. \(error), \(error.userInfo)")
}
}
private func loadStores() {
let container = self.persistentContainer
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
/*
Pull request will be accepted if anyone wants to do the error handling.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
} else {
print("DB loaded: \(storeDescription)")
print()
}
})
}
}
| 914b6f7922ea8bb87cd830aa64eec153 | 34.3 | 199 | 0.598506 | false | false | false | false |
gfjalar/pavo | refs/heads/master | Pavo/DisplayMonitor.swift | mit | 1 | //
// DisplayMonitor.swift
// Pavo
//
// Created by Piotr Galar on 01/05/2015.
// Copyright (c) 2015 Piotr Galar. All rights reserved.
//
import Cocoa
import ImageIO
public class DisplayMonitor {
var buffer: ImageBuffer
let interval: NSTimeInterval
let display: CGDirectDisplayID
var timer: NSTimer?
public init(duration: Int = 1, fps: Int = 1, display: CGDirectDisplayID =
CGMainDisplayID()) {
buffer = ImageBuffer(capacity: duration * fps)
interval = 1.0 / Double(fps)
self.display = display
}
public func start() -> Bool {
if timer == nil {
timer = NSTimer.scheduledTimerWithTimeInterval(interval,
target: self, selector: Selector("capture"), userInfo: nil,
repeats: true)
return true
}
return false
}
public func stop() -> Bool {
if let t = timer {
t.invalidate()
timer = nil
return true
}
return false
}
public func clearCaptured() {
sync {
self.buffer.clear()
}
}
public func takeCaptured() -> [CGImage] {
var captured: ImageBuffer?
sync {
captured = self.buffer
}
return captured!.toArray()
}
public func takeScreenShot() -> CGImage {
// TODO: Error handling
return CGDisplayCreateImage(display)!
}
@objc func capture() {
sync {
self.buffer.add(self.takeScreenShot())
}
}
func sync(closure: () -> ()) {
objc_sync_enter(self)
closure()
objc_sync_exit(self)
}
}
| 0526fa20ce5341085eabbe11e99499de | 20.922078 | 77 | 0.542654 | false | false | false | false |
Jaelene/PhotoBroswer | refs/heads/master | PhotoBroswer/PhotoTypeChooseVC.swift | mit | 2 | //
// TypeChooseVC.swift
// PhotoBroswer
//
// Created by 冯成林 on 15/8/14.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
enum PhotoType: Int {
case Local
case Host
}
class PhotoTypeChooseVC: UIViewController {
var langType: LangType!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var localBtn: UIButton!
@IBOutlet weak var hostBtn: UIButton!
}
extension PhotoTypeChooseVC{
override func viewDidLoad() {
super.viewDidLoad()
if langType == LangType.Chinese {return}
titleLabel.text = "Select Type"
localBtn.setTitle("Local Album", forState: UIControlState.Normal)
localBtn.titleLabel?.font = UIFont.systemFontOfSize(20)
hostBtn.setTitle("Host Album", forState: UIControlState.Normal)
hostBtn.titleLabel?.font = UIFont.systemFontOfSize(20)
}
@IBAction func btnClick(sender: UIButton) {
let showTypeChooseVC = ShowTypeChooseTVC(style: UITableViewStyle.Plain)
showTypeChooseVC.langType = langType
showTypeChooseVC.photoType = PhotoType(rawValue: sender.tag)
self.navigationController?.pushViewController(showTypeChooseVC, animated: true)
}
} | 5a0de83604c8d55ca87eaf3ecd1804a1 | 21.946429 | 87 | 0.656542 | false | false | false | false |
MaorS/macOS-PasswordManager | refs/heads/master | Pods/CSV.swift/Sources/BinaryReader.swift | apache-2.0 | 2 | //
// BinaryReader.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/20.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
internal let utf8BOM: [UInt8] = [0xef, 0xbb, 0xbf]
internal let utf16BigEndianBOM: [UInt8] = [0xfe, 0xff]
internal let utf16LittleEndianBOM: [UInt8] = [0xff, 0xfe]
internal let utf32BigEndianBOM: [UInt8] = [0x00, 0x00, 0xfe, 0xff]
internal let utf32LittleEndianBOM: [UInt8] = [0xff, 0xfe, 0x00, 0x00]
private func readBOM(buffer: UnsafePointer<UInt8>, length: Int) -> (Endian, Int)? {
if length >= 4 {
if memcmp(buffer, utf32BigEndianBOM, 4) == 0 {
return (.big, 4)
}
if memcmp(buffer, utf32LittleEndianBOM, 4) == 0 {
return (.little, 4)
}
}
if length >= 3 {
if memcmp(buffer, utf8BOM, 3) == 0 {
return (.unknown, 3)
}
}
if length >= 2 {
if memcmp(buffer, utf16BigEndianBOM, 2) == 0 {
return (.big, 2)
}
if memcmp(buffer, utf16LittleEndianBOM, 2) == 0 {
return (.little, 2)
}
}
return nil
}
internal class BinaryReader {
private let stream: InputStream
private let endian: Endian
private let closeOnDeinit: Bool
private var buffer = malloc(4).assumingMemoryBound(to: UInt8.self)
private var tempBuffer = malloc(4).assumingMemoryBound(to: UInt8.self)
private let tempBufferSize = 4
private var tempBufferOffset = 0
internal init(
stream: InputStream,
endian: Endian,
closeOnDeinit: Bool) throws {
var endian = endian
if stream.streamStatus == .notOpen {
stream.open()
}
if stream.streamStatus != .open {
throw CSVError.cannotOpenFile
}
let readCount = stream.read(tempBuffer, maxLength: tempBufferSize)
if let (e, l) = readBOM(buffer: tempBuffer, length: readCount) {
if endian != .unknown && endian != e {
throw CSVError.stringEndianMismatch
}
endian = e
tempBufferOffset = l
}
self.stream = stream
self.endian = endian
self.closeOnDeinit = closeOnDeinit
}
deinit {
if closeOnDeinit && stream.streamStatus != .closed {
stream.close()
}
free(buffer)
free(tempBuffer)
}
internal var hasBytesAvailable: Bool {
return stream.hasBytesAvailable
}
private func readStream(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) throws -> Int {
if stream.streamStatus != .open {
throw CSVError.cannotReadFile
}
var i = 0
while tempBufferOffset < tempBufferSize {
buffer[i] = tempBuffer[tempBufferOffset]
i += 1
tempBufferOffset += 1
if i >= maxLength {
return i
}
}
return stream.read(buffer + i, maxLength: maxLength - i)
}
internal func readUInt8() throws -> UInt8 {
let bufferSize = 1
let length = try readStream(buffer, maxLength: bufferSize)
if length < 0 {
throw CSVError.streamErrorHasOccurred(error: stream.streamError!)
}
if length != bufferSize {
throw CSVError.cannotReadFile
}
return buffer[0]
}
internal func readUInt16() throws -> UInt16 {
let bufferSize = 2
let length = try readStream(buffer, maxLength: bufferSize)
if length < 0 {
throw CSVError.streamErrorHasOccurred(error: stream.streamError!)
}
if length != bufferSize {
throw CSVError.stringEncodingMismatch
}
return try buffer.withMemoryRebound(to: UInt16.self, capacity: 1) {
switch endian {
case .big:
return UInt16(bigEndian: $0[0])
case .little:
return UInt16(littleEndian: $0[0])
default:
throw CSVError.stringEndianMismatch
}
}
}
internal func readUInt32() throws -> UInt32 {
let bufferSize = 4
let length = try readStream(buffer, maxLength: bufferSize)
if length < 0 {
throw CSVError.streamErrorHasOccurred(error: stream.streamError!)
}
if length != bufferSize {
throw CSVError.stringEncodingMismatch
}
return try buffer.withMemoryRebound(to: UInt32.self, capacity: 1) {
switch endian {
case .big:
return UInt32(bigEndian: $0[0])
case .little:
return UInt32(littleEndian: $0[0])
default:
throw CSVError.stringEndianMismatch
}
}
}
}
extension BinaryReader {
internal class UInt8Iterator: Sequence, IteratorProtocol {
private let reader: BinaryReader
internal var errorHandler: ((Error) -> Void)?
fileprivate init(reader: BinaryReader) {
self.reader = reader
}
internal func next() -> UInt8? {
if !reader.hasBytesAvailable {
return nil
}
do {
return try reader.readUInt8()
} catch {
errorHandler?(error)
return nil
}
}
}
internal func makeUInt8Iterator() -> UInt8Iterator {
return UInt8Iterator(reader: self)
}
}
extension BinaryReader {
internal class UInt16Iterator: Sequence, IteratorProtocol {
private let reader: BinaryReader
internal var errorHandler: ((Error) -> Void)?
fileprivate init(reader: BinaryReader) {
self.reader = reader
}
internal func next() -> UInt16? {
if !reader.hasBytesAvailable {
return nil
}
do {
return try reader.readUInt16()
} catch {
errorHandler?(error)
return nil
}
}
}
internal func makeUInt16Iterator() -> UInt16Iterator {
return UInt16Iterator(reader: self)
}
}
extension BinaryReader {
internal class UInt32Iterator: Sequence, IteratorProtocol {
private let reader: BinaryReader
internal var errorHandler: ((Error) -> Void)?
fileprivate init(reader: BinaryReader) {
self.reader = reader
}
internal func next() -> UInt32? {
if !reader.hasBytesAvailable {
return nil
}
do {
return try reader.readUInt32()
} catch {
errorHandler?(error)
return nil
}
}
}
internal func makeUInt32Iterator() -> UInt32Iterator {
return UInt32Iterator(reader: self)
}
}
| 6e35052dc4faeb80db733aa9048d9265 | 25.686047 | 98 | 0.554684 | false | false | false | false |
ibari/StationToStation | refs/heads/master | StationToStation/CollaboratorsViewController.swift | gpl-2.0 | 1 | //
// CollaboratorsViewController.swift
// StationToStation
//
// Created by Ian on 6/8/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
class CollaboratorsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var headerView: StationHeaderView!
@IBOutlet weak var tableView: UITableView!
var station: Station!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "People"
self.configureHeader()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 80
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.backgroundColor = UIColor.clearColor()
self.tableView.reloadData()
}
// MARK: - Configuration
func configureHeader() {
headerView.contentView.imageView.setImageWithURL(NSURL(string: station!.imageUrl))
headerView.contentView.name = station!.name
headerView.contentView.trackCount = station!.playlist!.tracks.count
headerView.contentView.collaboratorCount = station!.collaborators!.count
headerView.contentView.commentCount = station!.comments!.count
headerView.contentView.commentsButton.addTarget(self, action: "didTapComments", forControlEvents: UIControlEvents.TouchUpInside)
headerView.contentView.collaboratorsButton.enabled = false
}
// MARK: - Actions
func didTapComments() {
var storyboard = UIStoryboard(name: "Comments", bundle: nil)
var stationCommentsVC = storyboard.instantiateViewControllerWithIdentifier("StationCommentsViewController") as! StationCommentsViewController
stationCommentsVC.station = self.station!
self.navigationController!.pushViewController(stationCommentsVC, animated: true)
}
// MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return station!.collaborators!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as! UserCell
cell.user = station!.collaborators![indexPath.row]
if indexPath.row == station!.collaborators!.count - 1 {
cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var storyboard = UIStoryboard(name: "Profile", bundle: nil)
var profileVC = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
profileVC.user = station!.collaborators![indexPath.item]
self.navigationController!.pushViewController(profileVC, animated: true)
}
}
| 785ab5a42bbe8161439488ff1e937d32 | 35.7 | 149 | 0.694217 | false | false | false | false |
shvets/WebAPI | refs/heads/master | Sources/WebAPI/HttpService2.swift | mit | 1 | import Foundation
import SwiftSoup
open class HttpService2 {
public func httpRequest(_ url: String,
headers: [String: String] = [:],
parameters: [String: String] = [:],
method: String = "GET") -> Data? {
// var dataResponse: DataResponse<Data>?
//
// if let sessionManager = sessionManager {
// let utilityQueue = DispatchQueue.global(qos: .utility)
// let semaphore = DispatchSemaphore.init(value: 0)
//
// sessionManager.request(url, method: method, parameters: parameters,
// headers: headers).validate().responseData(queue: utilityQueue) { response in
// dataResponse = response
//
// switch response.result {
// case .success:
// //print("success")
//
// if let response = response.response {
// print("Status: \(response.statusCode)")
// }
//
// case .failure:
// print("Status: failure")
// }
//
// semaphore.signal()
// }
//
// //debugPrint(request)
//
// _ = semaphore.wait(timeout: DispatchTime.distantFuture)
// }
//
// return dataResponse
var urlResponse: Data?
//httpRequest(url, headers: headers, parameters: parameters, method: method)
// print(response!.response!.allHeaderFields)
let url = URL(string: url)
var request = URLRequest(url: url!)
for (key, value) in headers {
request.setValue(key, forHTTPHeaderField: value)
}
//let session = URLSession(configuration: .default)
request.httpMethod = "GET"
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// print(error)
// print(data)
urlResponse = data
semaphore.signal()
}
task.resume()
semaphore.wait()
return urlResponse
}
public func fetchDocument(_ url: String,
headers: [String: String] = [:],
parameters: [String: String] = [:],
method: String = "GET",
encoding: String.Encoding = .utf8) throws -> Document? {
var document: Document?
if let dataResponse = httpRequest(url, headers: headers, parameters: parameters, method: method),
let html = String(data: dataResponse, encoding: encoding) {
document = try SwiftSoup.parse(html)
}
return document
}
// public func httpRequest(url: String, headers: [String: String] = [:], query: [String: String] = [:],
// data: [String: String] = [:], method: String? = "get") {
//// var response: HTTPResult
//
//// let networking = Networking(baseURL: url)
////
//// networking.get("/get") { result in
//// switch result {
//// case .success(let response):
//// let json = response.dictionaryBody
//// // Do something with JSON, you can also get arrayBody
//// case .failure(let response):
//// print(response)
//// // Handle error
//// }
//// }
//
//// if method == "get" {
//// response = SwiftHTTP.GET(url, params: query, headers: headers)
//// }
//// else if method == "post" {
//// response = SwiftHTTP.POST(url, params: query, data: data, headers: headers)
//// }
//// else if method == "put" {
//// response = SwiftHTTP.PUT(url, params: query, data: data, headers: headers)
//// }
//// else if method == "delete" {
//// response = SwiftHTTP.DELETE(url, params: query, data: data, headers: headers)
//// }
//// else {
//// response = SwiftHTTP.GET(url, params: query, headers: headers)
//// }
//
// //return response
// }
// public func buildUrl(path: String, params: [String: AnyObject] = [:]) -> String {
// let paramsArray = params.map { (key, value) -> String in
// return "\(key)=\(value)"
// }
//
// var url = path
//
// if !paramsArray.isEmpty {
// url += "?" + paramsArray.joined(separator: "&")
// }
//
// return url
// }
//
// func getPlayListUrls(_ url: String) throws -> [[String: String]] {
// var urls = [[String: String]]()
//
// let playList = try getPlayList(url)
//
// playList.enumerateLines {(line, _) in
// if line[line.startIndex] != "#" {
// urls.append(["url": line])
// }
// }
//
// return urls
// }
// func getPlayList(_ url: String, baseUrl: String="") throws -> String {
// var localBaseUrl = baseUrl
//
// if localBaseUrl.isEmpty {
// localBaseUrl = getBaseUrl(url)
// }
//
// let data = httpRequest(url: url).content
// let content = toString(data!)
//
// var newLines = [String]()
//
// content!.enumerateLines {(line, _) in
// if line[line.startIndex] == "#" {
// newLines.append(line)
// }
// else {
// newLines.append(localBaseUrl + "/" + line)
// }
// }
//
// return newLines.joined(separator: "\n")
// }
//
// func getBaseUrl(_ url: String) -> String {
// var pathComponents = url.components(separatedBy: "/")
//
// return pathComponents[0...pathComponents.count-2].joined(separator: "/")
// }
// public func fetchDocument(_ url: String, headers: [String: String] = [:], data: [String: String] = [:],
// method: String?="get", encoding: String.Encoding=String.Encoding.utf8) throws -> Document? {
// let content = fetchContent(url, headers: headers, data: data, method: method)
//
// return try toDocument(content, encoding: encoding)
// }
//
// public func fetchContent(_ url: String, headers: [String: String] = [:], data: [String: String] = [:],
// method: String?="get") -> Data? {
// return httpRequest(url: url, headers: headers, data: data, method: method).content
// }
//
// public func toDocument(_ data: Data?, encoding: String.Encoding=String.Encoding.utf8) throws -> Document? {
// return try SwiftSoup.parse(toString(data, encoding: encoding)!)
// }
//
// public func toString(_ data: Data?, encoding: String.Encoding=String.Encoding.utf8) -> String? {
// return String(data: data!, encoding: encoding)
// }
}
| bd8e9792a9d97551c20a90832be07efd | 29.318627 | 122 | 0.567664 | false | false | false | false |
radvansky-tomas/NutriFacts | refs/heads/master | nutri-facts/nutri-facts/Controls/NutriButton.swift | gpl-2.0 | 1 | //
// ALLocalizableButton.swift
// entreinfidele
//
// Created by Tomas Radvansky on 02/02/2015.
// Copyright (c) 2015 Tomas Radvansky. All rights reserved.
//
import UIKit
@IBDesignable class NutriButton: UIButton {
//MARK: Localization
@IBInspectable
var localizeString:String = "" {
didSet {
#if TARGET_INTERFACE_BUILDER
var bundle = NSBundle(forClass: self.dynamicType)
self.setTitle(bundle.localizedStringForKey(self.localizeString, value:"", table: nil), forState: UIControlState.Normal)
#else
self.setTitle(NSLocalizedString(self.localizeString, comment:""), forState: UIControlState.Normal)
#endif
}
}
//MARK: Layer parameters
@IBInspectable
var borderColor:UIColor = UIColor.clearColor() {
didSet {
self.layer.borderColor = borderColor.CGColor
}
}
@IBInspectable
var borderWidth:CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
@IBInspectable
var cornerRadius:CGFloat = 0.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
@IBInspectable
var rounded:Bool = false {
didSet {
if rounded
{
self.layer.cornerRadius = self.frame.size.width / 2
self.layer.masksToBounds = true
}
else
{
self.layer.cornerRadius = 0
self.layer.masksToBounds = false
}
}
}
//MARK: Icomoon
@IBInspectable
var iconColor:UIColor = UIColor.whiteColor() {
didSet {
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.Center
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: self.frame.height)!,
NSForegroundColorAttributeName : iconColor,
NSParagraphStyleAttributeName : style
]
self.setAttributedTitle(NSAttributedString(string: MoonIcons.allValues[icon].rawValue , attributes: textFontAttributes), forState: UIControlState.Normal)
}
}
@IBInspectable
var icon:Int = 0 {
didSet {
if icon <= MoonIcons.allValues.count-1
{
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.Center
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: self.frame.height)!,
NSForegroundColorAttributeName : iconColor,
NSParagraphStyleAttributeName : style
]
self.setAttributedTitle(NSAttributedString(string: MoonIcons.allValues[icon].rawValue , attributes: textFontAttributes), forState: UIControlState.Normal)
}
}
}
@IBInspectable
var IconsSize:Double = 16.0 {
didSet {
if icon <= MoonIcons.allValues.count-1 && icon > -1
{
self.setAttributedTitle(Globals.GetAttributedTextForIcon(NSTextAlignment.Center, iconSize: CGFloat(IconsSize), iconColor: iconColor, icon: MoonIcons.allValues[icon].rawValue), forState: UIControlState.Normal)
}
}
}
}
| f7100d2b7aad7e5ab500261658b1ba62 | 33.264706 | 224 | 0.586838 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/AssetBalanceView/AssetBalanceViewPresenter.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
public final class AssetBalanceViewPresenter {
public typealias PresentationState = AssetBalanceViewModel.State.Presentation
// MARK: - Exposed Properties
public var state: Observable<PresentationState> {
_ = setup
return stateRelay
.observe(on: MainScheduler.instance)
}
var alignment: Driver<UIStackView.Alignment> {
alignmentRelay.asDriver()
}
// MARK: - Injected
private lazy var setup: Void = {
// Map interaction state into presentation state
// and bind it to `stateRelay`.
Observable
.combineLatest(
interactor.state.catchAndReturn(.loading),
alignmentRelay.asObservable()
)
.map { [descriptors] state, alignment in
.init(
with: state,
alignment: alignment,
descriptors: descriptors
)
}
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
}()
private let interactor: AssetBalanceViewInteracting
private let descriptors: AssetBalanceViewModel.Value.Presentation.Descriptors
// MARK: - Private Accessors
private let alignmentRelay: BehaviorRelay<UIStackView.Alignment>
private let stateRelay = BehaviorRelay<PresentationState>(value: .loading)
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(
alignment: UIStackView.Alignment = .fill,
interactor: AssetBalanceViewInteracting,
descriptors: AssetBalanceViewModel.Value.Presentation.Descriptors
) {
self.interactor = interactor
self.descriptors = descriptors
alignmentRelay = BehaviorRelay<UIStackView.Alignment>(value: alignment)
}
}
| 4e97d79a920e9502d2b090e137df421b | 28.723077 | 81 | 0.642857 | false | false | false | false |
pointfreeco/swift-web | refs/heads/main | Sources/HttpPipeline/NIO.swift | mit | 1 | import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import NIO
import NIOHTTP1
import NIOHTTPCompression
import Optics
import Prelude
public func run(
_ middleware: @escaping Middleware<StatusLineOpen, ResponseEnded, Prelude.Unit, Data>,
on port: Int = 8080,
eventLoopGroup: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),
gzip: Bool = false,
baseUrl: URL
) {
do {
let reuseAddrOpt = ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR)
let bootstrap = ServerBootstrap(group: eventLoopGroup)
.serverChannelOption(ChannelOptions.backlog, value: 256)
.serverChannelOption(reuseAddrOpt, value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline().flatMap {
let handlers: [ChannelHandler] = gzip
? [HTTPResponseCompressor(), Handler(baseUrl: baseUrl, middleware: middleware)]
: [Handler(baseUrl: baseUrl, middleware: middleware)]
return channel.pipeline.addHandlers(handlers, position: .last)
}
}
.childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.childChannelOption(reuseAddrOpt, value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1)
let host = "0.0.0.0"
let serverChannel = try bootstrap.bind(host: host, port: port).wait()
print("Listening on \(host):\(port)...")
try serverChannel.closeFuture.wait()
try eventLoopGroup.syncShutdownGracefully()
} catch {
fatalError(error.localizedDescription)
}
}
private final class Handler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
let baseUrl: URL
var request: URLRequest?
let middleware: Middleware<StatusLineOpen, ResponseEnded, Prelude.Unit, Data>
init(baseUrl: URL, middleware: @escaping Middleware<StatusLineOpen, ResponseEnded, Prelude.Unit, Data>) {
self.baseUrl = baseUrl
self.middleware = middleware
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let reqPart = self.unwrapInboundIn(data)
switch reqPart {
case let .head(header):
self.request = URL(string: header.uri).map {
var req = URLRequest(url: $0)
req.httpMethod = method(from: header.method)
req.allHTTPHeaderFields = header.headers.reduce(into: [:]) { $0[$1.name] = $1.value }
let proto = req.value(forHTTPHeaderField: "X-Forwarded-Proto") ?? "http"
req.url = req.value(forHTTPHeaderField: "Host").flatMap {
URL(string: proto + "://" + $0 + header.uri)
}
return req
}
case var .body(bodyPart):
self.request = self.request |> map <<< \.httpBody %~ {
var data = $0 ?? .init()
bodyPart.readBytes(length: bodyPart.readableBytes).do { data.append(Data($0)) }
return data
}
case .end:
guard let req = self.request else {
context.channel.write(
HTTPServerResponsePart.head(
HTTPResponseHead(
version: .init(major: 1, minor: 1),
status: .init(statusCode: 307),
headers: .init([("location", self.baseUrl.absoluteString)])
)
),
promise: nil
)
_ = context.channel.writeAndFlush(HTTPServerResponsePart.end(nil)).flatMap {
context.channel.close()
}
return
}
let promise = context.eventLoop.makePromise(of: Conn<ResponseEnded, Data>.self)
self.middleware(connection(from: req)).parallel.run(promise.succeed)
_ = promise.futureResult.flatMap { conn -> EventLoopFuture<Void> in
let res = conn.response
let head = HTTPResponseHead(
version: .init(major: 1, minor: 1),
status: .init(statusCode: res.status.rawValue),
headers: .init(res.headers.map { ($0.name, $0.value) })
)
context.channel.write(HTTPServerResponsePart.head(head), promise: nil)
var buffer = context.channel.allocator.buffer(capacity: res.body.count)
buffer.writeBytes(res.body)
context.channel.write(HTTPServerResponsePart.body(.byteBuffer(buffer)), promise: nil)
return context.channel.writeAndFlush(HTTPServerResponsePart.end(nil)).flatMap {
context.channel.close()
}
}
}
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
context.close(promise: nil)
}
}
private func method(from method: HTTPMethod) -> String {
switch method {
case .GET: return "GET"
case .PUT: return "PUT"
case .ACL: return "ACL"
case .HEAD: return "HEAD"
case .POST: return "POST"
case .COPY: return "COPY"
case .LOCK: return "LOCK"
case .MOVE: return "MOVE"
case .BIND: return "BIND"
case .LINK: return "LINK"
case .PATCH: return "PATCH"
case .TRACE: return "TRACE"
case .MKCOL: return "MKCOL"
case .MERGE: return "MERGE"
case .PURGE: return "PURGE"
case .NOTIFY: return "NOTIFY"
case .SEARCH: return "SEARCH"
case .UNLOCK: return "UNLOCK"
case .REBIND: return "REBIND"
case .UNBIND: return "UNBIND"
case .REPORT: return "REPORT"
case .DELETE: return "DELETE"
case .UNLINK: return "UNLINK"
case .CONNECT: return "CONNECT"
case .MSEARCH: return "MSEARCH"
case .OPTIONS: return "OPTIONS"
case .PROPFIND: return "PROPFIND"
case .CHECKOUT: return "CHECKOUT"
case .PROPPATCH: return "PROPPATCH"
case .SUBSCRIBE: return "SUBSCRIBE"
case .MKCALENDAR: return "MKCALENDAR"
case .MKACTIVITY: return "MKACTIVITY"
case .UNSUBSCRIBE: return "UNSUBSCRIBE"
case .SOURCE: return "SOURCE"
case let .RAW(value): return value
}
}
| fd0d6574fd84b09560b3b3496e8edc0a | 33.809816 | 107 | 0.669017 | false | false | false | false |
PeeJWeeJ/SwiftyHUD | refs/heads/master | SwiftyHUD/SwiftyHUD/SwiftyHUD/SwiftyHUDModule/ProgressHUD.swift | mit | 1 | ////
//// ProgressHUD.swift
//// SVProgressHUD
////
//// Created by Paul Fechner on 12/26/15.
//// Copyright © 2015 EmbeddedSources. All rights reserved.
////
//
//import UIKit
//
//let ProgressHUDDidReceiveTouchEventNotification = "ProgressHUDDidReceiveTouchEventNotification";
//let ProgressHUDDidTouchDownInsideNotification = "ProgressHUDDidTouchDownInsideNotification";
//let ProgressHUDWillDisappearNotification = "ProgressHUDWillDisappearNotification";
//let ProgressHUDDidDisappearNotification = "ProgressHUDDidDisappearNotification";
//let ProgressHUDWillAppearNotification = "ProgressHUDWillAppearNotification";
//let ProgressHUDDidAppearNotification = "ProgressHUDDidAppearNotification";
//
//let ProgressHUDStatusUserInfoKey = "ProgressHUDStatusUserInfoKey";
//
//let ProgressHUDParallaxDepthPoints: CGFloat = 10;
//let ProgressHUDUndefinedProgress: CGFloat = -1;
//
//let url = NSBundle(forClass: ProgressHUD.classForCoder()).URLForResource("SVProgressHUD", withExtension: "bundle")
//let imageBundle = NSBundle(URL: url!)
//
//class ProgressHUD: UIView {
//
// var backgroundLayer: CALayer?
//
// var progress: CGFloat?
// var activityCount = 0
//
// var defaultStyle: ProgressHUDStyle = .Light
// var defaultMaskType: ProgressHUDMaskType = .None
// var defaultAnimationType: ProgressHUDAnimationType = .Flat
// var minimumSize = CGSize.zero
//
// var ringThickeness: CGFloat = 2
// var ringRadius: CGFloat = 18
// var ringNoTextRadius: CGFloat = 24
// var cornerRadius: CGFloat = 14
// var font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
//
// var infoImage = UIImage(contentsOfFile: (imageBundle?.pathForResource("info", ofType: "png"))!)!.imageWithRenderingMode(.AlwaysTemplate)
// var successImage = UIImage(contentsOfFile: (imageBundle?.pathForResource("success", ofType: "png"))!)!.imageWithRenderingMode(.AlwaysTemplate)
// var errorImage = UIImage(contentsOfFile: (imageBundle?.pathForResource("error", ofType: "png"))!)!.imageWithRenderingMode(.AlwaysTemplate)
// var viewForExtension: UIView?
// var minimumDismissTimeInterval = NSTimeInterval(5.0)
// var offsetFromCenter = UIOffset(horizontal: 0, vertical: 0)
//
// var fadeOutTimer: NSTimer? {
// willSet {
// if let fadeOutTimer = fadeOutTimer {
// fadeOutTimer.invalidate()
// self.fadeOutTimer = nil
// }
// }
// }
// var clear: Bool {
// get {
// return (self.defaultMaskType == .Clear || self.defaultMaskType == .None);
// }
// }
//
// private var realVisibleKeyboardHeight: CGFloat?
// var visibleKeyboardHeight: CGFloat? {
// get {
// if let keyboardWindow = (UIApplication.sharedApplication().windows.filter(){ $0.isKindOfClass(UIWindow.classForCoder()) }.first) {
// return getHeightFromViews(keyboardWindow.subviews)
// }
// else{
// return 0
// }
// }
// set { realVisibleKeyboardHeight = newValue }
// }
//
//
// var realHudView: UIView?
// var hudView: UIView? {
// get {
// if (realHudView == nil) {
// realHudView = UIView(frame: CGRectZero, layerCornerRadius: self.cornerRadius, layerMasksToBounds: true,
// autoresizingMask: [.FlexibleBottomMargin, .FlexibleTopMargin, .FlexibleRightMargin, .FlexibleLeftMargin])
// }
//
// if let realHudView = realHudView {
// realHudView.backgroundColor = self.backgroundColor
//
// if let _ = realHudView.superview {
// addSubview(realHudView)
// }
// }
// return realHudView
// }
// set { realHudView = newValue }
// }
//
//
// private var realStringLabel: UILabel?
// var stringLabel: UILabel? {
// get {
// if (realStringLabel == nil){
// realStringLabel = UILabel(frame: CGRectZero, backgroundColor: UIColor.clearColor(), adjustsFontSizeToFitWidth: true, textAlignment: .Center, baselineAdjustment: .AlignCenters, numberOfLines: 0)
// }
//
// if let realStringLabel = realStringLabel {
// realStringLabel.textColor = self.foregroundColor
// realStringLabel.font = self.font
// if let _ = realStringLabel.superview {
// hudView?.addSubview(realStringLabel)
// }
// }
// return realStringLabel
// }
// set { realStringLabel = newValue }
// }
//
//
// private var realImageView: UIImageView?
// var imageView: UIImageView? {
// get {
// if (realImageView == nil) {
// realImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 28.0, height: 28.0))
// }
// if let realImageView = realImageView {
// if let _ = realImageView.superview{
// self.hudView?.addSubview(realImageView)
// }
// }
// return realImageView
// }
// set { realImageView = newValue }
// }
//
//
// private var realOverlayView: UIControl?
// var overlayView: UIControl? {
// get {
//
// if(realOverlayView == nil){
//
// let windowBounds = UIApplication.sharedApplication().delegate?.window!?.bounds
// realOverlayView = UIControl(frame: windowBounds!, autoResizingMask: [.FlexibleWidth, .FlexibleHeight], backgroundColor: UIColor.clearColor())
// realOverlayView?.addTarget(self, action: Selector("overlayViewDidReceiveTouchEvent"), forControlEvents: .TouchDown)
// }
// return realOverlayView;
// }
// set { realOverlayView = newValue }
// }
//
//
// private var realHudBackgroundColor: UIColor?
// var hudBackgroundColor: UIColor? {
// get {
// switch defaultStyle {
// case .Light:
// return UIColor.whiteColor()
// case .Dark:
// return UIColor.blackColor()
// default:
// return self.realHudBackgroundColor
// }
// }
// set{ realHudBackgroundColor = newValue }
// }
//
//
// private var realForegroundColor: UIColor = UIColor.blackColor()
// var foregroundColor: UIColor {
// get {
// switch defaultStyle {
// case .Light:
// return UIColor.blackColor()
// case .Dark:
// return UIColor.whiteColor()
// default:
// return self.realForegroundColor
// }
//
// }
// set { realForegroundColor = newValue}
// }
//
//
// private var realIndefinateAnimatedView : UIView?
// var indefiniteAnimatedView: UIView? {
// get{
// if (realIndefinateAnimatedView == nil) {
// realIndefinateAnimatedView = (defaultAnimationType == .Flat) ? createIndefiniteAnimatedView() : createActivityIndicatorView()
// }
// return realIndefinateAnimatedView
// }
// set { realIndefinateAnimatedView = newValue }
// }
//
//
// private var realRingLayer: CAShapeLayer?
// var ringLayer: CAShapeLayer? {
// get {
// if realRingLayer == nil {
// realBackgroundRingLayer = createHudLayer(hudView, radius: ringRadius, strokeEnd: 1)
// }
// if let realRingLayer = realRingLayer {
// updateLayer(realRingLayer, strokeColor: foregroundColor.CGColor, lineWidth: ringThickeness)
// }
// return realRingLayer
// }
// set{ realRingLayer = newValue }
// }
//
//
// private var realBackgroundRingLayer: CAShapeLayer?
// var backgroundRingLayer: CAShapeLayer? {
// get{
// if (realBackgroundRingLayer == nil){
// realBackgroundRingLayer = createHudLayer(hudView, radius: ringRadius, strokeEnd: 1)
// }
//
// if let realBackgroundRingLayer = realBackgroundRingLayer {
// updateLayer(realBackgroundRingLayer, strokeColor: foregroundColor.colorWithAlphaComponent(0.1).CGColor, lineWidth: ringThickeness)
// }
// return realBackgroundRingLayer
// }
// set{ realBackgroundRingLayer = newValue }
// }
//
// override init(frame: CGRect) {
// super.init(frame: frame)
// backgroundColor = UIColor.whiteColor()
//
//
// userInteractionEnabled = false
// alpha = 0.0
// activityCount = 0
// accessibilityIdentifier = "SVProgressHUD"
// accessibilityLabel = "SVProgressHUD"
// isAccessibilityElement = true
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
//
// func createHudLayer(addingView: UIView?, radius: CGFloat, strokeEnd: CGFloat) -> CAShapeLayer? {
//
// var layer: CAShapeLayer?
// if let addingView = addingView {
// layer = createRingLayer(addingView.center, radius: radius, strokeEnd: strokeEnd)
// addingView.layer.addSublayer(layer!)
// }
// return layer
// }
//
// func updateLayer(layer: CAShapeLayer, strokeColor: CGColor, lineWidth: CGFloat) {
//
// layer.strokeColor = strokeColor
// layer.lineWidth = lineWidth
// }
//
// func updateHUDFrame() {
//
// var hudWidth = 100.0
// var hudHeight = 100.0
// let stringHeightBuffer = 20.0
// let stringAndContentHeightBuffer = 80.0
//// let labelRect = CGRectZero
//
// let progressUsed = (self.progress != ProgressHUDUndefinedProgress) && (self.progress >= 0.0)
//
// let stringWidth: Double = Double((self.stringLabel?.frame.width)!)
// let stringHeight = Double((self.stringLabel?.frame.height)!)
//
// if ((self.imageView != nil && self.imageView?.image != nil) || progressUsed){
// hudHeight = stringAndContentHeightBuffer + stringHeight
// }
// else{
// hudHeight = stringHeightBuffer + stringHeight
// }
//
// if(stringWidth > hudWidth){
// hudWidth = ceil(stringWidth / 2) * 2.0
// }
//
// // Update values on subviews
// self.hudView!.bounds = CGRectMake(0.0, 0.0, [self.minimumSize.width, CGFloat(hudWidth)].maxElement()!, [self.minimumSize.height, CGFloat(hudHeight)].maxElement()!);
//// labelRect.size.width += max(CGFloat(0), CGFloat(self.minimumSize.width - hudWidth));
//// updateBlurBounds()
//
// if let imageView = imageView, hudView = hudView {
// if let _ = self.stringLabel?.text{
// imageView.center = CGPointMake(CGRectGetWidth(hudView.bounds)/2, 36.0)
// }
// else{
// imageView.center = CGPointMake(CGRectGetWidth(hudView.bounds)/2, CGRectGetHeight(hudView.bounds)/2)
// }
// }
//
// if let stringLabel = stringLabel {
// stringLabel.hidden = false
// }
//
// CATransaction.begin()
// CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
//
// if let _ = stringLabel?.text {
// if(self.defaultAnimationType == .Flat){
//
// if let view = indefiniteAnimatedView as? IndefiniteAnimatedView {
// view.radius = self.ringNoTextRadius
// }
// indefiniteAnimatedView?.sizeToFit()
// }
//
// let viewCenter = CGPointMake((CGRectGetWidth(self.hudView!.bounds) / 2 ), 36.0)
// indefiniteAnimatedView?.center = viewCenter
//
// if(self.progress != ProgressHUDUndefinedProgress){
// self.ringLayer!.position = CGPointMake((CGRectGetWidth(self.hudView!.bounds) / 2), 36.0);
// self.backgroundRingLayer!.position = (self.ringLayer?.position)!
// }
// }
// else {
// if(self.defaultAnimationType == .Flat){
//
// if let view = indefiniteAnimatedView as? IndefiniteAnimatedView {
// view.radius = self.ringNoTextRadius
// }
// indefiniteAnimatedView?.sizeToFit()
// }
//
// let viewCenter = CGPointMake((CGRectGetWidth(self.hudView!.bounds) / 2), CGRectGetHeight(self.hudView!.bounds) / 2)
// indefiniteAnimatedView?.center = viewCenter
//
// if(self.progress != ProgressHUDUndefinedProgress){
// self.ringLayer!.position = CGPointMake((CGRectGetWidth(self.hudView!.bounds) / 2), CGRectGetHeight(self.hudView!.bounds) / 2)
// self.backgroundRingLayer!.position = (self.ringLayer?.position)!
// }
// }
//
// CATransaction.commit()
// }
//
// func updateMask(){
//
// if let _ = backgroundLayer {
// backgroundLayer?.removeFromSuperlayer()
// backgroundLayer = nil
// }
// switch defaultMaskType {
//
// case .Black:
// self.backgroundLayer = CALayer(frame: self.bounds, backgroundColor: UIColor(white: 0, alpha: 0.5).CGColor, needsDisplay: true)
// self.layer.insertSublayer(backgroundLayer!, atIndex: 0)
// break;
//
// case .Gradient:
// var gradientCenter = self.center;
// gradientCenter.y = (self.bounds.size.height - self.visibleKeyboardHeight!) / 2;
// backgroundLayer = RadialGradientLayer(gradientCenter: gradientCenter, frame: self.bounds, needsDisplay: true)
// layer.insertSublayer(self.backgroundLayer!, atIndex: 0)
// break
//
// default:
// break
//
// }
// }
//
// func updateBlurBounds(){
//
// if(defaultStyle != .Custom){
// hudView?.backgroundColor = UIColor.clearColor()
//
// hudView?.subviews.forEach({ (view: UIView) -> () in
// if let _ = view as? UIVisualEffectView {
// view.removeFromSuperview()
// }
// })
//
// if(self.backgroundColor != UIColor.clearColor()){
// self.hudView?.addBlurEffect(true, blurStyle: getBlurStyle())
// }
// }
// }
//
// func getBlurStyle() -> UIBlurEffectStyle{
//
// return (self.defaultStyle == .Dark) ? .Dark : .Light
// }
//
// func updateMotionEffectsForOrientation(orientation: UIInterfaceOrientation){
//
// let isPortrait = UIInterfaceOrientationIsPortrait(orientation)
//
// let xMotionEffectType: UIInterpolatingMotionEffectType = (isPortrait) ? .TiltAlongHorizontalAxis : .TiltAlongVerticalAxis
// let yMotionEffectType: UIInterpolatingMotionEffectType = (isPortrait) ? .TiltAlongVerticalAxis : .TiltAlongHorizontalAxis
//
// updateMotionEffect(xMotionEffectType, yMotionEffectType: yMotionEffectType)
// }
//
// func updateMotionEffect(xMotionEffectType: UIInterpolatingMotionEffectType, yMotionEffectType: UIInterpolatingMotionEffectType) {
//
// let effectX = UIInterpolatingMotionEffect(keyPath: "center.x", type: xMotionEffectType)
// effectX.minimumRelativeValue = -ProgressHUDParallaxDepthPoints
// effectX.maximumRelativeValue = ProgressHUDParallaxDepthPoints
//
// let effectY = UIInterpolatingMotionEffect(keyPath: "center.y", type: yMotionEffectType)
// effectY.minimumRelativeValue = -ProgressHUDParallaxDepthPoints
// effectY.maximumRelativeValue = ProgressHUDParallaxDepthPoints
//
// hudView?.motionEffects = [effectX, effectY]
// }
//
// func setStatus(text: String) {
// self.stringLabel?.text = text
// updateHUDFrame()
// }
//
// func registerNotifications() {
//
// [UIKeyboardDidShowNotification, UIApplicationDidChangeStatusBarOrientationNotification,
// UIApplicationDidBecomeActiveNotification, UIKeyboardWillHideNotification,
// UIKeyboardDidHideNotification, UIKeyboardWillShowNotification, UIKeyboardDidShowNotification]
// .forEach(addNotificationForPositionHud)
// }
//
// func addNotificationForPositionHud(notificationName: String){
// NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("positionHud"), name: notificationName, object: nil)
// }
//
// func getNotificationUserInfo() -> [String : String]? {
//
// if let text = self.stringLabel?.text {
// return [SVProgressHUDStatusUserInfoKey : text]
// }
// else {
// return nil
// }
// }
//
// func positionHud(notification: NSNotification?){
//
// var keyboardHeight = CGFloat(0.0)
// let animationDuration = 0.0
//
// self.frame = (UIApplication.sharedApplication().delegate?.window!!.bounds)!
// let orientation = UIApplication.sharedApplication().statusBarOrientation
//
//// let ignoreOrientation = true
//
// if let notification = notification {
// let keyboardInfo = notification.userInfo
// let keyboardFrame = keyboardInfo![UIKeyboardFrameBeginUserInfoKey]?.CGRectValue
//// let animationDuration = keyboardInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
//
// if notification.name == UIKeyboardAnimationDurationUserInfoKey || notification.name == UIKeyboardDidShowNotification {
// keyboardHeight = (keyboardFrame?.height)!
// }
// }
// else{
// keyboardHeight = self.visibleKeyboardHeight!;
// }
//
// let orientationFrame = self.bounds
// let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
// updateMotionEffectsForOrientation(orientation)
// updateMotionEffect(.TiltAlongHorizontalAxis, yMotionEffectType: .TiltAlongHorizontalAxis)
//
// var activeHeight = orientationFrame.height
// if(keyboardHeight > 0){
// activeHeight += statusBarFrame.height
// }
// activeHeight -= keyboardHeight
// let posX = orientationFrame.width / 2.0
// let posY = floor(activeHeight * 0.45)
//
// let rotateAngle = CGFloat(0.0)
// let newCenter = CGPoint(x: posX, y: posY)
//
// if let _ = notification {
// UIView.animateWithDuration(animationDuration, delay: 0, options: .AllowUserInteraction, animations: { () -> Void in
// self.moveToPoint(newCenter, rotateAngle: rotateAngle)
// self.hudView!.setNeedsDisplay()
// }, completion: nil)
// }
// else{
// moveToPoint(newCenter, rotateAngle: rotateAngle)
// self.hudView?.setNeedsDisplay()
// }
//
// updateMask()
// }
//
// func moveToPoint(newCenter: CGPoint, rotateAngle: CGFloat) {
//
// hudView?.transform = CGAffineTransformMakeRotation(rotateAngle)
// hudView?.center = CGPoint(x: newCenter.x + offsetFromCenter.horizontal, y: newCenter.y + offsetFromCenter.vertical)
// }
//
// func overlayViewDidReceiveTouchEvent(sender: AnyObject, event: UIEvent) {
//
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDDidReceiveTouchEventNotification, object: event)
// let touch = event.allTouches()?.first
// let touchLocation = touch?.locationInView(self)
// if((hudView?.frame.contains(touchLocation!)) != nil){
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDDidTouchDownInsideNotification, object: event)
// }
// }
//
// func showProgress(progress: Float, status: String?) {
//
// if let view = overlayView?.superview {
// view.bringSubviewToFront(overlayView!)
//
// }
// else{
//
// for window in UIApplication.sharedApplication().windows.reverse() {
// let windowOnMainScreen = window.screen == UIScreen.mainScreen()
// let windowIsVisible = !window.hidden && window.alpha > 0
// let windowLevelNormal = window.windowLevel == UIWindowLevelNormal
//
// if(windowOnMainScreen && windowIsVisible && windowLevelNormal){
// window.addSubview(overlayView!)
// break;
// }
// }
// }
//
// if let _ = self.superview {
// overlayView?.addSubview(self)
// }
//
// if let _ = self.fadeOutTimer {
// activityCount = 0
// }
//
// fadeOutTimer = nil
// self.imageView?.hidden = true
// self.progress = CGFloat(progress)
//
// stringLabel?.text = status
// updateHUDFrame()
//
// if (progress >= 0) {
// imageView?.image = nil
// imageView?.hidden = false
// indefiniteAnimatedView?.removeFromSuperview()
// if let view = indefiniteAnimatedView as? UIActivityIndicatorView {
// view.stopAnimating()
// }
//
// }
//
// ringLayer?.strokeEnd = CGFloat(progress)
// activityCount += 1
// if (progress != 0){
// activityCount += 1
// cancelRingLayerAnimation()
// hudView?.addSubview(indefiniteAnimatedView!)
// if let view = indefiniteAnimatedView as? UIActivityIndicatorView {
// view.stopAnimating()
// }
// }
//
// if(self.defaultMaskType != .None){
// overlayView?.userInteractionEnabled = true
// accessibilityLabel = status
// isAccessibilityElement = true
// }
// else{
// overlayView?.userInteractionEnabled = false
// hudView?.accessibilityLabel = status
// hudView?.isAccessibilityElement = true
// }
//
// overlayView?.hidden = false
// overlayView?.backgroundColor = UIColor.clearColor()
// positionHud(nil)
//
// if(self.alpha != 1 || self.hudView?.alpha != 1){
// let userInfo = getNotificationUserInfo()
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDWillAppearNotification, object: nil, userInfo: userInfo)
// registerNotifications()
// hudView?.transform = CGAffineTransformScale((hudView?.transform)!, 1.3, 1.3)
//
// if(clear){
// self.alpha = 1
// self.hudView?.alpha = 0
// }
//
// let weakSelf: ProgressHUD? = self
// UIView.animateWithDuration(0.15, delay: 0, options: [.AllowUserInteraction, .CurveEaseOut, .BeginFromCurrentState], animations: { () -> Void in
// if let strongSelf = weakSelf {
// strongSelf.hudView!.transform = CGAffineTransformScale(strongSelf.hudView!.transform, 1 / 1.3, 1 / 1.3)
//
// if (strongSelf.clear) {
// strongSelf.hudView!.alpha = 1
// }
// else{
// strongSelf.alpha = 1
// }
// }
//
// }, completion: { (Bool) -> Void in
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDDidAppearNotification, object: nil, userInfo: userInfo)
// UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, status)
// self.setNeedsDisplay()
// })
// }
// }
//
// func showImage(var image: UIImage, status: String, duration: NSTimeInterval) {
//
// self.progress = ProgressHUDUndefinedProgress
// cancelRingLayerAnimation()
//
// if(!self.classForCoder.isVisible()){
// self.classForCoder.show()
// }
//
// let tintColor = self.foregroundColor
// if(image.renderingMode != .AlwaysTemplate) {
// image = image.imageWithRenderingMode(.AlwaysTemplate)
// }
// self.imageView?.tintColor = tintColor
//
// imageView?.image = image
// imageView?.hidden = false
//
// stringLabel?.text = status
// updateHUDFrame()
// indefiniteAnimatedView?.removeFromSuperview()
// if let view = indefiniteAnimatedView as? UIActivityIndicatorView {
// view.stopAnimating()
// }
//
// if(self.defaultMaskType != .None){
// overlayView?.userInteractionEnabled = false
// self.accessibilityLabel = status
// self.isAccessibilityElement = true
// }
// else{
// self.overlayView?.userInteractionEnabled = false
// self.hudView?.accessibilityLabel = status
// self.hudView?.isAccessibilityElement = true
// }
//
// UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, status)
//
// self.fadeOutTimer = NSTimer(timeInterval: duration, target: self, selector: Selector("dismiss"), userInfo: nil, repeats: false)
// NSRunLoop.mainRunLoop().addTimer(fadeOutTimer!, forMode: NSRunLoopCommonModes)
//
// }
//
// func dismiss(){
// dismissWithDelay(0)
// }
//
// func dismissWithDelay(delay: NSTimeInterval) {
//
// let userInfo = self.getNotificationUserInfo()
//
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDWillDisappearNotification, object: nil, userInfo: userInfo)
//
// activityCount = 0
// let weakSelf: ProgressHUD? = self
// UIView.animateWithDuration(0.15, delay: delay, options: [.CurveEaseIn, .AllowUserInteraction], animations: { () -> Void in
//
// if let strongSelf = weakSelf {
// strongSelf.hudView!.transform = CGAffineTransformScale((self.hudView?.transform)!, 0.8, 0.8)
// if(strongSelf.clear){
// strongSelf.hudView!.alpha = 0.0
// }
// else{
// strongSelf.alpha = 0.0
// }
// }
// }) { (Bool) -> Void in
// if let strongSelf = weakSelf {
// if(strongSelf.alpha == 0.0 || strongSelf.hudView?.alpha == 0.0){
// strongSelf.alpha = 0.0
// strongSelf.hudView?.alpha = 0.0
//
// NSNotificationCenter.defaultCenter().removeObserver(strongSelf)
// strongSelf.cancelRingLayerAnimation()
//
// self.resetViews()
//
// UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// NSNotificationCenter.defaultCenter().postNotificationName(SVProgressHUDDidDisappearNotification, object: nil, userInfo: userInfo)
//
// let rootController = UIApplication.sharedApplication().keyWindow?.rootViewController
// rootController?.setNeedsStatusBarAppearanceUpdate()
//
// }
// }
// }
// }
//
// func resetViews(){
// self.hudView?.removeFromSuperview()
// self.hudView = nil
//
// self.overlayView?.removeFromSuperview()
// self.overlayView = nil
//
// self.indefiniteAnimatedView?.removeFromSuperview()
// self.indefiniteAnimatedView = nil
// }
//
//
//
// func createActivityIndicatorView() -> UIActivityIndicatorView{
//
// let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
// indicatorView.color = self.foregroundColor
// indicatorView.sizeToFit()
// return indicatorView
// }
//
// func createIndefiniteAnimatedView() -> IndefiniteAnimatedView {
//
// let animatedView = IndefiniteAnimatedView(frame: CGRectZero)
// animatedView.strokeColor = foregroundColor
// let radius: CGFloat
// if let _ = self.stringLabel?.text {
// radius = self.ringRadius
// }
// else{
// radius = self.ringNoTextRadius
// }
// animatedView.refresh(radius, strokeThickness: ringThickeness)
// return animatedView
// }
//
// func cancelRingLayerAnimation(){
// CATransaction.begin()
// CATransaction.setDisableActions(true)
// hudView?.layer.removeAllAnimations()
// ringLayer?.strokeEnd = 0.0
//
// if let _ = ringLayer?.superlayer {
// ringLayer?.removeFromSuperlayer()
// }
// ringLayer = nil
//
// if let _ = backgroundRingLayer?.superlayer{
// backgroundRingLayer?.removeFromSuperlayer()
// }
// backgroundRingLayer = nil
//
// CATransaction.commit()
// }
//
// func createRingLayer(center: CGPoint, radius: CGFloat, strokeEnd: CGFloat) -> CAShapeLayer {
//
// let smoothedPath = UIBezierPath(arcCenter: CGPoint(x: radius, y: radius), radius: radius, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(M_PI + M_PI_2), clockwise: true)
//
// let frame = CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2)
// let slice = CAShapeLayer(contentsScale: UIScreen.mainScreen().scale, frame: frame, fillColor: UIColor.clearColor().CGColor, lineCap: kCALineCapRound, lineJoin: kCALineJoinBevel, path: smoothedPath.CGPath, strokeEnd: strokeEnd)
//
// return slice
// }
//
// func getHeightFromViews(views: [UIView]) -> CGFloat {
//
// var height: CGFloat = 0
// views.forEach { (view) -> () in
// if (view.isKindOfClass(NSClassFromString("UIPeripheralHostView")!) || view.isKindOfClass(NSClassFromString("UIKeyboard")!)){
// height = view.bounds.height
// return
// }
// else if( view.isKindOfClass(NSClassFromString("UIInputSetContainerView")!)){
// height = getHeightFromViews(view.subviews)
// return
// }
// }
// return height
// }
//
//}
| 152f1e0513e545cd7658b478039a4b37 | 31.779618 | 230 | 0.700218 | false | false | false | false |
movabletype/smartphone-app | refs/heads/master | MT_iOS/MT_iOS/Classes/Model/EntryCategoryItem.swift | mit | 1 | //
// EntryCategoryItem.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/02.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class EntryCategoryItem: BaseEntryItem {
var selected = [Category]()
override init() {
super.init()
type = "category"
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(self.selected, forKey: "selected")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.selected = aDecoder.decodeObjectForKey("selected") as! [Category]
}
override func value()-> String {
var array = [String]()
for item in selected {
array.append(item.label)
}
return array.joinWithSeparator(",")
}
override func dispValue()-> String {
return self.value()
}
override func makeParams()-> [String : AnyObject] {
var categories = [[String: String]]()
for item in selected {
categories.append(["id":item.id])
}
return ["categories":categories]
}
override func clear() {
selected.removeAll(keepCapacity: false)
}
}
| 33da0e1cdc3a4cc22919b12373c66d8a | 22.924528 | 78 | 0.582019 | false | false | false | false |
multinerd/Mia | refs/heads/master | Mia/Extensions/Foundation/Date/Date+Constants.swift | mit | 1 | import Foundation
extension Date {
// MARK: Intervals In Seconds
internal static let minuteInSeconds: Double = 60
internal static let hourInSeconds: Double = 3600
internal static let dayInSeconds: Double = 86400
internal static let weekInSeconds: Double = 604800
internal static let yearInSeconds: Double = 31556926
}
| d814988855296c96d54b2cb22eb6f4f1 | 30.272727 | 56 | 0.747093 | false | false | false | false |
mamouneyya/TheSkillsProof | refs/heads/master | SouqTask/Modules/Common/Helpers/BackgroundFetcher.swift | mit | 1 | //
// BackgroundFetcher.swift
// SouqTask
//
// Created by Ma'moun Diraneyya on 3/6/16.
// Copyright © 2016 Mamouneyya. All rights reserved.
//
import UIKit
class BackgroundFetcher {
// MARK: - Public Vars
/// Singleton's class shared instance
static let sharedInstance = BackgroundFetcher()
typealias FetchResultHandler = (UIBackgroundFetchResult) -> ()
typealias FetchProductHandler = (success: Bool, updated: Bool) -> ()
private init() {}
func updateTrackedPricesForFavoritedProducts(completion: FetchResultHandler) {
FavoritesManager.asyncGetAllProductsInFavorite { (products, error) -> () in
if let products = products where products.count > 0 {
var requestsCount = 0
var succeededRequestsCount = 0
var updatedAtLeastOne = false
for product in products {
self.requestProductWithUpdatingPricesIfNeeded(product.id, completion: { (success, updated) -> () in
requestsCount++
if success {
succeededRequestsCount++
}
if updated {
updatedAtLeastOne = true
}
if requestsCount == products.count {
// be forgiveness with up to two failed requests
if succeededRequestsCount >= products.count - 2 {
if updatedAtLeastOne {
completion(UIBackgroundFetchResult.NewData)
} else {
completion(UIBackgroundFetchResult.NoData)
}
} else {
completion(UIBackgroundFetchResult.Failed)
}
}
})
}
} else if error != nil {
completion(UIBackgroundFetchResult.Failed)
} else {
completion(UIBackgroundFetchResult.NoData)
}
}
}
private func requestProductWithUpdatingPricesIfNeeded(productId: String, completion: FetchProductHandler? = nil) {
Networker.request(Product.Request.getProduct(productId: productId)).responseObject { (response: Response<Product, NSError>) -> Void in
switch response.result {
case .Success(let product):
product.updateTrackedPrices() { (updated) -> () in
//print("Item updated: \(updated)")
completion?(success: true, updated: updated)
}
case .Failure(_):
//print("Item update failed!: \(productId)")
completion?(success: false, updated: false)
}
}
}
}
| 290694e93f56e8720b26656fcf4a779c | 37.275 | 142 | 0.489549 | false | false | false | false |
benjaminsnorris/SharedHelpers | refs/heads/master | Sources/Date+Helpers.swift | mit | 1 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
public extension Date {
// MARK: - Formatters
static fileprivate var ISO8601MillisecondFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
static fileprivate var ISO8601SecondFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
static fileprivate var ISO8601YearMonthDayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
static fileprivate var mediumDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
static fileprivate var dateAndTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}()
static fileprivate var fullDateAndTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .short
return formatter
}()
static fileprivate var fullDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .full
return formatter
}()
static fileprivate var timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter
}()
static fileprivate var dayAndMonthFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM d", options: 0, locale: Locale.current)
return formatter
}()
static fileprivate var julianDayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "g"
return formatter
}()
static fileprivate let parsingFormatters = [ISO8601MillisecondFormatter, ISO8601SecondFormatter, ISO8601YearMonthDayFormatter]
static func fromISO8601String(_ dateString: String?) -> Date? {
guard let dateString = dateString else { return nil }
for formatter in parsingFormatters {
if let date = formatter.date(from: dateString) {
return date
}
}
return .none
}
static func fromMillisecondsSince1970(_ milliseconds: Double) -> Date {
let dateSeconds = milliseconds / 1000.0
let dateInterval = TimeInterval(dateSeconds)
let date = Date(timeIntervalSince1970: dateInterval)
return date
}
// MARK: - Formatted computed vars
/// E.g. "3:30 PM"
var timeString: String {
return Date.timeFormatter.string(from: self)
}
// E.g. "Nov 23, 1937"
var monthDayYearString: String {
return Date.mediumDateFormatter.string(from: self)
}
/// E.g. "Nov 23, 1937, 3:30 PM"
var dateAndTimeString: String {
return Date.dateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937 at 3:30 PM"
var fullDateAndTimeString: String {
return Date.fullDateAndTimeFormatter.string(from: self)
}
/// E.g. "Tuesday, November 23, 1937"
var fullDateString: String {
return Date.fullDateFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00-0700"
var iso8601DateAndTimeString: String {
return Date.ISO8601SecondFormatter.string(from: self)
}
/// E.g. "1937-11-23T15:30:00.023-0700"
var iso8601MillisecondString: String {
return Date.ISO8601MillisecondFormatter.string(from: self)
}
/// E.g. "1937-11-23"
var iso8601DateString: String {
return Date.ISO8601YearMonthDayFormatter.string(from: self)
}
var millisecondsSince1970: TimeInterval {
return round(self.timeIntervalSince1970 * 1000)
}
/// E.g. "Nov 23"
var dayAndMonthString: String {
return Date.dayAndMonthFormatter.string(from: self)
}
/// `Today`, `Yesterday`, `Tomorrow`, or `nil`
var relativeDayString: String? {
let calendar = Calendar.autoupdatingCurrent
if calendar.isDateInYesterday(self) {
return NSLocalizedString("Yesterday", comment: "Relative date string for previous day")
}
if calendar.isDateInToday(self) {
return NSLocalizedString("Today", comment: "Relative date string for current day")
}
if calendar.isDateInTomorrow(self) {
return NSLocalizedString("Tomorrow", comment: "Relative date string for next day")
}
return nil
}
/// `Today`, `Yesterday`, `Tomorrow`, or month and day (e.g. Aug 15)
var relativeDayAndMonthString: String {
if let relative = relativeDayString {
return relative
}
return dayAndMonthString
}
/// `Today`, `Yesterday`, `Tomorrow`, or month and day and year (e.g. Aug 15, 1927)
var relativeMonthDayYearString: String {
if let relative = relativeDayString {
return relative
}
return monthDayYearString
}
/// `Today`, `Yesterday`, `Tomorrow`, or month and day, along with time (e.g. Aug 15, 3:30 PM)
var relativeDayAndTimeString: String {
return String.localizedStringWithFormat(NSLocalizedString("%@, %@", comment: "Relative date and time string. First parameter is relative date, second is time."), relativeDayAndMonthString, timeString)
}
// MARK: - Helper computed vars
var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
var isYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
var isTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}
var endOfDay: Date {
let nextDay = Calendar.current.date(byAdding: .day, value: 1, to: self)!
return nextDay.startOfDay
}
var julianDay: Int {
let dayString = Date.julianDayFormatter.string(from: self)
return Int(dayString) ?? 0
}
var isInCurrentMonth: Bool {
let now = Date()
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.year, .month], from: now)
guard let startOfMonth = calendar.date(from: components),
let startOfNextMonth = calendar.date(byAdding: .month, value: 1, to: startOfMonth)
else { return false }
return self >= startOfMonth && self < startOfNextMonth
}
/// The hour of the date
var hour: Int {
return Calendar.current.component(.hour, from: self)
}
/// The minute of the date
var minute: Int {
return Calendar.current.component(.minute, from: self)
}
/// Rounds sender to the next half hour ex. 10:12 -> 10:30
var nextHalfHour: Date {
let currentMinutes = Calendar.current.component(.minute, from: self)
guard currentMinutes != 0 && currentMinutes != 30 else { return self }
if currentMinutes < 30, let next30Date = Calendar.current.date(bySetting: .minute, value: 30, of: self) {
return next30Date
} else if let nextHourDate = Calendar.current.date(byAdding: .minute, value: 60 - currentMinutes, to: self) {
return nextHourDate
} else {
return self
}
}
// MARK: - Functions
func isSameDay(as date: Date) -> Bool {
return Calendar.current.isDate(date, inSameDayAs: self)
}
}
// MARK: - Time intervals on Int
public extension Int {
var seconds: TimeInterval {
return TimeInterval(self)
}
var minutes: TimeInterval {
return TimeInterval(self * 60)
}
var hours: TimeInterval {
return TimeInterval(minutes * 60)
}
var days: TimeInterval {
return TimeInterval(hours * 24)
}
var weeks: TimeInterval {
return TimeInterval(days * 7)
}
}
| 7ea713d0d6ba84b8e8ef22da819a0c64 | 29.403571 | 208 | 0.614942 | false | false | false | false |
meantheory/octopus | refs/heads/master | repeats.swift | apache-2.0 | 2 | class Many<T:Parser> : Parser {
typealias Target = [T.Target]
let body: T
let emptyOk: Bool
init(body:T, emptyOk:Bool) {
self.body = body
self.emptyOk = emptyOk
}
func parse(stream:CharStream) -> Target? {
var result = Target()
while let r = body.parse(stream) {
result.append(r)
}
if !emptyOk && result.count == 0 {
return nil
}
return result
}
}
func many<T:Parser>(body:T) -> Many<T> {
return Many(body:body, emptyOk:true)
}
func many1<T:Parser>(body:T) -> Many<T> {
return Many(body:body, emptyOk:false)
}
class SepBy<T:Parser, S:Parser> : Parser {
typealias Target = [T.Target]
let item: T
let sep: S
let pair: FollowedBySecond<S,T>
init(item:T, sep:S) {
self.item = item
self.sep = sep
self.pair = sep >~ item
}
func parse(stream:CharStream) -> Target? {
var result = Target()
if let x = item.parse(stream) {
result.append(x)
while let next = pair.parse(stream) {
result.append(next)
}
}
return result
}
}
func sepby<T:Parser, S:Parser>(item:T, sep:S) -> SepBy<T,S> {
return SepBy(item:item, sep:sep)
}
| e0843d971059136c70c2dde910099c31 | 18.559322 | 61 | 0.599653 | false | false | false | false |
DerekSelander/FrameworkFun | refs/heads/master | FrameworkFun/ViewController.swift | mit | 1 | /**
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import SuperNeatOFramework
class ViewController: UIViewController {
@IBOutlet weak var doggieImageView: UIImageView!
let neatoClass = NeatOClass()
override func viewDidLoad() {
super.viewDidLoad()
//*****************************************************************
// MARK: - Section 0: Inspecting load commands in executable
//*****************************************************************
//*****************************************************************
// MARK: - Section 1: Dynamic linking
//*****************************************************************
// let text = "hello, world"
// let cstring = text.cString(using: .utf8)
// let charArray = UnsafeMutablePointer<Int8>(mutating: cstring)
// let count = strcnt(charArray)
// print("Count of: \"\(text)\" is: \(count)")
//*****************************************************************
// MARK: - Section 2: Dlopen & Dlsym w/ C
//*****************************************************************
//// TODO: 1. What's the framework responsible for "strcat" C function?
// let handle = dlopen("TODO", RTLD_NOW)
// assert(handle != nil)
// let strcat_address = dlsym(handle, "strcat")
//
//// TODO: 2. How do we cast/call a method queried at runtime through Swift?
// typealias strcatAlias = @convention(c)(UnsafeMutablePointer<Int8>, UnsafeMutablePointer<Int8>) -> UnsafeMutablePointer<Int8>
//
// let strcat_function = unsafeBitCast(strcat_address, to: strcatAlias.self)
// let cstr = strcat_function("hello".cstr, ", world".cstr)
// let str = String(utf8String: cstr)!
// print("\(str)")
//*****************************************************************
// MARK: - Section 3: Dlopen & Dlsym w/ Swift
//*****************************************************************
// TODO: 3. Why can't you execute this method?
// self.neatoClass.doCrazyCoolThing()
//
// let handle = dlopen(Bundle.main.privateFrameworksPath! + "/SuperNeatOFramework.framework/SuperNeatOFramework", RTLD_NOW)
// assert(handle != nil)
//
// TODO: 4 What's the symbol name for this swift function?
// let privateFunction = dlsym(handle, "TODO")
// typealias privateFunctionAlias = @convention(c)() -> Void
// let doSuperCoolThing = unsafeBitCast(privateFunction, to: privateFunctionAlias.self)
// TODO: 5 Will this work for an Object oriented language?
// doSuperCoolThing()
//*****************************************************************
// MARK: - Section 4: Exploring Private Frameworks
//*****************************************************************
//// TODO: 6 What's the location of the private frameworks directory on an actual iOS Device?
// let privateFrameworks = try! FileManager.default.contentsOfDirectory(atPath: "TODO")
// for framework in privateFrameworks {
// let name = framework.replacingOccurrences(of: ".framework", with: "")
// let fullPath = "/System/Library/PrivateFrameworks/" + framework + "/" + name
// dlopen(fullPath, RTLD_NOW)
// }
// print("*****************************\nDone!")
}
}
//*****************************************************************
// MARK: - String Extensions
//*****************************************************************
extension String {
var cstr: UnsafeMutablePointer<Int8> {
return strdup(self.cString(using: .utf8))
}
}
//*****************************************************************
// MARK: - UIView Extensions
//*****************************************************************
extension UIView {
func overlay(view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.contentMode = contentMode
addSubview(view)
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: centerXAnchor),
view.centerYAnchor.constraint(equalTo: centerYAnchor),
view.widthAnchor.constraint(equalTo: widthAnchor),
view.heightAnchor.constraint(equalTo: heightAnchor)
])
}
}
| 08a3d589b5d75d77b15a8b154ece5327 | 40.44 | 130 | 0.567375 | false | false | false | false |
JustasL/mapbox-navigation-ios | refs/heads/master | MapboxNavigation/Style.swift | isc | 1 | import UIKit
fileprivate extension CGFloat {
fileprivate static var defaultManeuverViewHeight: CGFloat = 100
}
extension UIColor {
class var defaultRouteCasing: UIColor { get { return .defaultTintStroke } }
class var defaultRouteLayer: UIColor { get { return UIColor.defaultTintStroke.withAlphaComponent(0.6) } }
class var defaultArrowStroke: UIColor { get { return .defaultTint } }
}
fileprivate extension UIColor {
// General styling
fileprivate class var defaultTint: UIColor { get { return #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1) } }
fileprivate class var defaultTintStroke: UIColor { get { return #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1) } }
fileprivate class var defaultPrimaryText: UIColor { get { return #colorLiteral(red: 45.0/255.0, green: 45.0/255.0, blue: 45.0/255.0, alpha: 1) } }
fileprivate class var defaultSecondaryText: UIColor { get { return #colorLiteral(red: 0.4509803922, green: 0.4509803922, blue: 0.4509803922, alpha: 1) } }
fileprivate class var defaultLine: UIColor { get { return #colorLiteral(red: 0.7825912237, green: 0.7776457667, blue: 0.7863886952, alpha: 0.7) } }
// Maneuver view (Page view)
fileprivate class var defaultManeuverViewBackground: UIColor { get { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } }
// Table view (Drawer)
fileprivate class var defaultHeaderBackground: UIColor { get { return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } }
fileprivate class var defaultHeaderTitleLabel: UIColor { get { return defaultPrimaryText } }
fileprivate class var defaultHeaderSubtitleLabel: UIColor { get { return defaultSecondaryText } }
}
fileprivate extension UIFont {
// General styling
fileprivate class var defaultPrimaryText: UIFont { get { return UIFont.systemFont(ofSize: 16) } }
fileprivate class var defaultSecondaryText: UIFont { get { return UIFont.systemFont(ofSize: 16) } }
fileprivate class var defaultCellTitleLabel: UIFont { get { return UIFont.systemFont(ofSize: 28, weight: UIFontWeightMedium) } }
// Table view (drawer)
fileprivate class var defaultHeaderTitleLabel: UIFont { get { return UIFont.preferredFont(forTextStyle: .headline) } }
}
/**
`Style` is a convenient wrapper for styling the appearance of various interface
components throughout the Navigation UI.
*/
@objc(MBStyle)
public class Style: NSObject {
public var traitCollection: UITraitCollection
/**
Initializes a style that will be applied for any system traits of an
interface’s environment.
*/
convenience override public init() {
self.init(traitCollection: UITraitCollection())
}
/**
Initializes a style for a specific system trait(s) of an interface’s
environment.
*/
required public init(traitCollection: UITraitCollection) {
self.traitCollection = traitCollection
super.init()
}
/// General styling
/**
`tintColor` is used for guidance arrow, highlighted text, progress bar and
more.
*/
public var tintColor: UIColor?
/**
`primaryTextColor` sets the color for titles and other prominent information.
*/
public var primaryTextColor: UIColor?
/**
`secondaryTextColor` sets the color for subtitles and other subtle
information.
*/
public var secondaryTextColor: UIColor?
/**
`buttonTextColor` sets the text color on buttons for normal state.
*/
public var buttonTextColor: UIColor?
/**
`lineColor` sets the color of dividers and separators.
*/
public var lineColor: UIColor?
/// Maneuver view (Page view)
/**
`maneuverViewBackgroundColor` sets the background color of the maneuver
view, positioned at the top.
*/
public var maneuverViewBackgroundColor: UIColor?
/**
`maneuverViewHeight` sets the height of the maneuver view.
*/
public var maneuverViewHeight: CGFloat?
/// Table view (Drawer)
/**
`headerBackgroundColor` sets the color of the drawer header, positioned at
the bottom.
*/
public var headerBackgroundColor: UIColor?
/**
`cellTitleLabelFont` sets the font of the title labels in table views.
*/
public var cellTitleLabelFont: UIFont?
/**
`cellTitleLabelTextColor` sets the title text color in table views.
*/
public var cellTitleLabelTextColor: UIColor?
/**
`cellSubtitleLabelFont` sets the font of the subtitle label in table views.
*/
public var cellSubtitleLabelFont: UIFont?
/**
`cellSubtitleLabelTextColor` sets the text color of the subtitle label in
table views.
*/
public var cellSubtitleLabelTextColor: UIColor?
/**
`wayNameTextColor` sets the color for the current way name label.
*/
public var wayNameTextColor: UIColor?
/**
`wayNameLabelFont` sets the font of the current way name label.
*/
public var wayNameLabelFont: UIFont?
/**
`defaultStyle` returns the default style for Mapbox Navigation SDK.
*/
public class var defaultStyle: Style {
let style = Style(traitCollection: UITraitCollection())
// General styling
if let tintColor = UIApplication.shared.delegate?.window??.tintColor {
style.tintColor = tintColor
} else {
style.tintColor = .defaultTint
}
style.primaryTextColor = .defaultPrimaryText
style.secondaryTextColor = .defaultSecondaryText
style.buttonTextColor = .defaultPrimaryText
style.lineColor = .defaultLine
// Maneuver view (Page view)
style.maneuverViewBackgroundColor = .defaultManeuverViewBackground
style.maneuverViewHeight = .defaultManeuverViewHeight
// Table view (Drawer)
style.headerBackgroundColor = .defaultHeaderBackground
style.cellTitleLabelFont = .defaultPrimaryText
style.cellTitleLabelTextColor = .defaultPrimaryText
style.cellSubtitleLabelFont = .defaultSecondaryText
style.cellSubtitleLabelTextColor = .defaultSecondaryText
return style
}
/**
Applies the style for all changed properties.
*/
public func apply() {
// General styling
if let color = tintColor {
NavigationMapView.appearance(for: traitCollection).tintColor = color
ProgressBar.appearance(for: traitCollection).backgroundColor = color
Button.appearance(for: traitCollection).tintColor = color
}
if let color = primaryTextColor {
TitleLabel.appearance(for: traitCollection).textColor = color
CellTitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = secondaryTextColor {
SubtitleLabel.appearance(for: traitCollection).textColor = color
CellSubtitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = buttonTextColor {
Button.appearance(for: traitCollection).textColor = color
}
if let color = lineColor {
// Line view can be a dashed line view so we add a lineColor to avoid changing the background.
LineView.appearance(for: traitCollection).lineColor = color
// Separator view can also be a divider (vertical/horizontal) with a solid background color.
SeparatorView.appearance(for: traitCollection).backgroundColor = color
}
// Maneuver page view controller
if let color = maneuverViewBackgroundColor {
ManeuverView.appearance(for: traitCollection).backgroundColor = color
}
if let height = maneuverViewHeight {
ManeuverView.appearance(for: traitCollection).height = height
}
// Table view (drawer)
if let color = headerBackgroundColor {
RouteTableViewHeaderView.appearance(for: traitCollection).backgroundColor = color
}
if let font = cellTitleLabelFont {
CellTitleLabel.appearance(for: traitCollection).font = font
}
if let color = cellTitleLabelTextColor {
CellTitleLabel.appearance(for: traitCollection).textColor = color
}
if let font = cellSubtitleLabelFont {
CellSubtitleLabel.appearance(for: traitCollection).font = font
}
if let color = cellSubtitleLabelTextColor {
CellSubtitleLabel.appearance(for: traitCollection).textColor = color
}
if let color = wayNameTextColor {
WayNameLabel.appearance(for: traitCollection).textColor = color
}
if let font = wayNameLabelFont {
WayNameLabel.appearance(for: traitCollection).font = font
}
}
}
@objc(MBButton)
public class Button: StylableButton { }
@objc(MBStylableLabel)
public class StylableLabel : UILabel { }
@objc(MBTitleLabel)
public class TitleLabel: StylableLabel { }
@objc(MBSubtitleLabel)
public class SubtitleLabel: StylableLabel { }
@objc(MBCellTitleLabel)
public class CellTitleLabel: StylableLabel { }
@objc(MBCellSubtitleLabel)
public class CellSubtitleLabel: StylableLabel { }
@objc(MBWayNameLabel)
public class WayNameLabel: StylableLabel { }
@objc(MBProgressBar)
public class ProgressBar: UIView { }
@objc(MBLineView)
public class LineView: UIView {
dynamic var lineColor: UIColor = .defaultLine {
didSet {
setNeedsDisplay()
setNeedsLayout()
}
}
}
@objc(MBSeparatorView)
public class SeparatorView: UIView { }
@objc(MBStylableButton)
public class StylableButton: UIButton {
dynamic var textColor: UIColor = .defaultPrimaryText {
didSet {
setTitleColor(textColor, for: .normal)
}
}
}
@objc(MBManeuverView)
class ManeuverView: UIView {
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
dynamic var height: CGFloat = .defaultManeuverViewHeight {
didSet {
heightConstraint.constant = height
setNeedsUpdateConstraints()
}
}
}
| d2f31333f516f8b14eb91beab3a461d3 | 32.783871 | 158 | 0.662656 | false | false | false | false |
RxLeanCloud/rx-lean-swift | refs/heads/master | src/RxLeanCloudSwiftTests/SMSTests.swift | mit | 1 | //
// SMSTests.swift
// RxLeanCloudSwiftTests
//
// Created by WuJun on 19/12/2017.
// Copyright © 2017 LeanCloud. All rights reserved.
//
import XCTest
import RxLeanCloudSwift
import RxSwift
class SMSTests: LeanCloudUnitTestBase {
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 testAVUserSMSSignUpSend() {
var user = RxAVUser()
user.mobilePhoneNumber = "18612438929"
user.email = "[email protected]"
user.password = "iwannabeaengineer"
user.set(key: "nickName", value: "hahaha")
user.sendSignUpSMS().flatMap { (sms) -> Observable<Bool> in
sms.setShortCode(receivedShortCode: "064241")
return user.signUpWithSms(sms: sms)
}.subscribe(onNext: { (success) in
if success {
print("sign up successful")
}
})
let result = user.sendSignUpSMS().flatMap { (sms) -> Observable<Bool> in
sms.setShortCode(receivedShortCode: "064241")
return user.signUpWithSms(sms: sms)
}.toBlocking().materialize()
switch result {
case .completed(let elements):
print(elements[0])
case .failed(let elements, let error):
print(error.localizedDescription)
}
}
func testAVUserSMSSignUp() {
var signUpSMS = AVUserSignUpSMS(mobilePhoneNumber: "18612438929")
signUpSMS.setShortCode(receivedShortCode: "064241")
let result = RxAVUser.signUpOrLogIn(sms: signUpSMS).toBlocking().materialize()
switch result {
case .completed(let elements):
print(elements[0].objectId)
case .failed(let elements, let error):
print(error.localizedDescription)
}
}
}
| ff46369803aa35d286d2aeaef0f91265 | 29.626866 | 111 | 0.62037 | false | true | false | false |
MrLSPBoy/LSPDouYu | refs/heads/master | LSPDouYuTV/LSPDouYuTV/Classes/Home/Controller/LSGameViewController.swift | mit | 1 | //
// LSGameViewController.swift
// LSPDouYuTV
//
// Created by lishaopeng on 17/3/3.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
fileprivate let kEdgeMargin : CGFloat = 10
fileprivate let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
fileprivate let kItemH : CGFloat = kItemW * 6 / 5
fileprivate let kHeaderViewH : CGFloat = 50
fileprivate let kGameViewH : CGFloat = 90
fileprivate let kGameCellID = "kGameCellID"
fileprivate let kCellHeadViewID = "kCellHeadViewID"
class LSGameViewController: LSBaseViewController {
fileprivate lazy var gameViewModel : LSGameViewModel = LSGameViewModel()
//MARK: 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
//2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(UINib(nibName: "LSCollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.register(UINib(nibName: "LSCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kCellHeadViewID)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collectionView.dataSource = self
return collectionView
}()
fileprivate lazy var topHeaderView : LSCollectionHeaderView = {
let headerView = LSCollectionHeaderView.collectionHeadView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
headerView.iconImageView.image = UIImage(named: "Img_orange")
headerView.titleLabel.text = "常见"
headerView.moreBtn.isHidden = true
return headerView
}()
fileprivate lazy var gameView : LSRecommendGameView = {
let gameView = LSRecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: - 设置UI界面
extension LSGameViewController {
override func setupUI(){
contentView = collectionView
super.setupUI()
//1.添加UICollectionView
view.addSubview(collectionView)
//2.添加顶部的headetView
collectionView.addSubview(topHeaderView)
//3.将常用游戏的View添加到collectionView中
collectionView.addSubview(gameView)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
//MARK: - 请求数据
extension LSGameViewController {
fileprivate func loadData() {
gameViewModel.loadAllGameData {
//1.展示全部游戏
self.collectionView.reloadData()
//2.展示常用游戏
self.gameView.groups = Array(self.gameViewModel.games[0..<10])
//3.数据请求完成
self.loadDataFinished()
}
}
}
//MARK:- UICollectionViewDataSource 和 delegate
extension LSGameViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameViewModel.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! LSCollectionGameCell
let gameModel = gameViewModel.games[indexPath.item]
cell.baseGameModel = gameModel
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1.取出headerView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kCellHeadViewID, for: indexPath) as! LSCollectionHeaderView
//2.给headView设置属性
headerView.titleLabel.text = "全部"
headerView.iconImageView.image = UIImage(named: "Img_orange")
headerView.moreBtn.isHidden = true
return headerView
}
}
| a08cdbcce3c0e931c9340ddeab1fa3e1 | 34.903704 | 190 | 0.685785 | false | false | false | false |
michaelvu812/MVPaginator | refs/heads/master | MVPaginator/MVPaginator.swift | mit | 1 | //
// MVPaginator.swift
// MVPaginator
//
// Created by Michael on 19/6/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import Foundation
import CoreData
enum MVPaginatorType:Int {
case Default = 0, Array, CoreData, Url, Json
}
enum MVPaginatorStatus:Int {
case None = 0, InProgress, Done
}
let MVPaginatorDefaultPageSize = 10
@objc protocol MVPaginatorDelegate {
func paginator(paginator:MVPaginator, didReceiveResults results:NSMutableArray)
@optional func paginatorDidFail(paginator:MVPaginator, error:NSError)
@optional func paginatorDidReset(paginator:MVPaginator)
}
@objc class MVPaginator: NSObject {
var paginatorType:MVPaginatorType = .Default
var pageSize:Int? = MVPaginatorDefaultPageSize
var totalCount:Int = 0
var totalPage:Int = 0
var currentPage:Int = 0
var collection:NSMutableArray?
var paginatorDelegate: MVPaginatorDelegate?
var paginatorStatus: MVPaginatorStatus = .None
var paginatorObject:AnyObject?
var paginatorClass:AnyClass?
var managedContext: NSManagedObjectContext = NSManagedObjectContext()
var predicateOption:NSPredicate?
init(_ array:NSMutableArray, type: MVPaginatorType? = .Array as MVPaginatorType, delegate:MVPaginatorDelegate?) {
self.paginatorObject = array
self.paginatorType = type!
self.paginatorDelegate = delegate!
}
init(_ object:AnyClass, type: MVPaginatorType? = .CoreData as MVPaginatorType, context:NSManagedObjectContext, delegate:MVPaginatorDelegate?) {
self.paginatorClass = object
self.paginatorType = type!
self.managedContext = context
self.paginatorDelegate = delegate!
}
init(_ object:AnyClass, predicate:NSPredicate, type: MVPaginatorType? = .CoreData as MVPaginatorType, context:NSManagedObjectContext, delegate:MVPaginatorDelegate?) {
self.paginatorClass = object
self.predicateOption = predicate
self.paginatorType = type!
self.managedContext = context
self.paginatorDelegate = delegate!
}
func setDefaultValues() {
self.totalCount = 0
self.totalPage = 0
self.currentPage = 0
self.collection = NSMutableArray()
self.paginatorStatus = .None
}
func load() {
self.reset()
self.fetchNextPage()
}
func reset() {
self.setDefaultValues()
self.paginatorDelegate?.paginatorDidReset?(self)
}
func isLastPage() -> Bool {
if self.paginatorStatus == .None {return false}
return (self.currentPage >= self.totalPage)
}
func fetchFirstPage() {
self.load()
}
func fetchNextPage() {
if self.paginatorStatus == .InProgress {return}
if self.isLastPage() == false {
self.paginatorStatus = .InProgress
self.fetchResultsWithPage(self.currentPage+1, pageSize: self.pageSize!)
}
}
func fetchResultsWithPage(page:Int, pageSize:Int) {
if self.paginatorType == .Array {
let array = self.paginatorObject? as NSMutableArray
if (array.count > 0) {
let location = (page * pageSize) - pageSize
var length:Int
if self.totalCount > 0 && (self.totalCount - location) < pageSize {
length = (self.totalCount - location)
} else {
length = pageSize
}
var results = array.subarrayWithRange(NSMakeRange(location, length))
self.receivedResults(results, total: array.count as Int)
} else {
self.receivedResults(NSArray(), total: 0)
}
} else if self.paginatorType == .CoreData {
if self.paginatorClass?.isSubclassOfClass(NSManagedObject.classForCoder()) {
var array = NSArray()
if self.predicateOption != nil {
array = self.paginatorClass?.fetchWithCondition(self.predicateOption!, context: self.managedContext) as NSArray
} else {
array = self.paginatorClass?.fetchInContext(self.managedContext) as NSArray
}
if (array.count > 0) {
let location = (page * pageSize) - pageSize
var length:Int
if self.totalCount > 0 && (self.totalCount - location) < pageSize {
length = (self.totalCount - location)
} else {
length = pageSize
}
var results = array.subarrayWithRange(NSMakeRange(location, length))
self.receivedResults(results, total: array.count as Int)
} else {
self.receivedResults(NSArray(), total: 0)
}
} else {
self.receivedResults(NSArray(), total: 0)
}
} else if self.paginatorType == .Url {
} else if self.paginatorType == .Json {
} else {
self.receivedFailedResults(self.errorWithMessage("Wrong pagination type"))
}
}
func errorWithMessage(message:String) -> NSError {
var errorDetail = NSMutableDictionary()
errorDetail.setValue(message, forKey: NSLocalizedDescriptionKey)
var errorMessage = NSError(domain: "MVPaginator", code: NSURLErrorUnknown, userInfo: errorDetail)
return errorMessage
}
func receivedResults(results:NSArray, total:Int) {
self.collection!.addObjectsFromArray(results)
self.currentPage += 1
self.totalCount = total
self.totalPage = Int(ceil(CDouble(self.totalCount)/CDouble(self.pageSize!)))
self.paginatorStatus = .Done
self.paginatorDelegate?.paginator(self, didReceiveResults: self.collection!)
}
func receivedFailedResults(error:NSError) {
self.paginatorStatus = .Done
self.paginatorDelegate?.paginatorDidFail?(self, error: error)
}
}
extension NSManagedObject {
class func entityName() -> String {
return NSStringFromClass(self.classForCoder())
}
class func fetchInContext(context:NSManagedObjectContext) -> NSArray {
let request = NSFetchRequest()
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: context)
request.entity = entity
return context.executeFetchRequest(request, error: nil)
}
class func fetchWithCondition(condition:NSPredicate, context:NSManagedObjectContext) -> NSArray {
let request = NSFetchRequest()
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: context)
request.entity = entity
if condition != nil {
request.predicate = condition
}
return context.executeFetchRequest(request, error: nil)
}
} | 871074770a659cdbedaa538acc439db6 | 36.148936 | 170 | 0.626092 | false | false | false | false |
whitepixelstudios/Material | refs/heads/master | Sources/iOS/Font.swift | bsd-3-clause | 1 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public protocol FontType {}
public struct Font {
/// Size of font.
public static let pointSize: CGFloat = 16
/**
Retrieves the system font with a specified size.
- Parameter ofSize size: A CGFloat.
*/
public static func systemFont(ofSize size: CGFloat) -> UIFont {
return UIFont.systemFont(ofSize: size)
}
/**
Retrieves the bold system font with a specified size..
- Parameter ofSize size: A CGFloat.
*/
public static func boldSystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont.boldSystemFont(ofSize: size)
}
/**
Retrieves the italic system font with a specified size.
- Parameter ofSize size: A CGFloat.
*/
public static func italicSystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont.italicSystemFont(ofSize: size)
}
/**
Loads a given font if needed.
- Parameter name: A String font name.
*/
public static func loadFontIfNeeded(name: String) {
FontLoader.loadFontIfNeeded(name: name)
}
}
/// Loads fonts packaged with Material.
private class FontLoader {
/// A Dictionary of the fonts already loaded.
static var loadedFonts: Dictionary<String, String> = Dictionary<String, String>()
/**
Loads a given font if needed.
- Parameter fontName: A String font name.
*/
static func loadFontIfNeeded(name: String) {
let loadedFont: String? = FontLoader.loadedFonts[name]
if nil == loadedFont && nil == UIFont(name: name, size: 1) {
FontLoader.loadedFonts[name] = name
let bundle = Bundle(for: FontLoader.self)
let identifier = bundle.bundleIdentifier
let fontURL = true == identifier?.hasPrefix("org.cocoapods") ? bundle.url(forResource: name, withExtension: "ttf", subdirectory: "com.cosmicmind.material.fonts.bundle") : bundle.url(forResource: name, withExtension: "ttf")
if let v = fontURL {
let data = NSData(contentsOf: v as URL)!
let provider = CGDataProvider(data: data)!
let font = CGFont(provider)
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font!, &error) {
let errorDescription = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as Any as! Error
NSException(name: .internalInconsistencyException, reason: errorDescription as String?, userInfo: [NSUnderlyingErrorKey: nsError as Any]).raise()
}
}
}
}
}
| a7d2a614c770152f61fa8df9b9eaec28 | 38.72381 | 234 | 0.698394 | false | false | false | false |
HeartRateLearning/HRLEngine | refs/heads/master | Example/Tests/RecordTest.swift | mit | 1 | //
// RecordTest.swift
// HRLEngine
//
// Created by Enrique de la Torre (dev) on 27/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
@testable import HRLEngine
class RecordTest: XCTestCase {
func testAnyDateAndAnyBPM_init_createVectorWithExpectedNumberOfValues() {
// given
let date = RecordTest.anyDate()
let bpm = Constants.anyBPM
// when
let record = Record(date: date, bpm: bpm)
// then
XCTAssertEqual(record.count(), Constants.valueCount)
}
func testAnyDateAndKnownBPM_init_createVectorWithExpectedBPMValue() {
// given
let date = RecordTest.anyDate()
let bpm = Constants.knownBPM
// when
let record = Record(date: date, bpm: bpm)
// then
XCTAssertEqual(record.value(at: Constants.bpmIndex), Double(bpm))
}
func testKnownGMTDateAndAnyBPM_init_createVectorWithExpectedtimeIntervalFromMidnightValue() {
// given
let hour = 17
let minute = 0
let second = 0
let secondsFromGMT = 0
let date = RecordTest.date(secondsFromGMT: secondsFromGMT,
hour: hour,
minute: minute,
second: second)
let bpm = Constants.anyBPM
// when
let record = Record(date: date, bpm: bpm)
// then
let timeInterval = RecordTest.timeIntervalFromMidnight(secondsFromGMT: secondsFromGMT,
hour: hour,
minute: minute,
second: second)
XCTAssertEqual(record.value(at: Constants.timeIntervalFromMidnightIndex), timeInterval)
}
func testKnownNonGMTDateAndAnyBPM_init_createVectorWithExpectedTimeIntervalFromMidnightValue() {
// given
let hour = 1
let minute = 0
let second = 0
// Notice that, because the time zone is 1 hour more than the number of hours,
// the UTC day will be the day before. I.e. the UTC date is: 2016-12-26 23:00:00 UTC.
let secondsFromGMT = (hour + 1) * 60 * 60
let date = RecordTest.date(secondsFromGMT: secondsFromGMT,
hour: hour,
minute: minute,
second: second)
let bpm = Constants.anyBPM
// when
let record = Record(date: date, bpm: bpm)
// then
let timeInterval = RecordTest.timeIntervalFromMidnight(secondsFromGMT: secondsFromGMT,
hour: hour,
minute: minute,
second: second)
XCTAssertEqual(record.value(at: Constants.timeIntervalFromMidnightIndex), timeInterval)
}
func testDatesForEachWeekDay_initRecordsWithDates_createVectorsWith7DifferentsWeekDayValues() {
// given
let anyDate = RecordTest.anyDate()
var dates: [Date] = []
for i in 0..<14 {
let timeInterval = TimeInterval(i * 24 * 60 * 60)
let date = anyDate.addingTimeInterval(timeInterval)
dates.append(date)
}
let bpm = Constants.anyBPM
// when
let repeatedWeekDays = dates.map { date -> Double in
let record = Record(date: date, bpm: bpm)
return record.value(at: Constants.weekDayIndex)
}
let weekDays = Set(repeatedWeekDays)
// then
XCTAssertEqual(weekDays.count, 7)
}
}
private extension RecordTest {
enum Constants {
static let weekDayIndex = UInt64(0)
static let timeIntervalFromMidnightIndex = UInt64(1)
static let bpmIndex = UInt64(2)
static let valueCount = UInt64(3)
static let anyBPM = Float(50)
static let knownBPM = Float(72)
}
static func anyDate() -> Date {
return Date(timeIntervalSinceReferenceDate: 0)
}
static func date(secondsFromGMT: Int,
hour: Int,
minute: Int,
second: Int,
year: Int = 2016,
month: Int = 12,
day: Int = 27) -> Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: secondsFromGMT)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
return calendar.date(from: dateComponents)!
}
static func timeIntervalFromMidnight(secondsFromGMT: Int,
hour: Int,
minute: Int,
second: Int) -> TimeInterval {
let timeInterval = hour * 60 * 60 + minute * 60 + second - secondsFromGMT
return TimeInterval(timeInterval >= 0 ? timeInterval : 24 * 60 * 60 + timeInterval)
}
}
| bb8c5488248eff22d445a58164923218 | 32.030864 | 100 | 0.541955 | false | true | false | false |
huonw/swift | refs/heads/master | test/IRGen/protocol_conformance_records.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
import resilient_struct
import resilient_protocol
public protocol Associate {
associatedtype X
}
// Dependent conformance
// CHECK-LABEL: @"$S28protocol_conformance_records9DependentVyxGAA9AssociateAAMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$S28protocol_conformance_records9AssociateMp"
// -- nominal type descriptor
// CHECK-SAME: @"$S28protocol_conformance_records9DependentVMn"
// -- witness table accessor
// CHECK-SAME: @"$S28protocol_conformance_records9DependentVyxGAA9AssociateAAWa"
// -- flags
// CHECK-SAME: i32 1
// CHECK-SAME: }
public struct Dependent<T> {}
extension Dependent : Associate {
public typealias X = (T, T)
}
public protocol Runcible {
func runce()
}
// CHECK-LABEL: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE:@"\$S28protocol_conformance_records8RuncibleMp"]]
// -- type metadata
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeValueType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- class metadata
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public class NativeClassType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeGenericType<T>: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$SSi28protocol_conformance_records8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- type metadata
// CHECK-SAME: @"{{got.|__imp_}}$SSiMn"
// -- witness table
// CHECK-SAME: @"$SSi28protocol_conformance_records8RuncibleAAWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Int: Runcible {
public func runce() {}
}
// For a resilient struct, reference the NominalTypeDescriptor
// CHECK-LABEL: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|__imp_}}$S16resilient_struct4SizeVMn"
// -- witness table
// CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Size: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"\01l_protocols"
// CHECK-SAME: @"$S28protocol_conformance_records8RuncibleMp"
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
public protocol Spoon { }
// Conditional conformances
// CHECK-LABEL: {{^}}@"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
// -- nominal type descriptor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table accessor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlWa
// -- flags
// CHECK-SAME: i32 258
// -- conditional requirement #1
// CHECK-SAME: i32 128,
// CHECK-SAME: i32 0,
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
// CHECK-SAME: }
extension NativeGenericType : Spoon where T: Spoon {
public func runce() {}
}
// Retroactive conformance
// CHECK-LABEL: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ dllexport | protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"{{got.|__imp_}}$S18resilient_protocol22OtherResilientProtocolMp"
// -- nominal type descriptor
// CHECK-SAME: @"{{got.|__imp_}}$SSiMn"
// -- witness table accessor
// CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsWa"
// -- flags
// CHECK-SAME: i32 73,
// -- module context for retroactive conformance
// CHECK-SAME: @"$S28protocol_conformance_recordsMXM"
// CHECK-SAME: }
extension Int : OtherResilientProtocol { }
// CHECK-LABEL: @"\01l_protocol_conformances" = private constant
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc"
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc"
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc"
// CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc"
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc"
// CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc"
| 2930b3a594b23a3f85d9439279f28afd | 41.112583 | 177 | 0.693663 | false | false | false | false |
alblue/swift | refs/heads/master | test/ClangImporter/objc_redeclared_properties.swift | apache-2.0 | 12 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D ONE_MODULE %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D SUB_MODULE %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules -D TWO_MODULES %s -verify
#if ONE_MODULE
import RedeclaredProperties
#elseif SUB_MODULE
import RedeclaredPropertiesSub
import RedeclaredPropertiesSub.Private
#elseif TWO_MODULES
import RedeclaredPropertiesSplit
import RedeclaredPropertiesSplit2
#endif
func test(obj: RPFoo) {
if let _ = obj.nonnullToNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
obj.nonnullToNullable = obj // expected-error {{cannot assign to property: 'nonnullToNullable' is a get-only property}}
if let _ = obj.nullableToNonnull {} // okay
obj.nullableToNonnull = obj // expected-error {{cannot assign to property: 'nullableToNonnull' is a get-only property}}
let _: RPFoo = obj.typeChangeMoreSpecific // expected-error {{cannot convert value of type 'Any' to specified type 'RPFoo'}}
obj.typeChangeMoreSpecific = obj // expected-error {{cannot assign to property: 'typeChangeMoreSpecific' is a get-only property}}
let _: RPFoo = obj.typeChangeMoreGeneral
obj.typeChangeMoreGeneral = obj // expected-error {{cannot assign to property: 'typeChangeMoreGeneral' is a get-only property}}
if let _ = obj.accessorRedeclaredAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
if let _ = obj.accessorDeclaredFirstAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
obj.accessorInProto = nil // okay
}
func sr8490(obj: RPSub) {
obj.accessorInProto = nil
}
| 68c5e9c9eabaca073eee944541426632 | 51.805556 | 147 | 0.761704 | false | false | false | false |
dnlosx/Cart | refs/heads/master | Sources/Cart/Cart.swift | mit | 1 | // Cart.swift
//
// Copyright 2017 Fco Daniel BR.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// An object that coordinate the products to sell.
open class Cart<T: ProductProtocol> {
/// Describes the product and quantity.
public typealias Item = (product: T, quantity: Int)
/// Counts the number of items without regard to quantity of each one.
/// Use this to know the number of items in a list, e.g. To get the number of rows in a table view.
public var count: Int {
get {
return items.count
}
}
/// Counts the number of products regarding the quantity of each one.
/// Use this to know the total of products e.g. To display the number of products in cart.
public var countQuantities: Int {
get {
var numberOfProducts = 0
for item in items {
numberOfProducts += item.quantity
}
return numberOfProducts
}
}
/// The amount to charge.
open var amount: Double {
var total: Double = 0
for item in items {
total += (item.product.price * Double(item.quantity))
}
return total
}
/// The delegate to communicate the changes.
public var delegate: CartDelegate?
/// The list of products to sell.
private var items = [Item]()
/// Public init
public init() {}
/// Gets the item at index.
public subscript(index: Int) -> Item {
return items[index]
}
/// Adds a product to the items.
/// if the product already exists, increments the quantity, otherwise adds as new one.
///
/// - parameter product: The product to add.
/// - parameter quantity: How many times will add the products. Default is 1.
///
public func add(_ product: T, quantity: Int = 1) {
for (index, item) in items.enumerated() {
if product == item.product {
items[index].quantity += quantity
delegate?.cart(self, itemsDidChangeWithType: .increment(at: index))
return
}
}
items.append((product: product, quantity: quantity))
delegate?.cart(self, itemsDidChangeWithType: .add(at: (items.count - 1)))
}
/// Increments the quantity of an item at index in 1.
///
/// - parameter index: The index of the product to increment.
///
public func increment(at index: Int) {
items[index].quantity += 1
delegate?.cart(self, itemsDidChangeWithType: .increment(at: index))
}
/// Increments the quantity of the product item.
///
/// - parameter product: The product to increment the quantity.
///
public func increment(_ product: T) {
for (index, item) in items.enumerated() {
if product == item.product {
increment(at: index)
break
}
}
}
/// Decrements the quantity of an item at index in 1, removes from items if the quantity downs to 0.
///
/// - parameter index: The index of the product to reduce.
///
public func decrement(at index: Int) {
if items[index].quantity > 1 {
items[index].quantity -= 1
delegate?.cart(self, itemsDidChangeWithType: .decrement(at: index))
} else {
remove(at: index)
}
}
/// Decrements the quantity of a product item.
///
/// - parameter product: The product to reduce the quantity.
///
public func decrement(_ product: T) {
for (index, item) in items.enumerated() {
if product == item.product {
decrement(at: index)
break
}
}
}
/// Removes completely the product at index from the items list, not matter the quantity.
///
/// - parameter index: The index of the product to remove.
///
public func remove(at index: Int) {
items.remove(at: index)
delegate?.cart(self, itemsDidChangeWithType: .delete(at: index))
}
/// Removes all products from the items list.
open func clean() {
items.removeAll()
delegate?.cart(self, itemsDidChangeWithType: .clean)
}
}
| 9d0c63ff134cf9dd1408692db756f846 | 33.363636 | 123 | 0.616213 | false | false | false | false |
remirobert/Suitchi | refs/heads/master | Sources/Suitchi.swift | mit | 1 | //
// Suitchi.swift
// Custom Switch
//
// Created by Remi Robert on 26/03/15.
// Copyright (c) 2015 Remi Robert. All rights reserved.
//
import UIKit
//Suitchi
class Suitchi: UIView, UIGestureRecognizerDelegate {
//MARK: -
//MARK: public propreties
var on: Bool = true
var completionOn: (() -> ())!
var completionOff: (() -> ())!
/// Label text on the on state.
var onLabel: String! {
didSet {
self.onButton.activeLabel.text = self.onLabel
self.onButton.inactiveLabel.text = self.onLabel
}
}
/// Label text off the on state.
var offLabel: String! {
didSet {
self.offButton.activeLabel.text = self.offLabel
self.offButton.inactiveLabel.text = self.offLabel
}
}
/// The background color of Suitchi.
var colorBackground: UIColor! {
didSet {
self.contentView.backgroundColor = self.colorBackground
}
}
/// Color on the on state.
var onColor: UIColor! {
didSet {
if (self.on) {
self.sliderWindow.backgroundColor = self.onColor
self.onButton.inactiveLabel.textColor = self.onColor
}
}
}
/// Color on the off state.
var offColor: UIColor! {
didSet {
if (!self.on) {
self.sliderWindow.backgroundColor = self.offColor
self.offButton.inactiveLabel.textColor = self.offColor
}
}
}
/// Color for all state, overload onColor and offColor.
var sliderColor: UIColor! {
didSet {
self.onColor = self.sliderColor
self.offColor = self.sliderColor
}
}
/// Center text for indication in the center of Suitchi.
var centerText: String! {
didSet {
self.addSubview(self.centerViewLabel)
self.centerViewLabel.text = self.centerText
//self.centerViewLabel.resizeContainer()
self.centerViewLabel.center = self.contentView.center
}
}
//MARK: -
//MARK: private propreties
private lazy var centerViewLabel: CustomCenterLabel! = {
let centerView = CustomCenterLabel(text: self.centerText)
return centerView
}()
private lazy var centerLabel: UILabel! = {
let label = UILabel()
label.text = self.centerText
label.font = UIFont.systemFontOfSize(11)
label.textAlignment = NSTextAlignment.Center
return label
}()
private lazy var onButton: customSwitchButton! = {
let onButton = customSwitchButton(frame: CGRectMake(0, 0, self.frame.size.width / 2, self.frame.size.height), label: self.onLabel)
onButton.enabled = false
onButton.backgroundColor = UIColor.clearColor()
onButton.inactiveLabel.alpha = 0.0
onButton.activeLabel.text = self.onLabel
onButton.inactiveLabel.text = self.onLabel
onButton.activeLabel.textColor = UIColor.whiteColor()
onButton.inactiveLabel.textColor = self.onColor
onButton.addTarget(self, action: "switchOn", forControlEvents: UIControlEvents.TouchUpInside)
return onButton
}()
private lazy var offButton: customSwitchButton! = {
let offButton = customSwitchButton(frame: CGRectMake(self.frame.size.width / 2, 0, self.frame.size.width / 2, self.frame.size.height), label: self.offLabel)
offButton.activeLabel.text = self.offLabel
offButton.inactiveLabel.text = self.offLabel
offButton.activeLabel.textColor = UIColor.whiteColor()
offButton.inactiveLabel.textColor = self.offColor
offButton.enabled = true
offButton.backgroundColor = UIColor.clearColor()
offButton.addTarget(self, action: "switchOff", forControlEvents: UIControlEvents.TouchUpInside)
return offButton
}()
private lazy var sliderWindow: UIView! = {
let slider = UIView()
slider.backgroundColor = UIColor(red:0.22, green:0.22, blue:0.22, alpha:1)
slider.frame = CGRectMake(0, 0, self.frame.size.width / 2, self.frame.size.height)
slider.layer.cornerRadius = 4.0
return slider
}()
private lazy var contentView: UIView! = {
let centerView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
centerView.layer.cornerRadius = 4
centerView.backgroundColor = UIColor.whiteColor()
return centerView
}()
//MARK: -
//MARK: Custom private class
//MARK: CustomCenterLabel Custom class
private class CustomCenterLabel: UIView {
var text: String! {
didSet {
self.centerLabel.text = text
self.addSubview(centerLabel)
}
}
func resizeContainer() {
self.centerLabel.sizeToFit()
centerLabel.font = UIFont.systemFontOfSize(10)
centerLabel.textAlignment = NSTextAlignment.Center
self.centerLabel.frame.size.width += 4
self.centerLabel.textColor = UIColor.grayColor()
self.centerLabel.layer.cornerRadius = centerLabel.frame.size.height / 2
self.frame.size = CGSizeMake(self.centerLabel.frame.size.width, self.frame.size.height)
self.layer.cornerRadius = self.centerLabel.frame.size.height / 2
}
lazy var centerLabel: UILabel! = {
let centerLabel = UILabel()
centerLabel.text = self.text
centerLabel.sizeToFit()
centerLabel.font = UIFont.systemFontOfSize(10)
centerLabel.textAlignment = NSTextAlignment.Center
centerLabel.frame.size.width += 4
centerLabel.textColor = UIColor.grayColor()
centerLabel.layer.cornerRadius = centerLabel.frame.size.height / 2
return centerLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(text: String) {
self.init()
self.text = text
self.frame.size = CGSizeMake(self.centerLabel.frame.size.width, self.centerLabel.frame.size.height)
self.addSubview(self.centerLabel)
self.layer.cornerRadius = self.centerLabel.frame.size.height / 2
self.backgroundColor = UIColor.whiteColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: customSwitchButton Custom class
private class customSwitchButton: UIButton {
lazy var activeLabel: UILabel = {
let activeLabel = UILabel()
activeLabel.frame.origin = CGPointZero
activeLabel.frame.size = self.frame.size
activeLabel.alpha = 1.0
activeLabel.textAlignment = NSTextAlignment.Center
return activeLabel
}()
lazy var inactiveLabel: UILabel = {
let inactiveLabel = UILabel()
inactiveLabel.frame.origin = CGPointZero
inactiveLabel.frame.size = self.frame.size
inactiveLabel.alpha = 1.0
inactiveLabel.textAlignment = NSTextAlignment.Center
return inactiveLabel
}()
override func drawRect(rect: CGRect) {
self.addSubview(self.activeLabel)
self.addSubview(self.inactiveLabel)
}
init(frame: CGRect, label: String) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: -
//MARK: State method:
func switchOn() {
if (self.on) {
return
}
self.on = true
UIView.animateWithDuration(0.4, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 14.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.sliderWindow.frame.origin.x -= self.frame.size.width / 2
}, completion: nil)
self.sliderWindow.backgroundColor = self.onColor
self.onButton.activeLabel.alpha = 1.0
self.onButton.inactiveLabel.alpha = 0.0
self.offButton.activeLabel.alpha = 0.0
self.offButton.inactiveLabel.alpha = 1.0
self.onButton.enabled = false
self.offButton.enabled = true
}) { (anim: Bool) -> Void in
if self.completionOn != nil {
self.completionOn()
}
}
}
func switchOff() {
if (!self.on) {
return
}
self.on = false
UIView.animateWithDuration(0.4, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 14.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.sliderWindow.frame.origin.x += self.frame.size.width / 2
}, completion: nil)
self.sliderWindow.backgroundColor = self.offColor
self.onButton.activeLabel.alpha = 0.0
self.onButton.inactiveLabel.alpha = 1.0
self.offButton.activeLabel.alpha = 1.0
self.offButton.inactiveLabel.alpha = 0.0
self.onButton.enabled = true
self.offButton.enabled = false
}){ (anim: Bool) -> Void in
if self.completionOff != nil {
self.completionOff()
}
}
}
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.whiteColor()
self.layer.masksToBounds = true
self.layer.cornerRadius = 4
self.onButton.frame = CGRectMake(0, 0, rect.size.width / 2, rect.size.height)
self.offButton.frame = CGRectMake(rect.size.width / 2, 0, rect.size.width / 2, rect.size.height)
self.addSubview(self.contentView)
self.contentView.addSubview(sliderWindow)
self.contentView.addSubview(onButton)
self.contentView.addSubview(offButton)
let recogniserRight = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
recogniserRight.direction = UISwipeGestureRecognizerDirection.Right
recogniserRight.delegate = self
let recogniserLeft = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
recogniserLeft.direction = UISwipeGestureRecognizerDirection.Left
recogniserLeft.delegate = self
self.sliderWindow.addGestureRecognizer(recogniserRight)
self.sliderWindow.addGestureRecognizer(recogniserLeft)
let centerView = UIView()
centerView.backgroundColor = UIColor.whiteColor()
if self.centerText != nil {
self.bringSubviewToFront(self.centerViewLabel)
}
}
func swipeGesture(sender: UISwipeGestureRecognizer) {
if (sender.direction == UISwipeGestureRecognizerDirection.Left) {
self.switchOn()
}
else {
self.switchOff()
}
}
//MARK: -
//MARK: init method
private func initDefault() {
self.contentView.backgroundColor = UIColor.whiteColor()
self.onLabel = "ON"
self.offLabel = "OFF"
self.sliderColor = UIColor(red:0.22, green:0.22, blue:0.22, alpha:1)
}
//MARK: constructor
override init(frame: CGRect) {
super.init(frame: frame)
self.initDefault()
}
init(frame: CGRect, onSwitchedBlock completionOn: () -> (), offSwitchedBlock completionOff: () -> ()) {
super.init(frame: frame)
self.initDefault()
self.completionOn = completionOn
self.completionOff = completionOff
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | 243693570617926bf4e66528fc44618d | 34.312676 | 187 | 0.595692 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/TextViewSelfsizingController.swift | mit | 1 | //
// TextViewSelfsizing.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/12/23.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
class TextViewSelfsizingCell: UITableViewCell, Reusable {
private lazy var textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
textView.isScrollEnabled = false
return textView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
contentView.addSubview(textView)
textView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
textView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
textView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
textView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextViewSelfsizingCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let vc: TextViewSelfsizingController? = viewController()
let currentOffset = vc!.tableView.contentOffset
UIView.setAnimationsEnabled(false)
vc?.tableView.beginUpdates()
vc?.tableView.endUpdates()
UIView.setAnimationsEnabled(true)
vc?.tableView.setContentOffset(currentOffset, animated: false)
}
}
class TextViewSelfsizingController: AutoLayoutBaseController {
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .grouped)
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
tableView.register(TextViewSelfsizingCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
override func initSubviews() {
view.addSubview(tableView)
}
}
extension TextViewSelfsizingController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}
}
| 03fbb39fae4f17255111959c8899599d | 33.878378 | 110 | 0.712515 | false | false | false | false |
zeeshankhan/WeatherApp | refs/heads/master | WeatherApp/DetailsViewController.swift | mit | 1 | //
// DetailsViewController.swift
// WeatherApp
//
// Created by Zeeshan Khan on 10/14/16.
// Copyright © 2016 Zeeshan. All rights reserved.
//
import UIKit
class DetailsViewController: UIViewController {
var info: WeatherInfo? = nil
@IBOutlet weak var detailsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Details"
detailsTableView.tableFooterView = UIView(frame: .zero)
addRefreshControl()
}
lazy var tableItems: [TableRowItem] = {
return self.populateTableItems()
}()
func populateTableItems() -> [TableRowItem] {
var items: [TableRowItem] = []
let imageItem = ImageRowItem(.city, image: .icon)
items.append(imageItem)
let timeItem = InfoRowItem(.observationTime)
items.append(timeItem)
let humidItem = InfoRowItem(.humidity)
items.append(humidItem)
let descItem = InfoRowItem(.weatherDescription)
items.append(descItem)
return items
}
private func addRefreshControl() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshDetails(_:)), for: .valueChanged)
detailsTableView.addSubview(refreshControl)
}
func refreshDetails(_ refreshControl: UIRefreshControl) {
guard let city = info?.city else {
refreshControl.endRefreshing()
return
}
WeatherInfo.fetchWeather(forCity: city) { [weak self] (result) in
refreshControl.endRefreshing()
switch result {
case .success(let info):
self?.info = info
self?.detailsTableView.reloadData()
case .failure(let err):
switch err {
case .other(let msg):
print(msg)
default: break
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension DetailsViewController : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableItems.count;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let item = tableItems[indexPath.row]
return item.cellType.height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowItem = tableItems[indexPath.row]
switch rowItem.cellType {
case .image:
let cell = tableView.dequeueReusableCell(indexPath: indexPath, cellType: ImageTableViewCell.self)
let valueItem = rowItem as! ImageRowItem
cell.cityLabel.text = (info?.tempC)! + "℃ / " + (info?.tempF)! + "℉\n" + valueItem.item.itemValue(info!)
cell.populateImage(fromPath: valueItem.image.itemValue(info!))
return cell
case .info:
let cell = tableView.dequeueReusableCell(indexPath: indexPath, cellType: InfoTableViewCell.self)
cell.titleLabel.text = rowItem.item.description
cell.detailLabel.text = rowItem.item.itemValue(info!)
return cell
}
}
}
enum CellType {
case image
case info
var height : CGFloat {
get {
switch(self) {
case .image: return 104.0
case .info: return 60.0
}
}
}
var identifier : String {
get {
switch(self) {
case .image: return "ImageTableViewCell"
case .info: return "InfoTableViewCell"
}
}
}
}
protocol TableRowItem {
var cellType: CellType { get }
var item: WeatherItem { get }
}
private struct InfoRowItem : TableRowItem {
let cellType: CellType = .info
let item: WeatherItem
init(_ item: WeatherItem) {
self.item = item
}
}
struct ImageRowItem : TableRowItem {
let cellType: CellType = .image
let item: WeatherItem
let image: WeatherItem
init(_ item: WeatherItem, image: WeatherItem) {
self.item = item
self.image = image
}
}
class ImageTableViewCell : UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
func populateImage(fromPath path: String?) {
DispatchQueue.global().async { [weak self] () -> Void in
// wow 🤘🏻
guard let url = path.flatMap(URL.init) else {
print("Icon URL is nil.")
return
}
guard let imgData = try? Data(contentsOf: url) else {
print("Icon data is nil.")
return
}
DispatchQueue.main.async {
self?.iconImageView.image = UIImage(data: imgData)
}
}
}
}
class InfoTableViewCell : UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
}
| e5eee6e6eab2781fa6d339374851682f | 24.432039 | 120 | 0.583127 | false | false | false | false |
Ataraxiis/MGW-Esport | refs/heads/develop | Carthage/Checkouts/RxSwift/RxSwift/Observables/Observable+Debug.swift | apache-2.0 | 25 | //
// Observable+Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: debug
extension ObservableType {
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- returns: An observable sequence whose events are printed to standard output.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func debug(identifier: String? = nil, file: String = #file, line: UInt = #line, function: String = #function)
-> Observable<E> {
return Debug(source: self.asObservable(), identifier: identifier, file: file, line: line, function: function)
}
} | fd046b42ef1694e7bb496b7eae3d4f24 | 31.892857 | 120 | 0.692391 | false | false | false | false |
KaiCode2/swift-corelibs-foundation | refs/heads/master | Foundation/NSXMLDTD.swift | apache-2.0 | 3 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/*!
@class NSXMLDTD
@abstract Defines the order, repetition, and allowable values for a document
*/
public class NSXMLDTD : NSXMLNode {
internal var _xmlDTD: _CFXMLDTDPtr {
return _CFXMLDTDPtr(_xmlNode)
}
public convenience init(contentsOfURL url: NSURL, options mask: Int) throws {
let urlString = url.absoluteString
guard let node = _CFXMLParseDTD(urlString) else {
//TODO: throw error
fatalError("parsing dtd string failed")
}
self.init(ptr: node)
}
public convenience init(data: NSData, options mask: Int) throws {
var unmanagedError: Unmanaged<CFError>? = nil
guard let node = _CFXMLParseDTDFromData(data._cfObject, &unmanagedError) else {
if let error = unmanagedError?.takeRetainedValue()._nsObject {
throw error
}
//TODO: throw a generic error?
fatalError("parsing dtd from data failed")
}
self.init(ptr: node)
} //primitive
/*!
@method publicID
@abstract Sets the public id. This identifier should be in the default catalog in /etc/xml/catalog or in a path specified by the environment variable XML_CATALOG_FILES. When the public id is set the system id must also be set.
*/
public var publicID: String? {
get {
return _CFXMLDTDExternalID(_xmlDTD)?._swiftObject
}
set {
if let value = newValue {
_CFXMLDTDSetExternalID(_xmlDTD, value)
} else {
_CFXMLDTDSetExternalID(_xmlDTD, nil)
}
}
}
/*!
@method systemID
@abstract Sets the system id. This should be a URL that points to a valid DTD.
*/
public var systemID: String? {
get {
return _CFXMLDTDSystemID(_xmlDTD)?._swiftObject
}
set {
if let value = newValue {
_CFXMLDTDSetSystemID(_xmlDTD, value)
} else {
_CFXMLDTDSetSystemID(_xmlDTD, nil)
}
}
}
/*!
@method insertChild:atIndex:
@abstract Inserts a child at a particular index.
*/
public func insertChild(_ child: NSXMLNode, atIndex index: Int) {
_insertChild(child, atIndex: index)
} //primitive
/*!
@method insertChildren:atIndex:
@abstract Insert several children at a particular index.
*/
public func insertChildren(_ children: [NSXMLNode], atIndex index: Int) {
_insertChildren(children, atIndex: index)
}
/*!
@method removeChildAtIndex:
@abstract Removes a child at a particular index.
*/
public func removeChildAtIndex(_ index: Int) {
_removeChildAtIndex(index)
} //primitive
/*!
@method setChildren:
@abstract Removes all existing children and replaces them with the new children. Set children to nil to simply remove all children.
*/
public func setChildren(_ children: [NSXMLNode]?) {
_setChildren(children)
} //primitive
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
public func addChild(_ child: NSXMLNode) {
_addChild(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
public func replaceChildAtIndex(_ index: Int, withNode node: NSXMLNode) {
_replaceChildAtIndex(index, withNode: node)
}
/*!
@method entityDeclarationForName:
@abstract Returns the entity declaration matching this name.
*/
public func entityDeclarationForName(_ name: String) -> NSXMLDTDNode? {
guard let node = _CFXMLDTDGetEntityDesc(_xmlDTD, name) else { return nil }
return NSXMLDTDNode._objectNodeForNode(node)
} //primitive
/*!
@method notationDeclarationForName:
@abstract Returns the notation declaration matching this name.
*/
public func notationDeclarationForName(_ name: String) -> NSXMLDTDNode? {
guard let node = _CFXMLDTDGetNotationDesc(_xmlDTD, name) else { return nil }
return NSXMLDTDNode._objectNodeForNode(node)
} //primitive
/*!
@method elementDeclarationForName:
@abstract Returns the element declaration matching this name.
*/
public func elementDeclarationForName(_ name: String) -> NSXMLDTDNode? {
guard let node = _CFXMLDTDGetElementDesc(_xmlDTD, name) else { return nil }
return NSXMLDTDNode._objectNodeForNode(node)
} //primitive
/*!
@method attributeDeclarationForName:
@abstract Returns the attribute declaration matching this name.
*/
public func attributeDeclarationForName(_ name: String, elementName: String) -> NSXMLDTDNode? {
guard let node = _CFXMLDTDGetAttributeDesc(_xmlDTD, elementName, name) else { return nil }
return NSXMLDTDNode._objectNodeForNode(node)
} //primitive
/*!
@method predefinedEntityDeclarationForName:
@abstract Returns the predefined entity declaration matching this name.
@discussion The five predefined entities are
<ul><li>&lt; - <</li><li>&gt; - ></li><li>&amp; - &</li><li>&quot; - "</li><li>&apos; - &</li></ul>
*/
public class func predefinedEntityDeclarationForName(_ name: String) -> NSXMLDTDNode? {
guard let node = _CFXMLDTDGetPredefinedEntity(name) else { return nil }
return NSXMLDTDNode._objectNodeForNode(node)
}
internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> NSXMLDTD {
precondition(_CFXMLNodeGetType(node) == _kCFXMLTypeDTD)
if let privateData = _CFXMLNodeGetPrivateData(node) {
let unmanaged = Unmanaged<NSXMLDTD>.fromOpaque(privateData)
return unmanaged.takeUnretainedValue()
}
return NSXMLDTD(ptr: node)
}
internal override init(ptr: _CFXMLNodePtr) {
super.init(ptr: ptr)
}
}
| c088d64354368c3b122e3d723c96b702 | 33.109375 | 234 | 0.627882 | false | false | false | false |
SomeHero/iShopAwayAPIManager | refs/heads/master | IShopAwayApiManager/Classes/IShopAwayApiManager.swift | mit | 1 | //
// ApiManager.swift
// PersonalShopper
//
// Created by James Rhodes on 5/15/16.
// Copyright © 2016 James Rhodes. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper
public enum ProductSize: Int {
case Small
case Medium
case Large
case XLarge
}
public struct AuthenticateUser {
let emailAddress: String
let password: String
public init(emailAddress: String, password: String) {
self.emailAddress = emailAddress
self.password = password
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"email_address": emailAddress,
"password": password
]
return parameters
}
}
public struct AuthenticateFacebookUser {
let accessToken: String
public init(access_token: String) {
self.accessToken = access_token
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"access_token": accessToken
]
return parameters
}
}
public struct CreateUser {
let authType: String = "email"
let emailAddress: String
let password: String
let firstName: String
let lastName: String
let role: String
public init(emailAddress: String, password: String, firstName: String, lastName: String, role: String) {
self.emailAddress = emailAddress
self.password = password
self.firstName = firstName
self.lastName = lastName
self.role = role
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"auth_type": authType,
"email_address": emailAddress,
"password": password,
"first_name": firstName,
"last_name": lastName,
"role": role
]
return parameters
}
}
public struct CreateFacebookUser {
let accessToken: String
let authType: String = "facebook"
public init(access_token: String) {
self.accessToken = access_token
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"auth_type": authType,
"access_token": accessToken
]
return parameters
}
}
public struct CreateShoppingSession {
let marketId: String
public init(marketId: String) {
self.marketId = marketId
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"market_id": marketId
]
return parameters
}
}
public struct ShoppingSessionCheckout {
let shoppingSession: ShoppingSession
//let stripeToken: String
public init(shoppingSession: ShoppingSession) {
self.shoppingSession = shoppingSession
//self.stripeToken = stripeToken
}
func parameterize() -> [String : AnyObject] {
// let parameters = [
// "stripe_token": stripeToken
// ]
//
// return parameters
let parameters:[String : AnyObject] = [:]
return parameters
}
}
public struct ShoppingSessionAuthorization {
let shoppingSession: ShoppingSession
let stripeToken: String
public init(shoppingSession: ShoppingSession, stripeToken: String) {
self.shoppingSession = shoppingSession
self.stripeToken = stripeToken
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"stripe_token": stripeToken
]
return parameters
}
}
public struct UpdateMarket {
public let marketId: String
public let name: String
public let about: String
public let personalShopperId: String
public init(marketId: String, name: String, about: String, personalShopperId: String) {
self.marketId = marketId
self.name = name
self.about = about
self.personalShopperId = personalShopperId
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"name": name,
"about": about,
"personal_shopper_id": personalShopperId
]
return parameters
}
}
public struct PersonalShopperCheckin {
public let marketId: String
public init(marketId: String) {
self.marketId = marketId
}
func parameterize() -> [String : AnyObject] {
let parameters:[String : AnyObject] = [:]
return parameters
}
}
public struct CreatePersonalShopper {
public let firstName: String
public let lastName: String
public let emailAddress: String
public var avatarUrl: String?
public var facebookProfile: AnyObject?
public init(firstName: String, lastName: String, emailAddress: String) {
self.firstName = firstName
self.lastName = lastName
self.emailAddress = emailAddress
}
func parameterize() -> [String : AnyObject] {
var parameters: [String: AnyObject] = [
"first_name": firstName,
"last_name": lastName,
"email_address": emailAddress,
]
if let avatarUrl = avatarUrl {
parameters["avatar_url"] = avatarUrl
}
if let facebookProfile = facebookProfile {
parameters["facebook_profile"] = facebookProfile
}
return parameters
}
}
public struct RegisterForPushNotifications {
public let apn_device_token: String
public init(apn_device_token: String) {
self.apn_device_token = apn_device_token
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"device_type": "iPhone",
"device_token": apn_device_token
]
return parameters
}
}
public struct CreatePaymentMethod {
public let userId: String
public let stripeToken: String
public init(userId: String, stripeToken: String) {
self.userId = userId
self.stripeToken = stripeToken
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"stripe_token": stripeToken
]
return parameters
}
}
public struct CreateAddress {
public let userId: String
public let address1: String
public let postalCode: String
public init(userId: String, address1: String, postalCode: String) {
self.userId = userId
self.address1 = address1
self.postalCode = postalCode
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"address_1": address1,
"postal_code": postalCode
]
return parameters
}
}
public struct CreatePurchaseRequest {
public let name: String
public let amount: NSDecimalNumber
public let shoppingSession: ShoppingSession
public let productSize: ProductSize
public let productUrl: String
public init(name: String, amount: NSDecimalNumber, shoppingSession: ShoppingSession, productSize: ProductSize, productUrl: String) {
self.name = name
self.amount = amount
self.shoppingSession = shoppingSession
self.productSize = productSize
self.productUrl = productUrl
}
func parameterize() -> [String : AnyObject] {
guard let shoppingSessionId = shoppingSession.id else {
fatalError("Attempted to create a purchase request with no Shopping Session")
}
let parameters = [
"item_name": name,
"shopping_session_id": shoppingSessionId,
"amount": amount,
"product_size": productSize.rawValue,
"image_url": productUrl
]
return parameters
}
}
public struct CreateCheckoutRequest {
public let amount: NSDecimalNumber
public let shoppingSessionId: String
public init(amount: NSDecimalNumber, shoppingSessionId: String) {
self.amount = amount
self.shoppingSessionId = shoppingSessionId
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"shopping_session_id": shoppingSessionId,
"amount": amount
]
return parameters
}
}
public struct UpdatePurchaseRequest {
let purchaseRequest: PurchaseRequest
public init(purchaseRequest: PurchaseRequest) {
self.purchaseRequest = purchaseRequest
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"amount": purchaseRequest.amount,
"status": purchaseRequest.status
]
return parameters
}
}
public struct UpdateCheckoutRequest {
let checkoutRequest: CheckoutRequest
public init(checkoutRequest: CheckoutRequest) {
self.checkoutRequest = checkoutRequest
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"amount": checkoutRequest.amount,
"status": checkoutRequest.status
]
return parameters as! [String : AnyObject]
}
}
public struct CreateShippingInformation {
let shoppingSession: ShoppingSession
let name: String
let address1: String
let address2: String
let city: String
let state: String
let zipCode: String
public init(shoppingSession: ShoppingSession, name: String, address1: String, address2: String, city: String, state: String, zipCode: String) {
self.shoppingSession = shoppingSession
self.name = name
self.address1 = address1
self.address2 = address2
self.city = city
self.state = state
self.zipCode = zipCode
}
func parameterize() -> [String : AnyObject] {
let parameters = [
"name": name,
"address_1": address1,
"address_2": address2,
"city": city,
"state": state,
"zip_code": zipCode
]
return parameters
}
}
public class IShopAwayApiManager {
private var kApiBaseUrl:String?
public var apiBaseUrl: String {
set {
kApiBaseUrl = newValue
}
get {
if let kApiBaseUrl = kApiBaseUrl {
return kApiBaseUrl
} else {
fatalError("API Base URL must be set")
}
}
}
var token: String?
public static let sharedInstance = IShopAwayApiManager()
private init() {}
private var headers: [String: String]? {
var headers: [String: String] = [:]
if let token = token {
headers["x-access-token"] = token
}
return headers.count > 0 ? headers : nil;
}
public func authenticate(authenticateUser: AuthenticateUser, success: (shopperId: String, token: String) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = authenticateUser.parameterize()
Alamofire.request(.POST, apiBaseUrl + "/authenticate", parameters: params, encoding: .JSON)
.validate()
.responseJSON { response in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let result = response.result.value {
if let userId = result["user_id"] as? String, token = result["token"] as? String {
self.token = token
success(shopperId: userId, token: token)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
}
public func authenticateWithFacebook(authenticateFacebookUser: AuthenticateFacebookUser, success: (userId: String, token: String) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = authenticateFacebookUser.parameterize()
Alamofire.request(.POST, apiBaseUrl + "authenticate/facebook", parameters: params, encoding: .JSON)
.validate()
.responseJSON { response in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let result = response.result.value {
if let userId = result["user_id"] as? String, token = result["token"] as? String {
self.token = token
success(userId: userId, token: token)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
}
public func createUser(createUser: CreateUser, success: (userId: String, token: String) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createUser.parameterize()
Alamofire.request(.POST, apiBaseUrl + "users", parameters: params, encoding: .JSON)
.validate()
.responseJSON { response in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let result = response.result.value {
if let userId = result["user_id"] as? String, token = result["token"] as? String {
self.token = token
success(userId: userId, token: token)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
}
public func createUserWithFaceook(createFacebookUser: CreateFacebookUser, success: (userId: String, token: String) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createFacebookUser.parameterize()
Alamofire.request(.POST, apiBaseUrl + "users", parameters: params, encoding: .JSON)
.validate()
.responseJSON { response in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let result = response.result.value {
if let userId = result["user_id"] as? String, token = result["token"] as? String {
self.token = token
success(userId: userId, token: token)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
}
public func me(success: (response: User) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.GET, apiBaseUrl + "me", parameters: nil, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<User, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let user = response.result.value {
success(response: user)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
public func registerForPushNotifications(registerForPushNotifications: RegisterForPushNotifications, success: (success: Bool) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = registerForPushNotifications.parameterize()
Alamofire.request(.POST, apiBaseUrl + "devices", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseJSON { response in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let result = response.result.value {
if let isSuccess = result["success"] as? Bool {
success(success: isSuccess)
} else {
failure(error: nil, errorDictionary: nil)
}
}
}
}
public func addPaymentMethod(createPaymentMethod: CreatePaymentMethod, success: (response: PaymentMethod) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createPaymentMethod.parameterize()
Alamofire.request(.POST, apiBaseUrl + "users/\(createPaymentMethod.userId)" + "/payment_methods", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<PaymentMethod, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let paymentMethod = response.result.value {
success(response: paymentMethod)
}
}
}
public func addAddress(createAddress: CreateAddress, success: (response: Address) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createAddress.parameterize()
Alamofire.request(.POST, apiBaseUrl + "users/\(createAddress.userId)" + "/shipping_addresses", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<Address, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let address = response.result.value {
success(response: address)
}
}
}
public func getShoppingSession(shoppingSessionId: String, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.GET, apiBaseUrl + "shopping_sessions/\(shoppingSessionId)", parameters: nil, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
public func createShoppingSession(createShoppingSession: CreateShoppingSession, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createShoppingSession.parameterize()
Alamofire.request(.POST, apiBaseUrl + "shopping_sessions", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
public func authorize(shoppingSessionCheckout: ShoppingSessionAuthorization, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = shoppingSessionCheckout.parameterize()
if let shoppingSessionId = shoppingSessionCheckout.shoppingSession.id {
Alamofire.request(.POST, apiBaseUrl + "shopping_sessions/\(shoppingSessionId)/authorize", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
}
public func checkout(shoppingSessionCheckout: ShoppingSessionCheckout, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = shoppingSessionCheckout.parameterize()
if let shoppingSessionId = shoppingSessionCheckout.shoppingSession.id {
Alamofire.request(.POST, apiBaseUrl + "shopping_sessions/\(shoppingSessionId)/checkout", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
}
public func addShipping(createShippingInformation: CreateShippingInformation, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createShippingInformation.parameterize()
if let shoppingSessionId = createShippingInformation.shoppingSession.id {
Alamofire.request(.POST, apiBaseUrl + "shopping_sessions/\(shoppingSessionId)/shipping", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
}
public func getMarkets(success: (response: [Market]?) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.GET, apiBaseUrl + "markets")
.validate()
.responseArray(keyPath: "results") { (response: Response<[Market], NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let markets = response.result.value {
success(response: markets)
}
}
}
public func updateMarket(updateMarket: UpdateMarket, success: (response: Market?) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = updateMarket.parameterize()
Alamofire.request(.PUT, apiBaseUrl + "markets/\(updateMarket.marketId)", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<Market, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let market = response.result.value {
success(response: market)
}
}
}
public func personalShopperCheckin(personalShopperCheckin: PersonalShopperCheckin, success: (response: Market?) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = personalShopperCheckin.parameterize()
Alamofire.request(.POST, apiBaseUrl + "markets/\(personalShopperCheckin.marketId)/checkin", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<Market, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let market = response.result.value {
success(response: market)
}
}
}
public func publishFeed(shoppingSessionId: String, success: (response: ShoppingSession) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.POST, apiBaseUrl + "shopping_sessions/" + shoppingSessionId + "/publish", parameters: nil, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<ShoppingSession, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let shoppingSession = response.result.value {
success(response: shoppingSession)
}
}
}
public func createPurchaseRequest(createPurchaseRequest: CreatePurchaseRequest, success: (response: PurchaseRequest?) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createPurchaseRequest.parameterize()
Alamofire.request(.POST, apiBaseUrl + "purchase_requests", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<PurchaseRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let purchaseRequest = response.result.value {
success(response: purchaseRequest)
}
}
}
public func updatePurchaseRequest(updatePurchaseRequest: UpdatePurchaseRequest, success: (response: PurchaseRequest) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = updatePurchaseRequest.parameterize()
Alamofire.request(.PUT , apiBaseUrl + "purchase_requests/\(updatePurchaseRequest.purchaseRequest.id)", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<PurchaseRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let purchaseRequest = response.result.value {
success(response: purchaseRequest)
}
}
}
public func getPurchaseRequest(purchaseRequestId: String, success: (response: PurchaseRequest) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.GET, apiBaseUrl + "purchase_requests/\(purchaseRequestId)", parameters: nil, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<PurchaseRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let purchaseRequest = response.result.value {
success(response: purchaseRequest)
}
}
}
public func createCheckoutRequest(createCheckoutRequest: CreateCheckoutRequest, success: (response: CheckoutRequest?) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = createCheckoutRequest.parameterize()
Alamofire.request(.POST, apiBaseUrl + "checkout_requests", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<CheckoutRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let checkoutRequest = response.result.value {
success(response: checkoutRequest)
}
}
}
public func updateCheckoutRequest(updateCheckoutRequest: UpdateCheckoutRequest, success: (response: CheckoutRequest) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
let params = updateCheckoutRequest.parameterize()
Alamofire.request(.PUT , apiBaseUrl + "checkout_requests/\(updateCheckoutRequest.checkoutRequest.id)", parameters: params, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<CheckoutRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let checkoutRequest = response.result.value {
success(response: checkoutRequest)
}
}
}
public func getCheckoutRequest(checkoutRequestId: String, success: (response: CheckoutRequest) -> Void, failure: (error: ErrorType?, errorDictionary: [String: AnyObject]?) -> Void) {
Alamofire.request(.GET, apiBaseUrl + "checkout_requests/\(checkoutRequestId)", parameters: nil, encoding: .JSON, headers: headers)
.validate()
.responseObject { (response: Response<CheckoutRequest, NSError>) in
if let error = response.result.error {
var errorResponse: [String: AnyObject]? = [:]
if let data = response.data {
do {
errorResponse = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
failure(error: error, errorDictionary: nil)
}
catch let error {
failure(error: error, errorDictionary: nil)
}
failure(error: error, errorDictionary: errorResponse)
} else {
failure(error: error, errorDictionary: nil)
}
}
if let checkoutRequest = response.result.value {
success(response: checkoutRequest)
}
}
}
} | ebe15d664cf0125fadf46627073a3084 | 42.634669 | 221 | 0.516841 | false | false | false | false |
frootloops/swift | refs/heads/master | test/SILGen/objc_protocols.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import objc_protocols_Bas
@objc protocol NSRuncing {
func runce() -> NSObject
func copyRuncing() -> NSObject
func foo()
static func mince() -> NSObject
}
@objc protocol NSFunging {
func funge()
func foo()
}
protocol Ansible {
func anse()
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[THIS:%.*]] : @owned $T):
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_THIS]] : {{\$.*}}, #NSRuncing.runce!1.foreign
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject
// CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]]
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_THIS]] : {{\$.*}}, #NSRuncing.copyRuncing!1.foreign
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject
// CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]]
// -- Arguments are not consumed by objc calls
// CHECK: destroy_value [[THIS]]
func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () {
func objc_generic_partial_apply<T : NSRuncing>(_ x: T) {
// CHECK: bb0([[ARG:%.*]] : @owned $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] :
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[METHOD]]
_ = x.runce
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] :
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T>()
// CHECK: destroy_value [[METHOD]]
_ = T.runce
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]]
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]])
// CHECK: destroy_value [[METHOD:%.*]]
_ = T.mince
// CHECK: destroy_value [[ARG]]
}
// CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF'
// CHECK: sil shared [serializable] [thunk] @[[THUNK1]] :
// CHECK: bb0([[SELF:%.*]] : @owned $Self):
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] :
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>([[SELF]])
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK1]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK1_THUNK]]
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Self):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[FN:%.*]] = objc_method [[SELF_COPY]] : $Self, #NSRuncing.runce!1.foreign
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK1_THUNK]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK2]] :
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]]
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>(%0)
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK2]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK2_THUNK]] :
// CHECK: [[FN:%.*]] = objc_method %0 : $@thick Self.Type, #NSRuncing.mince!1.foreign
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0)
// CHECK-NEXT: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK2_THUNK]]'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[THIS:%.*]] : @owned $NSRuncing):
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[BORROWED_THIS_1:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS1:%.*]] = open_existential_ref [[BORROWED_THIS_1]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = objc_method [[THIS1]] : $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]])
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[BORROWED_THIS_2:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS2:%.*]] = open_existential_ref [[BORROWED_THIS_2]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = objc_method [[THIS2]] : $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]])
// -- Arguments are not consumed by objc calls
// CHECK: end_borrow [[BORROWED_THIS_2]] from [[THIS]]
// CHECK: end_borrow [[BORROWED_THIS_1]] from [[THIS]]
// CHECK: destroy_value [[THIS]]
func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () {
func objc_protocol_partial_apply(_ x: NSRuncing) {
// CHECK: bb0([[ARG:%.*]] : @owned $NSRuncing):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[BORROWED_ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[FN:%.*]] = function_ref @_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO
// CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]])
// CHECK: destroy_value [[RESULT]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
_ = x.runce
// FIXME: rdar://21289579
// _ = NSRuncing.runce
}
// CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F
func objc_protocol_composition(_ x: NSRuncing & NSFunging) {
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.runce()
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSFunging.funge!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.funge()
}
// -- ObjC thunks get emitted for ObjC protocol conformances
class Foo : NSRuncing, NSFunging, Ansible {
// -- NSRuncing
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc static func mince() -> NSObject { return NSObject() }
// -- NSFunging
@objc func funge() {}
// -- Both NSRuncing and NSFunging
@objc func foo() {}
// -- Ansible
func anse() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo
// CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}}
class Bar { }
extension Bar : NSRuncing {
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo
// class Bas from objc_protocols_Bas module
extension Bas : NSRuncing {
// runce() implementation from the original definition of Bas
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- Inherited objc protocols
protocol Fungible : NSFunging { }
class Zim : Fungible {
@objc func funge() {}
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo
// class Zang from objc_protocols_Bas module
extension Zang : Fungible {
// funge() implementation from the original definition of Zim
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- objc protocols with property requirements in extensions
// <rdar://problem/16284574>
@objc protocol NSCounting {
var count: Int {get}
}
class StoredPropertyCount {
@objc let count = 0
}
extension StoredPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_protocols19StoredPropertyCountC5countSivgTo
class ComputedPropertyCount {
@objc var count: Int { return 0 }
}
extension ComputedPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols21ComputedPropertyCountC5countSivgTo
// -- adding @objc protocol conformances to native ObjC classes should not
// emit thunks since the methods are already available to ObjC.
// Gizmo declared in Inputs/usr/include/Gizmo.h
extension Gizmo : NSFunging { }
// CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}}
@objc class InformallyFunging {
@objc func funge() {}
@objc func foo() {}
}
extension InformallyFunging: NSFunging { }
@objc protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable {
func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable {
// CHECK: bb0([[META:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable }
// CHECK: [[PB:%.*]] = project_box [[I2_BOX]]
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type
// CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = objc_method [[I2_ALLOC]] : $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}}
// CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0
// CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable
// CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Initializable
// CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*Initializable
// CHECK: destroy_value [[I2_BOX]] : ${ var Initializable }
// CHECK: return [[I2]] : $Initializable
var i2 = im.init(int: i)
return i2
}
// CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF'
class InitializableConformer: Initializable {
@objc required init(int: Int) {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo
final class InitializableConformerByExtension {
init() {}
}
extension InitializableConformerByExtension: Initializable {
@objc convenience init(int: Int) {
self.init()
}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo
// Make sure we're crashing from trying to use materializeForSet here.
@objc protocol SelectionItem {
var time: Double { get set }
}
func incrementTime(contents: SelectionItem) {
contents.time += 1.0
}
| 3364960f9255108415996afa8158c6f8 | 43.029508 | 204 | 0.644203 | false | false | false | false |
Babylonpartners/ReactiveFeedback | refs/heads/develop | Example/SingleStoreExample/Movies/MovieCell.swift | mit | 1 | import UIKit
import ReactiveSwift
import ReactiveCocoa
class ImageFetcher {
static let shared = ImageFetcher()
private let cache = NSCache<NSURL, UIImage>()
func image(for url: URL) -> SignalProducer<UIImage, Never> {
return SignalProducer.deferred {
if let image = self.cache.object(forKey: url as NSURL) {
return SignalProducer(value: image)
}
return URLSession.shared.reactive.data(with: URLRequest(url: url))
.map { $0.0 }
.map(UIImage.init(data:))
.skipNil()
.on(value: {
self.cache.setObject($0, forKey: url as NSURL)
})
.flatMapError { _ in SignalProducer<UIImage, Never>(value: UIImage()) }
.observe(on: UIScheduler())
}
}
}
extension SignalProducer {
static func deferred(_ producer: @escaping () -> SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer { $1 += producer().start($0) }
}
}
final class MovieCell: UICollectionViewCell, NibLoadable {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.backgroundColor = .gray
}
}
private var disposable: Disposable? {
willSet {
disposable?.dispose()
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.title.text = nil
self.imageView.image = nil
}
func configure(with movie: Movie) {
title.text = movie.title
disposable = (movie.posterURL.map(ImageFetcher.shared.image(for:)) ?? .empty)
.startWithValues { [weak self] in
self?.imageView.image = $0
}
}
}
| 0ce9764eac0ffebb0bfa260abf862cf8 | 28.322581 | 116 | 0.572057 | false | false | false | false |
XWebView/XWebView | refs/heads/master | XWebViewTests/ConstructorPlugin.swift | apache-2.0 | 1 | /*
Copyright 2015 XWebView
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 XCTest
import XWebView
class ConstructorPlugin : XWVTestCase {
class Plugin0 : NSObject, XWVScripting {
@objc init(expectation: Any?) {
if let e = expectation as? XWVScriptObject {
e.callMethod("fulfill", with: nil, completionHandler: nil)
}
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin0.init(expectation:)) ? "" : nil
}
}
class Plugin1 : NSObject, XWVScripting {
@objc dynamic var property: Int
@objc init(value: Int) {
property = value
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin1.init(value:)) ? "" : nil
}
}
class Plugin2 : NSObject, XWVScripting {
private let expectation: XWVScriptObject?
@objc init(expectation: Any?) {
self.expectation = expectation as? XWVScriptObject
}
func finalizeForScript() {
expectation?.callMethod("fulfill", with: nil, completionHandler: nil)
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin2.init(expectation:)) ? "" : nil
}
}
let namespace = "xwvtest"
func testConstructor() {
let desc = "constructor"
let script = "if (\(namespace) instanceof Function) fulfill('\(desc)')"
_ = expectation(description: desc)
loadPlugin(Plugin0(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
func testConstruction() {
let desc = "construction"
let script = "new \(namespace)(expectation('\(desc)'))"
_ = expectation(description: desc)
loadPlugin(Plugin0(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
func testSyncProperties() {
let desc = "syncProperties"
let script = "(new \(namespace)(456)).then(function(o){if (o.property==456) fulfill('\(desc)');})"
_ = expectation(description: desc)
loadPlugin(Plugin1(value: 123), namespace: namespace, script: script)
waitForExpectations()
}
func testFinalizeForScript() {
let desc = "finalizeForScript"
let script = "(new \(namespace)(expectation('\(desc)'))).then(function(o){o.dispose();})"
_ = expectation(description: desc)
loadPlugin(Plugin2(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
}
| 412e69836ab1efa4f62294365441ac6b | 36.666667 | 106 | 0.637168 | false | true | false | false |
danielgindi/Charts | refs/heads/master | Source/Charts/Highlight/HorizontalBarHighlighter.swift | apache-2.0 | 2 | //
// HorizontalBarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(HorizontalBarChartHighlighter)
open class HorizontalBarHighlighter: BarHighlighter
{
open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight?
{
guard let barData = self.chart?.data as? BarChartData else { return nil }
let pos = getValsForTouch(x: y, y: x)
guard let high = getHighlight(xValue: Double(pos.y), x: y, y: x) else { return nil }
if let set = barData[high.dataSetIndex] as? BarChartDataSetProtocol,
set.isStacked
{
return getStackedHighlight(high: high,
set: set,
xValue: Double(pos.y),
yValue: Double(pos.x))
}
return high
}
internal override func buildHighlights(
dataSet set: ChartDataSetProtocol,
dataSetIndex: Int,
xValue: Double,
rounding: ChartDataSetRounding) -> [Highlight]
{
guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return [] }
var entries = set.entriesForXValue(xValue)
if entries.isEmpty, let closest = set.entryForXValue(xValue, closestToY: .nan, rounding: rounding)
{
// Try to find closest x-value and take all entries for that x-value
entries = set.entriesForXValue(closest.x)
}
return entries.map { e in
let px = chart.getTransformer(forAxis: set.axisDependency)
.pixelForValues(x: e.y, y: e.x)
return Highlight(x: e.x, y: e.y, xPx: px.x, yPx: px.y, dataSetIndex: dataSetIndex, axis: set.axisDependency)
}
}
internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat
{
return abs(y1 - y2)
}
}
| aff550a5bdd18504d8cab9dc8107e4fe | 32.460317 | 120 | 0.60389 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Foundation/BaseScreen/BaseScreenViewController.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
open class BaseScreenViewController: UIViewController {
// MARK: - Types
private enum Constant {
static let titleViewHeight: CGFloat = 40
}
// MARK: - Public Properties
/**
The style of the navigation bar.
Defines the background, and the content colors.
*/
public var barStyle: Screen.Style.Bar = .darkContent() {
didSet {
baseNavigationController?.navigationBar.titleTextAttributes = barStyle.titleTextAttributes
setBackground(by: barStyle)
}
}
/**
The title style of the navigation bar.
By setting this property, the title of the navigation bar
readjusts its content.
Also, if the title is `.none` - it becomes hidden
*/
public var titleViewStyle = Screen.Style.TitleView.none {
didSet {
set(titleViewStyle: titleViewStyle)
}
}
/// Indicates if the view controller should extend safe area under the navigation bar.
/// This is achieved by making `additionalSafeAreaInsets.top` the negative of navigation bar height.
public var extendSafeAreaUnderNavigationBar = false {
didSet {
if oldValue != extendSafeAreaUnderNavigationBar {
viewIfLoaded?.setNeedsLayout()
}
}
}
/**
The style of the left button in the navigation bar.
By setting this property, the left button of the navigation bar
readjusts its color and content (image / title).
Also, if *leftButtonStyle* is *.none*, The left button becomes hidden
*/
public var leadingButtonStyle = Screen.Style.LeadingButton.none {
didSet {
let itemType: NavigationBarButtonItem.ItemType
if let content = leadingButtonStyle.content {
itemType = NavigationBarButtonItem.ItemType.content(content: content) { [weak self] in
self?.navigationBarLeadingButtonPressed()
}
} else {
itemType = .none
}
leadingBarButtonItem = NavigationBarButtonItem(type: itemType, color: barStyle.tintColor)
}
}
/**
The style of the right button in the navigation bar.
By setting this property, the right button of the navigation bar
readjusts its color and content (image / title).
Also, if *rightButtonStyle* is *.none*, The right button becomes hidden,
in that case, it won't be an accessibility element.
*/
public var trailingButtonStyle = Screen.Style.TrailingButton.none {
didSet {
let itemType: NavigationBarButtonItem.ItemType
var color = barStyle.tintColor
switch trailingButtonStyle {
case .content(let content):
itemType = .content(content: content) { [weak self] in
self?.navigationBarTrailingButtonPressed()
}
case .processing:
itemType = .processing
case .qrCode, .questionMark:
itemType = .content(content: trailingButtonStyle.content!) { [weak self] in
self?.navigationBarTrailingButtonPressed()
}
case .close:
itemType = .content(content: trailingButtonStyle.content!) { [weak self] in
self?.navigationBarTrailingButtonPressed()
}
color = UIColor.NavigationBar.closeButton
case .none:
itemType = .none
case .skip:
itemType = .content(content: trailingButtonStyle.content!) { [weak self] in
self?.navigationBarTrailingButtonPressed()
}
color = UIColor.NavigationBar.closeButton
}
trailingBarButtonItem = NavigationBarButtonItem(type: itemType, color: color)
}
}
public var automaticallyApplyNavigationBarStyle: Bool = true
override open var preferredStatusBarStyle: UIStatusBarStyle {
loadViewIfNeeded()
return determineStatusBarStyle()
}
// MARK: - Private Properties
/// The ancestor navigation controller
private weak var _baseNavigationController: UINavigationController?
private var baseNavigationController: UINavigationController? {
if _baseNavigationController == nil {
var result: UIViewController? = self
while result != nil, !(result is UINavigationController) {
result = result?.parent
}
_baseNavigationController = result as? UINavigationController
}
return _baseNavigationController
}
private lazy var drawerRouter: DrawerRouting = resolve()
private lazy var qrCodeScannerRouter: QRCodeScannerRouting = resolve()
private var currentNavigationItem: UINavigationItem? {
navigationItem
}
private var trailingBarButtonItem: UIBarButtonItem! {
didSet {
currentNavigationItem?.setRightBarButton(trailingBarButtonItem, animated: false)
}
}
private var leadingBarButtonItem: UIBarButtonItem! {
didSet {
currentNavigationItem?.setLeftBarButton(leadingBarButtonItem, animated: false)
}
}
private var standardNavigationBarButtonStyles: (leading: Screen.Style.LeadingButton, trailing: Screen.Style.TrailingButton) {
var trailing: Screen.Style.TrailingButton = .none
var leading: Screen.Style.LeadingButton = .none
let viewControllersCount = navigationController?.viewControllers.count ?? 1
if viewControllersCount > 1 {
leading = .back
} else {
trailing = .close
}
return (leading, trailing)
}
// MARK: - Lifecycle
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if automaticallyApplyNavigationBarStyle {
setBackground(by: barStyle)
currentNavigationItem?.setHidesBackButton(true, animated: false)
setNeedsStatusBarAppearanceUpdate()
}
}
override open func viewWillLayoutSubviews() {
updateExtendSafeAreaUnderNavigationBar()
super.viewWillLayoutSubviews()
}
private func updateExtendSafeAreaUnderNavigationBar() {
guard isViewLoaded else {
// Do not trigger if view is not loaded.
return
}
let navigationBarHeight: CGFloat
if extendSafeAreaUnderNavigationBar {
navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0
} else {
navigationBarHeight = 0
}
additionalSafeAreaInsets.top = -navigationBarHeight
}
// MARK: - Setup
private func determineStatusBarStyle() -> UIStatusBarStyle {
if isPresentedModally {
return .lightContent
}
switch barStyle {
case .lightContent:
return .lightContent
case .darkContent:
return .default
}
}
private func setBackground(by style: Screen.Style.Bar) {
baseNavigationController?.navigationBar.shadowImage = UIImage()
baseNavigationController?.navigationBar.barTintColor = style.backgroundColor
}
private func set(titleViewStyle: Screen.Style.TitleView) {
guard let navigationItem = currentNavigationItem else {
return
}
switch titleViewStyle {
case .text(value: let text):
navigationItem.titleView = nil
navigationItem.title = text
case .image(name: let image, width: let width):
let view = UIImageView(image: UIImage(named: image))
view.contentMode = .scaleAspectFit
view.layout(size: CGSize(width: width, height: Constant.titleViewHeight))
navigationItem.titleView = view
navigationItem.title = nil
case .view(value: let titleView):
navigationItem.title = nil
navigationItem.titleView = titleView
case .none:
navigationItem.titleView = nil
navigationItem.title = nil
}
}
public func setStandardDarkContentStyle() {
let (leading, trailing) = standardNavigationBarButtonStyles
set(
barStyle: .darkContent(),
leadingButtonStyle: leading,
trailingButtonStyle: trailing
)
}
public func setStandardLightContentStyle() {
let (leading, trailing) = standardNavigationBarButtonStyles
set(
barStyle: .lightContent(),
leadingButtonStyle: leading,
trailingButtonStyle: trailing
)
}
public func set(
barStyle: Screen.Style.Bar,
leadingButtonStyle: Screen.Style.LeadingButton = .none,
trailingButtonStyle: Screen.Style.TrailingButton = .none
) {
guard automaticallyApplyNavigationBarStyle else { return }
self.barStyle = barStyle
self.leadingButtonStyle = leadingButtonStyle
self.trailingButtonStyle = trailingButtonStyle
}
public func setNavigationBar(visible: Bool) {
baseNavigationController?.navigationBar.isHidden = !visible
baseNavigationController?.isNavigationBarHidden = !visible
}
// MARK: - User Interaction
open func navigationBarTrailingButtonPressed() {
switch trailingButtonStyle {
case .close, .skip:
dismiss(animated: true, completion: nil)
case .qrCode:
qrCodeScannerRouter.showQRCodeScanner()
case .none, .processing, .content, .questionMark:
break
}
}
open func navigationBarLeadingButtonPressed() {
switch leadingButtonStyle {
case .back:
baseNavigationController?.popViewController(animated: true)
case .close:
dismiss(animated: true, completion: nil)
case .drawer:
drawerRouter.toggleSideMenu()
case .none,
.text:
break
}
}
public func removeFromHierarchy() {
switch (leadingButtonStyle, trailingButtonStyle) {
case (.close, _), (_, .close):
dismiss(animated: true, completion: nil)
case (.back, _):
baseNavigationController?.popViewController(animated: true)
default:
if isPresentedModally {
dismiss(animated: true, completion: nil)
} else {
baseNavigationController?.popViewController(animated: true)
}
}
}
}
| acec661a02c628d729a80d8364ba226a | 33.745928 | 129 | 0.625199 | false | false | false | false |
kodlian/Eki | refs/heads/master | Eki/Timer.swift | mit | 1 | //
// Timer.swift
// Eki
//
// Created by Jeremy Marchand on 20/10/2014.
// Copyright (c) 2014 Jérémy Marchand. All rights reserved.
//
import Foundation
/**
A wrapper for Grand Central Dispatch Source Type Timer
*/
public final class Timer {
//MARK: factory
public class func scheduleWithInterval(interval: NSTimeInterval, onQueue queue: Queue, byRepeating shouldRepeat: Bool = false, block: () -> Void) -> Timer {
let timer = Timer(queue: queue, interval: interval, shouldRepeat: shouldRepeat)
timer.block = block
timer.start()
return timer
}
public class func scheduleWithDate(date: NSDate, onQueue queue: Queue, block: () -> Void) -> Timer {
let timer = Timer(queue: queue, date: date)
timer.block = block
timer.start()
return timer
}
//MARK: Properties
public let queue: Queue
private let source: dispatch_source_t
private let syncQueue = Queue(name: "Timer.syncQueue", kind: .Serial)
private var suspended = false
//MARK: Timer setter
public var startTime: TimeConvertible = 0 {
didSet {
startDispatchTime = startTime.dispatchTime
updateSourceTimer()
}
}
private var startDispatchTime: dispatch_time_t = 0
public var repeatInterval: NSTimeInterval? = nil {
didSet {
if repeatInterval != oldValue {
updateSourceTimer()
}
}
}
public var tolerance: NSTimeInterval = 0.0 {
didSet {
if tolerance != oldValue {
updateSourceTimer()
}
}
}
private func updateSourceTimer() {
let deltaTime: UInt64
if let interval = repeatInterval {
deltaTime = UInt64(interval * NSTimeInterval(NSEC_PER_SEC))
} else {
deltaTime = DISPATCH_TIME_FOREVER
}
dispatch_source_set_timer(
source,
startDispatchTime,
deltaTime,
UInt64(tolerance * NSTimeInterval(NSEC_PER_SEC)))
}
//MARK: Handler setter
public var block: (() -> Void)? = nil {
didSet {
updateHandler(dispatch_source_set_event_handler, handler: block)
}
}
public var cancelHandler: (() -> Void)? = nil {
didSet {
updateHandler(dispatch_source_set_cancel_handler, handler: cancelHandler)
}
}
public var startHandler: (() -> Void)? = nil {
didSet {
updateHandler(dispatch_source_set_registration_handler, handler: startHandler)
}
}
private func updateHandler(handlerSetMethod:(source: dispatch_source_t, handler: dispatch_block_t!) -> Void, handler someHandler:(() -> Void)?) {
let handler = someHandler != nil ? someHandler : { () -> Void in }
handlerSetMethod(source: source, handler: handler)
}
//MARK: init
private init(queue: Queue) {
self.queue = queue
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue.dispatchQueue)
}
convenience public init(queue: Queue, interval: NSTimeInterval, shouldRepeat: Bool = false) {
self.init(queue: queue)
startTime = interval
if shouldRepeat {
repeatInterval = interval
}
startDispatchTime = startTime.dispatchTime
updateSourceTimer()
}
convenience public init(queue: Queue, interval: NSTimeInterval, repeatInterval rInterval: NSTimeInterval? = nil) {
self.init(queue: queue)
startTime = interval
repeatInterval = rInterval
startDispatchTime = startTime.dispatchTime
updateSourceTimer()
}
convenience public init(queue: Queue, date: NSDate) {
self.init(queue: queue)
startTime = date
startDispatchTime = startTime.dispatchTime
updateSourceTimer()
}
deinit {
block = nil
startHandler = nil
cancelHandler = nil
if !stopped {
stop()
}
}
//MARK: Suspend & Resume
public func start() {
syncQueue.sync {
let suspended = self.suspended
if suspended {
self.suspended = false
dispatch_resume(self.source)
}
}
}
public func pause() {
syncQueue.sync {
let suspended = self.suspended
if !suspended {
self.suspended = true
dispatch_suspend(self.source)
}
}
}
public var isRunning: Bool {
var isSuspended = false
syncQueue.sync {
isSuspended = self.suspended
}
return !isSuspended
}
//MARK: cancel
public func stop() {
dispatch_source_cancel(source)
}
var stopped: Bool {
return 0 != dispatch_source_testcancel(source)
}
}
//MARK: Time
public protocol TimeConvertible {
var dispatchTime: dispatch_time_t { get }
}
extension NSTimeInterval: TimeConvertible {
public var dispatchTime: dispatch_time_t {
let deltaTime = self * NSTimeInterval(NSEC_PER_SEC)
return dispatch_time(DISPATCH_TIME_NOW, Int64(deltaTime))
}
}
private extension NSTimeInterval {
private var timeSpec: timespec {
var seconds: NSTimeInterval = 0.0
let nanoSeconds = modf(self, &seconds) * NSTimeInterval(NSEC_PER_SEC)
return timespec(tv_sec: __darwin_time_t(seconds), tv_nsec: Int(nanoSeconds))
}
}
extension NSDate: TimeConvertible {
public var dispatchTime: dispatch_time_t {
var walltime = self.timeIntervalSince1970.timeSpec
return dispatch_walltime(&walltime, 0)
}
}
| 76f8da555a66006c790f778303353973 | 25.938679 | 160 | 0.598319 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | Sources/Modules/FilesModule+Representations.swift | apache-2.0 | 1 | //
// FilesModule+Representations.swift
// BoxSDK
//
// Created by Daniel Cech on 01/08/2019.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Extension of FilesModule that handles file representations
public extension FilesModule {
/// Get representations for a file.
///
/// - Parameters:
/// - fileId: The id of the file to retrieve representations for.
/// - representationHint: The representation to retrieve for the file. It can be one of predefined
/// options or custom representation, see [representation
/// documentation](https://developer.box.com/reference#representations).
/// - completion: Returns an array of the specified representations.
func listRepresentations(
fileId: String,
representationHint: FileRepresentationHint? = nil,
completion: @escaping Callback<[FileRepresentation]>
) {
var headers: [String: String] = [:]
if let xRepHints = representationHint?.description {
headers["x-rep-hints"] = xRepHints
}
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: boxClient.configuration),
httpHeaders: headers,
queryParameters: ["fields": FieldsQueryParam(["representations"])],
completion: { result in
let objectResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) }
switch objectResult {
case let .success(file):
guard let entries = file.representations?.entries else {
return completion(.failure(BoxAPIError(message: .notFound("File does not have any representations"))))
}
completion(.success(entries))
case let .failure(error):
return completion(.failure(error))
}
}
)
}
/// Get particular representation for a file.
///
/// - Parameters:
/// - fileId: The id of the file to retrieve representations for.
/// - representationHint: The representation to retrieve for the file. It can be one of predefined
/// options or custom representation. If multiple representations match the representationHint,
/// the behavior is undefined - used representation is selected nondeterministically.
/// See [representation documentation](https://developer.box.com/reference#representations).
/// - assetPath: Asset path for representations with multiple files
/// - destinationURL: A URL for the location on device that we want to store the file once been donwloaded
/// - completion: Returns an array of the specified representations.
func getRepresentationContent(
fileId: String,
representationHint: FileRepresentationHint,
assetPath: String = "",
destinationURL: URL,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<Void>
) {
listRepresentations(fileId: fileId, representationHint: representationHint) { [weak self] result in
guard let self = self else {
completion(.failure(BoxSDKError(message: .instanceDeallocated("Unable to get representation content - FilesModule deallocated"))))
return
}
switch result {
case let .success(representations):
guard let firstRepresentation = representations.first else {
completion(.failure(BoxAPIError(message: .notFound("File does not have representations"))))
return
}
self.processRepresentation(firstRepresentation, assetPath: assetPath) { result in
switch result {
case let .success(url):
self.downloadRepresentation(sourceURL: url, destinationURL: destinationURL, progress: progress, completion: completion)
case .failure:
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
}
}
case let .failure(error):
completion(.failure(error))
}
}
}
}
extension FilesModule {
func processRepresentation(
_ representation: FileRepresentation,
assetPath: String = "",
completion: @escaping Callback<URL>
) {
guard
let status = representation.status?.state,
let assetString = representation.content?.urlTemplate?.replacingOccurrences(of: "{+asset_path}", with: assetPath),
let assetURL = URL(string: assetString),
let infoURLString = representation.info?.url,
let infoURL = URL(string: infoURLString)
else {
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
return
}
switch status {
case .none, .pending:
pollRepresentation(infoURL: infoURL, assetPath: assetPath, completion: completion)
case .success, .viewable:
completion(.success(assetURL))
case .error:
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
default:
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
}
}
func pollRepresentation(
infoURL: URL,
assetPath: String = "",
completion: @escaping Callback<URL>
) {
boxClient.get(url: infoURL) { result in
switch result {
case let .success(response):
guard let bodyData = response.body else {
completion(.failure(BoxAPIError(message: .representationCreationFailed, response: response)))
return
}
// swiftlint:disable:next force_unwrapping
let responseJsonData = bodyData.isEmpty ? "{}".data(using: .utf8)! : bodyData
let responseJSON = try? JSONSerialization.jsonObject(with: responseJsonData, options: []) as? [String: Any]
guard
let statusDict = responseJSON?["status"] as? [String: Any],
let stateString = statusDict["state"] as? String,
let contentDict = responseJSON?["content"] as? [String: Any],
let contentURLString = contentDict["url_template"] as? String,
let contentURL = URL(string: contentURLString.replacingOccurrences(of: "{+asset_path}", with: assetPath))
else {
completion(.failure(BoxAPIError(message: .representationCreationFailed, response: response)))
return
}
let state = FileRepresentation.StatusEnum(stateString)
switch state {
case .none, .pending:
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
guard let self = self else {
completion(.failure(BoxSDKError(message: .instanceDeallocated("Unable to poll for representations - FilesModule deallocated"))))
return
}
self.pollRepresentation(infoURL: infoURL, completion: completion)
}
case .viewable, .success:
completion(.success(contentURL))
case .error:
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
default:
completion(.failure(BoxAPIError(message: .representationCreationFailed)))
}
case let .failure(error):
completion(.failure(error))
}
}
}
/// Download a file to a specified folder.
///
/// - Parameters:
/// - fileId: The ID of the file
/// - destinationURL: A URL for the location on device that we want to store the file once been donwloaded
/// - version: Optional file version ID to download (defaults to the current version)
/// - completion: Returns an empty response or an error
/// - Returns: BoxDownloadTask
@discardableResult
public func downloadRepresentation(
sourceURL: URL,
destinationURL: URL,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<Void>
) -> BoxDownloadTask {
return boxClient.download(
url: sourceURL,
downloadDestinationURL: destinationURL,
progress: progress,
completion: { result in
completion(result.map { _ in })
}
)
}
}
| 209b2ba26afbb8595753c03c807bfc78 | 40.311628 | 156 | 0.590295 | false | false | false | false |
r9ronaldozhang/ZYColumnViewController | refs/heads/master | ZYColumnViewDemo/ZYColumnViewDemo/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ZYColumnViewDemo
//
// Created by 张宇 on 2016/10/28.
// Copyright © 2016年 成都拓尔思. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let navVC = UINavigationController(rootViewController: ViewController())
let tbVC = UITabBarController()
tbVC.addChildViewController(navVC)
tbVC.title = "首页"
window?.rootViewController = tbVC
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 1ec7761bd9136cc457b436d68a39995d | 44.849057 | 285 | 0.739918 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | packages/TGUIKit/Sources/SPopoverRowItem.swift | gpl-2.0 | 1 | //
// SPopoverRowItem.swift
// Telegram-Mac
//
// Created by keepcoder on 28/09/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
class SPopoverRowItem: TableRowItem {
private let _height: CGFloat
override var height: CGFloat {
return _height
}
private var unique:Int64
override var stableId: AnyHashable {
return unique
}
let iStyle:ControlStyle = ControlStyle(backgroundColor: presentation.colors.accentSelect, highlightColor: presentation.colors.underSelectedColor)
// data
let image:CGImage?
let title:TextViewLayout
let activeTitle: TextViewLayout
let clickHandler:() -> Void
override func viewClass() -> AnyClass {
return SPopoverRowView.self
}
let alignAsImage: Bool
let additionView: SPopoverAdditionItemView?
init(_ initialSize:NSSize, height: CGFloat, image:CGImage? = nil, alignAsImage: Bool, title:String, textColor: NSColor, additionView: SPopoverAdditionItemView? = nil, clickHandler:@escaping() ->Void = {}) {
self.image = image
self._height = height
self.alignAsImage = alignAsImage
self.title = TextViewLayout(.initialize(string: title, color: textColor, font: .normal(.title)), maximumNumberOfLines: 1)
self.activeTitle = TextViewLayout(.initialize(string: title, color: presentation.colors.underSelectedColor, font: .normal(.title)), maximumNumberOfLines: 1)
self.additionView = additionView
self.title.measure(width: 200)
self.activeTitle.measure(width: 200)
self.clickHandler = clickHandler
unique = Int64(arc4random())
super.init(initialSize)
}
var itemWidth: CGFloat {
return self.title.layoutSize.width + (additionView != nil ? 40 : 0)
}
}
private class SPopoverRowView: TableRowView {
var image:ImageView = ImageView()
var overlay:OverlayControl = OverlayControl()
var text:TextView = TextView();
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.addSubview(overlay)
overlay.addSubview(image)
overlay.addSubview(text)
text.isSelectable = false
text.userInteractionEnabled = false
overlay.set(handler: {[weak self] (state) in
self?.overlay.backgroundColor = presentation.colors.accentSelect
if let item = self?.item as? SPopoverRowItem {
if let image = item.image {
self?.image.image = item.iStyle.highlight(image: image)
}
self?.text.backgroundColor = presentation.colors.accentSelect
self?.text.update(item.activeTitle)
item.additionView?.updateIsSelected?(self?.mouseInside() ?? false)
}
}, for: .Hover)
overlay.set(handler: {[weak self] (state) in
self?.overlay.backgroundColor = presentation.colors.background
if let item = self?.item as? SPopoverRowItem {
self?.image.image = item.image
self?.text.backgroundColor = presentation.colors.background
self?.text.update(item.title)
item.additionView?.updateIsSelected?(self?.mouseInside() ?? false)
}
}, for: .Normal)
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
overlay.setFrameSize(newSize)
}
override func layout() {
super.layout()
if let item = item as? SPopoverRowItem {
if item.image != nil || item.alignAsImage {
text.centerY(self, x: 45)
} else {
text.center()
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateMouse() {
overlay.updateState()
}
override func set(item:TableRowItem, animated:Bool = false) {
super.set(item: item, animated: animated)
overlay.removeAllHandlers()
overlay.backgroundColor = presentation.colors.background
text.backgroundColor = presentation.colors.background
if let item = item as? SPopoverRowItem {
if let view = item.additionView {
overlay.addSubview(view.view)
view.view.setFrameOrigin(NSMakePoint(frame.width - 34, 10))
}
image.image = item.image
overlay.removeAllHandlers()
overlay.set(handler: {_ in
item.clickHandler()
}, for: .Click)
image.sizeToFit()
image.centerY(self, x: floorToScreenPixels(backingScaleFactor, (45 - image.frame.width) / 2))
text.update(item.title)
if item.image != nil || item.alignAsImage {
text.centerY(self, x: 45)
} else {
text.center()
}
}
}
}
public final class SPopoverSeparatorItem : TableRowItem {
let drawBorder: Bool
override public var stableId: AnyHashable {
return arc4random()
}
override public init(_ initialSize: NSSize) {
self.drawBorder = true
super.init(initialSize)
}
public init(_ drawBorder: Bool = true) {
self.drawBorder = drawBorder
super.init(NSZeroSize)
}
override public func viewClass() -> AnyClass {
return SPopoverSeparatorView.self
}
override public var height: CGFloat {
return drawBorder ? 10 : 1
}
}
private final class SPopoverSeparatorView : TableRowView {
private let separator: View = View()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(separator)
}
override func updateColors() {
super.updateColors()
separator.backgroundColor = presentation.colors.border
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? SPopoverSeparatorItem else {
return
}
// separator.isHidden = !item.drawBorder
}
override func layout() {
super.layout()
separator.setFrameSize(NSMakeSize(frame.width, .borderSize))
separator.center()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| e02214f616dfb6dbf38664fa681a542f | 30.023364 | 210 | 0.601446 | false | false | false | false |
willrichman/GithubToGo | refs/heads/master | GithubToGo/UserSearchViewController.swift | mit | 1 | //
// UserSearchViewController.swift
// GithubToGo
//
// Created by William Richman on 10/22/14.
// Copyright (c) 2014 Will Richman. All rights reserved.
//
import UIKit
class UserSearchViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionView: UICollectionView!
var userResults = [User]()
let searchType = NetworkController.SearchType.Users
var selectedCell : UICollectionViewCell?
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.collectionView.dataSource = self
self.collectionView.delegate = self
}
//MARK: - UICollectionViewDataSource Methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.userResults.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("USER_CELL", forIndexPath: indexPath) as UserCell
var userForCell = userResults[indexPath.row] as User
cell.userImage.image = nil
var currentTag = cell.tag + 1
cell.tag = currentTag
cell.label.text = userForCell.login
if let userImage = userForCell.avatarImage {
if cell.tag == currentTag {
cell.userImage.image = userImage
}
} else {
NetworkController.controller.getAvatar(userForCell.avatarURL!, completionHandler: { (image, errorDescription) -> Void in
if cell.tag == currentTag {
cell.userImage.image = image
userForCell.avatarImage = image
}
})
}
return cell
}
//MARK: - UICollectionViewDelegate Methods
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// Find tapped image, initialize next view controller
let image = self.userResults[indexPath.row % self.userResults.count].avatarImage!
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController
// Set image and reverseOrigin properties on next view controller
viewController.image = image
let user = self.userResults[indexPath.row]
viewController.selectedUser = user
self.selectedCell = self.collectionView.cellForItemAtIndexPath(indexPath)
// Trigger a normal push animations; let navigation controller take over.
self.navigationController?.pushViewController(viewController, animated: true)
}
//MARK: - UISearchBarDelegate Methods
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
NetworkController.controller.search(searchBar.text, type: searchType, completionHandler: { (returnedArray, errorDescription) -> Void in
self.userResults = returnedArray as [User]
self.collectionView.reloadData()
searchBar.resignFirstResponder()
})
}
func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
var warningRect = CGRect(x: 37, y: 114, width: 300, height: 40)
var warningLabel = UILabel()
warningLabel.frame = warningRect
warningLabel.backgroundColor = UIColor.redColor()
warningLabel.textColor = UIColor.whiteColor()
warningLabel.textAlignment = NSTextAlignment.Center
warningLabel.layer.cornerRadius = 8
warningLabel.clipsToBounds = true
warningLabel.alpha = 0
warningLabel.text = "Search does not support character '\(text)'"
if text.validate() == false {
view.addSubview(warningLabel)
UIView.animateWithDuration(0.8, delay: 0.0, options: nil, animations: { () -> Void in
warningLabel.alpha = 1.0
}, completion: { (finished) -> Void in
UIView.animateWithDuration(0.8, delay: 2.0, options: nil, animations: { () -> Void in
warningLabel.alpha = 0.0
}, completion: { (finished) -> Void in
})
})
}
return text.validate()
}
}
| ee145559c0a91d4c3fe19d2600f7da9e | 39.434783 | 143 | 0.647097 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SILOptimizer/diagnose_lifetime_issues.swift | apache-2.0 | 9 | // RUN: %target-swift-frontend -emit-sil -enable-lexical-borrow-scopes=false -enable-copy-propagation %s -o /dev/null -verify
class Delegate {
func foo() { }
}
final class Container {
weak var delegate: Delegate?
var strongRef: Delegate
func callDelegate() {
delegate!.foo()
}
init(_ d: Delegate) { strongRef = d }
init(weakDelegate: Delegate, strongDelegate: Delegate) {
delegate = weakDelegate
strongRef = strongDelegate
}
}
func warningForDeadDelegate(container: Container) {
let delegate = Delegate()
container.delegate = delegate // expected-warning {{weak reference will always be nil because the referenced object is deallocated here}}
container.callDelegate()
}
func noWarningForStoredDelegate(container: Container) {
let delegate = Delegate()
container.strongRef = delegate
container.delegate = delegate
container.callDelegate()
}
func noWarningWithFixLifetime(container: Container) {
let delegate = Delegate()
defer { _fixLifetime(delegate) }
container.delegate = delegate
container.callDelegate()
}
func warningWithControlFlow(container: Container, _ b: Bool) {
let delegate = Delegate()
container.delegate = delegate // expected-warning {{weak reference will always be nil because the referenced object is deallocated here}}
if b {
container.callDelegate()
}
}
var globalClosure: (() -> ())?
func storeClosure(_ c: @escaping () -> ()) {
globalClosure = c
}
func warningForDeadClosureCapture() {
let k = Delegate()
storeClosure({ [weak k] in // expected-warning {{weak reference will always be nil because the referenced object is deallocated here}}
k!.foo()
})
}
func noWarningWithFixLifetime2() {
let k = Delegate()
defer { _fixLifetime(k) }
storeClosure({ [weak k] in
k!.foo()
})
}
func warningWithStoreWeakInCalledFunction() {
let d = Delegate()
let c = Container(weakDelegate: d, strongDelegate: Delegate()) // expected-warning {{weak reference will always be nil because the referenced object is deallocated here}}
c.callDelegate()
}
final class StrongContainer {
var k: Delegate
init(_ k: Delegate) { self.k = k }
func set(_ newk: Delegate) { k = newk }
func noset(_ newk: Delegate) { }
}
final class Testcl {
private weak var wk: Delegate?
func test_set(_ c: StrongContainer) {
let k = Delegate()
c.set(k)
wk = k // No warning here, because k is kept alive by c
}
func test_noset(_ c: StrongContainer) {
let k = Delegate()
c.noset(k)
wk = k // expected-warning {{weak reference will always be nil because the referenced object is deallocated here}}
}
}
| f1a1699dd60aa4695803dc9335144f4d | 26.070707 | 173 | 0.685075 | false | false | false | false |
dduan/swift | refs/heads/master | benchmark/single-source/Array2D.swift | apache-2.0 | 2 | //===--- Array2D.swift ----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@inline(never)
public func run_Array2D(N: Int) {
var A: [[Int]] = []
for _ in 0 ..< 1024 {
var B: [Int] = []
for y in 0 ..< 1024 {
B.append(y)
}
A.append(B)
}
for _ in 0..<N {
for i in 0 ..< 1024 {
for y in 0 ..< 1024 {
A[i][y] = A[i][y] + 1
A[i][y] = A[i][y] - 1
}
}
}
}
| 080f89c15d36e8035c4d746b243c5fd8 | 26.677419 | 80 | 0.472028 | false | false | false | false |
ronaldbroens/jenkinsapp | refs/heads/master | JenkinsApp/JobsReader.swift | apache-2.0 | 1 |
//
// JobsReader.swift
// JenkinsApp
//
// Created by Ronald Broens on 07/02/15.
// Copyright (c) 2015 Ronald Broens. All rights reserved.
//
import Foundation
class JobsReader
{
func LoadJenkinsJobs(jobshandler : Array<JenkinsJob> -> Void){
var results = Array<JenkinsJob>()
var settings = JenkinsSettings()
let url = NSURL(string: settings.Url + "/api/json")!
print(settings.Url + "/api/json");
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
return
}
print("Data received");
var err: NSError?
// 3
do{
var jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print("Data " + (jsonResult["nodeDescription"] as! String))
var jobs = jsonResult["jobs"] as! NSArray
for(var i = 0; i < jobs.count; i++)
{
var job = jobs[i] as! NSDictionary
var name = job["name"] as! String
var url = job["url"] as! String
var color = job["color"] as! String
//url color
var jobObject = JenkinsJob(Name: name, Url: url, Color: color)
results.append(jobObject)
}
jobshandler(results);
}catch{
print("Error")
}
})
jsonQuery.resume()
}
func GetJobDetails(joburl: String, detailhandler : JenkinsDetailInfo -> Void)
{
var buildjoburl = joburl + "api/json";
print("Will call to get job details " + buildjoburl)
let urlSession = NSURLSession.sharedSession()
let url = NSURL(string: buildjoburl)!
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
return
}
print("Data received");
var err: NSError?
// 3
do {
var jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (err != nil) {
print("JSON Error \(err!.localizedDescription)")
}
var color = (jsonResult["color"] as! String)
print("Color " + color)
var lastBuildObject = jsonResult["lastBuild"] as! NSDictionary
var buildnumer = lastBuildObject["number"] as! Int
print("Last build buildnumer: " + String(buildnumer))
var buildUrl = lastBuildObject["url"] as! String
print("Last build url: " + buildUrl)
var lastBuild = JenkinsBuildReference(Url: buildUrl, Number: buildnumer)
var builds = Array<JenkinsBuildReference>()
// lastBuild
var result = JenkinsDetailInfo(LastBuild: lastBuild, Color: color, Builds: builds)
detailhandler(result)
}catch{
print("error parsing json")
}
})
jsonQuery.resume()
}
func GetBuildDetails(buildurl: String, detailhandler : JenkinsBuild -> Void)
{
var buildjoburl = buildurl + "api/json";
print("Will call to get build details " + buildjoburl)
let urlSession = NSURLSession.sharedSession()
let url = NSURL(string: buildjoburl)!
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
return
}
print("Data received");
var err: NSError?
// 3
do{
var jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (err != nil) {
print("JSON Error \(err!.localizedDescription)")
}
var building = (jsonResult["building"] as! Bool)
var fullDisplayName = (jsonResult["fullDisplayName"] as! String)
var estimatedDuration = (jsonResult["estimatedDuration"] as! Int)
var timestamp = (jsonResult["timestamp"] as! NSNumber).longLongValue
// println("TImestamp: \(timestamp)")
var unixTimestamp = timestamp / 1000;
//println("Unixt timestamp \(unixTimestamp)")
var startTime = NSDate(timeIntervalSince1970: NSTimeInterval(unixTimestamp))
var expectedEndTime = NSDate(timeIntervalSince1970: NSTimeInterval(unixTimestamp + (estimatedDuration/1000)))
var durationInSeconds : Int = Int(expectedEndTime.timeIntervalSinceDate(startTime))
var result = JenkinsBuild(Building: building, FullDisplayName: fullDisplayName, Duration: estimatedDuration, EstimatedDuration: durationInSeconds, StartTime : startTime, ExpectedEndTime : expectedEndTime)
detailhandler(result);
}catch{
print("Error at json parse");
}
})
jsonQuery.resume()
}
func StartJobs( joburl: String)
{
let buildjoburl = joburl + "build";
print("Will call to start job " + buildjoburl)
let urlSession = NSURLSession.sharedSession()
let url = NSURL(string: buildjoburl)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
// set up the base64-encoded credentials
let settings = JenkinsSettings()
let loginString = NSString(format: "%@:%@", settings.Username, settings.Password)
let loginData: NSData? = loginString.dataUsingEncoding(NSUTF8StringEncoding)
let base64LoginString = loginData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
let jsonQuery = urlSession.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
return
}
let status = (response as! NSHTTPURLResponse).statusCode
print("status code is \(status)")
let responseText = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(responseText)
})
jsonQuery.resume()
}
} | a48cd67072e5f09ec5f6ce6b3002102e | 35.30622 | 224 | 0.526559 | false | false | false | false |
skywinder/PageMenu | refs/heads/master | Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/TestTableViewController.swift | bsd-3-clause | 1 | //
// TestTableViewController.swift
// NFTopMenuController
//
// Created by Niklas Fahl on 12/17/14.
// Copyright (c) 2014 Niklas Fahl. All rights reserved.
//
import UIKit
class TestTableViewController: UITableViewController {
var namesArray : [String] = ["David Fletcher", "Charles Gray", "Timothy Jones", "Marie Turner", "Kim White"]
var photoNameArray : [String] = ["man8.jpg", "man2.jpg", "man3.jpg", "woman4.jpg", "woman1.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "FriendTableViewCell", bundle: nil), forCellReuseIdentifier: "FriendTableViewCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("favorites page: viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
// println("favorites page: viewDidAppear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return namesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : FriendTableViewCell = tableView.dequeueReusableCellWithIdentifier("FriendTableViewCell") as FriendTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 94.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
} | bce434415dd7c91955bdad0e14d2a655 | 33.041096 | 133 | 0.683172 | false | false | false | false |
moyazi/SwiftDayList | refs/heads/master | SwiftDayList/Days/Day4/VideoCell.swift | mit | 1 | //
// VideoCell.swift
// SwiftDayList
//
// Created by leoo on 2017/6/2.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
struct video {
let image: String
let title: String
let source: String
}
class VideoCell: UITableViewCell {
var videoScreenshot: UIImageView!
var videoTitleLabel: UILabel!
var videoSourceLabel: UILabel!
var playBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
// Class 初始化
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.white
videoScreenshot = UIImageView()
videoScreenshot.isUserInteractionEnabled = true
self.contentView.addSubview(videoScreenshot)
videoTitleLabel = UILabel()
videoTitleLabel.textColor = UIColor.white
videoTitleLabel.font = UIFont.systemFont(ofSize: 18)
videoTitleLabel.textAlignment = NSTextAlignment.center
self.contentView.addSubview(videoTitleLabel)
videoSourceLabel = UILabel()
videoSourceLabel.textColor = UIColor.lightText
videoSourceLabel.font = UIFont.systemFont(ofSize: 14)
videoSourceLabel.textAlignment = NSTextAlignment.center
self.contentView.addSubview(videoSourceLabel)
playBtn = UIButton(type: UIButtonType.custom)
self.contentView.addSubview(self.playBtn)
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)!
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 226f2c7dface622883ac91037f6769ce | 27.603175 | 72 | 0.6798 | false | false | false | false |
qvik/HelsinkiOS-IBD-Demo | refs/heads/master | HelsinkiOS-Demo/Views/Base/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// HelsinkiOS-Demo
//
// Created by Jerry Jalava on 28/09/15.
// Copyright © 2015 Qvik. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var appNavBar: BaseNavigationView?
// MARK: Private methods
private func prepareNavigationBar() {
self.navigationController?.setNavigationBarHidden(true, animated: false)
appNavBar?.alpha = 1.0
if let view = appNavBar {
if let backButton = view.backButton {
backButton.addTarget(self, action: "backTapped:", forControlEvents: UIControlEvents.TouchUpInside)
}
}
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
navigationBarAttached()
}
// MARK: Default action handlers
func backTapped(sender: AnyObject?) {
if self.navigationController != nil {
self.navigationController!.popViewControllerAnimated(true)
}
}
// MARK: Overridable methods
func navigationBarAttached() {
}
func navigationBarWillAppear(animated: Bool) {
}
func navigationBarWillDisappear(animated: Bool) {
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if appNavBar != nil {
self.prepareNavigationBar()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if appNavBar != nil {
navigationBarWillAppear(animated)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if appNavBar != nil {
navigationBarWillDisappear(animated)
}
}
}
| c93798a7bc5c1c6247ff6488f1659499 | 23.911392 | 114 | 0.614837 | false | false | false | false |
longsirhero/DinDinShop | refs/heads/master | DinDinShopDemo/DinDinShopDemo/海外/Views/WCSeasCountryHeadView.swift | mit | 1 | //
// WCSeasCountryHeadView.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/8/23.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
import FSPagerView
class WCSeasCountryHeadView: UICollectionReusableView {
let pagerView = FSPagerView()
var dataSource:NSArray = NSArray() {
didSet {
self.pagerView.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
pagerView.automaticSlidingInterval = 3.0
pagerView.isInfinite = true
pagerView.dataSource = self
pagerView.delegate = self
pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
self.addSubview(pagerView)
pagerView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WCSeasCountryHeadView:FSPagerViewDataSource,FSPagerViewDelegate {
func numberOfItems(in pagerView: FSPagerView) -> Int {
return dataSource.count
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
let model:WCSeasCountryBanerModel = dataSource[index] as! WCSeasCountryBanerModel
cell.imageView?.kf.setImage(with: URL(string: model.picLogpath!))
return cell
}
}
| 02f038c97c4b70ea51880ef0aa39c962 | 26.372881 | 91 | 0.653251 | false | false | false | false |
FelixMLians/NVActivityIndicatorView | refs/heads/master | ICSPullToRefresh/NVActivityIndicatorAnimationCubeTransition.swift | apache-2.0 | 66 | //
// NVActivityIndicatorAnimationCubeTransition.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationCubeTransition: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let squareSize = size.width / 5
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let deltaX = size.width - squareSize
let deltaY = size.height - squareSize
let duration: CFTimeInterval = 1.6
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0, -0.8]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
scaleAnimation.values = [1, 0.5, 1, 0.5, 1]
scaleAnimation.duration = duration
// Translate animation
let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation")
translateAnimation.keyTimes = scaleAnimation.keyTimes
translateAnimation.timingFunctions = scaleAnimation.timingFunctions
translateAnimation.values = [
NSValue(CGSize: CGSize(width: 0, height: 0)),
NSValue(CGSize: CGSize(width: deltaX, height: 0)),
NSValue(CGSize: CGSize(width: deltaX, height: deltaY)),
NSValue(CGSize: CGSize(width: 0, height: deltaY)),
NSValue(CGSize: CGSize(width: 0, height: 0))
]
translateAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = scaleAnimation.timingFunctions
rotateAnimation.values = [0, CGFloat(-M_PI_2), CGFloat(-M_PI), CGFloat(-1.5 * M_PI), CGFloat(-2 * M_PI)]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, translateAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw squares
for var i = 0; i < 2; i++ {
let square = NVActivityIndicatorShape.Rectangle.createLayerWith(size: CGSize(width: squareSize, height: squareSize), color: color)
let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize)
animation.beginTime = beginTime + beginTimes[i]
square.frame = frame
square.addAnimation(animation, forKey: "animation")
layer.addSublayer(square)
}
}
}
| 63114aaf6c088023c4e50f5e166b6551 | 42.082192 | 142 | 0.650556 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.