repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
azu/NSDate-Escort
SwiftTest/EscortComparingSpec.swift
1
20895
import XCTest import Quick import AZDateBuilder class EscortComparingSpec: QuickSpec { override func spec() { describe("- isEqual(ignoringTime: date)") { let currentDate = Date() it("when same the date should be true") { XCTAssertTrue(currentDate.isEqual(ignoringTime: currentDate)) } context("when target is today") { it("of start should return true") { let beginOfDate = currentDate.date(by: [ .hour: 0, .minute: 0, .second: 0, ]) XCTAssertTrue(currentDate.isEqual(ignoringTime: beginOfDate)) } it("of end should return true") { let endOfDate = currentDate.date(by: [ .hour: 0, .minute: 0, .second: 0, ]) XCTAssertTrue(currentDate.isEqual(ignoringTime: endOfDate)) } } it("when target is a later day should return false") { let laterDate = currentDate.date(by: [ .day: currentDate.day + Int(arc4random()) + 1, .hour: 0, .minute: 0, .second: 0, ]) XCTAssertFalse(currentDate.isEqual(ignoringTime: laterDate)) } it("when target is a earler day should return false") { let earlerDate = currentDate.date(by: [ .day: currentDate.day - Int(arc4random()) - 1, .hour: 0, .minute: 0, .second: 0, ]) XCTAssertFalse(currentDate.isEqual(ignoringTime: earlerDate)) } it("when target is previous era should return false") { let currentDate = Date.date(by: [ .year: 2014, .month: 5, .day: 19, ]) let previousEraDate = Date.date(by: [ .year: 1951, .month: 5, .day: 19, ]) Date.identifier = .japanese XCTAssertFalse(currentDate.isEqual(ignoringTime: previousEraDate)) } } describe("isToday") { let currentDate = Date() it("when subject is same date should return true") { XCTAssertTrue(currentDate.isToday()) } it("when subject is a later day should return false") { let laterDate = currentDate.date(by: [ .day: currentDate.day + 1, .hour: 0, .minute: 0, .second: 0, ]) XCTAssertFalse(laterDate.isToday()) } it("when subject is a earler day should return false") { let earlerDate = currentDate.date(by: [ .day: currentDate.day - 1, .hour: 23, .minute: 59, .second: 59, ]) XCTAssertFalse(earlerDate.isToday()) } } describe("isTomorrow") { let currentDate = Date() it("when subject is same date should return false") { XCTAssertFalse(currentDate.isTomorrow()) } it("when subject is a tomorrow should return true") { let tomorrow = currentDate.date(by: [ .day: currentDate.day + 1, .hour: 0, .minute: 0, .second: 0, ]) XCTAssertTrue(tomorrow.isTomorrow()) } it("when subject is a 2 days later should return false") { let laterDate = currentDate.date(by: [ .day: currentDate.day + 2, .hour: 23, .minute: 59, .second: 59, ]) XCTAssertFalse(laterDate.isTomorrow()) } } describe("isYesterday") { let currentDate = Date() it("when subject is same date should return false") { XCTAssertFalse(currentDate.isYesterday()) } it("when subject is a tomorrow should return true") { let tomorrow = currentDate.date(by: [ .day: currentDate.day - 1, .hour: 0, .minute: 0, .second: 0, ]) XCTAssertTrue(tomorrow.isYesterday()) } it("when subject is a 2 days later should return false") { let laterDate = currentDate.date(by: [ .day: currentDate.day - 2, .hour: 23, .minute: 59, .second: 59, ]) XCTAssertFalse(laterDate.isYesterday()) } } describe("isSameWeekAsDate") { context("today is 2010-10-10") { let currentDate = Date.date(by: [ .year: 2010, .month: 10, .day: 10, ]) it("same date should return false") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate)) } context("next day (monday)") { context("firstWeekday is sunday") { beforeEach { var beginingOfMondayCalendar = Calendar(identifier: .gregorian) beginingOfMondayCalendar.firstWeekday = 1 Date._currentCalendar = beginingOfMondayCalendar Date.identifier = .gregorian } afterEach { Date._currentCalendar = nil Date.identifier = nil } it("should return true") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate.add(day: 1))) } } context("firstWeekday is monday") { beforeEach { var beginingOfMondayCalendar = Calendar(identifier: .gregorian) beginingOfMondayCalendar.firstWeekday = 2 Date._currentCalendar = beginingOfMondayCalendar Date.identifier = .gregorian } afterEach { Date._currentCalendar = nil Date.identifier = nil } it("should return true") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.add(day: 1))) } } } context("within this week") { it("firstOfWeek should return true") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate.startDateOfWeekday())) } it("endOfWeek should return true") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let weekend = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(currentDate.isSameWeek(as: weekend)) } } it("when same the week, but difference year should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.add(year: 1))) } it("next week should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.addingTimeInterval(currentDate.date(of: .weekOfYear).interval))) } it("last week should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.addingTimeInterval(-(currentDate.date(of: .weekOfYear).interval)))) } } context("today is 2015-03-30") { let currentDate = Date.date(by: [ .year: 2015, .month: 3, .day: 30, ]) it("same date should return false") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate)) } context("within this week") { it("firstOfWeek should return true") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate.startDateOfWeekday())) } it("endOfWeek should return true") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let weekend = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(currentDate.isSameWeek(as: weekend)) } } it("when same the week, but difference year should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.add(year: 1))) } it("next week should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.addingTimeInterval(currentDate.date(of: .weekOfYear).interval))) } it("last week should return false") { XCTAssertFalse(currentDate.isSameWeek(as: currentDate.addingTimeInterval(-(currentDate.date(of: .weekOfYear).interval)))) } } context("today is 1989-01-07") { let currentDate = Date.date(by: [ .year: 1989, .month: 1, .day: 7, ]) beforeEach { var beginingOfMondayCalendar = Calendar(identifier: .japanese) beginingOfMondayCalendar.firstWeekday = 2 Date._currentCalendar = beginingOfMondayCalendar Date.identifier = .japanese } afterEach { Date._currentCalendar = nil Date.identifier = nil } it("next era of same week should return true") { XCTAssertTrue(currentDate.isSameWeek(as: currentDate.add(day: 1))) } } } describe("isThisWeek") { let currentDate = Date() it("when now should return true") { XCTAssertTrue(currentDate.isThisWeek()) } it("when start date of weekday should return true") { XCTAssertTrue(currentDate.startDateOfWeekday().isThisWeek()) } it("when end date of weekday should return true") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let weekend = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(weekend.isThisWeek()) } it("when last week should return false") { XCTAssertFalse(currentDate.startDateOfWeekday().addingTimeInterval(-1).isThisWeek()) } it("when next week should return false") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let nextWeek = startDate.addingTimeInterval(interval) XCTAssertFalse(nextWeek.isThisWeek()) } } describe("isNextWeek") { let currentDate = Date().add(weekOfYear: 1) it("when next week should return true") { XCTAssertTrue(currentDate.isNextWeek()) } it("when start date of weekday should return true") { XCTAssertTrue(currentDate.startDateOfWeekday().isNextWeek()) } it("when end date of weekday should return true") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let weekend = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(weekend.isNextWeek()) } it("when last week should return false") { XCTAssertFalse(currentDate.startDateOfWeekday().addingTimeInterval(-1).isNextWeek()) } it("when next week should return false") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let nextWeek = startDate.addingTimeInterval(interval) XCTAssertFalse(nextWeek.isNextWeek()) } } describe("isLastWeek") { let currentDate = Date().add(weekOfYear: -1) it("when next week should return true") { XCTAssertTrue(currentDate.isLastWeek()) } it("when start date of weekday should return true") { XCTAssertTrue(currentDate.startDateOfWeekday().isLastWeek()) } it("when end date of weekday should return true") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let weekend = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(weekend.isLastWeek()) } it("when last week should return false") { XCTAssertFalse(currentDate.startDateOfWeekday().addingTimeInterval(-1).isLastWeek()) } it("when next week should return false") { let (startDate, interval) = currentDate.date(of: .weekOfYear) let nextWeek = startDate.addingTimeInterval(interval) XCTAssertFalse(nextWeek.isLastWeek()) } } describe("isSameMonthAsDate") { context("today is 2010-10-10") { let currentDate = Date.date(by: [ .year: 2010, .month: 10, .day: 10, ]) it("same day should return true") { XCTAssertTrue(currentDate.isSameMonth(as: currentDate)) } it("with in this month at start of month should return true") { XCTAssertTrue(currentDate.isSameMonth(as: currentDate.startDateOfMonth())) } it("with in this month at end of month should return true") { let (startDate, interval) = currentDate.date(of: .month) let endOfMonth = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(currentDate.isSameMonth(as: endOfMonth)) } it("with in last month at end of month should return false") { XCTAssertFalse(currentDate.isSameMonth(as: currentDate.startDateOfMonth().addingTimeInterval(-1))) } it("with in next month at start of month should return false") { let (startDate, interval) = currentDate.date(of: .month) let nextMonth = startDate.addingTimeInterval(interval) XCTAssertFalse(currentDate.isSameMonth(as: nextMonth)) } it("next year should return false") { XCTAssertFalse(currentDate.isSameMonth(as: currentDate.add(year: 1))) } } context("today is 1989-01-07") { let currentDate = Date.date(by: [ .year: 1989, .month: 1, .day: 7, ]) beforeEach { Date.identifier = .japanese } afterEach { Date.identifier = nil } it("next era of same month should return true") { XCTAssertTrue(currentDate.isSameMonth(as: currentDate.add(day: 1))) } } context("today is 2010-02-13") { let currentDate = Date.date(by: [ .year: 2010, .month: 2, .day: 13, ]) beforeEach { Date.identifier = .chinese } afterEach { Date.identifier = nil } it("next era of same month should return true") { XCTAssertTrue(currentDate.isSameMonth(as: currentDate.add(day: 1))) } } } describe("isThisMonth") { let currentDate = Date() it("when sameMonth as Date should return true") { XCTAssertTrue(currentDate.isThisMonth()) } } describe("isSameYearAsDate") { context("today is 2010-10-10") { let currentDate = Date.date(by: [ .year: 2010, .month: 10, .day: 10, ]) context("within this year") { it("date at start of year should return true") { XCTAssertTrue(currentDate.isSameYear(as: currentDate.startDateOfYear())) } it("date at end of year should return true") { let (startDate, interval) = currentDate.date(of: .year) let endOfYear = startDate.addingTimeInterval(interval - 1) XCTAssertTrue(currentDate.isSameYear(as: endOfYear)) } } context("without this year") { it("date at last of year should return false") { XCTAssertFalse(currentDate.isSameYear(as: currentDate.startDateOfYear().add(second: -1 - Int(arc4random())))) } it("date at last of year should return false") { let (startDate, interval) = currentDate.date(of: .year) let nextyear = startDate.addingTimeInterval(interval) XCTAssertFalse(currentDate.isSameYear(as: nextyear)) } } } context("today is 1988-01-07") { let currentDate = Date.date(by: [ .year: 1988, .month: 1, .day: 7, ]) beforeEach { Date.identifier = .japanese } afterEach { Date.identifier = nil } it("next era of same year should return true") { XCTAssertTrue(currentDate.isSameYear(as: currentDate.add(day: 1))) } } context("today is 2010-02-13") { let currentDate = Date.date(by: [ .year: 2010, .month: 2, .day: 13, ]) beforeEach { Date.identifier = .chinese } afterEach { Date.identifier = nil } it("next era of same year should return true") { XCTAssertTrue(currentDate.isSameYear(as: currentDate.add(day: 1))) } } } describe("isThisYear") { let currentDate = Date() it("within this year should return true") { XCTAssertTrue(currentDate.isThisYear()) } it("other year should return true") { XCTAssertFalse(currentDate.add(year: 1 + Int(arc4random())).isThisYear()) } } describe("isInPast") { let currentDate = Date() it("when earlier time should return true") { XCTAssertFalse(currentDate.add(second: 1).isInPast()) } it("when later time should return false") { XCTAssertTrue(currentDate.add(second: -1).isInPast()) } } describe("isInFuture") { let currentDate = Date() it("when future time should return true") { XCTAssertTrue(currentDate.add(second: 1).isInFuture()) } it("when past time should return false") { XCTAssertFalse(currentDate.add(second: -1).isInFuture()) } } } }
mit
96fb18a3d6c3bc34ee6384eb14fca9c9
43.269068
141
0.466332
5.770505
false
false
false
false
joelbanzatto/MVCarouselCollectionView
MVCarouselCollectionViewDemo/Carousel/SDWebImageManagerHelper.swift
3
1944
// SDWebImageManagerHelper.swift // // Copyright (c) 2015 Andrea Bizzotto ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit var imageViewLoadCached : ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) = { (imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) in imageView.image = UIImage(named:imagePath) completion(newImage: imageView.image != nil) } var imageViewLoadFromPath: ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) = { (imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) in var url = NSURL(string: imagePath) imageView.sd_setImageWithURL(url, completed: { (image : UIImage?, error: NSError?, cacheType: SDImageCacheType, imageURL: NSURL?) in completion(newImage: image != nil) }) }
mit
7e26e8dc194e562a9cf5a63d72f7c080
46.414634
119
0.724794
4.468966
false
false
false
false
darkdong/DarkSwift
Source/Extension/UIViewController.swift
1
756
// // UIViewController.swift // DarkSwift // // Created by Dark Dong on 2017/8/18. // Copyright © 2017年 Dark Dong. All rights reserved. // import UIKit public extension UIViewController { class func setNavigationBarBackItemImageOnly() { let method = class_getInstanceMethod(self, #selector(viewDidLoad)) let swizzledMethod = class_getInstanceMethod(self, #selector(swizzledViewDidLoad)) method_exchangeImplementations(method!, swizzledMethod!) } @objc func swizzledViewDidLoad() { swizzledViewDidLoad() if navigationItem.backBarButtonItem == nil { navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } } }
mit
05117b9a40ce77d2a5b3ad737158d1da
29.12
114
0.681275
4.858065
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLock/Supporting/FileManager.swift
1
3148
// // FileManager.swift // GroupLock // // Created by Sergej Jaskiewicz on 27.04.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // import CoreData import JSQCoreDataKit import Photos /// FileManager object represents a singleton for imitating file system structure for Library. class FileManager: NSObject { /// Provides a singleton object of a file manager. static let sharedInstance = FileManager() private override init() {} private var context: NSManagedObjectContext { return AppDelegate.sharedInstance.managedObjectContext } /** Executes a request for all the files contained in `directory` and returns an array of them. - parameter directory: The directory we want to get files contained in. - returns: An array of files. */ func files(insideDirectory directory: Directory) -> [ManagedFile] { let fetchRequest = NSFetchRequest<ManagedFile>(entityName: "File") switch directory { case .Encrypted: fetchRequest.predicate = NSPredicate(format: "encrypted == true") case .Decrypted: fetchRequest.predicate = NSPredicate(format: "encrypted == false") } var files: [ManagedFile] = [] if #available(iOS 10.0, *) { context.performAndWait { do { files = try fetchRequest.execute() } catch { print(error) abort() } } } else { do { files = try context.fetch(fetchRequest) } catch { print(error) abort() } } return files } /** Creates NSManagedObject file. - returns: Created file */ func createFile(_ name: String, type: String, encrypted: Bool, contents: Data?) -> ManagedFile? { guard let entity = NSEntityDescription.entity(forEntityName: "File", in: context) else { return nil } let file = ManagedFile(entity: entity, insertInto: nil) file.name = name file.type = type file.encrypted = encrypted file.contents = contents return file } func createFileFromURL(_ url: URL, withName name: String, encrypted: Bool) -> ManagedFile? { let fileType = url.pathExtension let data = getImageContentsForURL(url) return createFile(name, type: fileType, encrypted: encrypted, contents: data) } private func getImageContentsForURL(_ url: URL) -> Data? { let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil) if let asset = fetchResult.firstObject { var data: Data? let options = PHImageRequestOptions() options.isSynchronous = true PHImageManager.default().requestImageData(for: asset, options: options) { (imageData, _, _, _) in data = imageData } return data } return nil } }
apache-2.0
1e8872d6bd01b956a7adeb3c43d09a3f
28.688679
101
0.57674
5.159016
false
false
false
false
murilloarturo/CurrencyConverter
CurrencyConverter/App/Home/Entity/CurrencyRate.swift
1
2457
// // CurrencyRate.swift // CurrencyConverter // // Created by Arturo on 5/12/18. // Copyright © 2018 AM. All rights reserved. // import Foundation import ObjectMapper private enum CodingKey: String { case base case date case rates } class CurrencyRateData: Mappable { var base: CurrencyCode var date: Date? var rates: [CurrencyRate] = [] var primaryRates: [CurrencyRate] { return rates.filter{ $0.isPrimary } } var otherRates: [CurrencyRate] { return rates.filter{ !$0.isPrimary } } required init?(map: Map) { guard let baseString = map.JSON[CodingKey.base.rawValue] as? String, let baseCode = CurrencyCode(rawValue: baseString) else { return nil } self.base = baseCode } func mapping(map: Map) { base <- map[CodingKey.base.rawValue] let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" date <- (map[CodingKey.date.rawValue], DateFormatterTransform(dateFormatter: dateFormatter)) rates <- (map[CodingKey.rates.rawValue], CurrencyRatesTransformType()) } } class CurrencyRate { var currency: CurrencyCode var rate: Double = 0.0 var isPrimary: Bool { return currency == .unitedKingdom || currency == .europe || currency == .japan || currency == .brazil || currency == .usa } init(currency: CurrencyCode, rate: Double) { self.currency = currency self.rate = rate } } struct CurrencyRatesTransformType: TransformType { typealias Object = [CurrencyRate] typealias JSON = [String: Any] func transformFromJSON(_ value: Any?) -> [CurrencyRate]? { guard let json = value as? JSON else { return [] } var data: [CurrencyRate] = [] json.forEach { (item) in guard let currencyCode = CurrencyCode(rawValue: item.key), let rate = item.value as? Double else { return } data.append(CurrencyRate(currency: currencyCode, rate: rate)) } return data } func transformToJSON(_ value: [CurrencyRate]?) -> [String : Any]? { guard let value = value else { return nil } var json: [String: Any] = [:] value.forEach{ json[$0.currency.rawValue] = $0.rate } return json } }
mit
c23642531fd6eaa4917613ec4c01bcde
26.288889
129
0.585505
4.370107
false
false
false
false
AnyPresence/justapis-swift-sdk
Source/Gateway.swift
1
8726
// // Gateway.swift // JustApisSwiftSDK // // Created by Andrew Palumbo on 12/29/15. // Copyright © 2015 AnyPresence. All rights reserved. // import Foundation let kGatewayDefaultCacheExpiration:UInt = 300 /// /// A client-side representation of a JustAPIs Gateway server /// public protocol Gateway : class { /// The Base URL to which requests will be sent var baseUrl:NSURL { get } var defaultRequestProperties:DefaultRequestPropertySet { get } /// Sends a request to the gateway func submitRequest(request:RequestProperties, callback:RequestCallback?) /// /// Request Queue /// --- /// Requests submitted to this gateway enter a queue. /// /// Features: /// * The queue can be rate-limited so that only a certain number of /// requests are active at any time. /// * The queue can be paused to prevent any requests from being processed /// * You can retrieve the list of unstarted requests the queue for persistence /// Requests that have been submitted to the gateway but not yet executed var pendingRequests:[Request] { get } /// The number of requests that may execute simultaneously on this gateway var maxActiveRequests:Int { get set } /// Indicated whether this gateway is currently paused var isPaused:Bool { get } /// Stops request processing on this Gateay func pause() /// Resumes request processing on this Gateway func resume() /// Removes a request from the queue, if it hasn't yet been started. The request must /// be from this gateway's pendingRequests queue func cancelRequest(request:Request) -> Bool } /// /// A protocol extension to Gateway that adds convenience methods for preparing GET requests /// public extension Gateway { /// A convenience method for sending a GET request func get(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, followRedirects:Bool, callback:RequestCallback?) { var request = self.defaultRequestProperties.get request.path = path request.params = params ?? request.params request.headers = headers ?? request.headers request.body = body request.followRedirects = followRedirects self.submitRequest(request, callback: callback) } /// A convenience method for sending a GET request func get(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, callback:RequestCallback?) { return self.get(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a GET request func get(path:String, params:QueryParameters?, headers:Headers?, callback:RequestCallback?) { return self.get(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a GET request func get(path:String, params:QueryParameters?, callback:RequestCallback?) { return self.get(path, params: params, headers: nil, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a GET request func get(path:String, callback:RequestCallback?) { return self.get(path, params: nil, headers: nil, body: nil, followRedirects: true, callback: callback) } } /// /// A protocol extension to Gateway that adds convenience methods for preparing POST requests /// public extension Gateway { /// A convenience method for sending a POST request func post(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, followRedirects:Bool, callback:RequestCallback?) { var request = self.defaultRequestProperties.post request.path = path request.params = params ?? request.params request.headers = headers ?? request.headers request.body = body request.followRedirects = followRedirects self.submitRequest(request, callback: callback) } /// A convenience method for sending a POST request func post(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, callback:RequestCallback?) { return self.post(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a POST request func post(path:String, params:QueryParameters?, headers:Headers?, callback:RequestCallback?) { return self.post(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a POST request func post(path:String, params:QueryParameters?, callback:RequestCallback?) { return self.post(path, params: params, headers: nil, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a POST request func post(path:String, callback:RequestCallback?) { return self.post(path, params: nil, headers: nil, body: nil, followRedirects: true, callback: callback) } } /// /// A protocol extension to Gateway that adds convenience methods for preparing PUT requests /// public extension Gateway { /// A convenience method for sending a PUT request func put(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, followRedirects:Bool, callback:RequestCallback?) { var request = self.defaultRequestProperties.put request.path = path request.params = params ?? request.params request.headers = headers ?? request.headers request.body = body request.followRedirects = followRedirects self.submitRequest(request, callback: callback) } /// A convenience method for sending a PUT request func put(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, callback:RequestCallback?) { return self.put(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a PUT request func put(path:String, params:QueryParameters?, headers:Headers?, callback:RequestCallback?) { return self.put(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a PUT request func put(path:String, params:QueryParameters?, callback:RequestCallback?) { return self.put(path, params: params, headers: nil, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a PUT request func put(path:String, callback:RequestCallback?) { return self.put(path, params: nil, headers: nil, body: nil, followRedirects: true, callback: callback) } } /// /// A protocol extension to Gateway that adds convenience methods for preparing DELETE requests /// public extension Gateway { /// A convenience method for sending a DELETE request func delete(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, followRedirects:Bool, callback:RequestCallback?) { var request = self.defaultRequestProperties.delete request.path = path request.params = params ?? request.params request.headers = headers ?? request.headers request.body = body request.followRedirects = followRedirects self.submitRequest(request, callback: callback) } /// A convenience method for sending a DELETE request func delete(path:String, params:QueryParameters?, headers:Headers?, body:NSData?, callback:RequestCallback?) { return self.delete(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a DELETE request func delete(path:String, params:QueryParameters?, headers:Headers?, callback:RequestCallback?) { return self.delete(path, params: params, headers: headers, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a DELETE request func delete(path:String, params:QueryParameters?, callback:RequestCallback?) { return self.delete(path, params: params, headers: nil, body: nil, followRedirects: true, callback: callback) } /// A convenience method for sending a DELETE request func delete(path:String, callback:RequestCallback?) { return self.delete(path, params: nil, headers: nil, body: nil, followRedirects: true, callback: callback) } }
mit
5595c830ff1a3df5bd93762dd1c24f8e
37.436123
134
0.689857
4.636026
false
false
false
false
4oby/TableTop-Ambience
TableTop Ambience/SoundPadViewController.swift
1
5251
// // ViewController.swift // TableTop Ambience // // Created by Victor Cebanu on 8/19/16. // Copyright © 2016 Victor Cebanu. All rights reserved. // import UIKit private let loadPadSegueID = "loadSoundPad" final class SoundPadViewController: UIViewController { @IBOutlet weak var editButton: UIBarButtonItem! @IBOutlet var addButton: UIBarButtonItem! @IBOutlet weak var collectionView: UICollectionView! var currentSoundPad = [SoundFlow]() var editModeEnabled = false //MARK: - Navigation bar actions @IBAction func editButtonTapped(_ sender: AnyObject) { toogleEditMode() } @IBAction func addButtonTapped(_ sender: AnyObject) { SoundPicker(self).start() } //MARK: - ToolBarItemActions @IBAction func saveSoundPad(_ sender: AnyObject) { if currentSoundPad.count > 0 { saveCurrentSoundPad() } } } //MARK: - InternalFunctions extension SoundPadViewController { func removeCell(_ sender: AnyObject) { //!!!: I don't like this being here, there must be another way currentSoundPad.remove(at: sender.tag) collectionView.reloadData() } func toogleEditMode() { if editModeEnabled == false { editButton.title = "Done" editButton.style = .done editModeEnabled = true self.navigationItem.leftBarButtonItem = nil } else { editButton.style = .plain editButton.title = "Edit" editModeEnabled = false self.navigationItem.leftBarButtonItem = addButton } collectionView.reloadData() } func saveCurrentSoundPad() { let defaultTitle = "Pad #" + String(Date().timeIntervalSince1970) let alertController = UIAlertController(title: nil, message: "Save current SoundBoard", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(cancelAction) alertController.addTextField { (textField) in textField.text = defaultTitle } let save = UIAlertAction(title: "Save", style: .default) { (action) in if let textField = (alertController.textFields?[0]) ?? nil { SoundPadManager.sharedInstance.savePad(pad: self.currentSoundPad.map({$0.baseItem}), named: textField.text ?? defaultTitle) } } alertController.addAction(save) self.present(alertController, animated: true) } } //MARK: - SoundPickerDelegate extension SoundPadViewController: SoudPickerDelegate { func soundPickerDidSelect(_ sound: String?) { currentSoundPad.append(SoundFlow(baseItem: SoundPadItem(fileAddress: sound ?? ""))) collectionView.reloadData() } } //MARK: - CollectionViewDataSource extension SoundPadViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentSoundPad.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: SoundPadCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", for: indexPath) as? SoundPadCell ?? SoundPadCell() cell.title.text = currentSoundPad[indexPath.row].baseItem.name cell.delegate = currentSoundPad[indexPath.row] cell.playStopButton.tag = indexPath.row cell.deleteButton.tag = indexPath.row currentSoundPad[indexPath.row].delegate = cell if currentSoundPad[indexPath.row].baseItem.autoRepeat { cell.repeatButton.setBackgroundImage(#imageLiteral(resourceName: "Repeat-96-highlight"), for: .normal) } if editModeEnabled { cell.deleteButton.isHidden = false cell.deleteButton.addTarget(self, action: #selector(self.removeCell(_:)), for: .touchUpInside) cell.iconImage.isHidden = true } else { cell.deleteButton.isHidden = true cell.iconImage.isHidden = false } return cell } } //MARK - pickerDelegate extension SoundPadViewController: SoundPadPickerDelegate { func soundPadPickerDidSelect(_ padName: String?) { if let items = SoundPadManager.sharedInstance.getPad(padName ?? "") { currentSoundPad.removeAll() for item in items { currentSoundPad.append(SoundFlow(baseItem: item)) } collectionView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == loadPadSegueID && segue.destination is SoundPadPicker { (segue.destination as? SoundPadPicker)?.delegate = self } } }
gpl-3.0
363f6607bfc58f0ddbf41056dd8895c9
33.768212
163
0.620952
5.116959
false
false
false
false
KrishMunot/swift
test/SILGen/c_function_pointers.swift
3
1966
// RUN: %target-swift-frontend -emit-silgen -verify %s | FileCheck %s func values(_ arg: @convention(c) Int -> Int) -> @convention(c) Int -> Int { return arg } // CHECK-LABEL: sil hidden @_TF19c_function_pointers6valuesFcSiSicSiSi // CHECK: bb0(%0 : $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int func calls(_ arg: @convention(c) Int -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden @_TF19c_function_pointers5callsFTcSiSiSi_Si // CHECK: bb0(%0 : $@convention(c) (Int) -> Int, %1 : $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden @_TF19c_function_pointers27pointers_to_swift_functionsFSiT_ func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @_TToF19c_function_pointers6globalFSiSi // CHECK: apply {{.*}}([[GLOBAL_C]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @_TToFF19c_function_pointers27pointers_to_swift_functionsFSiT_L_5localFSiSi // CHECK: apply {{.*}}([[LOCAL_C]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @_TToFF19c_function_pointers27pointers_to_swift_functionsFSiT_U_FSiSi // CHECK: apply {{.*}}([[CLOSURE_C]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @_TToF19c_function_pointers7no_argsFT_Si // CHECK: apply {{.*}}([[NO_ARGS_C]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) Int -> Int'}} }
apache-2.0
d0633558d061e032127e8d19c07f4be5
36.09434
153
0.605799
3.067083
false
false
false
false
varkor/firefox-ios
Client/Frontend/UIConstants.swift
1
5065
/* 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 public struct UIConstants { static let AboutHomePage = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/")! static let AppBackgroundColor = UIColor.blackColor() static let SystemBlueColor = UIColor(red: 0 / 255, green: 122 / 255, blue: 255 / 255, alpha: 1) static let PrivateModePurple = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeLocationBackgroundColor = UIColor(red: 31 / 255, green: 31 / 255, blue: 31 / 255, alpha: 1) static let PrivateModeLocationBorderColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.15) static let PrivateModeActionButtonTintColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.8) static let PrivateModeTextHighlightColor = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeInputHighlightColor = UIColor(red: 120 / 255, green: 120 / 255, blue: 165 / 255, alpha: 1) static let PrivateModeAssistantToolbarBackgroundColor = UIColor(red: 89 / 255, green: 89 / 255, blue: 89 / 255, alpha: 1) static let PrivateModeToolbarTintColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1) static let ToolbarHeight: CGFloat = 44 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let SnackbarButtonHeight: CGFloat = 48 // Static fonts static let DefaultChromeSize: CGFloat = 14 static let DefaultChromeSmallSize: CGFloat = 11 static let PasscodeEntryFontSize: CGFloat = 36 static let DefaultChromeFont: UIFont = UIFont.systemFontOfSize(DefaultChromeSize, weight: UIFontWeightRegular) static let DefaultChromeBoldFont = UIFont.boldSystemFontOfSize(DefaultChromeSize) static let DefaultChromeSmallFontBold = UIFont.boldSystemFontOfSize(DefaultChromeSmallSize) static let PasscodeEntryFont = UIFont.systemFontOfSize(PasscodeEntryFontSize, weight: UIFontWeightBold) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) static let PanelBackgroundColor = UIColor.whiteColor() static let SeparatorColor = UIColor(rgb: 0xcccccc) static let HighlightBlue = UIColor(red:76/255, green:158/255, blue:255/255, alpha:1) static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0) static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25) static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1) // These colours are used on the Menu static let MenuToolbarBackgroundColorNormal = UIColor(red: 241/255, green: 241/255, blue: 241/255, alpha: 1.0) static let MenuToolbarBackgroundColorPrivate = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1.0) static let MenuToolbarTintColorNormal = BackgroundColor static let MenuToolbarTintColorPrivate = UIColor.whiteColor() static let MenuBackgroundColorNormal = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1.0) static let MenuBackgroundColorPrivate = UIColor(red: 59/255, green: 59/255, blue: 59/255, alpha: 1.0) static let MenuSelectedItemTintColor = UIColor(red: 0.30, green: 0.62, blue: 1.0, alpha: 1.0) // settings static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0) static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0) static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0) static let TableViewDisabledRowTextColor = UIColor.lightGrayColor() static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4) static let TableViewHeaderFooterHeight = CGFloat(44) static let TableViewRowErrorTextColor = UIColor(red: 255/255, green: 0/255, blue: 26/255, alpha: 1.0) static let TableViewRowWarningTextColor = UIColor(red: 245/255, green: 166/255, blue: 35/255, alpha: 1.0) static let TableViewRowActionAccessoryColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1.0) // Firefox Orange static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1) // Passcode dot gray static let PasscodeDotColor = UIColor(rgb: 0x4A4A4A) /// JPEG compression quality for persisted screenshots. Must be between 0-1. static let ScreenshotQuality: Float = 0.3 static let ActiveScreenshotQuality: CGFloat = 0.5 static let OKString = NSLocalizedString("OK", comment: "OK button") static let CancelString = NSLocalizedString("Cancel", comment: "Label for Cancel button") }
mpl-2.0
c1f6917015e237dadd4901e6548ef87e
63.113924
125
0.730701
3.950858
false
false
false
false
PlayApple/SwiftyiRate
Examples/iPhoneDemo/iPhoneDemo/AppDelegate.swift
1
2652
// // AppDelegate.swift // iPhoneDemo // // Created by LiuYanghui on 16/5/31. // Copyright © 2016年 LiuYanghui. All rights reserved. // import UIKit import SwiftyiRate @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? override class func initialize () { //configure iRate SwiftyiRate.sharedInstance.daysUntilPrompt = 5 SwiftyiRate.sharedInstance.usesUntilPrompt = 15 // for test app id SwiftyiRate.sharedInstance.appStoreID = 1115972702 SwiftyiRate.sharedInstance.applicationBundleID = "com.cocos2dev.iBabyMusic" SwiftyiRate.sharedInstance.previewMode = true SwiftyiRate.sharedInstance.verboseLogging = true } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
4f4516397e17658ecf864b14eeea5e0f
43.15
285
0.741412
5.32998
false
false
false
false
RenanGreca/Advent-of-Code
AdventOfCode.playground/Pages/DayThree.xcplaygroundpage/Contents.swift
1
2830
//: [Previous](@previous) import Foundation /* Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: > delivers presents to 2 houses: one at the starting location, and one to the east. ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. */ func partOne(string:String) -> Int { let d:[Character:(Int, Int)] = [ "^": (0, 1), ">": (1, 0), "v": (0, -1), "<": (-1, 0) ] var pos = (0, 0) var set = Set<String>() for character in string.characters { pos.0 += d[character]!.0 pos.1 += d[character]!.1 set.insert("\(pos)") } return set.count } /* The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him. Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year. This year, how many houses receive at least one present? For example: ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. */ func partTwo(string:String) -> Int { let d:[Character:(Int, Int)] = [ "^": (0, 1), ">": (1, 0), "v": (0, -1), "<": (-1, 0) ] var pos: [(Int, Int)] = [(0, 0), (0, 0)] var sets = [Set<String>(), Set<String>()] var isRobotTurn = 0 for character in string.characters { pos[isRobotTurn].0 += d[character]!.0 pos[isRobotTurn].1 += d[character]!.1 sets[isRobotTurn].insert("\(pos[isRobotTurn])") isRobotTurn = (isRobotTurn == 0 ? 1 : 0) } return sets[0].union(sets[1]).count } var string = Helpers.readContents("input") partOne(string) partTwo(string) //: [Next](@next)
mit
a147eaac7ee3649382a28868498a1cc4
31.528736
326
0.640283
3.753316
false
false
false
false
proversity-org/edx-app-ios
Source/VersionUpgradeInfoController.swift
1
2158
// // VersionUpgradeInfoController.swift // edX // // Created by Saeed Bashir on 6/7/16. // Copyright © 2016 edX. All rights reserved. // private let AppLatestVersionKey = "EDX-APP-LATEST-VERSION" private let AppVersionLastSupportedDateKey = "EDX-APP-VERSION-LAST-SUPPORTED-DATE" let AppNewVersionAvailableNotification = "AppNewVersionAvailableNotification" class VersionUpgradeInfoController: NSObject { static let sharedController = VersionUpgradeInfoController() private(set) var latestVersion:String? private(set) var lastSupportedDateString:String? private func returnToDefaultState() { latestVersion = nil lastSupportedDateString = nil } func populateFromHeaders(httpResponseHeaders headers: [String : Any]?) { guard let responseHeaders = headers else { if let _ = latestVersion { // if server stop sending header information in response and version upgrade header is showing then hide it returnToDefaultState() postVersionUpgradeNotification() } return } var postNotification:Bool = false if let appLatestVersion = responseHeaders[AppLatestVersionKey] as? String { postNotification = latestVersion != appLatestVersion latestVersion = appLatestVersion } else { // In case if server stop sending version upgrade info in headers if let _ = latestVersion { returnToDefaultState() postNotification = true } } if let versionLastSupportedDate = responseHeaders[AppVersionLastSupportedDateKey] as? String { lastSupportedDateString = versionLastSupportedDate } if postNotification { postVersionUpgradeNotification() } } private func postVersionUpgradeNotification() { DispatchQueue.main.async { NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppNewVersionAvailableNotification), object: self) } } }
apache-2.0
2941769dfcb8911ac6960942dbc30306
33.238095
130
0.649513
5.573643
false
true
false
false
muneikh/xmpp-messenger-ios
Example/xmpp-messenger-ios/ContactListTableViewController.swift
1
3627
// // MainViewController.swift // OneChat // // Created by Paul on 13/02/2015. // Copyright (c) 2015 ProcessOne. All rights reserved. // import UIKit import XMPPFramework //import xmpp_messenger_ios protocol ContactPickerDelegate{ func didSelectContact(recipient: XMPPUserCoreDataStorageObject) } class ContactListTableViewController: UITableViewController, OneRosterDelegate { var delegate:ContactPickerDelegate? // Mark : Life Cycle override func viewDidLoad() { super.viewDidLoad() OneRoster.sharedInstance.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if OneChat.sharedInstance.isConnected() { navigationItem.title = "Select a recipient" } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) OneRoster.sharedInstance.delegate = nil } func oneRosterContentChanged(controller: NSFetchedResultsController) { tableView.reloadData() } // Mark: UITableView Datasources override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sections: NSArray? = OneRoster.buddyList.sections if section < sections!.count { let sectionInfo: AnyObject = sections![section] return sectionInfo.numberOfObjects } return 0; } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return OneRoster.buddyList.sections!.count } // Mark: UITableView Delegates override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sections: NSArray? = OneRoster.sharedInstance.fetchedResultsController()!.sections if section < sections!.count { let sectionInfo: AnyObject = sections![section] let tmpSection: Int = Int(sectionInfo.name)! switch (tmpSection) { case 0 : return "Available" case 1 : return "Away" default : return "Offline" } } return "" } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { _ = OneRoster.userFromRosterAtIndexPath(indexPath: indexPath) delegate?.didSelectContact(OneRoster.userFromRosterAtIndexPath(indexPath: indexPath)) close(self) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let user = OneRoster.userFromRosterAtIndexPath(indexPath: indexPath) cell!.textLabel!.text = user.displayName; cell!.detailTextLabel?.hidden = true if user.unreadMessages.intValue > 0 { cell!.backgroundColor = .orangeColor() } else { cell!.backgroundColor = .whiteColor() } OneChat.sharedInstance.configurePhotoForCell(cell!, user: user) return cell!; } // Mark: Segue support override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { if segue?.identifier != "One.HomeToSetting" { if let controller: ChatViewController? = segue?.destinationViewController as? ChatViewController { if let cell: UITableViewCell? = sender as? UITableViewCell { let user = OneRoster.userFromRosterAtIndexPath(indexPath: tableView.indexPathForCell(cell!)!) controller!.recipient = user } } } } // Mark: IBAction @IBAction func close(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } // Mark: Memory Management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6a8649ff9d5dc17dc25c4f9c0caf71a5
25.093525
115
0.739178
4.302491
false
false
false
false
Rahulclaritaz/rahul
ixprez/ixprez/PopupAlert.swift
1
945
// // PopupAlert.swift // ixprez // // Created by Quad on 7/13/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import Foundation import UIKit public extension UIAlertController { func show() { let window = UIWindow(frame: UIScreen.main.bounds) let vc = UIViewController() vc.view.backgroundColor = UIColor.clear window.rootViewController = vc window.makeKeyAndVisible() vc.present(self, animated: true, completion: { _ in UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseInOut, animations: { let delayInSeconds = 2.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) { self.dismiss(animated: true, completion: nil) } }, completion: nil) }) } }
mit
b44194fd1c50144a6ef1187b4999d16d
18.265306
91
0.561441
4.743719
false
false
false
false
NordicSemiconductor/IOS-nRF-For-HomeKit
nRFHomekit/Light/Lightbulb.swift
1
25776
/* * Copyright (c) 2015, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 Foundation import HomeKit /// - protocol: LightbulbProtocol /// - The LightbulbProtocol defines the communication method for state updates from Lightbulb accessory to their delegates. /// /// overview: /// set a delegate on a lightbulb accessory and implement methods in this protocol for updates you are interested in observing to keep your app's UI in sync with changes to lightbulb accessory's internal state protocol LightbulbProtocol { /// Invoked when lightbulb brightness has been read /// - Parameter value: the current value of lightbulb birightness, ranges from 0 to 100 func didReceiveBrightness(value: Int) /// Invoked when lightbulb hue has been read /// - Parameter value: the current value of lightbulb hue, ranges from 0 to 360 func didReceiveHue(value: Int) /// Invoked when lightbulb saturation has been read /// - Parameter value: the current value of lightbulb saturation, ranges from 0 to 100 func didReceiveSaturation(value: Int) /// Invoked when lightbulb powerstate has been read /// - Parameter value: the current value of lightbulb powerstate, 0 for OFF and 1 for ON func didReceivePowerState(value: Int) /// Invoked when lightbulb powerstate has been written /// - Parameter powerState: the current value of lightbulb powerstate, 0 for OFF and 1 for ON func didPowerStateChanged(powerState: Int) /// Invoked when all services and characteristics are found inside lightbulb /// - Parameter isAllFound: is true if all required Services and characteristics are found inside accessory and false otherwise func didFoundServiceAndCharacteristics(isAllFound: Bool) /// Invoked when an information is required to log /// - Parameter message: is log message of type string func didReceiveLogMessage(message: String) /// Invoked when an error occurs during communicating with accessory /// - Parameter message: is string representation of error code func didReceiveErrorMessage(message: String) /// Invoked when an accessory change its reachability status /// - Parameter accessory: is the HomeKit accessory that get back in range or go out of range func didReceiveAccessoryReachabilityUpdate(accessory:HMAccessory!) } /// - class: Lightbulb /// - The Lightbulb class implements the logic required to communicate with the Lightbulb accessory. /// /// overview: /// set a lightbulb accessory to function selectedAccessory(accessory: HMAccessory?), discover services and characteristics, readValues and then change the status of UI accordingly. Also you can write to lightbulb characteristics (brightness, powerlevel, hue and saturation) to change their values /// - required: the protocol LightbulbProtocol must be implemented in order to receive internal status of Lightbulb accessory public class Lightbulb: NSObject, HMAccessoryDelegate { var delegate:LightbulbProtocol? private var isLightbulbServiceFound:Bool = false private var characteristicName: HMCharacteristicName = HMCharacteristicName() private var serviceName: HMServiceName = HMServiceName() private var errorMessage: HMErrorCodeMessage = HMErrorCodeMessage() private var homekitAccessory: HMAccessory? private var lightbulbBrightness: HMCharacteristic? private var lightbulbHue: HMCharacteristic? private var lightbulbSaturation: HMCharacteristic? private var lightbulbPowerState: HMCharacteristic? /// Singleton implementation that will create only one instance of class Lightbulb public class var sharedInstance : Lightbulb { struct StaticLightbulb { static let instance : Lightbulb = Lightbulb() } return StaticLightbulb.instance } /// selectedAccessory sets the lightbulb accessory. /// If accessory is nil then it will call didReceiveErrorMessage method of its delegate object. /// - Parameter accessory: it is HomeKit Lightbulb accessory of type HMAccessory public func selectedAccessory(accessory: HMAccessory?) { if let accessory = accessory { homekitAccessory = accessory homekitAccessory!.delegate = self } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Accessory is nil") } } } /// isAccessoryConnected rerurns the reachablity status of lightbulb accessory /// - Returns: Bool value, true if lightbulb accessory is reachable and false otherwise public func isAccessoryConnected() -> Bool { if let homekitAccessory = homekitAccessory { return homekitAccessory.reachable } return false } private func clearAccessory() { homekitAccessory = nil lightbulbBrightness = nil lightbulbHue = nil lightbulbSaturation = nil lightbulbPowerState = nil } /// writeToBrightness sets the brightness value of lightbulb accessory /// If an error occurs during write operation then it will call didReceiveErrorMessage method of its delegate object. /// - Parameter brightnessValue: It is Int type value for lightbulb brightness and it ranges from 0 to 100 public func writeToBrightness(brightnessValue: Int) { if let lightbulbBrightness = lightbulbBrightness { lightbulbBrightness.writeValue(brightnessValue, completionHandler: { (error: NSError?) -> Void in if error != nil { print("Error in writing brightness value in lightbulb \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error writing Brightness: \(self.errorMessage.getHMErrorDescription(error!.code))") } } else { print("Brightness value changed successfully") } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Brightness is nil") } } } /// writeToHue sets the hue value of lightbulb accessory /// If an error occurs during write operation then it will call didReceiveErrorMessage method of its delegate object. /// - Parameter hueValue: It is Int type value for lightbulb hue and it ranges from 0 to 360 public func writeToHue(hueValue: Int) { if let lightbulbHue = lightbulbHue { lightbulbHue.writeValue(hueValue, completionHandler: { (error: NSError?) -> Void in if error != nil { print("Error in writting hue value in lightbulb \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error writing Hue: \(self.errorMessage.getHMErrorDescription(error!.code))") } } else { print("changed Hue successfully") } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Hue is nil") } } } /// writeToSaturation sets the saturation value of lightbulb accessory /// If an error occurs during write operation then it will call didReceiveErrorMessage method of its delegate object. /// - Parameter saturationValue: It is Int type value for lightbulb hue and it ranges from 0 to 100 public func writeToSaturation(saturationValue: Int) { if let lightbulbSaturation = lightbulbSaturation { lightbulbSaturation.writeValue(saturationValue, completionHandler: { (error: NSError?) -> Void in if error != nil { print("Error in writting saturation value in lightbulb \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error writing Saturation: \(self.errorMessage.getHMErrorDescription(error!.code))") } } else { print("changed Saturation successfully") } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Saturation is nil") } } } /// writeToPowerState sets the powerstate value of lightbulb accessory. /// If value is written successfully then it will call didPowerStateChanged method of its delegate object. /// If an error occurs during write operation then it will call didReceiveErrorMessage method of its delegate object. /// - Parameter powerStateValue: It is Int type value for lightbulb powerstate, 0 for OFF and 1 for ON. public func writeToPowerState(powerStateValue: Int) { if let lightbulbPowerState = lightbulbPowerState { lightbulbPowerState.writeValue(powerStateValue, completionHandler: { (error: NSError?) -> Void in if error == nil { print("successfully switched power state of lightbulb") if let delegate = self.delegate { delegate.didPowerStateChanged(powerStateValue) } } else { print("Error in switching power state of lightbulb \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error writing Powerstate: \(self.errorMessage.getHMErrorDescription(error!.code))") } } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: PowerState is nil") } } } /// discoverServicesAndCharacteristics finds all services and characteristics inside homekit accessory. /// After search of services and characteristics, It calls the didFoundServiceAndCharacteristics: method of its delegate object. /// if required services and characteristics are found then parameter of didFoundServiceAndCharacteristics is set to true or false otherwise /// It also calls didReceiveLogMessage method and can call didReceiveErrorMessage method of its delegate object. public func discoverServicesAndCharacteristics() { if let homekitAccessory = homekitAccessory { isLightbulbServiceFound = false for service in homekitAccessory.services { print("\(homekitAccessory.name) has Service: \(service.name) and ServiceType: \(service.serviceType) and ReadableServiceType: \(serviceName.getServiceType(service.serviceType))") if let delegate = delegate { delegate.didReceiveLogMessage("\(homekitAccessory.name) has Service: \(serviceName.getServiceType(service.serviceType))") } if isLightBulbService(service) { print("Lightbulb service found") isLightbulbServiceFound = true } discoverCharacteristics(service) } if isLightbulbServiceFound == true && lightbulbPowerState != nil && lightbulbBrightness != nil && lightbulbHue != nil && lightbulbSaturation != nil { if let delegate = delegate { delegate.didFoundServiceAndCharacteristics(true) } } else { if let delegate = delegate { delegate.didFoundServiceAndCharacteristics(false) } clearAccessory() } } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Accessory is nil") } } } private func discoverCharacteristics(service: HMService?) { if let service = service { for characteristic in service.characteristics { print("Service: \(service.name) has characteristicType: \(characteristic.characteristicType) and ReadableCharType: \(characteristicName.getCharacteristicType(characteristic.characteristicType))") if let delegate = delegate { delegate.didReceiveLogMessage(" characteristic: \(characteristicName.getCharacteristicType(characteristic.characteristicType))") } if isPowerStateCharacteristic(characteristic) { lightbulbPowerState = characteristic } else if isBrightnessCharacteristic(characteristic) { lightbulbBrightness = characteristic } else if isHueCharacteristic(characteristic) { lightbulbHue = characteristic } else if isSaturationCharacteristic(characteristic) { lightbulbSaturation = characteristic } } } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Service is nil") } } } private func isPowerStateCharacteristic(characteristic: HMCharacteristic?) -> Bool { if let characteristic = characteristic { if characteristic.characteristicType == HMCharacteristicTypePowerState { return true } return false } return false } private func isBrightnessCharacteristic(characteristic: HMCharacteristic?) -> Bool { if let characteristic = characteristic { if characteristic.characteristicType == HMCharacteristicTypeBrightness { return true } return false } return false } private func isHueCharacteristic(characteristic: HMCharacteristic?) -> Bool { if let characteristic = characteristic { if characteristic.characteristicType == HMCharacteristicTypeHue { return true } return false } return false } private func isSaturationCharacteristic(characteristic: HMCharacteristic?) -> Bool { if let characteristic = characteristic { if characteristic.characteristicType == HMCharacteristicTypeSaturation { return true } return false } return false } private func isLightBulbService(service: HMService?) -> Bool { if let service = service { if service.serviceType == HMServiceTypeLightbulb { return true } return false } return false } /// readValues will read values of lightbulb brightness, hue, saturation and powerstate. /// It will call didReceiveBrightness, didReceiveHue, didReceiveSaturation, and didReceivePowerState methods of its delegate object. /// If an error occurs during read operation then it will call didReceiveErrorMessage method of its delegate object. public func readValues() { if let homekitAccessory = homekitAccessory { if isAccessoryConnected() { print("\(homekitAccessory.name) is reachable") if let delegate = delegate { delegate.didReceiveLogMessage("Reading Lightbulb Characteristics values ...") } readBrightnessValue() readHueValue() readSaturationValue() readPowerStateValue() } else { print("Accessory is not reachable") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Accessory is not reachable") } clearAccessory() } } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Accessory is nil") } } } /// readBrightnessValue will read value of lightbulb brightness. /// It will call didReceiveBrightness method of its delegate object. /// If an error occurs during read operation then it will call didReceiveErrorMessage method of its delegate object. public func readBrightnessValue() { if let lightbulbBrightness = lightbulbBrightness { lightbulbBrightness.readValueWithCompletionHandler({ (error: NSError?) -> Void in if error == nil { print("Got brightness value from lightbulb \(lightbulbBrightness.value)") if lightbulbBrightness.value != nil { if let delegate = self.delegate { delegate.didReceiveBrightness(lightbulbBrightness.value as! Int) } } else { print("Brightness value is nil") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Brightness value is nil") } self.clearAccessory() } } else { print("Error in Reading brightness value \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error reading Brightness: \(self.errorMessage.getHMErrorDescription(error!.code))") } self.clearAccessory() } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Brigtness is nil") } } } /// readHueValue will read value of lightbulb hue. /// It will call didReceiveHue method of its delegate object. /// If an error occurs during read operation then it will call didReceiveErrorMessage method of its delegate object. public func readHueValue() { if let lightbulbHue = lightbulbHue { lightbulbHue.readValueWithCompletionHandler({ (error: NSError?) -> Void in if error == nil { print("Got hue value from lightbulb \(lightbulbHue.value)") if lightbulbHue.value != nil { if let delegate = self.delegate { delegate.didReceiveHue(lightbulbHue.value as! Int) } } else { print("Hue value is nil") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Hue value is nil") } self.clearAccessory() } } else { print("Error in Reading hue value \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error reading Hue: \(self.errorMessage.getHMErrorDescription(error!.code))") } self.clearAccessory() } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Hue is nil") } } } /// readSaturationValue will read value of lightbulb saturation. /// It will call didReceiveSaturation method of its delegate object. /// If an error occurs during read operation then it will call didReceiveErrorMessage method of its delegate object. public func readSaturationValue() { if let lightbulbSaturation = lightbulbSaturation { lightbulbSaturation.readValueWithCompletionHandler({ (error: NSError?) -> Void in if error == nil { print("Got saturation value from lightbulb \(lightbulbSaturation.value)") if lightbulbSaturation.value != nil { if let delegate = self.delegate { delegate.didReceiveSaturation(lightbulbSaturation.value as! Int) } } else { print("Saturation value is nil") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Saturation value is nil") } self.clearAccessory() } } else { print("Error in Reading saturation value \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error reading Saturation: \(self.errorMessage.getHMErrorDescription(error!.code))") } self.clearAccessory() } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: Saturation is nil") } } } /// readPowerStateValue will read value of lightbulb powerstate. /// It will call didReceivePowerState method of its delegate object. /// If an error occurs during read operation then it will call didReceiveErrorMessage method of its delegate object. public func readPowerStateValue() { if let lightbulbPowerState = lightbulbPowerState { lightbulbPowerState.readValueWithCompletionHandler({ (error: NSError?) -> Void in if error == nil { print("Got powerstate value from lightbulb \(lightbulbPowerState.value)") if lightbulbPowerState.value != nil { if let delegate = self.delegate { delegate.didReceivePowerState(lightbulbPowerState.value as! Int) } } else { print("Powerstate value is nil") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Powerstate value is nil") } self.clearAccessory() } } else { print("Error in Reading powerstate value \(self.errorMessage.getHMErrorDescription(error!.code))") if let delegate = self.delegate { delegate.didReceiveErrorMessage("Error reading Powerstate: \(self.errorMessage.getHMErrorDescription(error!.code))") } self.clearAccessory() } }) } else { if let delegate = self.delegate { delegate.didReceiveErrorMessage("Characteristic: PowerState is nil") } } } // Mark: - HMAccessoryDelegate protocol public func accessoryDidUpdateReachability(accessory: HMAccessory) { if accessory.reachable == true { print("accessory: \(accessory.name) is reachable") if let delegate = delegate { delegate.didReceiveLogMessage("\(accessory.name) is reachable") delegate.didReceiveAccessoryReachabilityUpdate(accessory) } } else { print("accessory: \(accessory.name) is not reachable") if let delegate = delegate { delegate.didReceiveErrorMessage("\(accessory.name) is not reachable") } } } }
bsd-3-clause
3e21f53724ad6ab4462c1967103a7480
45.952641
300
0.610335
5.796267
false
false
false
false
DianQK/Flix
Flix/UniqueCustomProvider/UniqueCustomTableViewProvider.swift
1
5219
// // UniqueCustomTableViewProvider.swift // Flix // // Created by DianQK on 04/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa public typealias SingleUITableViewCellProvider = SingleTableViewCellProvider<UITableViewCell> @available(*, deprecated, renamed: "SingleUITableViewCellProvider") public typealias UniqueCustomTableViewProvider = SingleUITableViewCellProvider open class SingleTableViewCellProvider<Cell: UITableViewCell>: CustomProvider, ProviderHiddenable, UniqueAnimatableTableViewProvider, CustomIdentityType { public let customIdentity: String public let contentView: UIView = NeverHitSelfView() open var selectedBackgroundView: UIView? { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.selectedBackgroundView = self.selectedBackgroundView } } } open var backgroundView: UIView? { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.backgroundView = self.backgroundView } } } open var accessoryType: UITableViewCell.AccessoryType = .none { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.accessoryType = self.accessoryType } } } open var accessoryView: UIView? { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.accessoryView = self.accessoryView } } } open var editingAccessoryType: UITableViewCell.AccessoryType = .none { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.editingAccessoryType = self.editingAccessoryType } } } open var editingAccessoryView: UIView? { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.editingAccessoryView = self.editingAccessoryView } } } open var separatorInset: UIEdgeInsets? { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } if let separatorInset = self.separatorInset { cell.separatorInset = separatorInset } } } } open var selectionStyle: UITableViewCell.SelectionStyle = .default { didSet { whenGetCell { [weak self] (cell) in guard let `self` = self else { return } cell.selectionStyle = self.selectionStyle } } } open var isEnabled = true @available(*, deprecated, renamed: "event.selectedEvent") open var tap: ControlEvent<()> { return self.event.selectedEvent } open var itemHeight: ((UITableView) -> CGFloat?)? open var didMoveToTableView: ((UITableView, UITableViewCell) -> ())? open var isHidden: Bool { get { return _isHidden.value } set { _isHidden.accept(newValue) } } private let _isHidden = BehaviorRelay(value: false) let disposeBag = DisposeBag() public init(customIdentity: String) { self.customIdentity = customIdentity } public init() { self.customIdentity = "" } open func onCreate(_ tableView: UITableView, cell: Cell, indexPath: IndexPath) { self.onGetCell(cell) cell.contentView.addSubview(contentView) self.contentView.translatesAutoresizingMaskIntoConstraints = false self.contentView.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true self.contentView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true self.contentView.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true self.contentView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true if let superview = cell.superview as? UITableView { self.didMoveToTableView?(superview, cell) } } open func itemSelected(_ tableView: UITableView, indexPath: IndexPath, value: SingleTableViewCellProvider) { tableView.deselectRow(at: indexPath, animated: true) } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath, value: SingleTableViewCellProvider) -> CGFloat? { return self.itemHeight?(tableView) } open func createValues() -> Observable<[SingleTableViewCellProvider]> { return self._isHidden.asObservable() .map { [weak self] isHidden in guard let `self` = self, !isHidden else { return [] } return [self] } } open func register(_ tableView: UITableView) { tableView.register(Cell.self, forCellReuseIdentifier: self._flix_identity) } }
mit
0ad46f918b8276ab0acd9f11c9088c3f
32.235669
154
0.616711
5.145957
false
false
false
false
Kiandr/CrackingCodingInterview
Swift/Ch 3. Stacks and Queues/Ch 3. Stacks and Queues.playground/Pages/3.4 Queue via Stacks.xcplaygroundpage/Contents.swift
1
1236
import Foundation /*: 3.4 Queue via Stacks: Implement a MyQueue data structure that implements a queue using two stacks. */ struct MyQueue<Element: Comparable> { fileprivate var stack = Stack<Element>() fileprivate var placeHolderStack = Stack<Element>() } extension MyQueue { mutating func enqueue(value: Element) { while let top = stack.pop() { placeHolderStack.push(top) } stack.push(value) while let top = placeHolderStack.pop() { stack.push(top) } } mutating func dequeue() -> Element? { return stack.pop() } var peek: Element? { return stack.peek } var isEmpty: Bool { return stack.peek == nil } } extension MyQueue: CustomStringConvertible { var description: String { var description = "" var stack = self.stack while let top = stack.pop() { description += "\(top)," } description.dropLast() return description } } var queue = MyQueue<Int>() for i in 0..<5 { queue.enqueue(value: i) } for i in 0..<5 { let value = queue.dequeue() assert(value == i) } assert(queue.isEmpty)
mit
b1d31dcb4ac795b37c1d77d65e3a291c
18.935484
77
0.571197
4.204082
false
false
false
false
anzfactory/QiitaCollection
Libraries/ObjC/PathMenu/PathMenuItem.swift
1
3643
// // PathMenuItem.swift // PathMenu // // Created by pixyzehn on 12/27/14. // Copyright (c) 2014 pixyzehn. All rights reserved. // import Foundation import UIKit protocol PathMenuItemDelegate:NSObjectProtocol { func PathMenuItemTouchesBegan(item: PathMenuItem) func PathMenuItemTouchesEnd(item:PathMenuItem) } class PathMenuItem: UIImageView { var contentImageView: UIImageView? var startPoint: CGPoint? var endPoint: CGPoint? var nearPoint: CGPoint? var farPoint: CGPoint? weak var delegate: PathMenuItemDelegate! var _highlighted: Bool = false override var highlighted: Bool { get { return _highlighted } set { _highlighted = newValue self.contentImageView?.highlighted = newValue } } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(image:UIImage!, highlightedImage himg:UIImage?, ContentImage cimg:UIImage?, highlightedContentImage hcimg:UIImage?) { self.init(frame: CGRectZero) self.image = image self.highlightedImage = himg self.userInteractionEnabled = true self.contentImageView = UIImageView(image: cimg) self.contentImageView?.highlightedImage = hcimg self.addSubview(self.contentImageView!) } private func ScaleRect(rect: CGRect, n: CGFloat) -> CGRect { let width = rect.size.width let height = rect.size.height return CGRectMake(CGFloat((width - width * n)/2), CGFloat((height - height * n)/2), CGFloat(width * n), CGFloat(height * n)) } // UIView's methods override func layoutSubviews() { super.layoutSubviews() if let image = self.image { self.bounds = CGRectMake(0, 0, image.size.width, image.size.height) } if let imageView = self.contentImageView { let width: CGFloat! = imageView.image?.size.width let height: CGFloat! = imageView.image?.size.height imageView.frame = CGRectMake(self.bounds.size.width/2 - width/2, self.bounds.size.height/2 - height/2, width, height) } } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.highlighted = true if self.delegate.respondsToSelector("PathMenuItemTouchesBegan:") { self.delegate.PathMenuItemTouchesBegan(self) } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if let any: AnyObject = touches.first as? AnyObject { let location:CGPoint? = any.locationInView(self) if let loc = location { if (!CGRectContainsPoint(ScaleRect(self.bounds, n: 2.0), loc)) { self.highlighted = false } } } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { self.highlighted = false if let any: AnyObject = touches.first as? AnyObject { let location: CGPoint? = any.locationInView(self) if let loc = location { if (CGRectContainsPoint(ScaleRect(self.bounds, n: 2.0), loc)) { self.delegate.PathMenuItemTouchesEnd(self) } } } } override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { self.highlighted = false } }
mit
21f07f5573370fd650d63905bcd7933b
30.136752
138
0.606643
4.712807
false
false
false
false
WTGrim/WTWeibo_Swift
Weibo/Weibo/Classes/Main/Visitor/VisitorView.swift
1
1299
// // VisitorView.swift // Weibo // // Created by dwt on 17/2/26. // Copyright © 2017年 Dwt. All rights reserved. // import UIKit class VisitorView: UIView { class func visitorView() -> VisitorView { return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).first as! VisitorView } @IBOutlet weak var rotationView: UIImageView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var loginBtn: UIButton! //自定义函数 func resetVisitorView(iconName:String, title:String){ rotationView.hidden = true iconView.image = UIImage(named: iconName) titleLabel.text = title } //旋转动画方法 func setRotationAnimation(){ let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = M_PI * 2 animation.repeatCount = MAXFLOAT animation.duration = 5 //需要设置这个属性 不然退回后台或者切换页面动画会消失 animation.removedOnCompletion = false rotationView.layer.addAnimation(animation, forKey: nil) } }
mit
711dd4b5334bb221dc8ace0c4d0c85a5
25.608696
112
0.642974
4.5
false
false
false
false
sgurnoor/TicTacToe
Tic Tac Toe/LogInViewController.swift
1
1439
// // LogInViewController.swift // Tic Tac Toe // // Created by Gurnoor Singh on 12/2/15. // Copyright © 2015 Cyberician. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class LogInViewController: UIViewController, FBSDKLoginButtonDelegate { override func viewDidLoad() { super.viewDidLoad() if (FBSDKAccessToken.currentAccessToken() == nil) { print("Not logged in..") } else { print("Logged in..") } let loginButton = FBSDKLoginButton() loginButton.readPermissions = ["public_profile", "email", "user_friends"] loginButton.center = self.view.center loginButton.delegate = self self.view.addSubview(loginButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { if error == nil { print("Login complete.") self.performSegueWithIdentifier("showNew", sender: self) } else { print(error.localizedDescription) } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { print("User logged out...") } }
mit
02e0a1fb820301915d036e38a24c3169
23.372881
130
0.612656
5.229091
false
false
false
false
alvinvarghese/DeLorean
DeLorean/Future.swift
1
18233
// // Future.swift // DeLorean // // Created by Junior B. on 16/02/15. // Copyright (c) 2015 Bonto.ch. All rights reserved. // import Foundation // MARK: - Global functions /// A convenience global function to create a Future public func future<T>(ec: ExecutionContext = ExecutionContext.defaultContext, t: () -> Result<T>) -> Future<T> { return Future<T>(ec, t) } // FutureVoid is a workaround to a closure bug in Swift 1.2 // It will be changed to future as soon the bug is fixed // rdar://19917034 /// A convenience global function to create a Future with no return result public func futureVoid(ec: ExecutionContext = ExecutionContext.defaultContext, t: () -> ()) -> Future<Void> { return Future<Void>(ec, t) } // MARK: - Future Implementation /** A Future is an object holding a result which may become available at some point. The result is usually the achieved with some other computation: * If the computation has not yet completed, we say that the Future is not completed. * If the computation has completed with a value or with an exception, we say that the Future is completed. So basically, asking for Future's result can have the following scenarios: * The returned value will be `nil`, if the computation is not completed. * The value will be `Value(t)`, in case it contains a valid result and is completed * The value will be `Error(e)` if it contains an error Once the result has been computed, all registered callbacks are fired. */ public class Future<T> { /// Runnable is the closure to run public typealias Runnable = () -> Result<T> typealias OnSuccessCallback = (T) -> () public typealias OnFailureCallback = (NSError) -> () typealias OnCompleCallback = (result: Result<T>) -> () /** The result value of this `Future`: - The returned value will be `nil`, if the future is not completed. - The value will be `Value(t)`, in case it contains a valid result and is completed - The value will be `Error(e)` if it contains an error Setting this value will immediately fire all the callbacks */ internal var result: Result<T>? = nil { didSet { self.performCallbacks(result) } } /** All callbacks to run **Note**: In the event that multiple callbacks are registered on the future, the order in which they are executed **IS DEFINED** by the array. */ var callbacks: [SinkOf<Result<T>>] = Array<SinkOf<Result<T>>>() // MARK: - Init init() { } /// Basic init with a Runnable public init(_ task: Runnable) { self.execute(ExecutionContext.defaultContext, task) } init(_ executor: ExecutionContext = ExecutionContext.defaultContext, _ task: Runnable) { self.execute(executor, task) } init(_ executor: ExecutionContext = ExecutionContext.defaultContext, _ task: () -> ()) { executor.executeAsync { task() } } /// Execute the current task using the executor private func execute(_ executor: ExecutionContext = ExecutionContext.defaultContext , _ task: Runnable) { // If the current future has a result, return if result != nil { return } // Execute the task, if provided executor.executeAsync { synchronized(self) { self.result = task() } return } } /** Perform all scheduled callbacks :param: result The optional result to use to perform callbacks */ internal func performCallbacks(result: Result<T>?) { if let res = result { for sink in self.callbacks { sink.put(res) } self.callbacks.removeAll() } } // MARK: - Convenience properties /// The current value, if exists public var value: T? { get { return self.result?.value } } /// The current error, if exists public var error: NSError? { get { return self.result?.error } } /// Return a Boolean indicating if the Future was successful public var isSuccess: Bool { get { return self.result?.isSuccess ?? false } } /// Return a Boolean indicating if the Future failed public var isFailure: Bool { get { return self.result?.isFailure ?? false } } /// Return a Boolean indicating if the Future is completed public var isCompleted: Bool { get { return self.result != nil } } // MARK: - Callbacks registration /** Register a callback that is executed when the `Future` is completed. This callback is executed once the `Future` has a result value available. :param: executor The execution context where the block will be performed. **Defaut:** current thread context. :param: callback The block of type `(Result<T>) -> ()` to perform. :returns: The future object where the completition block has been added to. */ public func onComplete(context executor: ExecutionContext = CurrentThreadExecutionContext(), callback: OnCompleCallback) -> Future<T> { let boxedCallback : Result<T> -> () = { res in executor.executeAsyncWithBarrier { callback(result: res) return } } if let res = self.result { executor.executeAsyncWithBarrier { callback(result: res) } } else { self.callbacks.append(SinkOf<Result<T>>(boxedCallback)) } return self } /** Register a callback that is executed when the `Future` is successfully completed. This callback is executed once the `Future` has a result value available without errors. :param: executor The execution context where the block will be performed. **Defaut:** current thread context. :param: callback The block of type `(T) -> ()` to perform. :returns: The future object where the *success block* has been added to. */ public func onSuccess(context executor: ExecutionContext = CurrentThreadExecutionContext(), callback: OnSuccessCallback) -> Future<T> { self.onComplete(context: executor) { result in switch result { case .Value(let val): callback(val.value) default: break } } return self } /** Register a callback that is executed when the `Future` has failed. This callback is executed once the `Future` has a result value available with an error. :param: executor The execution context where the block will be performed. **Defaut:** current thread context. :param: callback The block of type `(NSError) -> ()` to perform. :returns: The future object where the *failure block* has been added to. */ public func onFailure(context executor: ExecutionContext = CurrentThreadExecutionContext(), callback: OnFailureCallback) -> Future<T> { self.onComplete(context: executor) { result in switch result { case .Error(let err): callback(err) default: break } } return self } // MARK: - Monadic Operations /** Perform the given function to the result, if successfully computed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The function of type `(T) -> ()` to perform. */ public func foreach(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (value: T) -> ()) { self.onComplete(context: executor) { result in switch result { case .Value(let v): f(value: v.value) default: break } } } /** Creates a new `Future` by applying a function to the successful result of this future. If this future is completed with an error, the new one will contain the same error. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The function of type `(T) -> (U)` to perform. :returns: The new `Future` object. */ public func map<U>(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (value: T) -> U) -> Future<U> { let promise = Promise<U>() self.onComplete(context: executor) { result in switch result { case .Error(let e): promise.failure(e) case .Value(let v): promise.success(f(value: v.value)) } } return promise.future() } /** Creates a new `Future` by applying a filter function to the successful result of this future, returning a new future as the result of the function. If this future is completed with an error, the new one will contain the same error. **Note:** The returned `Future` is computed only when the current future is completed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The filter function of type `(T) -> (Bool)` to perform. :returns: The new `Future` object. */ public func filter(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (value: T) -> Bool) -> Future<T> { let promise = Promise<T>() self.onComplete(context: executor) { result in switch result { case .Error(let e): promise.failure(e) case .Value(let v): if f(value: v.value) { promise.success(v.value) } else { promise.failure(NSError(domain: "xyz.sideeffects.DeLorean", code: 99, userInfo: nil)) } } } return promise.future() } /** Creates a new `Future` by applying a function to the successful result of this future, returning a new future as the result of the function. If this future is completed with an error, the new one will contain the same error. **Note:** The returned `Future` is computed only when the current future and the one passed with `f` function are both completed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The function of type `(T) -> (Future<U>)` to perform. :returns: The new `Future` object. */ public func fmap<U>(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (value: T) -> Future<U>) -> Future<U> { let promise = Promise<U>() let boxedTask : (Result<U>) -> () = { (r: Result<U>) in switch r { case .Error(let e): promise.failure(e) case .Value(let v): promise.success(v.value) } return } self.onComplete(context: executor) { result in switch result { case .Error(let e): promise.failure(e) case .Value(let v): f(value: v.value).onComplete(context: executor, callback: boxedTask) } return } return promise.future() } /** Zips the values of `this` and `that` future, and creates a new future holding the tuple of their results. If `this` future fails, the resulting future is failed with the same error of `this`. Otherwise, if `that` future fails, the resulting future is failed with the error stored in `that`. **WARNING! The current implementation of Swift, doesn't work with plain generics tuples. To workaroud this, we are using an array to box the current result tuple. As soon as Swift will correctly hand generics and tuples, we are going to change this method to a better implementation.** :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The future to zip with. :returns: The new `Future` object. */ public func zip<U>(context executor: ExecutionContext = ExecutionContext.defaultContext, that: Future<U>) -> Future<[(T,U)]> { let promise = Promise<[(T,U)]>() self.onComplete(context: executor) { result in switch result { case .Error(let e): promise.failure(e) case .Value(let thisValue): that.onComplete(context: executor) { result2 in switch result2 { case .Error(let e): promise.failure(e) case .Value(let thatValue): let boxedResult = (thisValue.value, thatValue.value) promise.success([boxedResult]) } } } return } return promise.future() } // MARK: - Chaining /** Creates a new `Future` by chaining it with the previous one. If this future is completed with an error, the chained one will contain the same error. **Note:** The returned `Future` is executed only when the current future is completed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The function of type `(T) -> (Result<U>)` to perform. :returns: The new `Future` object. */ public func then<U>(_ executor: ExecutionContext = ExecutionContext.defaultContext, _ task: (value: T) -> Result<U>) -> Future<U> { let future = Future<U>() self.onComplete(){ result in switch result { case .Error(let e): synchronized(future) { future.result = Result<U>(e) } case .Value(let val): future.execute(executor){ return task(value: result.value!) } } } return future } // MARK: - Error Handling /** Creates a new `Future` by applying a recover function to the failed result of this future, returning a new future as the result of the function. If this future is completed sucessfully, the new one will contain the same result. **Note:** The returned `Future` is computed only when the current future is completed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The recover function of type `(NSError) -> (T)` to perform. :returns: The new `Future` object. */ public func recover(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (error: NSError) -> T) -> Future<T> { let promise = Promise<T>() self.onComplete(context: executor) { result in switch result { case .Error(let e): promise.success(f(error: e)) case .Value(let v): promise.success(v.value) } } return promise.future() } /** Creates a new `Future` by applying a recover function to the failed result of this future, returning a new future as the result of the function. If this future is completed sucessfully, the new one will contain the same result. **Note:** The returned `Future` is computed only when the current future is completed. :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The function of type `(NSError) -> (Future<U>)` to perform. :returns: The new `Future` object. */ public func recoverWith(context executor: ExecutionContext = ExecutionContext.defaultContext, f: (error: NSError) -> Future<T>) -> Future<T> { let promise = Promise<T>() let boxedTask : (Result<T>) -> () = { (r: Result<T>) in switch r { case .Error(let e): promise.failure(e) case .Value(let v): promise.success(v.value) } return } self.onComplete(context: executor) { result in switch result { case .Error(let e): f(error: e).onComplete(context: executor, callback: boxedTask) case .Value(let v): promise.success(v.value) } } return promise.future() } /** Creates a new `Future` that holds this future's value if successfully completed, otherwise it executes the passed one. In case both futures fail, the new one will hold the error of the this future (the original one). :param: executor The execution context where the block will be performed. **Defaut:** default context. :param: f The future to perform in case of failure. :returns: The new `Future` object. */ public func fallbackTo(context executor: ExecutionContext = ExecutionContext.defaultContext, f: Future<T>) -> Future<T> { let promise = Promise<T>() self.onComplete(context: executor) { result in switch result { case .Error(let firstError): f.onComplete(context: executor) { result2 in switch result2 { case .Error(let e): promise.failure(firstError) // Returns the original error case .Value(let v): promise.success(v.value) } } case .Value(let v): promise.success(v.value) } } return promise.future() } }
mit
72497be8f16de907fdd694c8cf65d8e3
35.320717
146
0.588
4.722352
false
false
false
false
szysz3/ios-timetracker
TimeTracker/TaskSession.swift
1
1626
// // TaskSession.swift // TimeTracker // // Created by Michał Szyszka on 23.09.2016. // Copyright © 2016 Michał Szyszka. All rights reserved. // import Foundation import FirebaseDatabase class TaskSession : Equatable { //MARK: Fields var taskSessionId: String var taskId: String var startTimestamp: String var endTimestamp: String! //MARK: Inits init(taskId: String, startTimestamp: String) { self.taskId = taskId self.startTimestamp = startTimestamp taskSessionId = NSUUID().uuidString endTimestamp = "" } init(firSnapshot: FIRDataSnapshot) { var snapshot = firSnapshot.value! as! [String:AnyObject] taskSessionId = snapshot["taskSessionId"] as! String taskId = snapshot["taskId"] as! String startTimestamp = snapshot["startTimestamp"] as! String endTimestamp = snapshot["endTimestamp"] as! String } //MARK: Functions func toAnyObject() -> AnyObject { let anyObject = [ "taskSessionId" : taskSessionId as AnyObject, "taskId" : taskId as AnyObject, "startTimestamp" : startTimestamp as AnyObject, "endTimestamp" : endTimestamp as AnyObject ] as [String : AnyObject] return anyObject as AnyObject } public static func ==(lhs: TaskSession, rhs: TaskSession) -> Bool { return lhs.taskId == rhs.taskId && lhs.taskSessionId == rhs.taskSessionId && lhs.startTimestamp == rhs.startTimestamp && lhs.endTimestamp == rhs.endTimestamp } }
mit
94c9f4c088a00f4ff7204bf57eda79f4
27.473684
165
0.623537
4.801775
false
false
false
false
ps2/rileylink_ios
NightscoutUploadKit/Models/LoopEnacted.swift
1
1683
// // LoopEnacted.swift // RileyLink // // Created by Pete Schwamb on 7/28/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct LoopEnacted { typealias RawValue = [String: Any] let rate: Double? let duration: TimeInterval? let timestamp: Date let received: Bool let bolusVolume: Double public init(rate: Double?, duration: TimeInterval?, timestamp: Date, received: Bool, bolusVolume: Double = 0) { self.rate = rate self.duration = duration self.timestamp = timestamp self.received = received self.bolusVolume = bolusVolume } public var dictionaryRepresentation: [String: Any] { var rval = [String: Any]() rval["rate"] = rate if let duration = duration { rval["duration"] = duration / 60.0 } rval["timestamp"] = TimeFormat.timestampStrFromDate(timestamp) rval["received"] = received rval["bolusVolume"] = bolusVolume return rval } init?(rawValue: RawValue) { guard let rate = rawValue["rate"] as? Double, let durationMinutes = rawValue["duration"] as? Double, let timestampStr = rawValue["timestamp"] as? String, let timestamp = TimeFormat.dateFromTimestamp(timestampStr), let received = rawValue["received"] as? Bool else { return nil } self.rate = rate self.duration = TimeInterval(minutes: durationMinutes) self.timestamp = timestamp self.received = received self.bolusVolume = rawValue["bolusVolume"] as? Double ?? 0 } }
mit
cc0824163d996dff4bbc593f7ffa81d1
27.508475
115
0.608799
4.558266
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/AssetsCatalog/AssetsCatalogParser.swift
1
891
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import PathKit public enum AssetsCatalog { public final class Parser: SwiftGenKit.Parser { var catalogs = [Catalog]() private let options: ParserOptionValues public var warningHandler: Parser.MessageHandler? public init(options: [String: Any] = [:], warningHandler: Parser.MessageHandler? = nil) throws { self.options = try ParserOptionValues(options: options, available: Self.allOptions) self.warningHandler = warningHandler } public static let defaultFilter = filterRegex(forExtensions: ["xcassets"]) public static let filterOptions: Filter.Options = [.skipsFiles, .skipsHiddenFiles, .skipsPackageDescendants] public func parse(path: Path, relativeTo parent: Path) throws { let catalog = Catalog(path: path) catalogs += [catalog] } } }
mit
0705c131329bf77cfcdb8b7cfc484fb5
29.689655
112
0.716854
4.517766
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/Former/Former/RowFormers/SwitchRowFormer.swift
1
2722
// // SwitchRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 7/27/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol SwitchFormableRow: FormableRow { func formSwitch() -> UISwitch func formTitleLabel() -> UILabel? } open class SwitchRowFormer<T: UITableViewCell> : BaseRowFormer<T>, Formable where T: SwitchFormableRow { // MARK: Public open var switched = false open var switchWhenSelected = false open var titleDisabledColor: UIColor? = .lightGray public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } @discardableResult public final func onSwitchChanged(_ handler: @escaping ((Bool) -> Void)) -> Self { onSwitchChanged = handler return self } open override func cellInitialized(_ cell: T) { super.cellInitialized(cell) cell.formSwitch().addTarget(self, action: #selector(SwitchRowFormer.switchChanged(_:)), for: .valueChanged) } open override func update() { super.update() if !switchWhenSelected { if selectionStyle == nil { selectionStyle = cell.selectionStyle } cell.selectionStyle = .none } else { _ = selectionStyle.map { cell.selectionStyle = $0 } selectionStyle = nil } let titleLabel = cell.formTitleLabel() let switchButton = cell.formSwitch() switchButton.isOn = switched switchButton.isEnabled = enabled if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } titleColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } titleLabel?.textColor = titleDisabledColor } } open override func cellSelected(indexPath: IndexPath) { former?.deselect(animated: true) if switchWhenSelected && enabled { let switchButton = cell.formSwitch() switchButton.setOn(!switchButton.isOn, animated: true) switchChanged(switchButton) } } // MARK: Private private final var onSwitchChanged: ((Bool) -> Void)? private final var titleColor: UIColor? private final var selectionStyle: UITableViewCellSelectionStyle? @objc private dynamic func switchChanged(_ switchButton: UISwitch) { if self.enabled { let switched = switchButton.isOn self.switched = switched onSwitchChanged?(switched) } } }
mit
84da8f721d289e08426a2f806f89037b
29.920455
115
0.616685
5.114662
false
false
false
false
jevy-wangfei/FeedMeIOS
FeedMeIOS/Reachability.swift
2
1608
// // Reachability.swift // FeedMeIOS // // Created by Jun Chen on 18/04/2016. // Copyright © 2016 FeedMe. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } class func alertNoInternetConnection(viewController: UIViewController) { let alert = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(okAction) viewController.presentViewController(alert, animated: true, completion: nil) } }
mit
abc3ddcc1405f173a6e6981bbb19d373
37.285714
180
0.672682
5.053459
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureReferral/Sources/FeatureReferralUI/ReferFriendReducer.swift
1
2689
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import ComposableArchitecture import UIKit public enum ReferFriendModule {} extension ReferFriendModule { public static var reducer: Reducer<ReferFriendState, ReferFriendAction, ReferFriendEnvironment> { .init { state, action, environment in switch action { case .onAppear: return .none case .onShareTapped: state.isShareModalPresented = true return .none case .onShowRefferalTapped: state.isShowReferralViewPresented = true return .none case .onCopyReturn: state.codeIsCopied = false return .none case .binding: return .none case .onCopyTapped: state.codeIsCopied = true return .merge( .fireAndForget { [referralCode = state.referralInfo.code] in UIPasteboard.general.string = referralCode }, Effect(value: .onCopyReturn) .delay( for: 2, scheduler: environment.mainQueue ) .eraseToEffect() ) } } .binding() .analytics() } } // MARK: - Analytics Extensions extension ReferFriendState { func analyticsEvent(for action: ReferFriendAction) -> AnalyticsEvent? { switch action { case .onAppear: return AnalyticsEvents.New.Referral.viewReferralsPage(campaign_id: referralInfo.code) case .onCopyTapped: return AnalyticsEvents.New.Referral.referralCodeCopied(campaign_id: referralInfo.code) case .onShareTapped: return AnalyticsEvents.New.Referral.shareReferralsCode(campaign_id: referralInfo.code) default: return nil } } } extension Reducer where Action == ReferFriendAction, State == ReferFriendState, Environment == ReferFriendEnvironment { fileprivate func analytics() -> Self { combined( with: Reducer< ReferFriendState, ReferFriendAction, ReferFriendEnvironment > { state, action, env in guard let event = state.analyticsEvent(for: action) else { return .none } return .fireAndForget { env.analyticsRecorder.record(event: event) } } ) } }
lgpl-3.0
1ad3653c842fb444122da6f9b96fd7ce
27.903226
101
0.541295
5.496933
false
false
false
false
hikki912/BeautyStory
BeautyStory/BeautyStory/Classes/Home/Model/DismissAnimation.swift
1
3583
// // DismissAnimation.swift // BeautyStory // // Created by hikki on 2017/3/4. // Copyright © 2017年 hikki. All rights reserved. // import UIKit class DismissAnimation: NSObject { } extension DismissAnimation: UIViewControllerAnimatedTransitioning { /// 动画的执行时间 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } /// 动画的执行过程 /// 动画执行完后必须调用 transitionContext的一个完成方法,不然不会执行成功 func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { /* 实现思路: 1.获取到fromVC->fromView(UICollectionView)的当前的cell的ImageView 2.将获取到的ImageView添加到window上 3.获取当前cell的indexPath(当前indexPath就是主界面的那个cell的indexPath) 4.将主界面的CollectionView传给fromVC 5.通过主界面的CollectionView和indexPath来找到对应的cell(有可能找不到(在当前界面如果看不到则会返回nil)) 6.将cell的frame转换到window上 7.执行ImageView的动画,让它的frame设置为cell的frame */ // 1.获取到fromVC guard let fromVC = transitionContext.viewController(forKey: .from) as? PhotoBrowserVC else { return } // 2.获取当前图片浏览器显示的cell guard let fromVisibleCell = fromVC.collectionView?.visibleCells.first as? PhotoBrowserCell else { return } // 3.获取keywindow guard let keyWindow = UIApplication.shared.keyWindow else { return } // 4.获取当前cell的indexPath guard let fromIndexPath = fromVC.collectionView?.indexPath(for: fromVisibleCell) else { return } // 初始化imageView的frame var frame = CGRect() // 获取主界面的可见的最后一个cell var indexPathsForVisibleItems = fromVC.homeCollectionView!.indexPathsForVisibleItems indexPathsForVisibleItems = indexPathsForVisibleItems.sorted(by: { (indexPath1, indexPath2) -> Bool in return indexPath1 < indexPath2 }) // 获取主界面的可见的最后一个cell的indexPath let lastHomeIndexPath = indexPathsForVisibleItems.last ?? IndexPath() // 判断主界面的indexPath与当前from的indexPath的大小 if lastHomeIndexPath < fromIndexPath { frame.origin.y = UIScreen.main.bounds.height } // 5.通过当前cell的IndexPath,和主界面的collectionView来获取那个位置的cell if let homeCell = fromVC.homeCollectionView?.cellForItem(at: fromIndexPath) { // 6.将cell的frame转换到window上 frame = homeCell.convert(homeCell.bounds, to: keyWindow) } // 7.从cell中获得图片 let imageView = fromVisibleCell.imageView // 8.将图片添加到windows上 keyWindow.addSubview(imageView) // 9.执行动画 let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, animations: { // 改变imageView的frame imageView.frame = frame }) { (_) in imageView.removeFromSuperview() } // 告诉系统动画执行完了 transitionContext.completeTransition(true) } }
mit
2e1574b859894243496efc5f43a8d4af
32.032258
110
0.64388
4.748068
false
false
false
false
GTMYang/GTMRefresh
GTMRefresh/GTMLoadMoreFooter.swift
1
7229
// // GTMRefreshFooter.swift // GTMRefresh // // Created by luoyang on 2016/12/7. // Copyright © 2016年 luoyang. All rights reserved. // import UIKit @objc public protocol SubGTMLoadMoreFooterProtocol { @objc optional func toNormalState() @objc optional func toNoMoreDataState() @objc optional func toWillRefreshState() @objc optional func toRefreshingState() /// 控件的高度(自定义控件通过该方法设置自定义高度) /// /// - Returns: 控件的高度 func contentHeith() -> CGFloat } open class GTMLoadMoreFooter: GTMRefreshComponent, SubGTMRefreshComponentProtocol { /// 加载更多Block var loadMoreBlock: () -> Void = {} var contentView: UIView = { let view = UIView() view.backgroundColor = UIColor.clear return view }() var lastBottomDelta: CGFloat = 0.0 public var subProtocol: SubGTMLoadMoreFooterProtocol? { get { return self as? SubGTMLoadMoreFooterProtocol } } public var isNoMoreData: Bool = false { didSet { if isNoMoreData { state = .noMoreData } else { state = .idle } } } override var state: GTMRefreshState { didSet { guard oldValue != state, let scrollV = scrollView else { return } if let header = scrollV.gtmHeader, header.isRefreshing { return } switch state { case .idle: // 结束加载 UIView.animate(withDuration: GTMRefreshConstant.slowAnimationDuration, animations: { scrollV.mj_insetB = self.lastBottomDelta // print("self.lastBottomDelta = \(self.lastBottomDelta)") }, completion: { (isComplet) in self.subProtocol?.toNormalState?() }) case .noMoreData: self.subProtocol?.toNoMoreDataState?() case .refreshing: guard oldValue != .refreshing else { return } self.loadMoreBlock() // 展示正在加载动效 UIView.animate(withDuration: GTMRefreshConstant.fastAnimationDuration, animations: { let overflowHeight = self.contentOverflowHeight var toInsetB = self.mj_h + (self.scrollViewOriginalInset?.bottom)! if overflowHeight < 0 { // 如果内容还没占满 toInsetB -= overflowHeight } // self.lastBottomDelta = toInsetB - scrollV.mj_insetB scrollV.mj_insetB = toInsetB scrollV.mj_offsetY = self.footerWillShowOffsetY + self.mj_h }, completion: { (isComplet) in }) self.subProtocol?.toRefreshingState?() case .willRefresh: self.subProtocol?.toWillRefreshState?() default: break } } } // MARK: - Life Cycle override public init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.contentView) self.contentView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) self.scollViewContentSizeDidChange(change: nil) } // MARK: - Layout override open func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds } /// 即将触发加载的高度(特殊的控件需要重写该方法,返回不同的数值) /// /// - Returns: 触发刷新的高度 open func willLoadMoreHeight() -> CGFloat { return self.mj_h // 默认使用控件高度 } // MARK: - SubGTMRefreshComponentProtocol open func scollViewContentOffsetDidChange(change: [NSKeyValueChangeKey : Any]?) { // refreshing或者noMoreData状态,直接返回 guard state != .refreshing, state != .noMoreData, let scrollV = scrollView else { return } self.scrollViewOriginalInset = scrollV.mj_inset let currentOffsetY = scrollV.mj_offsetY let footerWillShowOffsetY = self.footerWillShowOffsetY guard currentOffsetY >= footerWillShowOffsetY else { // footer还没出现, 直接返回 return } if scrollV.isDragging { // 拖动状态 let willLoadMoreOffsetY = footerWillShowOffsetY + self.willLoadMoreHeight() switch currentOffsetY { case footerWillShowOffsetY...willLoadMoreOffsetY: state = .pulling case willLoadMoreOffsetY...(willLoadMoreOffsetY + 1000): state = .willRefresh default: break } } else { // 停止拖动状态 switch state { case .pulling: state = .idle case .willRefresh: state = .refreshing default: break } } } open func scollViewContentSizeDidChange(change: [NSKeyValueChangeKey : Any]?) { // here do nothing guard let scrollV = scrollView, let originInset = scrollViewOriginalInset else { return } // 重设位置 let contentH = scrollV.mj_contentH // 内容高度 let visibleH = scrollV.mj_h - originInset.top - originInset.bottom // 可见区域高度 self.mj_y = contentH > visibleH ? contentH : visibleH } // MARK: - Public public func endLoadMore(isNoMoreData: Bool) { if isNoMoreData { state = .noMoreData } else { state = .idle } } // MARK: - Private /// ScrollView内容溢出的高度 private var contentOverflowHeight: CGFloat { get { guard let scrollV = scrollView, let originInset = scrollViewOriginalInset else { return 0.0 } // ScrollView内容占满的高度 let fullContentHeight = scrollV.mj_h - originInset.bottom - originInset.top return scrollV.mj_contentH - fullContentHeight } } /// 上拉刷新控件即将出现时的OffsetY private var footerWillShowOffsetY: CGFloat { get { guard let _ = scrollView, let originInset = scrollViewOriginalInset else { return 0.0 } let overflowHeight = contentOverflowHeight if overflowHeight > 0 { return overflowHeight - originInset.top } else { return -originInset.top } } } }
mit
8479a46c9ee89520f69571a0a1611969
29.530973
100
0.543913
5.149254
false
false
false
false
EugeneVegner/sit-autolifestory-vapor-server
Sources/App/Models/User.swift
1
8665
import Vapor import HTTP import Fluent import Foundation import BSON import MongoKitten final class User: MongoEntity { //var id: Node? var username: String var firstName: String var lastName: String var email: String var password: String? var fid: Int64? var provider: ProviderType var country: String required public init(request: Request) throws { fatalError("init(request:) has not been implemented") } //let title = Valid(Count<String>.max(5)) // public required init(from: String) { // self.id = nil // fatalError("init(from:) has not been implemented") // } // init?(email: String, username: String, password: String) { // //super.init(email) // self.id = nil // do { // self.username = try username.validated() // self.email = try email.validated() // self.password = try password.validated() // } catch { // print(error) // return nil // } // } // init?(username: String, email: String, password: String) { // // self.id = UUID().uuidString.makeNode() // do { // self.username = try username.validated() // self.email = try email.validated() // self.password = try password.validated() // } catch { // print(error) // return nil // } // } init(username: String, email: String, password: String?, firstName: String, lastName: String, fid: Int64? = nil, provider: ProviderType, country: String ) { self.username = username self.email = email self.password = password self.firstName = firstName self.lastName = lastName self.fid = fid self.provider = provider self.country = country super.init(uuid: nil) } required init(node: Node, in context: Context) throws { //print(#function) //print("context: \(context)") //print("node: \(node)") // self.username = node["username"]!.string!.validated()//.validated() // self.email = try node.extract("email").string.validated() // self.password = try node.extract("password").string.validated() // try super.init(node: node, in: context) do { self.username = try node.extract("username") self.email = try node.extract("email") self.password = try node.extract("password") self.firstName = try node.extract("firstName") self.lastName = try node.extract("lastName") self.fid = try node.extract("fid") self.provider = ConnectionProvider(rawValue: try node.extract("provider")) ?? .unknown self.country = try node.extract("country") try super.init(node: node, in: context) // self.id = try node.extract("_id") // let ddd = self.id?.string ?? "none" // // print("_id: \(ddd)") // // self.created = try node.extract("created") // self.updated = try node.extract("updated") } catch { print(error) throw Abort.badRequest } } public required init(request: Request, provider: ProviderType, data: Data? = nil) throws { print(#function) self.provider = provider switch provider { case .email: let username: Valid<Username> = try request.data["username"].validated() let email: Valid<Email> = try request.data["email"].validated() let password: Valid<Password> = try request.data["password"].validated() let country: Valid<Country> = try request.data["country"].validated() self.username = username.value self.email = email.value self.password = password.value self.country = country.value self.firstName = "" self.lastName = "" break case .fb: self.password = nil if let p = params { let username: Valid<Username> = try p["name"].validated() let firstName: Valid<Username> = try p["first_name"].validated() let lastName: Valid<Username> = try p["last_name"].validated() let email: Valid<Username> = try p["email"].validated() let id: Valid<Username> = try p["id"].validated() self.firstName } break } try super.init(request: request) } //// init(request: Request) throws { //// print(#function) //// //id = try request["id"] // username = try request.data["username"].validated()// extract("username").string.validated() // email = try request.data["email"].validated() // password = try request.data["password"].validated() //// } override func makeNode(context: Context) throws -> Node { var node = try super.makeNode(context: context) //let drop = Droplet() node.append(node: try Node(node: [ "username": username, "email": email, "password": password//drop.hash(password), ])) return node } override func json() throws -> Node { var node = try super.json() node.append(node: try Node(node: [ "username": username, "email": email, ])) // node["email"] = email.node // node["keyId"] = keyId.node return node } } //extension User { // /** // This will automatically fetch from database, using example here to load // automatically for example. Remove on real models. // */ // public convenience init?(email: String, username: String, password: String) { // self.init(email) // } // //} //extension User: Preparation { // static func prepare(_ database: Database) throws { // // try database.create("users") { users in // users.id() // users.string("name", unique: true) // users.custom("data", type: "JSON") // users.custom("time", type: "TIMESTAMP", default: 1234) // } // // } // // static func revert(_ database: Database) throws { // // // } //} // MARK: - Database requests extension User { static func getByFacebookId(fid: Int64) throws -> User? { let filter = Filter(self, .compare("fid", .equals, try fid.makeNode())) let query = try User.query() query.filters = [filter] return try query.limit(1).run().first } // static func getById(fid: Int64) throws -> User? { // let filter = Filter(self, .compare("fid", .equals, try fid.makeNode())) // let query = try User.query() // query.filters = [filter] // return try query.limit(1).run().first // } } // MARK: - Custom validators class Username: ValidationSuite { static func validate(input value: String) throws { print(#function) let evaluation = OnlyAlphanumeric.self && Count.min(2) && Count.max(20) try evaluation.validate(input: value) } } class Password: ValidationSuite { static func validate(input value: String) throws { print(#function) let evaluation = OnlyAlphanumeric.self && Count.min(4) && Count.max(16) try evaluation.validate(input: value) } } class Country: ValidationSuite { static func validate(input value: String) throws { print(#function) let evaluation = OnlyAlphanumeric.self && Count.min(2) && Count.max(4) try evaluation.validate(input: value) } } //class PasswordValidation: ValidationSuite { // // static func validate(input value: String) throws { // // 1 upper 1 lower 1 special 1 number at least 8 long // let regex = Matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$&*])(?=.*[0-9]).{8}$") // // /* // let evaluation = Matches.validate(regex) // try evaluation.validate(input: value) // */ // // let evaluation = OnlyAlphanumeric.self // && Count.min(8) // && Matches.validate(Matches<regex & value>) // // try evaluation.validate(input: value) // } // //}
mit
43f3d81a0128c419672cf0724828f66e
28.077181
160
0.534334
4.212445
false
false
false
false
lexrus/LTMorphingLabel
LTMorphingLabel/SwiftUI/MorphingText.swift
1
3554
// // MorphingText.swift // LTMorphingLabel // // Created by Lex on 2020/5/10. // Copyright © 2020 lexrus.com. All rights reserved. // #if canImport(SwiftUI) import SwiftUI #endif @available(iOS 13.0.0, *) public struct MorphingText: UIViewRepresentable { public typealias UIViewType = LTMorphingLabel var text: String var morphingEffect: LTMorphingEffect var moprhingEnabled: Bool = true var font: UIFont var textColor: UIColor var textAlignment: NSTextAlignment public init(_ text: String, effect: LTMorphingEffect = .scale, font: UIFont = .systemFont(ofSize: 16), textColor: UIColor = .black, textAlignment: NSTextAlignment = .center ) { self.text = text self.morphingEffect = effect self.font = font self.textColor = textColor self.textAlignment = textAlignment } public func makeUIView(context: Context) -> UIViewType { let label = LTMorphingLabel(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 50))) label.textAlignment = .center label.textColor = UIColor.white return label } public func updateUIView(_ uiView: UIViewType, context: Context) { uiView.text = text uiView.font = font uiView.morphingEnabled = moprhingEnabled uiView.morphingEffect = morphingEffect uiView.textColor = textColor uiView.textAlignment = textAlignment } } @available(iOS 13.0.0, *) struct MorphingText_Previews: PreviewProvider { static var previews: some View { PreviewWrapper() .previewDevice("iPhone SE") .environment(\.colorScheme, .dark) } struct PreviewWrapper: View { @State var morphingEnabled = true @State var textIndex: Double = 0 @State var effectIndex: Double = 0 private var textArray = [ "Supercalifragilisticexpialidocious", "Stay hungry, stay foolish.", "Love what you do and do what you love.", "Apple doesn't do hobbies as a general rule.", "iOS", "iPhone", "iPhone 11", "iPhone 11 Pro", "iPhone 11 Pro Max", "$9995.00", "$9996.00", "$9997.00", "$9998.00", "$9999.00", "$10000.00" ] public var body: some View { VStack { Spacer() Text("LTMorphingLabel").font(.largeTitle) Text("for SwiftUI").font(.title) MorphingText( textArray[Int(round(textIndex))], effect: LTMorphingEffect.allCases[Int(round(effectIndex))], font: UIFont.systemFont(ofSize: 20), textColor: .white ) .frame(maxWidth: 200, maxHeight: 100) Text("Effect: \(LTMorphingEffect.allCases[Int(round(effectIndex))].description)").font(.title) Slider(value: $effectIndex, in: 0...Double(LTMorphingEffect.allCases.count - 1)) Slider(value: $textIndex, in: 0...Double(textArray.count - 1)) Toggle("MorphingEnabled", isOn: $morphingEnabled) Spacer() } .padding(20) .foregroundColor(Color.white) .background(Color.black) } } }
mit
2dda3134f7afb5de82108e8cf5e432dc
30.442478
110
0.550802
4.731025
false
false
false
false
ming1016/smck
smck/Lib/RxSwift/ToArray.swift
47
1403
// // ToArray.swift // RxSwift // // Created by Junior B. on 20/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class ToArraySink<SourceType, O: ObserverType> : Sink<O>, ObserverType where O.E == [SourceType] { typealias Parent = ToArray<SourceType> let _parent: Parent var _list = Array<SourceType>() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let value): self._list.append(value) case .error(let e): forwardOn(.error(e)) self.dispose() case .completed: forwardOn(.next(_list)) forwardOn(.completed) self.dispose() } } } final class ToArray<SourceType> : Producer<[SourceType]> { let _source: Observable<SourceType> init(source: Observable<SourceType>) { _source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] { let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
c34904b4e76e23b1dba5935730fc268c
28.208333
149
0.601997
4.160237
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/Event.swift
1
2626
// // Event.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /// Due to current swift limitations, we have to include this Box in RxResult. /// Swift cannot handle an enum with multiple associated data (A, NSError) where one is of unknown size (A) /// This can be swiftified once the compiler is completed /** * Represents event that happened * `Box` is there because of a bug in swift compiler * >> error: unimplemented IR generation feature non-fixed multi-payload enum layout */ public enum Event<Element> : CustomStringConvertible { // Box is used because swift compiler doesn't know // how to handle `Next(Element)` and it crashes. case Next(Element) // next element of a sequence case Error(ErrorType) // sequence failed with error case Completed // sequence terminated successfully public var description: String { get { switch self { case .Next(let boxedValue): return "Next(\(boxedValue))" case .Error(let error): return "Error(\(error))" case .Completed: return "Completed" } } } } public func eventType<T>(event: Event<T>) -> String { switch event { case .Next: return "Next: \(event)" case .Completed: return "Completed" case .Error(let error): return "Error \(error)" } } public func == <T: Equatable>(lhs: Event<T>, rhs: Event<T>) -> Bool { switch (lhs, rhs) { case (.Completed, .Completed): return true // really stupid fix for now case (.Error(let e1), .Error(let e2)): return "\(e1)" == "\(e2)" case (.Next(let v1), .Next(let v2)): return v1 == v2 default: return false } } extension Event { public var isStopEvent: Bool { get { switch self { case .Next: return false case .Error: fallthrough case .Completed: return true } } } public var value: Element? { get { switch self { case .Next(let value): return value case .Error: fallthrough case .Completed: return nil } } } public var error: ErrorType? { get { switch self { case .Next: return nil case .Error(let error): return error case .Completed: return nil } } } }
mit
c7cef83b00da66d8077fbf6f1f7dd9e4
25.806122
107
0.549124
4.450847
false
false
false
false
mbernson/HomeControl.iOS
HomeControl/Extensions/NSUserDefaults+Subscript.swift
1
2832
// // NSUserDefaults+Subscript.swift // HomeControl // // Created by Mathijs Bernson on 22/04/16. // Copyright © 2016 Duckson. All rights reserved. // // https://gist.github.com/tomlokhorst/3d0d3f0b1bb95391b322 // We can use Phantom Types to provide strongly typed acces to NSUserDefaults // Similar to: http://www.objc.io/blog/2014/12/29/functional-snippet-13-phantom-types/ import Foundation // A key to UserDefaults has a name and phantom type struct Key<T> { let name: String } // Extensions to NSUserDefaults for subscripting using keys. // Apparently generics don't work with subscript. // But this code should be in a library somewhere, so who cares about a little repetition. extension Foundation.UserDefaults { subscript(key: Key<String>) -> String? { get { return string(forKey: key.name) } set { if let value = newValue { setValue(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<Int>) -> Int? { get { return integer(forKey: key.name) } set { if let value = newValue { set(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<Double>) -> Double? { get { return double(forKey: key.name) } set { if let value = newValue { set(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<Bool>) -> Bool? { get { return bool(forKey: key.name) } set { if let value = newValue { set(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<Data>) -> Data? { get { return data(forKey: key.name) } set { if let value = newValue { setValue(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<Date>) -> Date? { get { return object(forKey: key.name) as? Date } set { if let value = newValue { setValue(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<[String : Bool]>) -> [String : Bool]? { get { return object(forKey: key.name) as? [String : Bool] } set { if let value = newValue { setValue(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } subscript(key: Key<[String]>) -> [String]? { get { return stringArray(forKey: key.name) } set { if let value = newValue { setValue(value, forKey: key.name) } else { removeObject(forKey: key.name) } } } }
mit
befc02e0306db258d672336148185b9a
19.97037
90
0.563758
3.657623
false
false
false
false
SwiftKit/CuckooGenerator
Source/CuckooGeneratorFramework/Tokens/Key.swift
1
715
// // Key.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public enum Key: String { case Substructure = "key.substructure" case Kind = "key.kind" case Accessibility = "key.accessibility" case SetterAccessibility = "key.setter_accessibility" case Name = "key.name" case TypeName = "key.typename" case Length = "key.length" case Offset = "key.offset" case NameLength = "key.namelength" case NameOffset = "key.nameoffset" case BodyLength = "key.bodylength" case BodyOffset = "key.bodyoffset" case Attributes = "key.attributes" case Attribute = "key.attribute" }
mit
4035854861007f06cb0a5c56f178d101
24.535714
57
0.656863
3.757895
false
false
false
false
NghiaTranUIT/Titan
TitanCore/TitanCore/StackTableCell.swift
2
1587
// // StackTableCell.swift // Titan // // Created by Nghia Tran on 2/3/17. // Copyright © 2017 fe. All rights reserved. // import Cocoa import SwiftyPostgreSQL protocol StackTableCellDelegate: class { func StackTableCellDidSelectTable(_ table: Table) } class StackTableCell: NSCollectionViewItem { // // MARK: - Variable weak var delegate: StackTableCellDelegate? var table: Table! // // MARK: - OUTLET @IBOutlet weak var tableTitleLbl: NSTextField! // // MARK: - View Cycle override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } override var isSelected: Bool { didSet { self.tableTitleLbl.textColor = isSelected ? NSColor(hexString: "#2D2E30") : NSColor(hexString: "#8F9498") } } // // MARK: - Public func configureCell(with table: Table, isSelected: Bool = false) { self.table = table self.tableTitleLbl.stringValue = table.tableName! self.isSelected = isSelected } @IBAction func actionBtnTapped(_ sender: Any) { guard self.isSelected == false else {return} self.delegate?.StackTableCellDidSelectTable(self.table) } func minimumWidthCell(with table: Table) -> CGFloat { self.tableTitleLbl.stringValue = table.tableName! let labelSize = self.tableTitleLbl.intrinsicContentSize return labelSize.width + 24 } } // // MARK: - XIBInitializable extension StackTableCell: XIBInitializable { typealias T = StackTableCell }
mit
054a87519c6bed71bb7e70e78de345aa
23.4
117
0.639344
4.381215
false
false
false
false
Syject/MyLessPass-iOS
LessPass/Libraries/BigInteger/MG Basic Math.swift
1
4033
/* ———————————————————————————————————————————————————————————————————————————— MG Basic Math.swift ———————————————————————————————————————————————————————————————————————————— Created by Marcel Kröker on 03.04.15. Copyright (c) 2016 Blubyte. All rights reserved. */ #if os(Linux) import Glibc import CBSD #endif import Foundation func binomial(_ n: Int, _ k: Int) -> Int { return k == 0 ? 1 : n == 0 ? 0 : binomial(n - 1, k) + binomial(n - 1, k - 1) } func kronecker(_ i: Int, j: Int) -> Int { return i == j ? 1 : 0 } func numlen(_ n: Int) -> Int { if n == 0 { return 1 } return Int(log10(Double(abs(n)))) + 1 } func isPrime(_ n: Int) -> Bool { if n <= 3 { return n > 1 } if n % 2 == 0 || n % 3 == 0 { return false } var i = 5 while i * i <= n { if n % i == 0 || n % (i + 2) == 0 { return false } i += 6 } return true } /** Returns the n-th prime number. */ func getPrime(_ n: Int) -> Int { precondition(n > 0, "There is no 0-th prime number") var prime = 2 var primeCount = 1 while primeCount != n { prime += 1 if isPrime(prime) { primeCount += 1 } } return prime } /** Works with the Sieve of Eratosthenes. */ public func primesTo(_ n: Int) -> [Int] { if n < 2 { return [] } var A = [Bool](repeating: true, count: n) var i = 2 while i * i <= n { if A[i - 1] { var j = i * i var c = 1 while j <= n { A[j - 1] = false j = i * (i + c) c += 1 } } i += 1 } var res = [2] i = 3 while i <= n { if A[i - 1] { res.append(i) } i += 2 } return res } func nextPrime( _ n: inout Int) { repeat { n += 1 } while !isPrime(n) } // Returns random Int within range func random(_ range: Range<Int>) -> Int { let offset = Int(range.lowerBound) let delta = UInt32(range.upperBound - range.lowerBound) return offset + Int(arc4random_uniform(delta)) } // Neccessary for (...) to work func random(_ range: ClosedRange<Int>) -> Int { return random(Range(range)) } // Returns array filled with n random Ints within range func random(_ range: Range<Int>, _ count: Int) -> [Int] { var res = [Int](repeating: 0, count: count) for i in 0..<count { res[i] = random(range) } return res } enum LetterSet { case lowerCase case upperCase case numbers case specialSymbols case all } /** Creates a random String from one or multiple sets of letters. - Parameter length: Number of characters in random string. - Parameter letterSet: Specify desired letters as variadic parameters: - .All - .Numbers - .LowerCase - .UpperCase - .SpecialSymbols */ func randomString(_ length: Int, letterSet: LetterSet...) -> String { var letters = [String]() var ranges = [CountableClosedRange<Int>]() for ele in letterSet { switch ele { case .all: ranges.append(33...126) case .numbers: ranges.append(48...57) case .lowerCase: ranges.append(97...122) case .upperCase: ranges.append(65...90) case .specialSymbols: ranges += [33...47, 58...64, 91...96, 123...126] } } for range in ranges { for i in range { letters.append(String(describing: UnicodeScalar(i))) } } var res = "" for _ in 0..<length { res += letters[random(0..<letters.count)] } return res } func gcd(_ a: Int, _ b: Int) -> Int { if b == 0 { return a } return gcd(b, a % b) } func lcm(_ a: Int, _ b: Int) -> Int { return (a / gcd(a, b)) * b } func factorize(_ n: Int) -> [Int] { if isPrime(n) || n == 1 { return [n] } var n = n var res = [Int]() var nthPrime = 1 while true { nextPrime(&nthPrime) while n % nthPrime == 0 { n /= nthPrime res.append(nthPrime) if isPrime(n) { res.append(n) return res } } } }
gpl-3.0
5c4e223d24ff3d744884b4dc94416235
14.278689
77
0.549624
2.761481
false
false
false
false
zskyfly/twitter
twitter/NewTweetViewController.swift
1
5070
// // NewTweetViewController.swift // twitter // // Created by Zachary Matthews on 2/23/16. // Copyright © 2016 zskyfly productions. All rights reserved. // import UIKit import Foundation @objc protocol NewTweetViewControllerDelegate { optional func newTweetViewController(newTweetViewController: NewTweetViewController, didPostStatusUpdate tweet: Tweet) } class NewTweetViewController: UIViewController { @IBOutlet weak var charCountLabel: UILabel! @IBOutlet weak var tweetButton: UIButton! @IBOutlet weak var userHandleLabel: UILabel! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var statusUpdateTextField: UITextView! var user: User? var replyTweet: Tweet? var delegate: NewTweetViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() self.statusUpdateTextField.delegate = self self.setViewProperties() self.initButton() self.initTextField() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTapTweet(sender: AnyObject) { self.postStatusUpdate() } func postStatusUpdate() { let statusText = statusUpdateTextField.text let replyStatusId = replyTweet?.idStr TwitterClient.sharedInstance.statusUpdate(statusText, replyStatusId: replyStatusId, success: { (tweet: Tweet) -> () in self.delegate?.newTweetViewController?(self, didPostStatusUpdate: tweet) self.navigationController?.popViewControllerAnimated(true) }) { (error: NSError) -> () in print("\(error.localizedDescription)") } } func setViewProperties() { ImageHelper.stylizeUserImageView(userImageView) if let name = self.user?.name as? String { self.userNameLabel.text = name } if let userHandle = self.user?.screenName as? String { self.userHandleLabel.text = "@" + userHandle } ImageHelper.setImageForView(self.user?.profileUrl, placeholder: User.placeholderProfileImage, imageView: self.userImageView, success: nil) { (error) -> Void in print("\(error.localizedDescription)") } setCharCountLabelOk() } func initButton() { self.tweetButton.setTitleColor(MiscHelper.getUIColor(MiscHelper.twitterLightGrey), forState: UIControlState.Disabled) self.tweetButton.setTitleColor(MiscHelper.getUIColor(MiscHelper.twitterBlue), forState: UIControlState.Normal) self.tweetButton.layer.borderWidth = 1.0 self.tweetButton.layer.cornerRadius = 3.0 self.tweetButton.titleEdgeInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0) setButtonDisabled() } func setButtonDisabled() { self.tweetButton.layer.borderColor = MiscHelper.getCGColor(MiscHelper.twitterLightGrey) self.tweetButton.enabled = false } func setButtonEnabled() { self.tweetButton.layer.borderColor = MiscHelper.getCGColor(MiscHelper.twitterBlue) self.tweetButton.enabled = true } func enableTextField() { if self.statusUpdateTextField.text == Tweet.placeHolderText { self.statusUpdateTextField.text = "" } self.statusUpdateTextField.textColor = MiscHelper.getUIColor(MiscHelper.twitterDarkGrey) } func disableTextField() { self.statusUpdateTextField.textColor = MiscHelper.getUIColor(MiscHelper.twitterDarkGrey) self.statusUpdateTextField.textColor = MiscHelper.getUIColor(MiscHelper.twitterMediumGrey) } func initTextField() { if let inReplyToUser = self.replyTweet?.user { self.statusUpdateTextField.text = "@\(inReplyToUser.screenName!)" enableTextField() } else { self.statusUpdateTextField.text = Tweet.placeHolderText disableTextField() } } func setCharCountLabelOk() { self.charCountLabel.textColor = MiscHelper.getUIColor(MiscHelper.twitterBlue) } func setCharCountLabelNotOk() { self.charCountLabel.textColor = UIColor.redColor() } } extension NewTweetViewController: UITextViewDelegate { func textViewDidChange(textView: UITextView) { let textLength = self.statusUpdateTextField.text.characters.count self.setCharCountLabelOk() self.enableTextField() self.charCountLabel.text = "\(Tweet.maxLength - textLength)" if Tweet.acceptableLength ~= textLength { self.setButtonEnabled() } else if textLength == 0 { setButtonDisabled() } else { self.charCountLabel.text = "\(textLength - Tweet.maxLength)" self.disableTextField() self.setCharCountLabelNotOk() self.setButtonDisabled() } } func textViewDidBeginEditing(textView: UITextView) { self.enableTextField() } }
apache-2.0
d35879eb9fd2cfb81c586c45a43005b5
33.958621
167
0.679819
4.710967
false
false
false
false
DiegoSan1895/Smartisan-Notes
Smartisan-Notes/HomeViewController.swift
1
7792
// // HomeViewController.swift // Smartisan-Notes // // Created by DiegoSan on 3/2/16. // Copyright © 2016 DiegoSan. All rights reserved. // import UIKit import RealmSwift import CXAlertView import YYKit import MagicalRecord let cellIdentifier = "NotesCell" let writeSegueIdentifier = "writeNote" let contentSequeIdentifier = "showContent" let showUEVCIdentifire = "showUEVC" class HomeViewController: UIViewController, UISearchBarDelegate { // MARK: - properties let realm: Realm = (UIApplication.sharedApplication().delegate as! AppDelegate).realm lazy var notes: Results<Notes> = { self.realm.objects(Notes).sorted("created", ascending: false) }() var notificationToken: NotificationToken? var alertView: CXAlertView! @IBOutlet weak var tableView: UITableView! // CXAlertView @IBOutlet weak var alertContentView: UIView! @IBOutlet weak var checkButton: UIButton! var isChecked: Bool = true var selectedCell: NotesTableViewCell? var searchBarView: UIView! var searchTextField: UITextField! @IBAction func ueAdjustmentButtonDidPressed(sender: UIButton) { // 1. alertView.dismiss() // 2. performSegueWithIdentifier(showUEVCIdentifire, sender: self) } @IBAction func checkToAgreeUEPlanButtonDidPressed(sender: UIButton) { if !isChecked{ checkButton.setImage(UIImage(named: "icon_check"), forState: .Normal) NSUserDefaults.standardUserDefaults().setBool(true, forKey: ueAgreeOrNot) isChecked = true }else{ checkButton.setImage(UIImage(named: "icon_uncheck"), forState: .Normal) NSUserDefaults.standardUserDefaults().setBool(false, forKey: ueAgreeOrNot) isChecked = false } } @IBAction func aboutButtonDidPressed(sender: UIButton) { } @IBAction func writeButtonDidPressed(sender: UIButton) { let writeVC = storyboard?.instantiateViewControllerWithIdentifier("writeAndView") as! WriteViewController writeVC.stateHelper = 1 writeVC.note = Notes() navigationController?.pushViewController(writeVC, animated: true) } // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() setUpViews() populateDefaultNotes() self.tableView.panGestureRecognizer.addTarget(self, action: "startToScroll") // 在数据库变化的时候执行block里的代码 notificationToken = notes.addNotificationBlock({ (results, error) -> () in //self.tableView.reloadData() //已经执行了删除row,这里就不需要再次reloadData了 }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // if firstEnterApp, show the alertView // NSUserDefaults.standardUserDefaults().boolForKey 默认是false if !NSUserDefaults.standardUserDefaults().boolForKey(isNotFirstOpenSmartisanNotes){ alertView = CXAlertView(title: "用户体验改进计划", contentView: alertContentView, cancelButtonTitle: nil) alertView.titleFont = UIFont.boldSystemFontOfSize(16) alertView.cancelButtonFont = UIFont.boldSystemFontOfSize(16) alertView.addButtonWithTitle("确定", type: .Cancel, handler: { (alertView, buttonItem) -> Void in NSUserDefaults.standardUserDefaults().setBool(true, forKey: isNotFirstOpenSmartisanNotes) alertView.dismiss() }) alertView.show() } } // set the cell to normal state when scroll func startToScroll(){ let wrapperView = self.tableView.subviews.first for subview in (wrapperView?.subviews)!{ if let notesCell = subview as? NotesTableViewCell{ notesCell.setToNormalState() } } } // MARK: - private methods private func setUpViews() { self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!) self.tableView.registerNib(UINib(nibName: "NotesTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: cellIdentifier) searchBarView = UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: 40)) searchBarView.backgroundColor = UIColor.clearColor() tableView.tableHeaderView = searchBarView // bg let searchBarBackgroundImageView = UIImageView(image: UIImage(named: "bg_searchbar_n")) if isiPhone6(){ searchBarBackgroundImageView.image = UIImage(named: "bg_searchbar_n_iphone6") } searchBarBackgroundImageView.width = searchBarView.width searchBarBackgroundImageView.contentMode = UIViewContentMode.ScaleAspectFit searchBarBackgroundImageView.center = CGPointMake(searchBarView.width / 2, searchBarView.height / 2) searchBarView.addSubview(searchBarBackgroundImageView) // textField searchTextField = UITextField(frame: searchBarBackgroundImageView.frame) searchTextField.width = searchTextField.width * 0.75 searchTextField.center = searchBarBackgroundImageView.center searchTextField.backgroundColor = UIColor.clearColor() searchTextField.textColor = Colors.textColor searchTextField.font = UIFont.systemFontOfSize(12) let attributedPlaceHolder = NSMutableAttributedString(string: "请输入关键字") attributedPlaceHolder.font = UIFont.systemFontOfSize(12) //attributedPlaceHolder.color = Colors.textColor.colorWithAlphaComponent(0.55) searchTextField.attributedPlaceholder = attributedPlaceHolder searchTextField.tintColor = Colors.textColor searchBarView.addSubview(searchTextField) searchTextField.addTarget(self, action: "performSearch", forControlEvents: UIControlEvents.EditingChanged) } private func populateDefaultNotes() { // 1. if notes.count == 0{ // 2. try! realm.write({ () -> Void in // 3. for _ in 0..<40 { let note = Notes() note.created = NSDate.randomWithinDaysBeforeToday(10) note.contents = String.randomNoteContent() note.hasPhoto = Bool.random() note.stared = Bool.random() realm.add(note) } }) } } func getCells() -> [NotesTableViewCell] { var resultCells = [NotesTableViewCell]() let wrapperView = self.tableView.subviews.first for subview in (wrapperView?.subviews)!{ if let notesCell = subview as? NotesTableViewCell{ resultCells.append(notesCell) } } return resultCells } func performSearch() { } // MARK: - set statusBar override func prefersStatusBarHidden() -> Bool { return false } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - TextField Delegate func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { print("text did change") } }
mit
38dc2d954b525d6fbdcfec7d2a4d1107
33.325893
143
0.633502
5.414789
false
false
false
false
negusoft/Polyglot
Polyglot/Source/NSSegmentedControl+Polyglot.swift
1
2088
// // Copyright (c) 2015 NEGU Soft // // 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 AppKit @IBDesignable public extension NSSegmentedControl { /// Comma separated keys to set the corresponding items with the localized string. /// Note that each key is trimed to remove leading and trailing spaces. /// You may as well leave a key empty not to change that specific item. @IBInspectable var labelKeysCSV: String { get { return "" } set { let keys = newValue.components(separatedBy: CharacterSet(charactersIn: ",")) let spaceCharacterSet = CharacterSet(charactersIn: " ") for index in 0..<self.segmentCount { if index >= keys.count { break } let key = keys[index].trimmingCharacters(in: spaceCharacterSet) if (!key.isEmpty) { let label = Polyglot.localizedString(key) self.setLabel(label, forSegment: index) } } } } }
mit
7101282040206727f9fd7f167488aed0
41.612245
88
0.673851
4.901408
false
false
false
false
DeliveLee/Custom-TimePicker-for-PopUp
TimePicker/UtilKits/CommonMethod/AF+Date+Extension.swift
1
33258
// // AFDateExtension.swift // // Version 3.5.3 // // Created by Melvin Rivera on 7/15/14. // Copyright (c) 2014. All rights reserved. // import Foundation // DotNet: "/Date(1268123281843)/" let DefaultFormat = "EEE MMM dd HH:mm:ss Z yyyy" let RSSFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" // "Fri, 09 Sep 2011 15:26:08 +0200" let AltRSSFormat = "d MMM yyyy HH:mm:ss ZZZ" // "09 Sep 2011 15:26:08 +0200" public enum ISO8601Format: String { case Year = "yyyy" // 1997 case YearMonth = "yyyy-MM" // 1997-07 case Date = "yyyy-MM-dd" // 1997-07-16 case DateTime = "yyyy-MM-dd'T'HH:mmZ" // 1997-07-16T19:20+01:00 case DateTimeSec = "yyyy-MM-dd'T'HH:mm:ssZ" // 1997-07-16T19:20:30+01:00 case DateTimeMilliSec = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 1997-07-16T19:20:30.45+01:00 init(dateString:String) { switch dateString.characters.count { case 4: self = ISO8601Format(rawValue: ISO8601Format.Year.rawValue)! case 7: self = ISO8601Format(rawValue: ISO8601Format.YearMonth.rawValue)! case 10: self = ISO8601Format(rawValue: ISO8601Format.Date.rawValue)! case 22: self = ISO8601Format(rawValue: ISO8601Format.DateTime.rawValue)! case 25: self = ISO8601Format(rawValue: ISO8601Format.DateTimeSec.rawValue)! default:// 28: self = ISO8601Format(rawValue: ISO8601Format.DateTimeMilliSec.rawValue)! } } } public enum DateFormat { case iso8601(ISO8601Format?), dotNet, rss, altRSS, custom(String) } public enum TimeZone { case local, utc } public extension Date { // MARK: Intervals In Seconds private static func minuteInSeconds() -> Double { return 60 } private static func hourInSeconds() -> Double { return 3600 } private static func dayInSeconds() -> Double { return 86400 } private static func weekInSeconds() -> Double { return 604800 } private static func yearInSeconds() -> Double { return 31556926 } // MARK: Components private static func componentFlags() -> Set<Calendar.Component> { return [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second, Calendar.Component.weekday, Calendar.Component.weekdayOrdinal, Calendar.Component.weekOfYear] } private static func components(_ fromDate: Date) -> DateComponents! { return Calendar.current.dateComponents(Date.componentFlags(), from: fromDate) } private func components() -> DateComponents { return Date.components(self)! } // MARK: Date From String /** Creates a date based on a string and a formatter type. You can ise .ISO8601(nil) to for deducting an ISO8601Format automatically. - Parameter fromString Date string i.e. "16 July 1972 6:12:00". - Parameter format The Date Formatter type can be .ISO8601(ISO8601Format?), .DotNet, .RSS, .AltRSS or Custom(String). - Parameter timeZone: The time zone to interpret fromString can be .Local, .UTC applies to Custom format only - Returns A new date */ init(fromString string: String, format:DateFormat, timeZone: TimeZone = .local) { if string.isEmpty { self.init() return } let string = string as NSString let zone: Foundation.TimeZone switch timeZone { case .local: zone = Foundation.NSTimeZone.local case .utc: zone = Foundation.TimeZone(secondsFromGMT: 0)! } switch format { case .dotNet: let startIndex = string.range(of: "(").location + 1 let endIndex = string.range(of: ")").location let range = NSRange(location: startIndex, length: endIndex-startIndex) let milliseconds = (string.substring(with: range) as NSString).longLongValue let interval = TimeInterval(milliseconds / 1000) self.init(timeIntervalSince1970: interval) case .iso8601(let isoFormat): let dateFormat = (isoFormat != nil) ? isoFormat! : ISO8601Format(dateString: string as String) let formatter = Date.formatter(dateFormat.rawValue) formatter.locale = Foundation.Locale(identifier: "en_US_POSIX") formatter.timeZone = Foundation.NSTimeZone.local formatter.dateFormat = dateFormat.rawValue if let date = formatter.date(from: string as String) { self.init(timeInterval:0, since:date) } else { self.init() } case .rss: var s = string if string.hasSuffix("Z") { s = s.substring(to: s.length-1).appending("GMT") as NSString } let formatter = Date.formatter(RSSFormat) if let date = formatter.date(from: string as String) { self.init(timeInterval:0, since:date) } else { self.init() } case .altRSS: var s = string if string.hasSuffix("Z") { s = s.substring(to: s.length-1).appending("GMT") as NSString } let formatter = Date.formatter(AltRSSFormat) if let date = formatter.date(from: string as String) { self.init(timeInterval:0, since:date) } else { self.init() } case .custom(let dateFormat): let formatter = Date.formatter(dateFormat, timeZone: zone) formatter.locale = Foundation.Locale(identifier: "en_US") if let date = formatter.date(from: string as String) { self.init(timeInterval:0, since:date) } else { self.init() } } } // MARK: Comparing Dates /** Returns true if dates are equal while ignoring time. - Parameter date: The Date to compare. */ func isEqualToDateIgnoringTime(_ date: Date) -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(date) return ((comp1!.year == comp2!.year) && (comp1!.month == comp2!.month) && (comp1!.day == comp2!.day)) } /** Returns Returns true if date is today. */ func isToday() -> Bool { return self.isEqualToDateIgnoringTime(Date()) } /** Returns true if date is tomorrow. */ func isTomorrow() -> Bool { return self.isEqualToDateIgnoringTime(Date().dateByAddingDays(1)) } /** Returns true if date is yesterday. */ func isYesterday() -> Bool { return self.isEqualToDateIgnoringTime(Date().dateBySubtractingDays(1)) } /** Returns true if date are in the same week. - Parameter date: The date to compare. */ func isSameWeekAsDate(_ date: Date) -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(date) // Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week if comp1?.weekOfYear != comp2?.weekOfYear { return false } // Must have a time interval under 1 week return abs(self.timeIntervalSince(date)) < Date.weekInSeconds() } /** Returns true if date is this week. */ func isThisWeek() -> Bool { return self.isSameWeekAsDate(Date()) } /** Returns true if date is next week. */ func isNextWeek() -> Bool { let interval: TimeInterval = Date().timeIntervalSinceReferenceDate + Date.weekInSeconds() let date = Date(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Returns true if date is last week. */ func isLastWeek() -> Bool { let interval: TimeInterval = Date().timeIntervalSinceReferenceDate - Date.weekInSeconds() let date = Date(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Returns true if dates are in the same year. - Parameter date: The date to compare. */ func isSameYearAsDate(_ date: Date) -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(date) return comp1!.year == comp2!.year } /** Returns true if dates are in the same month - Parameter date: The date to compare */ func isSameMonthAsDate(_ date: Date) -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(date) return comp1!.year == comp2!.year && comp1!.month == comp2!.month } /** Returns true if date is this year. */ func isThisYear() -> Bool { return self.isSameYearAsDate(Date()) } /** Returns true if date is next year. */ func isNextYear() -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(Date()) return (comp1!.year! == comp2!.year! + 1) } /** Returns true if date is last year. */ func isLastYear() -> Bool { let comp1 = Date.components(self) let comp2 = Date.components(Date()) return (comp1!.year! == comp2!.year! - 1) } /** Returns true if date is earlier than date. - Parameter date: The date to compare. */ func isEarlierThanDate(_ date: Date) -> Bool { return (self as NSDate).earlierDate(date) == self } /** Returns true if date is later than date. - Parameter date: The date to compare. */ func isLaterThanDate(_ date: Date) -> Bool { return (self as NSDate).laterDate(date) == self } /** Returns true if date is in future. */ func isInFuture() -> Bool { return self.isLaterThanDate(Date()) } /** Returns true if date is in past. */ func isInPast() -> Bool { return self.isEarlierThanDate(Date()) } // MARK: Adjusting Dates /** Creates a new date by a adding months. - Parameter days: The number of months to add. - Returns A new date object. */ func dateByAddingMonths(_ months: Int) -> Date { var dateComp = DateComponents() dateComp.month = months return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a substracting months. - Parameter days: The number of months to substract. - Returns A new date object. */ func dateBySubtractingMonths(_ months: Int) -> Date { var dateComp = DateComponents() dateComp.month = (months * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a adding weeks. - Parameter days: The number of weeks to add. - Returns A new date object. */ func dateByAddingWeeks(_ weeks: Int) -> Date { var dateComp = DateComponents() dateComp.day = 7 * weeks return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a substracting weeks. - Parameter days: The number of weeks to substract. - Returns A new date object. */ func dateBySubtractingWeeks(_ weeks: Int) -> Date { var dateComp = DateComponents() dateComp.day = ((7 * weeks) * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a adding days. - Parameter days: The number of days to add. - Returns A new date object. */ func dateByAddingDays(_ days: Int) -> Date { var dateComp = DateComponents() dateComp.day = days return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a substracting days. - Parameter days: The number of days to substract. - Returns A new date object. */ func dateBySubtractingDays(_ days: Int) -> Date { var dateComp = DateComponents() dateComp.day = (days * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by a adding hours. - Parameter days: The number of hours to add. - Returns A new date object. */ func dateByAddingHours(_ hours: Int) -> Date { var dateComp = DateComponents() dateComp.hour = hours return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by substracting hours. - Parameter days: The number of hours to substract. - Returns A new date object. */ func dateBySubtractingHours(_ hours: Int) -> Date { var dateComp = DateComponents() dateComp.hour = (hours * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by adding minutes. - Parameter days: The number of minutes to add. - Returns A new date object. */ func dateByAddingMinutes(_ minutes: Int) -> Date { var dateComp = DateComponents() dateComp.minute = minutes return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by substracting minutes. - Parameter days: The number of minutes to add. - Returns A new date object. */ func dateBySubtractingMinutes(_ minutes: Int) -> Date { var dateComp = DateComponents() dateComp.minute = (minutes * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by adding seconds. - Parameter seconds: The number of seconds to add. - Returns A new date object. */ func dateByAddingSeconds(_ seconds: Int) -> Date { var dateComp = DateComponents() dateComp.second = seconds return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date by substracting seconds. - Parameter days: The number of seconds to substract. - Returns A new date object. */ func dateBySubtractingSeconds(_ seconds: Int) -> Date { var dateComp = DateComponents() dateComp.second = (seconds * -1) return Calendar.current.date(byAdding: dateComp, to: self)! } /** Creates a new date from the start of the day. - Returns A new date object. */ func dateAtStartOfDay() -> Date { var components = self.components() components.hour = 0 components.minute = 0 components.second = 0 return Calendar.current.date(from: components)! } /** Creates a new date from the end of the day. - Returns A new date object. */ func dateAtEndOfDay() -> Date { var components = self.components() components.hour = 23 components.minute = 59 components.second = 59 return Calendar.current.date(from: components)! } /** Creates a new date from the start of the week. - Returns A new date object. */ func dateAtStartOfWeek() -> Date { let flags: Set<Calendar.Component> = [Calendar.Component.year, Calendar.Component.month, Calendar.Component.weekOfYear, Calendar.Component.weekday] var components = Calendar.current.dateComponents(flags, from: self) components.weekday = Calendar.current.firstWeekday components.hour = 0 components.minute = 0 components.second = 0 return Calendar.current.date(from: components)! } /** Creates a new date from the end of the week. - Returns A new date object. */ func dateAtEndOfWeek() -> Date { let flags: Set<Calendar.Component> = [Calendar.Component.year, Calendar.Component.month, Calendar.Component.weekOfYear, Calendar.Component.weekday] var components = Calendar.current.dateComponents(flags, from: self) components.weekday = Calendar.current.firstWeekday + 6 components.hour = 0 components.minute = 0 components.second = 0 return Calendar.current.date(from: components)! } /** Creates a new date from the first day of the month - Returns A new date object. */ func dateAtTheStartOfMonth() -> Date { //Create the date components var components = self.components() components.day = 1 //Builds the first day of the month let firstDayOfMonthDate :Date = Calendar.current.date(from: components)! return firstDayOfMonthDate } /** Creates a new date from the last day of the month - Returns A new date object. */ func dateAtTheEndOfMonth() -> Date { //Create the date components var components = self.components() //Set the last day of this month components.month = (components.month ?? 0) + 1 components.day = 0 //Builds the first day of the month let lastDayOfMonth :Date = Calendar.current.date(from: components)! return lastDayOfMonth } /** Creates a new date based on tomorrow. - Returns A new date object. */ static func tomorrow() -> Date { return Date().dateByAddingDays(1).dateAtStartOfDay() } /** Creates a new date based on yesterdat. - Returns A new date object. */ static func yesterday() -> Date { return Date().dateBySubtractingDays(1).dateAtStartOfDay() } /** Return a new NSDate object with the new hour, minute and seconds values :returns: NSDate */ func setTimeOfDate(_ hour: Int, minute: Int, second: Int) -> Date { var components = self.components() components.hour = hour components.minute = minute components.second = second return Calendar.current.date(from: components)! } // MARK: Retrieving Intervals /** Gets the number of seconds after a date. - Parameter date: the date to compare. - Returns The number of seconds */ func secondsAfterDate(_ date: Date) -> Int { return Int(self.timeIntervalSince(date)) } /** Gets the number of seconds before a date. - Parameter date: The date to compare. - Returns The number of seconds */ func secondsBeforeDate(_ date: Date) -> Int { return Int(date.timeIntervalSince(self)) } /** Gets the number of minutes after a date. - Parameter date: the date to compare. - Returns The number of minutes */ func minutesAfterDate(_ date: Date) -> Int { let interval = self.timeIntervalSince(date) return Int(interval / Date.minuteInSeconds()) } /** Gets the number of minutes before a date. - Parameter date: The date to compare. - Returns The number of minutes */ func minutesBeforeDate(_ date: Date) -> Int { let interval = date.timeIntervalSince(self) return Int(interval / Date.minuteInSeconds()) } /** Gets the number of hours after a date. - Parameter date: The date to compare. - Returns The number of hours */ func hoursAfterDate(_ date: Date) -> Int { let interval = self.timeIntervalSince(date) return Int(interval / Date.hourInSeconds()) } /** Gets the number of hours before a date. - Parameter date: The date to compare. - Returns The number of hours */ func hoursBeforeDate(_ date: Date) -> Int { let interval = date.timeIntervalSince(self) return Int(interval / Date.hourInSeconds()) } /** Gets the number of days after a date. - Parameter date: The date to compare. - Returns The number of days */ func daysAfterDate(_ date: Date) -> Int { let interval = self.timeIntervalSince(date) return Int(interval / Date.dayInSeconds()) } /** Gets the number of days before a date. - Parameter date: The date to compare. - Returns The number of days */ func daysBeforeDate(_ date: Date) -> Int { let interval = date.timeIntervalSince(self) return Int(interval / Date.dayInSeconds()) } // MARK: Decomposing Dates /** Returns the nearest hour. */ func nearestHour () -> Int { let halfHour = Date.minuteInSeconds() * 30 var interval = self.timeIntervalSinceReferenceDate if self.seconds() < 30 { interval -= halfHour } else { interval += halfHour } let date = Date(timeIntervalSinceReferenceDate: interval) return date.hour() } /** Returns the year component. */ func year () -> Int { return self.components().year! } /** Returns the month component. */ func month () -> Int { return self.components().month! } /** Returns the week of year component. */ func week () -> Int { return self.components().weekOfYear! } /** Returns the day component. */ func day () -> Int { return self.components().day! } /** Returns the hour component. */ func hour () -> Int { return self.components().hour! } /** Returns the minute component. */ func minute () -> Int { return self.components().minute! } /** Returns the seconds component. */ func seconds () -> Int { return self.components().second! } /** Returns the weekday component. */ func weekday () -> Int { return self.components().weekday! } /** Returns the nth days component. e.g. 2nd Tuesday of the month is 2. */ func nthWeekday () -> Int { return self.components().weekdayOrdinal! } /** Returns the days of the month. */ func monthDays () -> Int { let range = Calendar.current.range(of: Calendar.Component.day, in: Calendar.Component.month, for: self)! return range.upperBound - range.lowerBound } /** Returns the first day of the week. */ func firstDayOfWeek () -> Int { let distanceToStartOfWeek = Date.dayInSeconds() * Double(self.components().weekday! - 1) let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek return Date(timeIntervalSinceReferenceDate: interval).day() } /** Returns the last day of the week. */ func lastDayOfWeek () -> Int { let distanceToStartOfWeek = Date.dayInSeconds() * Double(self.components().weekday! - 1) let distanceToEndOfWeek = Date.dayInSeconds() * Double(7) let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek return Date(timeIntervalSinceReferenceDate: interval).day() } /** Returns true if a weekday. */ func isWeekday() -> Bool { return !self.isWeekend() } /** Returns true if weekend. */ func isWeekend() -> Bool { let range = Calendar.current.maximumRange(of: Calendar.Component.weekday)! return (self.weekday() == range.lowerBound || self.weekday() == range.upperBound - range.lowerBound) } // MARK: To String /** A string representation using short date and time style. */ func toString() -> String { return self.toString(.short, timeStyle: .short, doesRelativeDateFormatting: false) } /** A string representation based on a format. - Parameter format: The format of date can be .ISO8601(.ISO8601Format?), .DotNet, .RSS, .AltRSS or Custom(FormatString). - Parameter timeZone: The time zone to interpret the date can be .Local, .UTC applies to Custom format only - Returns The date string representation */ func toString(_ format: DateFormat, timeZone: TimeZone = .local) -> String { var dateFormat: String let zone: Foundation.TimeZone switch format { case .dotNet: let offset = Foundation.NSTimeZone.default.secondsFromGMT() / 3600 let nowMillis = 1000 * self.timeIntervalSince1970 return "/Date(\(nowMillis)\(offset))/" case .iso8601(let isoFormat): dateFormat = (isoFormat != nil) ? isoFormat!.rawValue : ISO8601Format.DateTimeMilliSec.rawValue zone = NSTimeZone.local case .rss: dateFormat = RSSFormat zone = NSTimeZone.local case .altRSS: dateFormat = AltRSSFormat zone = NSTimeZone.local case .custom(let string): switch timeZone { case .local: zone = NSTimeZone.local case .utc: zone = Foundation.TimeZone(secondsFromGMT: 0)! } dateFormat = string } let formatter = Date.formatter(dateFormat, timeZone: zone) return formatter.string(from: self) } /** A string representation based on custom style. - Parameter dateStyle: The date style to use. - Parameter timeStyle: The time style to use. - Parameter doesRelativeDateFormatting: Enables relative date formatting. - Parameter timeZone: The time zone to use. - Parameter locale: The locale to use. - Returns A string representation of the date. */ func toString(_ dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, doesRelativeDateFormatting: Bool = false, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> String { let formatter = Date.formatter(dateStyle, timeStyle: timeStyle, doesRelativeDateFormatting: doesRelativeDateFormatting, timeZone: timeZone, locale: locale) return formatter.string(from: self) } /** A string representation based on a relative time language. i.e. just now, 1 minute ago etc.. */ func relativeTimeToString() -> String { let time = self.timeIntervalSince1970 let now = Date().timeIntervalSince1970 let timeIsInPast = now - time > 0 let seconds = abs(now - time) let minutes = round(seconds/60) let hours = round(minutes/60) let days = round(hours/24) func describe(_ time: String) -> String { if timeIsInPast { return "\(time) ago" } else { return "in \(time)" } } if seconds < 10 { return NSLocalizedString("just now", comment: "Show the relative time from a date") } else if seconds < 60 { let relativeTime = NSLocalizedString(describe("%.f seconds"), comment: "Show the relative time from a date") return String(format: relativeTime, seconds) } if minutes < 60 { if minutes == 1 { return NSLocalizedString(describe("1 minute"), comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString(describe("%.f minutes"), comment: "Show the relative time from a date") return String(format: relativeTime, minutes) } } if hours < 24 { if hours == 1 { return NSLocalizedString(describe("1 hour"), comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString(describe("%.f hours"), comment: "Show the relative time from a date") return String(format: relativeTime, hours) } } if days < 7 { if days == 1 { return NSLocalizedString(describe("1 day"), comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString(describe("%.f days"), comment: "Show the relative time from a date") return String(format: relativeTime, days) } } return self.toString() } /** A string representation of the weekday. */ func weekdayToString() -> String { let formatter = Date.formatter() return formatter.weekdaySymbols[self.weekday()-1] as String } /** A short string representation of the weekday. */ func shortWeekdayToString() -> String { let formatter = Date.formatter() return formatter.shortWeekdaySymbols[self.weekday()-1] as String } /** A very short string representation of the weekday. - Returns String */ func veryShortWeekdayToString() -> String { let formatter = Date.formatter() return formatter.veryShortWeekdaySymbols[self.weekday()-1] as String } /** A string representation of the month. - Returns String */ func monthToString() -> String { let formatter = Date.formatter() return formatter.monthSymbols[self.month()-1] as String } /** A short string representation of the month. - Returns String */ func shortMonthToString() -> String { let formatter = Date.formatter() return formatter.shortMonthSymbols[self.month()-1] as String } /** A very short string representation of the month. - Returns String */ func veryShortMonthToString() -> String { let formatter = Date.formatter() return formatter.veryShortMonthSymbols[self.month()-1] as String } // MARK: Static Cached Formatters /** Returns a cached static array of NSDateFormatters so that thy are only created once. */ private static func sharedDateFormatters() -> [String: DateFormatter] { struct Static { static var formatters: [String: DateFormatter]? = [String: DateFormatter]() } return Static.formatters! } /** Returns a cached formatter based on the format, timeZone and locale. Formatters are cached in a singleton array using hashkeys generated by format, timeZone and locale. - Parameter format: The format to use. - Parameter timeZone: The time zone to use, defaults to the local time zone. - Parameter locale: The locale to use, defaults to the current locale - Returns The date formatter. */ private static func formatter(_ format:String = DefaultFormat, timeZone: Foundation.TimeZone = Foundation.TimeZone.current, locale: Locale = Locale.current) -> DateFormatter { let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)" var formatters = Date.sharedDateFormatters() if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = DateFormatter() formatter.dateFormat = format formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } /** Returns a cached formatter based on date style, time style and relative date. Formatters are cached in a singleton array using hashkeys generated by date style, time style, relative date, timeZone and locale. - Parameter dateStyle: The date style to use. - Parameter timeStyle: The time style to use. - Parameter doesRelativeDateFormatting: Enables relative date formatting. - Parameter timeZone: The time zone to use. - Parameter locale: The locale to use. - Returns The date formatter. */ private static func formatter(_ dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, doesRelativeDateFormatting: Bool, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> DateFormatter { var formatters = Date.sharedDateFormatters() let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)" if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = DateFormatter() formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle formatter.doesRelativeDateFormatting = doesRelativeDateFormatting formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } }
mit
66815c5b83961a972dc318e3e528c05a
30.434783
358
0.598533
4.669756
false
false
false
false
DenHeadless/DTTableViewManager
Sources/Tests/CreationTestCase.swift
1
2748
// // CreationTestCase.swift // DTTableViewManager // // Created by Denys Telezhkin on 13.07.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // import UIKit import XCTest @testable import DTTableViewManager class FooCell : UITableViewCell, ModelTransfer { func update(with model: Int) { } } class OptionalTableViewController : UIViewController, DTTableViewManageable { var optionalTableView: UITableView? } class CreationTestCase: XCTestCase { func testManagingWithOptionalTableViewWorks() { let controller = OptionalTableViewController() controller.optionalTableView = UITableView() XCTAssert(controller.manager.isManagingTableView) } func testCreatingTableControllerFromCode() { let controller = DTTestTableViewController() controller.manager.register(FooCell.self) } func testDelegateIsNotNil() { let controller = DTTestTableViewController() XCTAssertNotNil((controller.manager.storage as? BaseUpdateDeliveringStorage)?.delegate) } func testDelegateIsNotNilForMemoryStorage() { let controller = DTTestTableViewController() XCTAssertNotNil(controller.manager.memoryStorage.delegate) } func testSwitchingStorages() { let controller = DTTestTableViewController() let first = MemoryStorage() let second = MemoryStorage() controller.manager.storage = first XCTAssert(first.delegate === controller.manager.tableViewUpdater) controller.manager.storage = second XCTAssertNil(first.delegate) XCTAssert(second.delegate === controller.manager.tableViewUpdater) } func testCreatingTableControllerFromXIB() { let controller = XibTableViewController(nibName: "XibTableViewController", bundle: Bundle(for: type(of: self))) let _ = controller.view controller.manager.register(FooCell.self) } func testConfigurationAssociation() { let foo = DTTestTableViewController(nibName: nil, bundle: nil) XCTAssertNotNil(foo.manager) XCTAssert(foo.manager === foo.manager) // Test if lazily instantiating using associations works correctly } func testManagerSetter() { let manager = DTTableViewManager() let foo = DTTestTableViewController(nibName: nil, bundle: nil) foo.manager = manager XCTAssert(foo.manager === manager) } func testCallingStartManagingMethodIsNotRequired() { let controller = DTTestTableViewController() controller.manager.register(NibCell.self) controller.manager.memoryStorage.addItem(3) } }
mit
e3bc8b9681e256b6b8d52178a839b12b
29.197802
119
0.68559
5.194707
false
true
false
false
bengottlieb/ios
FiveCalls/FiveCalls/Appearance.swift
1
1356
// // Appearance.swift // FiveCalls // // Created by Ben Scheirman on 2/22/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit class Appearance { static var instance = Appearance() var fontFamily: String { return "Roboto Condensed" } var fontDescriptor: UIFontDescriptor? { return UIFontDescriptor(fontAttributes: [ UIFontDescriptorFamilyAttribute: fontFamily ]).withSymbolicTraits([.traitBold, .traitCondensed]) // To match the website, fonts should be Bold and Condensed } func setup() { let pageControlAppearance = UIPageControl.appearance() pageControlAppearance.pageIndicatorTintColor = .fvc_lightBlue pageControlAppearance.currentPageIndicatorTintColor = .fvc_darkBlue UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName: headerFont ] } private func appFont(size: CGFloat, bold: Bool) -> UIFont! { if bold { return R.font.robotoCondensedBold(size: size) } else { return R.font.robotoCondensedRegular(size: size) } } var headerFont: UIFont { return appFont(size: 18, bold: true) } var bodyFont: UIFont { return appFont(size: 16, bold: false) } }
mit
70030b1b6e35be92488da0e1747a81ac
26.1
128
0.624354
4.927273
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Vendor/NetWorkOperation/NetWork.swift
1
5827
// // NetWork.swift // // Created by midoks on 15/6/9. // Copyright (c) 2015年 midoks. All rights reserved. // import Foundation class NetWork { //解析NSdata数据为NSString static func parseData(data:NSData) -> NSString { return NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)! } //GET获取数据带参数 static func get(url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){ self.request(method: "GET", url: url, params: params, callback: callback) } //GET获取数据带参数 static func getStr(url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSString?, _ response: URLResponse?, _ error:NSError?)->Void){ self.requestStr(method: "GET", url: url, params: params, callback: callback) } //POST数据 static func post(url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){ self.request(method: "POST", url: url, params: params, callback: callback) } //POST数据 static func postStr(url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSString?, _ response: URLResponse?, _ error:NSError?)->Void){ self.requestStr(method: "POST", url: url, params: params, callback: callback) } static func upload(url: String, files: Array<File>, callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){ let params = Dictionary<String, AnyObject>() Upload(url: url, method: "POST", params: params, files: files, callback: callback).run() } //文件上传 static func upload(url: String, params: Dictionary<String, AnyObject>, files: Array<File>, callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){ Upload(url: url, method: "POST", params: params, files: files, callback: callback).run() } //请求返回字符串 static func requestStr(method:String, url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSString?, _ response: URLResponse?, _ error:NSError?)->Void){ self.request(method: method, url: url, params: params) { (data, response, error) -> Void in let pData = self.parseData(data: data!) callback(pData, response, error) } } //更全面的请求 static func request(method:String, url:String, params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){ let session = URLSession.shared var newURL = url //GET传值 if method == "GET" { if newURL.range(of: "?") == nil { if params.count > 0 { newURL += self.buildParams(parameters: params) } } else { newURL += "&" + self.buildParams(parameters: params) } } let request = NSMutableURLRequest(url: NSURL(string: newURL)! as URL) request.httpMethod = method //POST传值 if method == "POST" { request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpBody = NetWork.buildParams(parameters: params).data(using: String.Encoding.utf8, allowLossyConversion: true) } request.addValue("DNSPOD DDNS Mac OSX Client/1.0.1([email protected])", forHTTPHeaderField: "User-Agent") let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in callback(data as NSData?, response, error as NSError?); }) task.resume() } //组装请求串 static func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key1 in Array(parameters.keys) { let value2: AnyObject! = parameters[key1] components += queryComponents(key1, value2) } let args = components.map(argsUrls) var buildUrl = "" var i = 0 for arg in args { if(i==(args.count - 1)){ buildUrl += "\(arg)" }else{ buildUrl += "\(arg)&" } i += 1 } return "?" + buildUrl } //组合请求参数 static func argsUrls(key:String, value:String) -> String { return "\(key)=\(value)" } //过滤特殊字符 static func queryComponents(_ key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.append(contentsOf: [(escape(string: key), escape(string: "\(value)"))]) } return components } //安全过滤 static func escape(string: String) -> String { return NSString().addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn: string) as CharacterSet)! } }
apache-2.0
2d56d96791bb0a35c1dd2a683bb3906d
39.390071
218
0.593152
4.377402
false
false
false
false
zisko/swift
test/SILGen/generic_property_base_lifetime.swift
1
6981
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s protocol ProtocolA: class { var intProp: Int { get set } } protocol ProtocolB { var intProp: Int { get } } @objc protocol ProtocolO: class { var intProp: Int { get set } } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[BORROWED_PROJECTION_COPY:%.*]] = begin_borrow [[PROJECTION_COPY]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!getter.1 : {{.*}}, [[PROJECTION]] // CHECK: [[RESULT:%.*]] = apply [[WITNESS_METHOD]]<@opened{{.*}}>([[BORROWED_PROJECTION_COPY]]) // CHECK: end_borrow [[BORROWED_PROJECTION_COPY]] from [[PROJECTION_COPY]] // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '$S30generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolA_pF' func getIntPropExistential(_ a: ProtocolA) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[BORROWED_PROJECTION_COPY:%.*]] = begin_borrow [[PROJECTION_COPY]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!setter.1 : {{.*}}, [[PROJECTION]] // CHECK: apply [[WITNESS_METHOD]]<@opened{{.*}}>({{%.*}}, [[BORROWED_PROJECTION_COPY]]) // CHECK: end_borrow [[BORROWED_PROJECTION_COPY]] from [[PROJECTION_COPY]] // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '$S30generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolA_pF' func setIntPropExistential(_ a: ProtocolA) { a.intProp = 0 } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolA>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolA>(_ a: T) { a.intProp = 0 } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolB_pF // CHECK: [[PROJECTION:%.*]] = open_existential_addr immutable_access %0 // CHECK: [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB // CHECK: copy_addr [[PROJECTION]] to [initialization] [[STACK]] // CHECK: apply {{%.*}}([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropExistential(_ a: ProtocolB) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: apply {{%.*}}<T>([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropGeneric<T: ProtocolB>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = objc_method [[PROJECTION_COPY]] : $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!getter.1.foreign : {{.*}} // CHECK: apply [[METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '$S30generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolO_pF' func getIntPropExistential(_ a: ProtocolO) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = objc_method [[PROJECTION_COPY]] : $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!setter.1.foreign : {{.*}} // CHECK: apply [[METHOD]]<@opened{{.*}}>({{.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '$S30generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolO_pF' func setIntPropExistential(_ a: ProtocolO) { a.intProp = 0 } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolO>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @$S30generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolO>(_ a: T) { a.intProp = 0 }
apache-2.0
0ef146b526e213e37b0599f0de7b19c4
48.161972
152
0.632861
3.31639
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/smallest-subtree-with-all-the-deepest-nodes.swift
2
2299
/** * https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ * * */ // Date: Sat Dec 12 23:42:50 PST 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ extension TreeNode: Hashable { public static func == (lhs: TreeNode, rhs: TreeNode) -> Bool { return lhs.val == rhs.val } public func hash(into hasher: inout Hasher) { hasher.combine(val) } } class Solution { func subtreeWithAllDeepest(_ root: TreeNode?) -> TreeNode? { guard let root = root else { return nil } var queue = [root] var path = [root : [root]] var level = 0 while queue.isEmpty == false { level += 1 var size = queue.count while size > 0 { size -= 1 let node = queue.removeFirst() let parent = path[node, default: [node]] if let left = node.left { queue.append(left) path[left] = parent + [left] } if let right = node.right { queue.append(right) path[right] = parent + [right] } } } let filteredPaths = (path.filter{ $0.value.count == level }).values // print("\(filteredPaths)") var index = 0 repeat { var node: TreeNode? = nil if (filteredPaths.first?.count) ?? 0 <= index { break } for p in filteredPaths { if node == nil { node = p[index] } else { if p[index].val != node!.val { return p[index - 1] } } } index += 1 } while true return filteredPaths.first?[index - 1] } }
mit
639921d2c108c7d61b3d9081c747a7c8
30.081081
85
0.472379
4.142342
false
false
false
false
alblue/swift
test/SILGen/init_ref_delegation.swift
2
7912
// RUN: %target-swift-emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @$s19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : @trivial $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S } // CHECK-NEXT: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin S.Type) -> S // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[PB]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*S // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] : ${ var S } // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // We don't want the enum to be uninhabited case Foo // CHECK-LABEL: sil hidden @$s19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : @trivial $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box ${ var E } // CHECK: [[MARKED_E_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[E_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_E_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin E.Type) -> E // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[PB]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*E self.init(x: X()) // CHECK: destroy_value [[MARKED_E_BOX]] : ${ var E } // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @$s19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : @trivial $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: assign [[SELF_BOX1]] to [[PB]] : $*S2 // CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[PB]] : $*S2 self.init(t: X()) // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var S2 } // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @$s19init_ref_delegation2C1C{{[_0-9a-zA-Z]*}}fC convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : @trivial $X, [[SELF_META:%[0-9]+]] : @trivial $@thick C1.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C1 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_META]] : $@thick C1.Type, #C1.init!allocator.1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_META]]) // CHECK: assign [[SELFP]] to [[PB]] // CHECK: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*C1 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C1 } // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : @trivial $X, [[SELF_META:%[0-9]+]] : @trivial $@thick C2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_META]] : $@thick C2.Type, #C2.init!allocator.1 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_META]]) // CHECK: assign [[REPLACE_SELF]] to [[PB_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[PB_SELF]] : $*C2 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C2 } // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @$s19init_ref_delegation2C3C{{[_0-9a-zA-Z]*}}fC convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $@thick C3.Type, #C3.init!allocator.1 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @$s19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fC // CHECK: [[PEER:%[0-9]+]] = function_ref @$s19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fC // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[META:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
apache-2.0
695790b9447860703c5bd5ae8ecdc8cf
40.403141
168
0.543121
2.742976
false
false
false
false
GuyKahlon/CloneYO
YO/YO/ViewController.swift
1
10080
// // ViewController.swift // YO // // Created by Guy Kahlon on 1/14/15. // Copyright (c) 2015 GuyKahlon. All rights reserved. // import UIKit let kRecover : Int = 1 let kLogin : Int = 2 let kSignup : Int = 3 let kBack : Int = 4 extension UIColor{ class func emeraldGreen()-> UIColor{ return UIColor(red: 30/255, green: 177/255, blue: 137/255, alpha: 1.0) } class func pastelGreen()-> UIColor{ return UIColor(red: 42/255, green: 197/255, blue: 93/255 , alpha: 1.0) } class func azure()-> UIColor{ return UIColor(red: 44/255, green: 132/255, blue: 210/255, alpha: 1.0) } class func darkBlue()-> UIColor{ return UIColor(red: 40/255, green: 56/255 , blue: 75/255 , alpha: 1.0) } class func celadonGreen()-> UIColor{ return UIColor(red: 25/255, green: 145/255 ,blue: 115/255, alpha: 1.0) } } class MenuTableViewCell: UITableViewCell{ @IBOutlet weak var titleTextField: UITextField! } class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView!{ didSet{ tableView.dataSource = self tableView.delegate = self } } @IBOutlet weak var menuButton: UIButton! let colors:[UIColor] = [UIColor.emeraldGreen(), UIColor.pastelGreen(), UIColor.azure(), UIColor.darkBlue(), UIColor.celadonGreen()] var model = Array<(title: String, inputEnable: Bool)>() let menusModel = MenusModel() var menuType: MenuType = MenuType.Main { willSet(newValue) { model = menusModel.getMenu(newValue) } didSet{ if menuType.rawValue < oldValue.rawValue{ tableView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Right) } else{ tableView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Left) } } } //MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() if (PFUser.currentUser() != nil){ menuType = MenuType.YO } else{ menuType = MenuType.Main } } override func prefersStatusBarHidden() -> Bool { return true; } //MARK: - Private methods func clearUsername(){ if let usernameCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as? MenuTableViewCell{ usernameCell.titleTextField.text = "" } } func getUserInputs() -> (username: String?, password: String?, email: String?){ var inputs = [String?](count: 3, repeatedValue: nil) for index in 0...2{ if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as? MenuTableViewCell where cell.titleTextField.enabled, let input = cell.titleTextField.text where !input.isEmpty{ inputs[index] = input } } return (inputs[0], inputs[1], inputs[2]) } func userConnected(){ self.menuType = .YO } func userConnectedFailure(error: NSError){ let errorMsg = error.userInfo![kErrorMessageKey] as! String? let alert = UIAlertController(title: "Connection Failed", message: errorMsg , preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Dissmis", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } func sendYO(){ if let username = getUserInputs().username{ ServerUtility.sentYO(username, callbackClosure: { (error: NSError?) -> () in if let errorSendYo = error{ let errorUserMeesage: String if errorSendYo.code == kUserNotFound{ if let errorMsg = errorSendYo.userInfo?[kErrorMessageKey] as! String?{ errorUserMeesage = errorMsg } else{ errorUserMeesage = "Your YO isn't sent, The username '\(username)' not found" } } else{ errorUserMeesage = "There was an error, your YO isn't sent" } var alert = UIAlertController(title: "YO Error", message: errorUserMeesage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Dissmis", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else{ self.clearUsername() } }) } } func recoverPassword(){ var alert = UIAlertController(title: "YO Password Reminder", message: "Please confirm your username and we will send you email for resetting your password.", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (alertAction:UIAlertAction!) -> Void in if let textField = alert.textFields?.first as? UITextField{ ServerUtility.sendResetPasswordMail(textField.text, callbackClosure: { (succeeded, error) -> () in if let errorResetPassword = error { var alert = UIAlertController(title: "YO Error", message: errorResetPassword.userInfo?["user"] as? String, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else{ self.menuType = .Main } }) } })) alert.addTextFieldWithConfigurationHandler { (textfield: UITextField!) -> Void in textfield.text = self.getUserInputs().username } presentViewController(alert, animated: true, completion: nil) } func login(){ let (username, password, _) = getUserInputs() if let user = username, let pass = password{ ServerUtility.login(user, password: pass, successClosure:userConnected, failureClosure: userConnectedFailure) } } func signup(){ let (username, password, email) = getUserInputs() if let user = username, let pass = password, let userEmail = email { ServerUtility.signUp(user, password: pass,email:userEmail, successClosure: userConnected, failureClosure: userConnectedFailure) } } func logout(){ ServerUtility.logout() self.menuType = .Main } } extension ViewController: UITableViewDelegate{ //MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ switch (menuType, indexPath.row) { case (.Main, _): menuType = MenuType(rawValue: indexPath.row)! case (.Signup, kSignup): signup() case (.Login,kLogin): login() case (.Recover,kRecover): recoverPassword() case (.YO,_): sendYO() default: menuType = .Main } } //MARK: - IBAction @IBAction func logoutButtonAction(sender: UIButton) { var actionSheet = UIAlertController(title: "YO Logout", message: "Do you sure you want to log out?", preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title: "Logout", style: UIAlertActionStyle.Destructive, handler: { (alertAction: UIAlertAction!) -> Void in self.logout() })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) presentViewController(actionSheet, animated: true, completion: nil) } } extension ViewController: UITableViewDataSource{ //MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return model.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("cellReuseIdentifier", forIndexPath: indexPath) as! MenuTableViewCell cell.titleTextField.textColor = UIColor.whiteColor() cell.titleTextField.enabled = model[indexPath.row].inputEnable cell.titleTextField.placeholder = "" cell.titleTextField.text = "" if model[indexPath.row].inputEnable{ cell.titleTextField.placeholder = model[indexPath.row].title } else{ cell.titleTextField.text = model[indexPath.row].title } cell.backgroundColor = colors[indexPath.row] return cell; } } extension ViewController: UITextFieldDelegate{ //MARK: - UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string == ""{ return true } var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789@.") if ((string as NSString).rangeOfCharacterFromSet(characterSet).location != NSNotFound ){ let start = advance(textField.text.startIndex, range.location) let end = advance(start, range.length) let textRange = Range<String.Index>(start: start, end: end) textField.text = textField.text.stringByReplacingCharactersInRange(textRange, withString: string.uppercaseString) } return false } }
mit
4d14f6a59f07cbcc581bae8569b98dfd
35.132616
215
0.59494
4.980237
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/Wizard/SiteCreationWizardLauncher.swift
1
3054
import AutomatticTracks /// Puts together the Site creation wizard, assembling steps. final class SiteCreationWizardLauncher { private lazy var creator: SiteCreator = { return SiteCreator() }() private var shouldShowSiteIntent: Bool { return FeatureFlag.siteIntentQuestion.enabled } private var shouldShowSiteName: Bool { return FeatureFlag.siteName.enabled } lazy var steps: [SiteCreationStep] = { // If Site Intent shouldn't be shown, fall back to the original steps. guard shouldShowSiteIntent else { return [ .design, .address, .siteAssembly ] } // If Site Intent should be shown but not the Site Name, only add Site Intent. guard shouldShowSiteName else { return [ .intent, .design, .address, .siteAssembly ] } // If Site Name should be shown, swap out the Site Address step. return [ .intent, .name, .design, .siteAssembly ] }() private lazy var wizard: SiteCreationWizard = { return SiteCreationWizard(steps: steps.map { initStep($0) }) }() lazy var ui: UIViewController? = { guard let wizardContent = wizard.content else { return nil } wizardContent.modalPresentationStyle = .pageSheet wizardContent.isModalInPresentation = true return wizardContent }() /// Closure to be executed upon dismissal of the SiteAssemblyWizardContent. /// private let onDismiss: ((Blog, Bool) -> Void)? init( onDismiss: ((Blog, Bool) -> Void)? = nil ) { self.onDismiss = onDismiss } private func initStep(_ step: SiteCreationStep) -> WizardStep { switch step { case .address: let addressService = DomainsServiceAdapter(managedObjectContext: ContextManager.sharedInstance().mainContext) return WebAddressStep(creator: self.creator, service: addressService) case .design: // we call dropLast to remove .siteAssembly let isLastStep = steps.dropLast().last == .design return SiteDesignStep(creator: self.creator, isLastStep: isLastStep) case .intent: return SiteIntentStep(creator: self.creator) case .name: return SiteNameStep(creator: self.creator) case .segments: let segmentsService = SiteCreationSegmentsService(managedObjectContext: ContextManager.sharedInstance().mainContext) return SiteSegmentsStep(creator: self.creator, service: segmentsService) case .siteAssembly: let siteAssemblyService = EnhancedSiteCreationService(managedObjectContext: ContextManager.sharedInstance().mainContext) return SiteAssemblyStep(creator: self.creator, service: siteAssemblyService, onDismiss: onDismiss) } } }
gpl-2.0
764b6423e3d0c716cdd6572ceb00caaf
32.195652
132
0.616568
5.265517
false
false
false
false
jphacks/KB_01
jphacks/Model/Spot.swift
1
524
// // Spot.swift // jphacks // // Created by 内村祐之 on 2015/11/28. // Copyright © 2015年 at. All rights reserved. // class Spot { let name: String let address: String let detail : String let latitude: Double let longitude: Double init(name: String, address: String, detail: String, latitude: Double, longitude: Double) { self.name = name self.address = address self.detail = detail self.latitude = latitude self.longitude = longitude } }
mit
3349121b3e71cdf1b5e53b28c2a43475
21.304348
94
0.615984
3.828358
false
false
false
false
DannyvanSwieten/SwiftSignals
SwiftAudio/Host.swift
1
1567
// // Host.swift // SwiftAudio // // Created by Danny van Swieten on 1/9/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import Foundation class Transport { var time: UInt64 = 0 private var samplesPerBeat: UInt64 = 0 var bpm: UInt64 { get { return self.bpm } set(newBpm) { samplesPerBeat = 44100 / 4 / newBpm } } private var playing = false init() { bpm = 120 } func start() -> Void { playing = true } func stop() -> Void { playing = false } func reset() -> Void { time = 0 } func step() -> Void { if(playing) { time++ } } } class Host { var transport = Transport() var audioSettings = AudioDeviceSettings() var audioStream = AudioStream() var midiClient = MidiClient() var midiIn : MidiInput? func startAudioStream() { audioStream.start() } //--------------------------------- static let sharedInstance = Host() private init() { midiIn = MidiInput(client: midiClient, name: "Midi In 1") audioStream.onRender = {numChannels, numFrames, timestamp, buffer in for _ in 0..<numFrames { for _ in 0..<numChannels { } self.transport.step() } } } }
gpl-3.0
5e7b2cc1dfbdb703c0349da2868d3939
18.097561
76
0.451469
4.474286
false
false
false
false
1985apps/PineKit
Pod/Classes/PineSegmentedControl.swift
2
2599
// // PineSegmentedControll.swift // Pods // // Created by Prakash Raman on 10/03/16. // // import UIKit open class PineSegmentedControl: UIControl { open var labels : [PineLabel] = [] var onchange : (PineSegmentedControl) -> Void = {_ in} open var active : Int = 0 { didSet { positionThumbview() } } open var thumbview : UIView = UIView() { didSet { setupThumbview() } willSet { if thumbview.isDescendant(of: self) { thumbview.removeFromSuperview() } } } public init(labels: [String], thumbview: UIView = UIView(), change: @escaping ((PineSegmentedControl) -> Void) = {_ in }){ super.init(frame: CGRect.zero) for l in labels { self.labels.append(PineLabel(text: l)) } setup() self.onchange = change self.thumbview = thumbview self.setupThumbview() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func setup(){ self.subviews.forEach { $0.removeFromSuperview() } for label in self.labels { self.addSubview(label) label.textAlignment = .center label.isUserInteractionEnabled = true label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PineSegmentedControl.ontap(_:)))) label.layer.zPosition = 2 } self.clipsToBounds = true } open func setupThumbview(){ self.addSubview(self.thumbview) } open func positionThumbview() { self.thumbview.layer.zPosition = 1 UIView.animate(withDuration: 0.2, animations: { () -> Void in self.thumbview.center = self.labels[self.active].center }) } open override func layoutSubviews() { super.layoutSubviews() let width = self.frame.width / CGFloat(self.labels.count) for index in 0...self.labels.count - 1 { let x = CGFloat(index) * width let label = self.labels[index] label.frame = CGRect(origin: CGPoint(x: x, y: 0), size: CGSize(width: width, height: self.frame.height)) } positionThumbview() } open func ontap(_ sender: UITapGestureRecognizer){ let label = sender.view as! PineLabel self.active = self.labels.index(of: label)! self.update() } open func update(){ self.onchange(self) } }
mit
1610014f99496119e2164f3221717b31
26.648936
127
0.569835
4.382799
false
false
false
false
coffee-cup/solis
SunriseSunset/Spring/SpringTextField.swift
1
2745
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SpringTextField: UITextField, Springable { @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var animation: String = "" @IBInspectable public var force: CGFloat = 1 @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var repeatCount: Float = 1 @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 @IBInspectable public var curve: String = "" public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring : Spring = Spring(self) override public func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } public override func layoutSubviews() { super.layoutSubviews() spring.customLayoutSubviews() } public func animate() { self.spring.animate() } public func animateNext(completion: @escaping () -> ()) { self.spring.animateNext(completion: completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: @escaping () -> ()) { self.spring.animateToNext(completion: completion) } }
mit
566db754d5d68b1b96e7b51567bb854c
37.661972
81
0.712933
4.708405
false
false
false
false
Swift3Home/Swift3_Object-oriented
TLAddressBook/TLAddressBook/TLListTableViewController.swift
1
6209
// // TLListTableViewController.swift // TLAddressBook // // Created by lichuanjun on 2017/6/5. // Copyright © 2017年 lichuanjun. All rights reserved. // import UIKit class TLListTableViewController: UITableViewController { // 联系人数组 var personList = [TLPerson]() override func viewDidLoad() { super.viewDidLoad() loadData { (list) in // print(list) // `拼接`数组,闭包中定义好的代码在需要的时候执行,需要self. 指定语境 self.personList += list // 刷新表格 self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 模拟异步,利用闭包回调 private func loadData(completion: @escaping (_ list: [TLPerson]) -> ()) -> () { print("正在努力加载中...") DispatchQueue.global().async { Thread.sleep(forTimeInterval: 0.5) var arrayPerson = [TLPerson]() for i in 0..<20 { let p = TLPerson() p.name = "zhangsan \(i)" p.phone = "1860" + String(format: "%06d", arc4random_uniform(1000000)) p.title = "boss" arrayPerson.append(p) } // 主线程回调 DispatchQueue.main.async (execute: { // 回调,执行闭包 completion(arrayPerson) print("加载完成.") }) } } @IBAction func addNewPerson(_ sender: Any) { // 执行segue 跳转界面 performSegue(withIdentifier: "ListToDetail", sender: nil) } // MARK: - 控制器跳转方法 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // 类型转换 as // Swift 中 String 之外,绝大多数使用as 需要 ? / ! // as! / as? 直接根据前面的返回值来决定 // 注意:if let / guard let 判空语句,一律使用 as? let vc = segue.destination as! TLDetailTableViewController // 设置选中的 person, indexPath if let indexPath = sender as? IndexPath { // indexPath 一定有值 vc.person = personList[indexPath.row] // 设置编辑完成的闭包 vc.completionCallBack = { // 刷新指定行 self.tableView.reloadRows(at: [indexPath], with: .automatic) } } else { // 新建个人记录 vc.completionCallBack = { [weak vc] in // 1. 获取明细控制器的 person guard let p = vc?.person else { print("person 为nil") return } // 2. 判断person的属性值是否为空串 if p.name == "" || p.phone == "" || p.title == "" { print("person 部分属性为空") return } // 3. 插入到数据顶部 self.personList.insert(p, at: 0) // 4. 刷新表格 self.tableView.reloadData() } } } // MARK: - 代理方法 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // 执行segue performSegue(withIdentifier: "ListToDetail", sender: indexPath) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return personList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "listCellId", for: indexPath) cell.textLabel?.text = personList[indexPath.row].name cell.detailTextLabel?.text = personList[indexPath.row].phone return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d91d0fa24247cb9f1d836d62714c988f
30.405405
136
0.560241
4.874161
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/Window/File Editor/FileStrategyCode.swift
1
4510
// // FileStrategyCode.swift // StemCode // // Created by David Evans on 12/05/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import UIKit import StemProjectKit class FileStrategyCode: FileStrategyText { var index = clang_createIndex(1, 0) var translationUnit: CXTranslationUnit! var cxFile: CXFile! let profile = ColourProfilesProvider.shared.profiles.first! var errorTimer: Timer? = nil override func openFile(_ file: StemFile) { super.openFile(file) let filePath = (file.absolutePath as NSString).cString(using: 8) let options = clang_defaultDiagnosticDisplayOptions() | clang_defaultCodeCompleteOptions() translationUnit = clang_parseTranslationUnit(index, filePath, nil, 0, nil, 0, options) translationUnit = clang_createTranslationUnitFromSourceFile(index, filePath, 0, nil, 0, nil) cxFile = clang_getFile(translationUnit, filePath) syntaxHighlight(from: 0, to: textView.text.count) runErrorCheck() } func syntaxHighlight(from: Int, to: Int) { let startLocation = clang_getLocationForOffset(translationUnit, cxFile, UInt32(from)) let endLocation = clang_getLocationForOffset(translationUnit, cxFile, UInt32(to)) let range = clang_getRange(startLocation, endLocation) let tokenCount = UnsafeMutablePointer<UInt32>.allocate(capacity: 1) var tokens: UnsafeMutablePointer<CXToken>? = UnsafeMutablePointer<CXToken>.allocate(capacity: 0) clang_tokenize(translationUnit, range, &tokens, tokenCount) for i in 0..<Int(tokenCount.pointee) { if let token = tokens?[i] { let tokenRange = clang_getTokenExtent(translationUnit, token) var start: UInt32 = 0 var end: UInt32 = 0 clang_getFileLocation(clang_getRangeStart(tokenRange), nil, nil, nil, &start) clang_getFileLocation(clang_getRangeEnd(tokenRange), nil, nil, nil, &end) let colour: UIColor switch clang_getTokenKind(token) { case CXToken_Comment: colour = profile.comment! break case CXToken_Keyword: colour = profile.keyword! break case CXToken_Literal: colour = profile.literal! break default: colour = UIColor.black break } let length = Int(end - start) let range = NSRange(location: Int(start), length: length) textView.textStorage.removeAttribute(NSAttributedString.Key.foregroundColor, range: range) textView.textStorage.addAttribute(NSAttributedString.Key.foregroundColor, value: colour, range: range) } } clang_disposeTokens(translationUnit, tokens, tokenCount.pointee) } deinit { if let translationUnit = translationUnit { clang_disposeTranslationUnit(translationUnit) } if let index = index { clang_disposeIndex(index) } errorTimer?.invalidate() errorTimer = nil } func runErrorCheck() { ErrorManager.shared.refreshErrors(for: file) { diagnostics in } } // MARK: - UITextViewDelegate override func textViewDidChange(_ textView: UITextView) { super.textViewDidChange(textView) var unsavedFiles: [CXUnsavedFile] = file.parentProject.unsavedFiles.map { unsavedFile in let fileName = (file.absolutePath as NSString).cString(using: 8) let fileText = (file.unsavedBuffer as? String) ?? "" return CXUnsavedFile(Filename: fileName, Contents: fileText, Length: UInt(fileText.count)) } let filePath = (file.absolutePath as NSString).cString(using: 8) let reparsed = clang_reparseTranslationUnit(translationUnit, UInt32(unsavedFiles.count), &unsavedFiles, clang_defaultReparseOptions(translationUnit)) guard reparsed == 0 else { return } cxFile = clang_getFile(translationUnit, filePath) syntaxHighlight(from: 0, to: textView.text.count) errorTimer?.invalidate() errorTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { [weak self] (_) in self?.runErrorCheck() }) } }
mit
ec3103d42b82c9d9e6d3c704830b6d93
35.658537
157
0.623642
4.658058
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/EventFeedbackComponent/Routing/EventFeedbackRoute.swift
1
1289
import ComponentBase import RouterCore import UIKit.UIViewController public struct EventFeedbackRoute { private let eventFeedbackFactory: EventFeedbackComponentFactory private let modalWireframe: ModalWireframe public init(eventFeedbackFactory: EventFeedbackComponentFactory, modalWireframe: ModalWireframe) { self.eventFeedbackFactory = eventFeedbackFactory self.modalWireframe = modalWireframe } } // MARK: - Route extension EventFeedbackRoute: Route { public typealias Parameter = EventFeedbackRouteable public func route(_ content: EventFeedbackRouteable) { let delegate = DismissControllerWhenCancellingFeedback() let contentController = eventFeedbackFactory.makeEventFeedbackModule( for: content.identifier, delegate: delegate ) delegate.viewController = contentController modalWireframe.presentModalContentController(contentController) } private class DismissControllerWhenCancellingFeedback: EventFeedbackComponentDelegate { weak var viewController: UIViewController? func eventFeedbackCancelled() { viewController?.dismiss(animated: true) } } }
mit
6e30c1a05f884febd285467d8cd06324
27.644444
102
0.704422
6.318627
false
false
false
false
antoniqhc/PageMenu
Demos/Demo 1/PageMenuDemoStoryboard/PageMenuDemoStoryboard/TestCollectionViewController.swift
1
2166
// // TestCollectionViewController.swift // NFTopMenuController // // Created by Niklas Fahl on 12/17/14. // Copyright (c) 2014 Niklas Fahl. All rights reserved. // import UIKit let reuseIdentifier = "MoodCollectionViewCell" class TestCollectionViewController: UICollectionViewController { var moodArray : [String] = ["Relaxed", "Playful", "Happy", "Adventurous", "Wealthy", "Hungry", "Loved", "Active"] var backgroundPhotoNameArray : [String] = ["mood1.jpg", "mood2.jpg", "mood3.jpg", "mood4.jpg", "mood5.jpg", "mood6.jpg", "mood7.jpg", "mood8.jpg"] var photoNameArray : [String] = ["relax.png", "playful.png", "happy.png", "adventurous.png", "wealthy.png", "hungry.png", "loved.png", "active.png"] override func viewDidLoad() { super.viewDidLoad() self.collectionView!.register(UINib(nibName: "MoodCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return 8 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : MoodCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MoodCollectionViewCell // Configure the cell cell.backgroundImageView.image = UIImage(named: backgroundPhotoNameArray[indexPath.row]) cell.moodTitleLabel.text = moodArray[indexPath.row] cell.moodIconImageView.image = UIImage(named: photoNameArray[indexPath.row]) return cell } }
bsd-3-clause
2cc67ffd41a7aeedaa9607dab91d3413
39.867925
159
0.705448
4.638116
false
false
false
false
zwaldowski/Lustre
Lustre/SequenceType+Result.swift
1
1539
// // SequenceType+Result.swift // Lustre // // Created by John Gallagher on 9/12/14. // Copyright © 2014-2015 Big Nerd Ranch Inc. Licensed under MIT. // extension SequenceType where Generator.Element: EitherType, Generator.Element.LeftType == ErrorType { private typealias Value = Generator.Element.RightType public func partition() -> ([ErrorType], [Value]) { var lefts = [ErrorType]() var rights = [Value]() for either in self { either.analysis(ifLeft: { lefts.append($0) }, ifRight: { rights.append($0) }) } return (lefts, rights) } public func extractAll() throws -> [Value] { var successes = [Value]() successes.reserveCapacity(underestimateCount()) for result in self { successes.append(try result.extract()) } return successes } public func collectAllSuccesses() -> Result<[Value]> { do { return .Success(try extractAll()) } catch { return .Failure(error) } } } extension EitherType where LeftType == ErrorType, RightType: SequenceType { private typealias Element = RightType.Generator.Element public func split<NewValue>(@noescape transform: Element -> Result<NewValue>) -> Result<([ErrorType], [NewValue])> { return map { $0.lazy.map(transform).partition() } } }
mit
736d030f4ccad835f2512ae1b0c19f69
24.633333
120
0.556567
4.646526
false
false
false
false
Schatzjason/cs212
LectureCode/Three-Delegates/TextFields/ViewController.swift
1
1720
// // ViewController.swift // TextFields // // Created by Jason on 11/11/14. // Copyright (c) 2014 CCSF. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { // Outlets @IBOutlet weak var textField1: UITextField! @IBOutlet weak var textField2: UITextField! @IBOutlet weak var textField3: UITextField! @IBOutlet weak var characterCountLabel: UILabel! // Text Field Delegate objects let emojiDelegate = EmojiTextFieldDelegate() let colorizerDelegate = ColorizerTextFieldDelegate() // Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() // set the label to be hidden self.characterCountLabel.isHidden = true // Set the three delegates self.textField1.delegate = colorizerDelegate self.textField2.delegate = emojiDelegate self.textField3.delegate = self } // Text Field Delegate Methods func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Figure out what the new text will be, if we return true var newText: NSString = textField.text! as NSString newText = newText.replacingCharacters(in: range, with: string) as NSString // hide the label if the newText will be an empty string self.characterCountLabel.isHidden = (newText.length == 0) // Write the length of newText into the label self.characterCountLabel.text = String(newText.length) // returning true gives the text field permission to change its text return true; } }
mit
06fe683f12426dcfc311895568ac7c80
29.714286
129
0.668605
5.058824
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/ItemCellView.swift
3
8602
// // CellView.swift // GamingStreamsTVApp // // Created by Brendan Kirchner on 10/8/15. // Copyright © 2015 Rivus Media Inc. All rights reserved. // import UIKit import Alamofire protocol CellItem { var urlTemplate: String? { get } var title: String { get } var subtitle: String { get } var bannerString: String? { get } var image: UIImage? { get } mutating func setImage(image: UIImage) } class ItemCellView: UICollectionViewCell { internal static let CELL_IDENTIFIER : String = "kItemCellView" internal static let LABEL_HEIGHT : CGFloat = 40 private var representedItem : CellItem? private var image : UIImage? private var imageView : UIImageView! private var activityIndicator : UIActivityIndicatorView! private var titleLabel : ScrollingLabel! private var subtitleLabel : UILabel! override init(frame: CGRect) { super.init(frame: frame) let imageViewFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height-80) self.imageView = UIImageView(frame: imageViewFrame) self.imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView.adjustsImageWhenAncestorFocused = true //we don't need to have this next line because we are turning on the 'adjustsImageWhenAncestorFocused' therefore we can't clip to bounds, and the corner radius has no effect if we aren't clipping self.imageView.layer.cornerRadius = 10 self.imageView.backgroundColor = UIColor(white: 0.25, alpha: 0.7) self.imageView.contentMode = UIViewContentMode.ScaleAspectFill self.activityIndicator = UIActivityIndicatorView(frame: imageViewFrame) self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge self.activityIndicator.startAnimating() self.titleLabel = ScrollingLabel(scrollSpeed: 0.5) self.subtitleLabel = UILabel() self.titleLabel.translatesAutoresizingMaskIntoConstraints = false self.subtitleLabel.translatesAutoresizingMaskIntoConstraints = false self.titleLabel.alpha = 0.5 self.subtitleLabel.alpha = 0.5 self.titleLabel.font = UIFont.systemFontOfSize(30, weight: UIFontWeightSemibold) self.subtitleLabel.font = UIFont.systemFontOfSize(30, weight: UIFontWeightThin) self.titleLabel.textColor = UIColor.whiteColor() self.subtitleLabel.textColor = UIColor.whiteColor() self.imageView.addSubview(self.activityIndicator) self.contentView.addSubview(self.imageView) self.contentView.addSubview(titleLabel) self.contentView.addSubview(subtitleLabel) let viewDict = ["image" : imageView, "title" : titleLabel, "subtitle" : subtitleLabel, "imageGuide" : imageView.focusedFrameGuide] self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[image]|", options: [], metrics: nil, views: viewDict)) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[title]|", options: [], metrics: nil, views: viewDict)) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subtitle]|", options: [], metrics: nil, views: viewDict)) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[image]", options: [], metrics: nil, views: viewDict)) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[imageGuide]-5-[title(\(ItemCellView.LABEL_HEIGHT))]-5-[subtitle(\(ItemCellView.LABEL_HEIGHT))]|", options: [], metrics: nil, views: viewDict)) self.imageView.addCenterConstraints(toView: self.activityIndicator) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* * prepareForReuse() * * Override the default method to free internal ressources and add * a loading indicator */ override func prepareForReuse() { super.prepareForReuse() self.representedItem = nil self.image = nil self.imageView.image = nil self.titleLabel.text = "" self.subtitleLabel.text = "" self.activityIndicator = UIActivityIndicatorView(frame: self.imageView.frame) self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge self.activityIndicator.startAnimating() self.imageView.addSubview(self.activityIndicator!) } /* * assignImageAndDisplay() * * Downloads the image from the actual game and assigns it to the image view * Removes the loading indicator on download callback success */ private func assignImageAndDisplay() { self.downloadImageWithSize(self.imageView!.bounds.size) { (image, error) in if let image = image { self.image = image } else { self.image = nil } dispatch_async(dispatch_get_main_queue(),{ if self.activityIndicator != nil { self.activityIndicator?.removeFromSuperview() self.activityIndicator = nil } self.imageView.image = self.image }) } } /* * downloadImageWithSize(size : CGSize, completionHandler : (image : UIImage?, error : NSError?) -> ()) * * Download an image from twitch server with the required size * Passes the downloaded image to a defined completion handler */ private func downloadImageWithSize(size : CGSize, completionHandler : (image : UIImage?, error : NSError?) -> ()) { if let image = representedItem?.image { completionHandler(image: image, error: nil) return } if let imgUrlTemplate = representedItem?.urlTemplate { let imgUrlString = imgUrlTemplate.stringByReplacingOccurrencesOfString("{width}", withString: "\(Int(size.width))") .stringByReplacingOccurrencesOfString("{height}", withString: "\(Int(size.height))") Alamofire.request(.GET, imgUrlString).response() { (_, _, data, error) in guard let data = data, image = UIImage(data: data) else { completionHandler(image: nil, error: nil) return } self.representedItem?.setImage(image) completionHandler(image: image, error: nil) } } } /* * didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) * * Responds to the focus update by either growing or shrinking * */ override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator) if(context.nextFocusedView == self){ coordinator.addCoordinatedAnimations({ self.titleLabel.alpha = 1 self.subtitleLabel.alpha = 1 self.titleLabel.beginScrolling() }, completion: nil ) } else if(context.previouslyFocusedView == self) { coordinator.addCoordinatedAnimations({ self.titleLabel.alpha = 0.5 self.subtitleLabel.alpha = 0.5 self.titleLabel.endScrolling() }, completion: nil ) } } var centerVerticalCoordinate: CGFloat { get { switch representedItem { case is TwitchGame: return 40 case is TwitchStream: return 22 default: return 22 } } } ///////////////////////////// // MARK - Getter and setters ///////////////////////////// func getRepresentedItem() -> CellItem? { return self.representedItem } func setRepresentedItem(item : CellItem) { self.representedItem = item titleLabel.text = item.title subtitleLabel.text = item.subtitle self.assignImageAndDisplay() } }
mit
7119e27aeee7aa7d588545d70fee4858
39.191589
233
0.634694
5.447118
false
false
false
false
Authman2/Pix
Pods/Hero/Sources/HeroDefaultAnimatorViewContext.swift
1
14215
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit internal class HeroDefaultAnimatorViewContext { weak var animator: HeroDefaultAnimator? var snapshot: UIView var state = [String: (Any?, Any?)]() var duration: TimeInterval = 0 var targetState: HeroTargetState var defaultTiming: (duration: TimeInterval, timingFunction: CAMediaTimingFunction)! // computed var contentLayer: CALayer? { return snapshot.layer.sublayers?.get(0) } var overlayLayer: CALayer? var currentTime: TimeInterval { return snapshot.layer.convertTime(CACurrentMediaTime(), from: nil) } var container: UIView? { return animator?.context.container } /* // return (delay, duration, easing) func getTiming(key:String, fromValue:Any?, toValue:Any?) -> (TimeInterval, TimeInterval, CAMediaTimingFunction){ // delay should be for a specific animation. this shouldn't include the baseDelay // TODO: dynamic delay and duration for different key // https://material.io/guidelines/motion/choreography.html#choreography-continuity switch key { case "opacity": if let value = (toValue as? NSNumber)?.floatValue{ switch value { case 0.0: // disappearing element return (0, 0.075, .standard) case 1.0: // appearing element return (0.075, defaultTiming.0 - 0.075, .standard) default: break } } default: break } return (0.0, defaultTiming.0, defaultTiming.1) } */ func getOverlayLayer() -> CALayer { if overlayLayer == nil { overlayLayer = CALayer() overlayLayer!.frame = snapshot.bounds overlayLayer!.opacity = 0 snapshot.layer.addSublayer(overlayLayer!) } return overlayLayer! } func overlayKeyFor(key: String) -> String? { if key.hasPrefix("overlay.") { var key = key key.removeSubrange(key.startIndex..<key.index(key.startIndex, offsetBy: 8)) return key } return nil } func getAnimation(key: String, beginTime: TimeInterval, fromValue: Any?, toValue: Any?, ignoreArc: Bool = false) -> CAPropertyAnimation { let key = overlayKeyFor(key: key) ?? key let anim: CAPropertyAnimation let (delay, duration, timingFunction) = (0.0, defaultTiming.0, defaultTiming.1) if !ignoreArc, key == "position", let arcIntensity = targetState.arc, let fromPos = (fromValue as? NSValue)?.cgPointValue, let toPos = (toValue as? NSValue)?.cgPointValue, abs(fromPos.x - toPos.x) >= 1, abs(fromPos.y - toPos.y) >= 1 { let kanim = CAKeyframeAnimation(keyPath: key) let path = CGMutablePath() let maxControl = fromPos.y > toPos.y ? CGPoint(x: toPos.x, y: fromPos.y) : CGPoint(x: fromPos.x, y: toPos.y) let minControl = (toPos - fromPos) / 2 + fromPos path.move(to: fromPos) path.addQuadCurve(to: toPos, control: minControl + (maxControl - minControl) * arcIntensity) kanim.values = [fromValue!, toValue!] kanim.path = path kanim.duration = duration kanim.timingFunctions = [timingFunction] anim = kanim } else if #available(iOS 9.0, *), key != "cornerRadius", let (stiffness, damping) = targetState.spring { let sanim = CASpringAnimation(keyPath: key) sanim.stiffness = stiffness sanim.damping = damping sanim.duration = sanim.settlingDuration * 0.9 sanim.fromValue = fromValue sanim.toValue = toValue anim = sanim } else { let banim = CABasicAnimation(keyPath: key) banim.duration = duration banim.fromValue = fromValue banim.toValue = toValue banim.timingFunction = timingFunction anim = banim } anim.fillMode = kCAFillModeBoth anim.isRemovedOnCompletion = false anim.beginTime = beginTime + delay return anim } // return the completion duration of the animation (duration + initial delay, not counting the beginTime) @discardableResult func addAnimation(key: String, beginTime: TimeInterval, fromValue: Any?, toValue: Any?) -> TimeInterval { let anim = getAnimation(key: key, beginTime:beginTime, fromValue: fromValue, toValue: toValue) if let overlayKey = overlayKeyFor(key:key) { getOverlayLayer().add(anim, forKey: overlayKey) } else { snapshot.layer.add(anim, forKey: key) if key == "cornerRadius" { contentLayer?.add(anim, forKey: key) overlayLayer?.add(anim, forKey: key) } else if key == "bounds.size" { let fromSize = (fromValue as? NSValue)!.cgSizeValue let toSize = (toValue as? NSValue)!.cgSizeValue // for the snapshotView(UIReplicantView): there is a // subview(UIReplicantContentView) that is hosting the real snapshot image. // because we are using CAAnimations and not UIView animations, // The snapshotView will not layout during animations. // we have to add two more animations to manually layout the content view. let fromPosn = NSValue(cgPoint:fromSize.center) let toPosn = NSValue(cgPoint:toSize.center) let positionAnim = getAnimation(key: "position", beginTime:0, fromValue: fromPosn, toValue: toPosn, ignoreArc: true) positionAnim.beginTime = anim.beginTime positionAnim.timingFunction = anim.timingFunction positionAnim.duration = anim.duration contentLayer?.add(positionAnim, forKey: "position") contentLayer?.add(anim, forKey: key) overlayLayer?.add(positionAnim, forKey: "position") overlayLayer?.add(anim, forKey: key) } } return anim.duration + anim.beginTime - beginTime } /** - Returns: a CALayer [keyPath:value] map for animation */ func viewState(targetState: HeroTargetState) -> [String: Any] { var targetState = targetState var rtn = [String: Any]() if let size = targetState.size { if targetState.useScaleBasedSizeChange ?? self.targetState.useScaleBasedSizeChange ?? false { let currentSize = snapshot.bounds.size targetState.append(.scale(x:size.width / currentSize.width, y:size.height / currentSize.height)) } else { rtn["bounds.size"] = NSValue(cgSize:size) } } if let position = targetState.position { rtn["position"] = NSValue(cgPoint:position) } if let opacity = targetState.opacity { rtn["opacity"] = NSNumber(value: opacity) } if let cornerRadius = targetState.cornerRadius { rtn["cornerRadius"] = NSNumber(value: cornerRadius.native) } if let zPosition = targetState.zPosition { rtn["zPosition"] = NSNumber(value: zPosition.native) } if let borderWidth = targetState.borderWidth { rtn["borderWidth"] = NSNumber(value: borderWidth.native) } if let borderColor = targetState.borderColor { rtn["borderColor"] = borderColor } if let masksToBounds = targetState.masksToBounds { rtn["masksToBounds"] = masksToBounds } if targetState.displayShadow { if let shadowColor = targetState.shadowColor { rtn["shadowColor"] = shadowColor } if let shadowRadius = targetState.shadowRadius { rtn["shadowRadius"] = NSNumber(value: shadowRadius.native) } if let shadowOpacity = targetState.shadowOpacity { rtn["shadowOpacity"] = NSNumber(value: shadowOpacity) } if let shadowPath = targetState.shadowPath { rtn["shadowPath"] = shadowPath } if let shadowOffset = targetState.shadowOffset { rtn["shadowOffset"] = NSValue(cgSize: shadowOffset) } } if let transform = targetState.transform { rtn["transform"] = NSValue(caTransform3D: transform) } if let (color, opacity) = targetState.overlay { rtn["overlay.backgroundColor"] = color rtn["overlay.opacity"] = NSNumber(value: opacity.native) } return rtn } func optimizedDurationAndTimingFunction() -> (duration: TimeInterval, timingFunction: CAMediaTimingFunction) { // timing function let fromPos = (state["position"]?.0 as? NSValue)?.cgPointValue ?? snapshot.layer.position let toPos = (state["position"]?.1 as? NSValue)?.cgPointValue ?? fromPos let fromTransform = (state["transform"]?.0 as? NSValue)?.caTransform3DValue ?? CATransform3DIdentity let toTransform = (state["transform"]?.1 as? NSValue)?.caTransform3DValue ?? CATransform3DIdentity let realFromPos = CGPoint.zero.transform(fromTransform) + fromPos let realToPos = CGPoint.zero.transform(toTransform) + toPos var timingFunction: CAMediaTimingFunction = .standard if let container = container, !container.bounds.contains(realToPos) { // acceleration if leaving screen timingFunction = .acceleration } else if let container = container, !container.bounds.contains(realFromPos) { // deceleration if entering screen timingFunction = .deceleration } let fromSize = (state["bounds.size"]?.0 as? NSValue)?.cgSizeValue ?? snapshot.layer.bounds.size let toSize = (state["bounds.size"]?.1 as? NSValue)?.cgSizeValue ?? fromSize let realFromSize = fromSize.transform(fromTransform) let realToSize = toSize.transform(toTransform) let movePoints = (realFromPos.distance(realToPos) + realFromSize.point.distance(realToSize.point)) // duration is 0.2 @ 0 to 0.375 @ 500 let duration = 0.208 + Double(movePoints.clamp(0, 500)) / 3000 return (duration, timingFunction) } func animate(delay: TimeInterval) { // calculate timing default defaultTiming = optimizedDurationAndTimingFunction() if let timingFunction = targetState.timingFunction { defaultTiming.timingFunction = timingFunction } if let duration = targetState.duration { defaultTiming.duration = duration } duration = 0 let beginTime = currentTime + delay for (key, (fromValue, toValue)) in state { let neededTime = addAnimation(key: key, beginTime:beginTime, fromValue: fromValue, toValue: toValue) duration = max(duration, neededTime + delay) } } func apply(state: HeroTargetState) { let targetState = viewState(targetState: state) for (key, targetValue) in targetState { if self.state[key] == nil { let current = currentValue(key: key) self.state[key] = (current, current) } addAnimation(key: key, beginTime: 0, fromValue: targetValue, toValue: targetValue) } // support changing duration if let duration = state.duration { self.targetState.duration = duration self.duration = duration animate(delay: self.targetState.delay - Hero.shared.progress * Hero.shared.totalDuration) } } func resume(timePassed: TimeInterval, reverse: Bool) { for (key, (fromValue, toValue)) in state { let realToValue = !reverse ? toValue : fromValue let realFromValue = currentValue(key: key) state[key] = (realFromValue, realToValue) } let realDelay = max(0, targetState.delay - timePassed) animate(delay: realDelay) } func seek(layer: CALayer, timePassed: TimeInterval) { let timeOffset = timePassed - targetState.delay for (key, anim) in layer.animations { anim.speed = 0 anim.timeOffset = max(0, min(anim.duration - 0.01, timeOffset)) layer.removeAnimation(forKey: key) layer.add(anim, forKey: key) } } func seek(timePassed: TimeInterval) { seek(layer:snapshot.layer, timePassed:timePassed) if let contentLayer = contentLayer { seek(layer:contentLayer, timePassed:timePassed) } if let overlayLayer = overlayLayer { seek(layer: overlayLayer, timePassed: timePassed) } } func clean() { snapshot.layer.removeAllAnimations() contentLayer?.removeAllAnimations() overlayLayer?.removeFromSuperlayer() overlayLayer = nil } func currentValue(key: String) -> Any? { if let key = overlayKeyFor(key: key) { return overlayLayer?.value(forKeyPath: key) } return (snapshot.layer.presentation() ?? snapshot.layer).value(forKeyPath: key) } init(animator: HeroDefaultAnimator, snapshot: UIView, targetState: HeroTargetState, appearing: Bool) { self.animator = animator self.snapshot = snapshot self.targetState = targetState let disappeared = viewState(targetState: targetState) if let beginState = targetState.beginState?.state { let appeared = viewState(targetState: beginState) for (key, value) in appeared { snapshot.layer.setValue(value, forKeyPath: key) } if let (color, opacity) = beginState.overlay { overlayLayer = getOverlayLayer() overlayLayer!.backgroundColor = color overlayLayer!.opacity = Float(opacity) } } for (key, disappearedState) in disappeared { let appearingState = currentValue(key: key) let toValue = appearing ? appearingState : disappearedState let fromValue = !appearing ? appearingState : disappearedState state[key] = (fromValue, toValue) } animate(delay: targetState.delay) } }
gpl-3.0
67da2fad4a20f5a2add9b6601d57496b
35.731266
139
0.679634
4.413226
false
false
false
false
functionaldude/XLPagerTabStrip
Sources/PagerTabStripViewController.swift
1
16772
// PagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: Protocols public protocol IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo } public protocol PagerTabStripDelegate: class { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) } public protocol PagerTabStripIsProgressiveDelegate: PagerTabStripDelegate { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) } public protocol PagerTabStripDataSource: class { func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] } // MARK: PagerTabStripViewController open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak public var containerView: UIScrollView! open weak var delegate: PagerTabStripDelegate? open weak var datasource: PagerTabStripDataSource? open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) open private(set) var viewControllers = [UIViewController]() open private(set) var currentIndex = 0 open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible open var pageWidth: CGFloat { return containerView.bounds.width } open var scrollPercentage: CGFloat { if swipeDirection != .right { let module = fmod(containerView.contentOffset.x, pageWidth) return module == 0.0 ? 1.0 : module / pageWidth } return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth } open var swipeDirection: SwipeDirection { if containerView.contentOffset.x > lastContentOffset { return .left } else if containerView.contentOffset.x < lastContentOffset { return .right } return .none } override open func viewDidLoad() { super.viewDidLoad() let conteinerViewAux = containerView ?? { let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return containerView }() containerView = conteinerViewAux if containerView.superview == nil { view.addSubview(containerView) } containerView.bounces = true containerView.alwaysBounceHorizontal = true containerView.alwaysBounceVertical = false containerView.scrollsToTop = false containerView.delegate = self containerView.showsVerticalScrollIndicator = false containerView.showsHorizontalScrollIndicator = false containerView.isPagingEnabled = true reloadViewControllers() let childController = viewControllers[currentIndex] addChildViewController(childController) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParentViewController: self) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isViewAppearing = true childViewControllers.forEach { $0.beginAppearanceTransition(true, animated: animated) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) lastSize = containerView.bounds.size updateIfNeeded() let needToUpdateCurrentChild = preCurrentIndex != currentIndex if needToUpdateCurrentChild { moveToViewController(at: preCurrentIndex) } isViewAppearing = false childViewControllers.forEach { $0.endAppearanceTransition() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) childViewControllers.forEach { $0.beginAppearanceTransition(false, animated: animated) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) childViewControllers.forEach { $0.endAppearanceTransition() } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateIfNeeded() } open override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } open func moveToViewController(at index: Int, animated: Bool = true) { guard isViewLoaded && view.window != nil && currentIndex != index else { preCurrentIndex = index return } if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 { var tmpViewControllers = viewControllers let currentChildVC = viewControllers[currentIndex] let fromIndex = currentIndex < index ? index - 1 : index + 1 let fromChildVC = viewControllers[fromIndex] tmpViewControllers[currentIndex] = fromChildVC tmpViewControllers[fromIndex] = currentChildVC pagerTabStripChildViewControllersForScrolling = tmpViewControllers containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false) (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true) } else { (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated) } } open func moveTo(viewController: UIViewController, animated: Bool = true) { moveToViewController(at: viewControllers.index(of: viewController)!, animated: animated) } // MARK: - PagerTabStripDataSource open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method") return [] } // MARK: - Helpers open func updateIfNeeded() { if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) { updateContent() } } open func canMoveTo(index: Int) -> Bool { return currentIndex != index && viewControllers.count > index } open func pageOffsetForChild(at index: Int) -> CGFloat { return CGFloat(index) * containerView.bounds.width } open func offsetForChild(at index: Int) -> CGFloat { return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5) } open func offsetForChild(viewController: UIViewController) throws -> CGFloat { guard let index = viewControllers.index(of: viewController) else { throw PagerTabStripError.viewControllerOutOfBounds } return offsetForChild(at: index) } open func pageFor(contentOffset: CGFloat) -> Int { let result = virtualPageFor(contentOffset: contentOffset) return pageFor(virtualPage: result) } open func virtualPageFor(contentOffset: CGFloat) -> Int { return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1 } open func pageFor(virtualPage: Int) -> Int { if virtualPage < 0 { return 0 } if virtualPage > viewControllers.count - 1 { return viewControllers.count - 1 } return virtualPage } open func updateContent() { if lastSize.width != containerView.bounds.size.width { lastSize = containerView.bounds.size containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) } lastSize = containerView.bounds.size let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height) for (index, childController) in pagerViewControllers.enumerated() { let pageOffsetForChild = self.pageOffsetForChild(at: index) if fabs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width { if childController.parent != nil { childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] } else { childController.beginAppearanceTransition(true, animated: false) addChildViewController(childController) childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParentViewController: self) childController.endAppearanceTransition() } } else { if childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParentViewController: nil) childController.view.removeFromSuperview() childController.removeFromParentViewController() childController.endAppearanceTransition() } } } let oldCurrentIndex = currentIndex let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x) let newCurrentIndex = pageFor(virtualPage: virtualPage) currentIndex = newCurrentIndex preCurrentIndex = currentIndex let changeCurrentIndex = newCurrentIndex != oldCurrentIndex if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator { let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage) progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex) } else { delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex) } } open func reloadPagerTabStripView() { guard isViewLoaded else { return } for childController in viewControllers where childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParentViewController: nil) childController.view.removeFromSuperview() childController.removeFromParentViewController() childController.endAppearanceTransition() } reloadViewControllers() containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height) if currentIndex >= viewControllers.count { currentIndex = viewControllers.count - 1 } preCurrentIndex = currentIndex containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) updateContent() } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if containerView == scrollView { updateContent() lastContentOffset = scrollView.contentOffset.x } } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if containerView == scrollView { lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x) } } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if containerView == scrollView { pagerTabStripChildViewControllersForScrolling = nil (navigationController?.view ?? view).isUserInteractionEnabled = true updateContent() } } // MARK: - Orientation open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) isViewRotating = true pageBeforeRotate = currentIndex coordinator.animate(alongsideTransition: nil) { [weak self] _ in guard let me = self else { return } me.isViewRotating = false me.currentIndex = me.pageBeforeRotate me.preCurrentIndex = me.currentIndex me.updateIfNeeded() } } // MARK: Private private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) { let count = viewControllers.count var fromIndex = currentIndex var toIndex = currentIndex let direction = swipeDirection if direction == .left { if virtualPage > count - 1 { fromIndex = count - 1 toIndex = count } else { if self.scrollPercentage >= 0.5 { fromIndex = max(toIndex - 1, 0) } else { toIndex = fromIndex + 1 } } } else if direction == .right { if virtualPage < 0 { fromIndex = 0 toIndex = -1 } else { if self.scrollPercentage > 0.5 { fromIndex = min(toIndex + 1, count - 1) } else { toIndex = fromIndex - 1 } } } let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage) return (fromIndex, toIndex, scrollPercentage) } private func reloadViewControllers() { guard let dataSource = datasource else { fatalError("dataSource must not be nil") } viewControllers = dataSource.viewControllers(for: self) // viewControllers guard !viewControllers.isEmpty else { fatalError("viewControllers(for:) should provide at least one child view controller") } viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }} } private var pagerTabStripChildViewControllersForScrolling: [UIViewController]? private var lastPageNumber = 0 private var lastContentOffset: CGFloat = 0.0 private var pageBeforeRotate = 0 private var lastSize = CGSize(width: 0, height: 0) internal var isViewRotating = false internal var isViewAppearing = false }
mit
3faf993c01c7e5fc591e07222b3fe702
41.353535
213
0.676008
5.594396
false
false
false
false
MarkQSchultz/NilLiterally
LiterallyNil.playground/Pages/Struct.xcplaygroundpage/Contents.swift
1
357
//: [Next](@next) //: ### Exercise: Custom `struct` struct Thing: NilLiteralConvertible { let a: Int init(a: Int) { self.a = a } internal init(nilLiteral: ()) { self.init(a: 5) } } let t: Thing = Thing(a: 3) let ta = t.a let t2: Thing = nil let ta2 = t2.a //: [Previous](@previous)
mit
75a3ad94bc5f4f7b3542e5783f6a0665
6.595745
37
0.487395
3.1875
false
false
false
false
BlueCocoa/Maria
Maria/MariaUserDefault.swift
1
6246
// // MariaUserDefault.swift // Maria // // Created by ShinCurry on 2016/10/15. // Copyright © 2016年 ShinCurry. All rights reserved. // import Foundation import SwiftyUserDefaults extension DefaultsKeys { // Notification Settings static let enableNotificationWhenStarted = DefaultsKey<Bool>("EnableNotificationWhenStarted") static let enableNotificationWhenStopped = DefaultsKey<Bool>("EnableNotificationWhenStopped") static let enableNotificationWhenPaused = DefaultsKey<Bool>("EnableNotificationWhenPaused") static let enableNotificationWhenCompleted = DefaultsKey<Bool>("EnableNotificationWhenCompleted") static let enableNotificationWhenError = DefaultsKey<Bool>("EnableNotificationWhenError") static let enableNotificationWhenConnected = DefaultsKey<Bool>("EnableNotificationWhenConnected") static let enableNotificationWhenDisconnected = DefaultsKey<Bool>("EnableNotificationWhenDisconnected") // Bandwidth Settings static let enableLowSpeedMode = DefaultsKey<Bool>("EnableLowSpeedMode") static let globalDownloadRate = DefaultsKey<Int>("GlobalDownloadRate") static let globalUploadRate = DefaultsKey<Int>("GlobalUploadRate") static let limitModeDownloadRate = DefaultsKey<Int>("LimitModeDownloadRate") static let limitModeUploadRate = DefaultsKey<Int>("LimitModeUploadRate") // General Settings static let launchAtStartup = DefaultsKey<Bool>("LaunchAtStartup") static let webAppPath = DefaultsKey<String?>("WebAppPath") static let enableSpeedStatusBar = DefaultsKey<Bool>("EnableSpeedStatusBar") static let enableStatusBarMode = DefaultsKey<Bool>("EnableStatusBarMode") // Aria2 Settings static let enableAutoConnectAria2 = DefaultsKey<Bool>("EnableAutoConnectAria2") static let rpcServerHost = DefaultsKey<String?>("RPCServerHost") static let rpcServerUsername = DefaultsKey<String?>("RPCServerUsername") static let rpcServerPassword = DefaultsKey<String?>("RPCServerPassword") static let rpcServerPort = DefaultsKey<String?>("RPCServerPort") static let rpcServerPath = DefaultsKey<String?>("RPCServerPath") static let rpcServerSecret = DefaultsKey<String?>("RPCServerSecret") static let rpcServerEnabledSSL = DefaultsKey<Bool>("RPCServerEnabledSSL") static let enableAria2AutoLaunch = DefaultsKey<Bool>("EnableAria2AutoLaunch") static let aria2ConfPath = DefaultsKey<String?>("Aria2ConfPath") // Today Settings static let todayTasksNumber = DefaultsKey<Int>("TodayTasksNumber") static let todayEnableTasksSortedByProgress = DefaultsKey<Bool>("TodayEnableTasksSortedByProgress") // Main settings static let isNotFirstLaunch = DefaultsKey<Bool>("IsNotFirstLaunch") static let useEmbeddedAria2 = DefaultsKey<Bool>("UseEmbeddedAria2") static let enableYouGet = DefaultsKey<Bool>("EnableYouGet") } class MariaUserDefault { static var main = UserDefaults(suiteName: "group.windisco.maria.main")! static var external = UserDefaults(suiteName: "group.windisco.maria.external")! static var builtIn = UserDefaults(suiteName: "group.windisco.maria.builtin")! static var auto: UserDefaults { get { if MariaUserDefault.main[.useEmbeddedAria2] { return builtIn } else { return external } } } static func initMain() { let defaults = main defaults[.isNotFirstLaunch] = true defaults[.useEmbeddedAria2] = false } static func initExternal() { MariaUserDefault.initShared(defaults: MariaUserDefault.external) let defaults = MariaUserDefault.external defaults[.rpcServerPort] = "6800" defaults[.rpcServerPath] = "/jsonrpc" defaults[.rpcServerSecret] = "" } static func initBuiltIn() { MariaUserDefault.initShared(defaults: MariaUserDefault.builtIn) let defaults = MariaUserDefault.builtIn defaults[.rpcServerPort] = "6789" defaults[.rpcServerPath] = "/jsonrpc" defaults[.rpcServerSecret] = "maria.rpc.2016" } private static func initShared(defaults: UserDefaults) { // Notification Settings defaults[.enableNotificationWhenStarted] = true defaults[.enableNotificationWhenStopped] = false defaults[.enableNotificationWhenPaused] = false defaults[.enableNotificationWhenCompleted] = true defaults[.enableNotificationWhenError] = false defaults[.enableNotificationWhenConnected] = false defaults[.enableNotificationWhenDisconnected] = true // Bandwidth Settings defaults[.enableLowSpeedMode] = false defaults[.globalDownloadRate] = 0 defaults[.globalUploadRate] = 0 defaults[.limitModeDownloadRate] = 0 defaults[.limitModeUploadRate] = 0 // General Settings defaults[.launchAtStartup] = false defaults[.webAppPath] = "" defaults[.enableSpeedStatusBar] = false defaults[.enableStatusBarMode] = false // Aria2 Settings defaults[.enableAutoConnectAria2] = true defaults[.rpcServerHost] = "localhost" defaults[.rpcServerUsername] = "" defaults[.rpcServerPassword] = "" defaults[.rpcServerEnabledSSL] = false defaults[.enableAria2AutoLaunch] = false defaults[.aria2ConfPath] = "" // Today Settings defaults[.todayTasksNumber] = 5 defaults[.todayEnableTasksSortedByProgress] = false defaults[.enableYouGet] = false defaults.synchronize() } static var RPCUrl: String { get { let defaults = MariaUserDefault.auto var url = "http\(defaults[.rpcServerEnabledSSL] ? "s" : "")://" if let value = defaults[.rpcServerHost] { url += value } url += ":" if let value = defaults[.rpcServerPort] { url += value } if let value = defaults[.rpcServerPath] { url += value } return url } } }
gpl-3.0
ddfd9792d9ad8a7d9355f94c50d548f4
38.764331
107
0.677879
4.935178
false
false
false
false
lfaoro/Cast
Cast/UserNotifications.swift
1
3508
// // Created by Leonardo on 29/07/2015. // Copyright © 2015 Leonardo Faoro. All rights reserved. // import Cocoa final class UserNotifications: NSObject { //--------------------------------------------------------------------------- var notificationCenter: NSUserNotificationCenter! var didActivateNotificationURL: NSURL? //--------------------------------------------------------------------------- override init() { super.init() notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() notificationCenter.delegate = self } //--------------------------------------------------------------------------- private func createNotification(title: String, subtitle: String) -> NSUserNotification { let notification = NSUserNotification() notification.title = title notification.subtitle = subtitle notification.informativeText = "Copied to your clipboard" notification.actionButtonTitle = "Open URL" notification.soundName = NSUserNotificationDefaultSoundName return notification } //--------------------------------------------------------------------------- func pushNotification(openURL url: String, title: String = "Casted to gist.GitHub.com") { didActivateNotificationURL = NSURL(string: url)! let notification = self.createNotification(title, subtitle: url) notificationCenter.deliverNotification(notification) startUserNotificationTimer() //IRC: calling from here doesn't work } //--------------------------------------------------------------------------- func pushNotification(error error: String, description: String = "An error occured, please try again.") { let notification = NSUserNotification() notification.title = error notification.informativeText = description notification.soundName = NSUserNotificationDefaultSoundName notification.hasActionButton = false notificationCenter.deliverNotification(notification) startUserNotificationTimer() } //--------------------------------------------------------------------------- private func startUserNotificationTimer() { print(__FUNCTION__) app.timer = NSTimer .scheduledTimerWithTimeInterval( 10.0, target: self, selector: "removeUserNotifcationsAction:", userInfo: nil, repeats: false) } //--------------------------------------------------------------------------- func removeUserNotifcationsAction(timer: NSTimer) { print(__FUNCTION__) notificationCenter.removeAllDeliveredNotifications() timer.invalidate() } //--------------------------------------------------------------------------- } //MARK:- NSUserNotificationCenterDelegate extension UserNotifications: NSUserNotificationCenterDelegate { //--------------------------------------------------------------------------- func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) { print("notification pressed") if let url = didActivateNotificationURL { NSWorkspace.sharedWorkspace().openURL(url) } else { center.removeAllDeliveredNotifications() } } // executes an action whenever the notification is pressed //--------------------------------------------------------------------------- func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } // forces the notification to display even when app is active app //--------------------------------------------------------------------------- }
mit
f3a3a2cc239b726bb70ff07146ea31d5
40.75
90
0.5931
5.864548
false
false
false
false
RobotsAndPencils/Scythe
Dependencies/HarvestKit-Swift/HarvestKit-Shared/ClientsController.swift
1
8775
// // ClientController.swift // HarvestKit // // Created by Matthew Cheetham on 06/05/2016. // Copyright © 2016 Matt Cheetham. All rights reserved. // import Foundation #if os(iOS) import ThunderRequest #elseif os(tvOS) import ThunderRequestTV #elseif os (OSX) import ThunderRequestMac #endif /** The client controller is responsible for adding, deleting and updating client information with the Harvest API. This controller will only work if your account has the client module enabled */ public final class ClientsController { /** The request controller used to load contact information. This is shared with other controllers */ let requestController: TSCRequestController /** Initialises a new controller. - parameter requestController: The request controller to use when loading client information. This must be passed down from HarvestController so that authentication may be shared */ internal init(requestController: TSCRequestController) { self.requestController = requestController } //MARK - Creating Clients /** Creates a new client entry in the Harvest system. You may configure any of the parameters on the contact object you are creating and they will be saved. - parameter client: The new client object to send to the API - parameter completion: The completion handler to return any errors to - requires: `name` on the client object as a minimum */ public func create(_ client: Client, completion: @escaping (_ error: Error?) -> ()) { guard let _ = client.name else { completion(ClientError.missingName) return } requestController.post("clients", bodyParams: client.serialisedObject) { (response: TSCRequestResponse?, error: Error?) in if let _error = error { completion(_error) return } if let responseStatus = response?.status, responseStatus == 201 { completion(nil) return } completion(ClientError.unexpectedResponseCode) } } //MARK - Requesting Clients /** Requests a specific client from the API by identifier - parameter clientIdentifier: The identifier of the client to look up in the system */ public func get(_ clientIdentifier: Int, completion: @escaping (_ client: Client?, _ error: Error?) -> ()) { requestController.get("clients/\(clientIdentifier)") { (response: TSCRequestResponse?, error: Error?) in if let _error = error { completion(nil, _error) return } if let responseDictionary = response?.dictionary as? [String: AnyObject] { let returnedClient = Client(dictionary: responseDictionary) completion(returnedClient, nil) return } completion(nil, ClientError.malformedData) } } /** Requests all clients in the system for this company - parameter completion: A closure to call with an optional array of `clients` and an optional `error` */ public func getClients(_ completion: @escaping (_ clients: [Client]?, _ error: Error?) -> ()) { requestController.get("clients") { (response: TSCRequestResponse?, error: Error?) in if let _error = error { completion(nil, _error) return } if let responseArray = response?.array as? [[String: AnyObject]] { let returnedClients = responseArray.flatMap({Client(dictionary: $0)}) completion(returnedClients, nil) return } completion(nil, ClientError.malformedData) } } //MARK - Modifying Clients /** Updates a client in the API. Any properties set on the client object will be sent to the server in an attempt to overwrite them. Not all properties are modifyable but Harvest does not make it clear which are so for now it will attempt all of them - parameter client: The client object to update - parameter completion: The closure to call to return any errors to or indicate success - requires: `identifier` on the client object as a minimum */ public func update(_ client: Client, completion: @escaping (_ error: Error?) -> ()) { guard let clientIdentifier = client.identifier else { completion(ClientError.missingIdentifier) return } requestController.put("clients/\(clientIdentifier)", bodyParams: client.serialisedObject) { (response: TSCRequestResponse?, error: Error?) in if let _error = error { completion(_error) return } if let responseStatus = response?.status, responseStatus == 200 { completion(nil) return } completion(ClientError.unexpectedResponseCode) } } /** Deletes a client from the Harvest API. - parameter client: The client to delete in the API - parameter completion: The closure to call with potential errors - requires: `identifier` on the client object as a minimum - note: You will not be able to delete a client if they have assosciated projects or invoices */ public func delete(_ client: Client, completion: @escaping (_ error: Error?) -> ()) { guard let clientIdentifier = client.identifier else { completion(ClientError.missingIdentifier) return } requestController.delete("clients/\(clientIdentifier)") { (response: TSCRequestResponse?, error: Error?) in if let _error = error { if let responseStatus = response?.status, responseStatus == 400 { completion(ClientError.hasProjectsOrInvoices) return } completion(_error) return } if let responseStatus = response?.status, responseStatus == 200 { completion(nil) return } completion(ClientError.unexpectedResponseCode) } } /** Toggles the active status of a client. - parameter client: The client to toggle the active status of in the API - parameter completion: The closure to call with potential errors - requires: `identifier` on the client object as a minimum - note: You will not be able to toggle a client if they have active projects */ public func toggle(_ client: Client, completion: @escaping (_ error: Error?) -> ()) { guard let clientIdentifier = client.identifier else { completion(ClientError.missingIdentifier) return } requestController.post("clients/\(clientIdentifier)/toggle", bodyParams: nil) { (response: TSCRequestResponse?, error: Error?) in if let _error = error { if let responseStatus = response?.status, responseStatus == 400 { completion(ClientError.hasActiveProjects) return } completion(_error) return } if let responseStatus = response?.status, responseStatus == 200 { completion(nil) return } completion(ClientError.unexpectedResponseCode) } } } /** An enum detailing the errors possible when dealing with client data */ enum ClientError: Error { /** The data we got back from the server was not suitable to be converted into a client object */ case malformedData /** The client object given did not have a name set so could not be saved */ case missingName /** The client object given did not have an identifier so cannot be updated in the system */ case missingIdentifier /** We got an unexpected response */ case unexpectedResponseCode /** The client has assosciated projects or invoices and cannot be deleted */ case hasProjectsOrInvoices /** The client has active projects and cannot be disabled */ case hasActiveProjects }
mit
34b907e1cae0f94cd69c5ab44b1bd662
34.959016
251
0.588899
5.627967
false
false
false
false
Sidetalker/TapMonkeys
TapMonkeys/TapMonkeys/TabBarController.swift
1
13283
// // TabBarController.swift // TapMonkeys // // Created by Kevin Sullivan on 5/8/15. // Copyright (c) 2015 Kevin Sullivan. All rights reserved. // import UIKit class TabBarController: UITabBarController, UITabBarControllerDelegate, DataHeaderDelegate { var allViews: [AnyObject]? var defaults: NSUserDefaults! var monkeyTimer = NSTimer() var incomeTimer = NSTimer() var lettersPerBuffer: Float = 0 var individualLettersBuffer = [Float]() var incomePerBuffer: Float = 0 var individualIncomeBuffer = [Float]() var saveData = SaveData() override func viewDidLoad() { super.viewDidLoad() initializeFormatters() loadSave() loadMonkeys(saveData) loadWritings(saveData) loadIncome(saveData) registerForUpdates() updateMonkeyProduction() configureView() } override func viewDidLayoutSubviews() { initializeHeaders() } func toggleLight(sender: DataHeader) { saveData.nightMode! = !saveData.nightMode! self.tabBar.barStyle = saveData.nightMode! ? UIBarStyle.Black : UIBarStyle.Default self.tabBar.tintColor = saveData.nightMode! ? UIColor.darkGrayColor() : UIColor.blackColor() if allViews == nil { return } for view in allViews! { if let tapView = view as? TapViewController { tapView.toggleNightMode(saveData.nightMode!) if tapView.dataHeader == nil { return } tapView.dataHeader.update(saveData, animated: false) } if let monkeyView = view as? MonkeyViewController { monkeyView.toggleNightMode(saveData.nightMode!) if monkeyView.dataHeader == nil { return } monkeyView.dataHeader.update(saveData, animated: false) monkeyView.dataHeader.delegate = self } if let writingView = view as? WritingViewController { writingView.toggleNightMode(saveData.nightMode!) if writingView.dataHeader == nil { return } writingView.dataHeader.update(saveData, animated: false) writingView.dataHeader.delegate = self } if let incomeView = view as? IncomeViewController { incomeView.toggleNightMode(saveData.nightMode!) if incomeView.dataHeader == nil { return } incomeView.dataHeader.update(saveData, animated: false) incomeView.dataHeader.delegate = self } if let upgradesView = view as? UpgradesViewController { if upgradesView.dataHeader == nil { return } upgradesView.dataHeader.update(saveData, animated: false) upgradesView.dataHeader.delegate = self } } } func initializeHeaders() { if allViews == nil { return } let letters = defaults.integerForKey("letters") let money = defaults.floatForKey("money") let stage = defaults.integerForKey("stage") if stage >= 2 { self.setTabBarVisible(true, animated: true) } self.tabBar.barStyle = saveData.nightMode! ? UIBarStyle.Black : UIBarStyle.Default self.tabBar.tintColor = saveData.nightMode! ? UIColor.darkGrayColor() : UIColor.blackColor() self.tabBar.translucent = false for view in allViews! { if let tapView = view as? TapViewController { tapView.toggleNightMode(saveData.nightMode!) if tapView.dataHeader == nil { return } tapView.dataHeader.delegate = self tapView.dataHeader.nightMode = saveData.nightMode! tapView.dataHeader.update(saveData, animated: false) } if let monkeyView = view as? MonkeyViewController { monkeyView.toggleNightMode(saveData.nightMode!) if monkeyView.dataHeader == nil { return } monkeyView.dataHeader.update(saveData, animated: false) monkeyView.dataHeader.delegate = self monkeyView.dataHeader.nightMode = saveData.nightMode! } if let writingView = view as? WritingViewController { writingView.toggleNightMode(saveData.nightMode!) if writingView.dataHeader == nil { return } writingView.dataHeader.update(saveData, animated: false) writingView.dataHeader.delegate = self writingView.dataHeader.nightMode = saveData.nightMode! } if let incomeView = view as? IncomeViewController { incomeView.toggleNightMode(saveData.nightMode!) if incomeView.dataHeader == nil { return } incomeView.dataHeader.update(saveData, animated: false) incomeView.dataHeader.delegate = self incomeView.dataHeader.nightMode = saveData.nightMode! } if let upgradesView = view as? UpgradesViewController { if upgradesView.dataHeader == nil { return } upgradesView.dataHeader.update(saveData, animated: false) upgradesView.dataHeader.delegate = self upgradesView.dataHeader.nightMode = saveData.nightMode! } } } func revealTab(index: Int) { self.viewControllers = [AnyObject]() for i in 0...index { self.viewControllers?.append(allViews![i]) } } func updateMonkeyProduction() { monkeyTimer.invalidate() incomeTimer.invalidate() let monkeyInterval: Float = 0.1 let incomeInterval: Float = 0.1 lettersPerBuffer = fullLettersPer(monkeyInterval) individualLettersBuffer = individualLettersPer(monkeyInterval) incomePerBuffer = fullIncomePer(incomeInterval) individualIncomeBuffer = individualIncomePer(incomeInterval) monkeyTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(monkeyInterval), target: self, selector: Selector("getMonkeyLetters"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(monkeyTimer, forMode: NSRunLoopCommonModes) incomeTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(incomeInterval), target: self, selector: Selector("getIncome"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(incomeTimer, forMode: NSRunLoopCommonModes) } func getMonkeyLetters() { for i in 0...count(monkeys) - 1 { monkeys[i].totalProduced += individualLettersBuffer[i] saveData.monkeyTotals![i] += individualLettersBuffer[i] } let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("updateHeaders", object: self, userInfo: [ "letters" : lettersPerBuffer, "animated" : false ]) } func getIncome() { for i in 0...count(incomes) - 1 { incomes[i].totalProduced += individualIncomeBuffer[i] saveData.incomeTotals![i] += individualIncomeBuffer[i] } let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("updateHeaders", object: self, userInfo: [ "money" : incomePerBuffer, "animated" : false ]) } func loadSave() { saveData = readDefaults() saveData = validate(saveData) NSUserDefaults.standardUserDefaults().synchronize() } func registerForUpdates() { self.delegate = self defaults = NSUserDefaults.standardUserDefaults() NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateSave:", name: "updateSave", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateHeaders:", name: "updateHeaders", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateMonkeyProduction", name: "updateMonkeyProduction", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateIncomeProduction", name: "updateIncomeProduction", object: nil) } func updateSave(notification: NSNotification) { let userInfo = notification.userInfo as! [String : AnyObject] if let encodedSave = userInfo["saveData"] as? NSData { var newSave = SaveData() encodedSave.getBytes(&newSave, length: sizeof(SaveData)) saveData = newSave save(self, saveData) } } func updateHeaders(notification: NSNotification) { if allViews == nil { return } let userInfo = notification.userInfo as! [String : AnyObject] if let letters = userInfo["letters"] as? Float { saveData.letters! += letters } if let money = userInfo["money"] as? Float { saveData.money! += money } if let animated = userInfo["animated"] as? Bool { for view in allViews! { if let tapView = view as? TapViewController, header = tapView.dataHeader { header.update(saveData, animated: animated) } if let monkeyView = view as? MonkeyViewController, header = monkeyView.dataHeader, table = monkeyView.monkeyTable { header.update(saveData, animated: animated) if self.selectedIndex != 1 { table.tableView.reloadData() } } if let writingView = view as? WritingViewController, header = writingView.dataHeader, table = writingView.writingTable { header.update(saveData, animated: animated) if self.selectedIndex != 2 { table.tableView.reloadData() } } if let incomeView = view as? IncomeViewController, header = incomeView.dataHeader, table = incomeView.incomeTable { header.update(saveData, animated: animated) if self.selectedIndex != 3 { table.tableView.reloadData() } } if let incomeView = view as? UpgradesViewController, header = incomeView.dataHeader // table = incomeView.incomeTable { header.update(saveData, animated: animated) // if self.selectedIndex != 3 { table.tableView.reloadData() } } } } save(self, saveData) } func configureView() { allViews = self.viewControllers self.setViewControllers([allViews![0], allViews![1]], animated: false) self.setTabBarVisible(false, animated: false) if saveData.stage <= 2 { self.setTabBarVisible(false, animated: false) } else { self.setTabBarVisible(true, animated: false) } if saveData.stage == 3 { revealTab(2) } else if saveData.stage == 4 || saveData.stage == 5 { revealTab(3) } } func setTabBarVisible(visible: Bool, animated: Bool) { if (tabBarIsVisible() == visible) { return } let screenRect = UIScreen.mainScreen().bounds UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animated ? 0.6 : 0.0) var height = screenRect.height if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation)) { height = screenRect.size.width } if visible { height -= self.tabBar.frame.height } self.tabBar.frame = CGRect(x: self.tabBar.frame.origin.x, y: height, width: self.tabBar.frame.width, height: self.tabBar.frame.height) UIView.commitAnimations() } func tabBarIsVisible() -> Bool { return self.tabBar.frame.origin.y != CGRectGetMaxY(self.view.frame) } func tabBarHeight() -> CGFloat { return self.tabBar.bounds.size.height } func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { initializeHeaders() return true } }
mit
dbb17615c69578ee3e225e0b4001080a
36.525424
176
0.568923
5.388641
false
false
false
false
OEASLAN/LetsEat
IOS/Let's Eat/Let's Eat/Swift Files/Alerts.swift
1
3773
// // Errors.swift // Let's Eat // // Created by Vidal_HARA on 17.03.2015. // Copyright (c) 2015 vidal hara S002866. All rights reserved. // import UIKit class Alerts { func getSuccesError(jsonData: NSDictionary, str: NSString, vc: UIViewController){ var error_msg:NSString if jsonData["message"] as? NSString != nil { error_msg = jsonData["message"] as! NSString } else { error_msg = "Unknown Error" } var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = error_msg as String alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func getStatusCodeError(str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "Connection Failed" alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func getUrlDataError(reponseError: NSError?, str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func loginError(vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Your username or password is incorrect" alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func getSuccesLogoutAleart(jsonData: NSDictionary, vc: UIViewController){ var message:NSString if jsonData["message"] as? NSString != nil { message = jsonData["message"] as! NSString } else { message = "You logout successfuly" } var alertView:UIAlertView = UIAlertView() alertView.title = "Perfect!" alertView.message = message as String alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func emptyFieldError(str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "Please fill empty fields" alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func confirmError(str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "Passwords doesn't Match!" alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func unValidEmailError(str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "E-mail is not valid! \nPlease check your e-mail." alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } func unValidPasswordError(str: NSString, vc: UIViewController){ var alertView:UIAlertView = UIAlertView() alertView.title = str as String alertView.message = "Your password needs minimum 6 characters and at least one upper case character, one lower case character and one numeric character" alertView.delegate = vc alertView.addButtonWithTitle("OK") alertView.show() } }
gpl-2.0
63db045efd9ddb5cda0c8d0e4f12e992
31.25641
160
0.629473
4.997351
false
false
false
false
rc2server/appserver
Sources/appcore/ModelHandler.swift
1
4832
// // ModelHandler.swift // // Copyright ©2017 Mark Lilback. This file is licensed under the ISC license. // import Foundation import Kitura import Rc2Model import servermodel import Logging import Zip class ModelHandler: BaseHandler { let logger = Logger(label: "rc2.ModelHandler") private enum Errors: Error { case unzipError } override func addRoutes(router: Router) { let prefix = settings.config.urlPrefixToIgnore router.post("\(prefix)/proj/:projId/wspace", middleware: BodyParser()) router.post("\(prefix)/proj/:projId/wspace") { [weak self] request, response, next in self?.createWorkspace(request: request, response: response, next: next) } router.delete("\(prefix)/proj/:projId/wspace/:wspaceId") { [weak self] request, response, next in self?.deleteWorkspace(request: request, response: response, next: next) } } /// handles a request to delete a workspace /// returns updated BulkInfo func deleteWorkspace(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { do { guard let user = request.user, let projectIdStr = request.parameters["projId"], let projectId = Int(projectIdStr), let wspaceIdStr = request.parameters["wspaceId"], let wspaceId = Int(wspaceIdStr), let project = try settings.dao.getProject(id: projectId), let _ = try settings.dao.getWorkspace(id: wspaceId), project.userId == user.id else { try handle(error: SessionError.invalidRequest, response: response) return } // can't delete last workspace if try settings.dao.getWorkspaces(project: project).count < 2 { try handle(error: .permissionDenied, response: response) return } try settings.dao.delete(workspaceId: wspaceId) let bulkInfo = try settings.dao.getUserInfo(user: user) response.send(bulkInfo) } catch { print("delete failed: \(error)") response.status(.notFound) } next() } // return bulk info for logged in user func createWorkspace(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { do { guard let user = request.user, let projectIdStr = request.parameters["projId"], let projectId = Int(projectIdStr), let wspaceName = request.headers["Rc2-WorkspaceName"], wspaceName.count > 1, let project = try settings.dao.getProject(id: projectId), project.userId == user.id else { try handle(error: SessionError.invalidRequest, response: response) return } let wspaces = try settings.dao.getWorkspaces(project: project) guard wspaces.filter({ $0.name == wspaceName }).count == 0 else { try handle(error: SessionError.duplicate, response: response) return } var zipUrl: URL? // will be set to the folder of uncompressed files for later deletion var fileUrls: [URL]? // urls of the files in the zipUrl if let zipFile = request.body?.asRaw { // write to file if let uploadUrl = try unpackFiles(zipData: zipFile) { zipUrl = uploadUrl // used to use options [.skipsHiddenFiles, .skipsSubdirectoryDescendants]. but the first isn't implemented in linux 4.0.2, and the second is the default behavior fileUrls = try FileManager.default.contentsOfDirectory(at: uploadUrl, includingPropertiesForKeys: nil) // filter out hidden files fileUrls = fileUrls!.filter { !$0.lastPathComponent.hasPrefix(".") } } } defer { if let zipUrl = zipUrl { try? FileManager.default.removeItem(at: zipUrl) } } let wspace = try settings.dao.createWorkspace(project: project, name: wspaceName, insertingFiles: fileUrls) let bulkInfo = try settings.dao.getUserInfo(user: user) let result = CreateWorkspaceResult(wspaceId: wspace.id, bulkInfo: bulkInfo) response.send(result) response.status(.created) } catch { logger.warning("error creating workspace with files: \(error)") response.status(.internalServerError) } next() } func unpackFiles(zipData: Data) throws -> URL? { do { let tmpDirStr = NSTemporaryDirectory() let topTmpDir = URL(fileURLWithPath: tmpDirStr, isDirectory: true) let fm = FileManager() // write incoming data to zip file that will be removed let zipTmp = topTmpDir.appendingPathComponent(UUID().uuidString).appendingPathExtension("zip") try zipData.write(to: zipTmp) defer { try? fm.removeItem(at: zipTmp) } //create directory to expand zip into let tmpDir = topTmpDir.appendingPathComponent(UUID().uuidString, isDirectory: true) try fm.createDirectory(at: tmpDir, withIntermediateDirectories: true, attributes: nil) try Zip.unzipFile(zipTmp, destination: tmpDir, overwrite: true, password: nil) // try fm.unzipItem(at: zipTmp, to: tmpDir) try? fm.removeItem(at: zipTmp) return tmpDir } catch { logger.warning("error upacking zip file: \(error)") throw Errors.unzipError } } }
isc
515590ed6f57719afb92c771c73ef057
35.877863
166
0.713103
3.629602
false
false
false
false
pacient/TVM
TVM/FavouritesViewController.swift
1
6406
// // FavouritesViewController.swift // TVM // // Created by Vasil Nunev on 02/04/2017. // Copyright © 2017 nunev. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import UserNotifications class FavouritesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{ @IBOutlet weak var searchbar: UISearchBar! @IBOutlet weak var tableview: UITableView! var storedShows = [Show]() var shows = [Show]() override func viewDidLoad() { super.viewDidLoad() searchbar.delegate = self let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(retrieveFavourites), for: .valueChanged) self.tableview.refreshControl = refreshControl } override func viewWillAppear(_ animated: Bool) { retrieveFavourites() } func retrieveFavourites() { let shows = UserDefaults.standard.array(forKey: "storedShows") as? [String] ?? [] if shows.count > 0 { storedShows.removeAll() for each in shows { Alamofire.request("http://api.tvmaze.com/shows/\(each)").responseJSON(completionHandler: { (response) in if let json = response.result.value { let data = JSON(json).dictionary let showObject = Show(dictionary: data!) if let nextURL = showObject?.nextEpURL { Alamofire.request(nextURL).responseJSON(completionHandler: { (res) in if let json = res.result.value, let data = JSON(json).dictionary { showObject?.dateForNotification = data["airdate"]!.string let arr = data["airdate"]!.string!.components(separatedBy: "-") let dateStr = "\(arr[2])/\(arr[1])/\(arr[0])" showObject?.nextEpDate = "\(dateStr) \(data["airtime"]!.stringValue)" self.scheduleNotification(for: showObject!) self.tableview.reloadData() } }) }else { showObject?.nextEpDate = "No info available" } self.storedShows.append(showObject!) self.storedShows.sort {$0.name < $1.name} self.shows = self.storedShows } self.tableview.setContentOffset(CGPoint.zero, animated: true) }) } self.tableview.refreshControl?.endRefreshing() } } func scheduleNotification(for show: Show) { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [show.name]) let content = UNMutableNotificationContent() content.body = "New \(show.name) episode is coming out today!" content.badge = 1 let dateFromatter = DateFormatter() dateFromatter.dateFormat = "yyyy-MM-dd" let dateToFire = dateFromatter.date(from: show.dateForNotification!) var dateComponents = Calendar.current.dateComponents([.year,.month,.day], from: dateToFire!) dateComponents.hour = 10 dateComponents.minute = 00 dateComponents.second = 00 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) let request = UNNotificationRequest(identifier: show.name, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error) in if let error = error { print(error.localizedDescription) } } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shows.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "showCell") as! ShowCell cell.showName.text = shows[indexPath.row].name cell.showDays.text = shows[indexPath.row].days.joined(separator: ", ") cell.nextEpDate.text = shows[indexPath.row].nextEpDate switch shows[indexPath.row].status { case .Finished: cell.statusView.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) case .Running: cell.statusView.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1) case .TBD: cell.statusView.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1) case .Unknown,.InDev: cell.statusView.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) } cell.showImage.downloadImage(from: shows[indexPath.row].imageURL) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "showDetails") as! ShowDetailsViewController vc.show = shows[indexPath.row] searchbar.endEditing(true) tableview.deselectRow(at: indexPath, animated: true) self.present(vc, animated: false, completion: nil) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let query = searchText.lowercased() let queryShows = storedShows.filter { (show) -> Bool in return show.name.lowercased().contains(query) } shows = query != "" ? queryShows : storedShows self.tableview.reloadData() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.searchbar.endEditing(true) } }
mit
66535ad311f5fa6f372c3c5d4eba06fc
43.479167
148
0.608587
5
false
false
false
false
matsune/YMCalendar
YMCalendar/Month/YMCalendarView.swift
1
25307
// // YMCalendarView.swift // YMCalendar // // Created by Yuma Matsune on 2017/02/21. // Copyright © 2017年 Yuma Matsune. All rights reserved. // import Foundation import UIKit final public class YMCalendarView: UIView, YMCalendarAppearance { private lazy var collectionView: UICollectionView = createCollectionView() private var reuseQueue = ReusableObjectQueue() private lazy var layout: YMCalendarLayout = { let calendarLayout = YMCalendarLayout() calendarLayout.dataSource = self return calendarLayout }() public weak var appearance: YMCalendarAppearance? public weak var delegate: YMCalendarDelegate? public weak var dataSource: YMCalendarDataSource? public var calendar = Calendar.current { didSet { reload() } } override public var backgroundColor: UIColor? { didSet { collectionView.backgroundColor = backgroundColor } } private var gradientLayer = CAGradientLayer() public var gradientColors: [UIColor]? { didSet { if let colors = gradientColors { gradientLayer.colors = colors.map {$0.cgColor} } else { gradientLayer.colors = nil } } } public var gradientLocations: [NSNumber]? { set { gradientLayer.locations = newValue } get { return gradientLayer.locations } } public var gradientStartPoint: CGPoint { set { gradientLayer.startPoint = newValue } get { return gradientLayer.startPoint } } public var gradientEndPoint: CGPoint { set { gradientLayer.endPoint = newValue } get { return gradientLayer.endPoint } } public var allowsMultipleSelection: Bool { get { return collectionView.allowsMultipleSelection } set { collectionView.allowsMultipleSelection = newValue } } public var allowsSelection: Bool { get { return collectionView.allowsSelection } set { collectionView.allowsSelection = newValue } } public var isPagingEnabled: Bool { get { return collectionView.isPagingEnabled } set { collectionView.isPagingEnabled = newValue } } public var scrollDirection: YMScrollDirection = .vertical { didSet { layout.scrollDirection = scrollDirection layout.invalidateLayout() } } public var decelerationRate: YMDecelerationRate = .normal { didSet { collectionView.decelerationRate = UIScrollView.DecelerationRate(rawValue: decelerationRate.value) } } public var dayLabelHeight: CGFloat = 18 { didSet { layout.dayHeaderHeight = dayLabelHeight collectionView.reloadData() } } public var monthRange: MonthRange? { didSet { if let range = monthRange { startDate = range.start } else { startDate = monthDate(from: Date()) } } } private var selectedIndexes: [IndexPath] = [] /// Height of event items in EventsRow. Default value is 16. public var eventViewHeight: CGFloat = 16 /// Number of visble events in a week row. /// If value is nil, events can be displayed by scroll. public var maxVisibleEvents: Int? /// Cache of EventsRowViews. EventsRowView belongs to MonthWeekView and /// has events(UIViews) for a week. This dictionary has start of week /// as key and events as value. fileprivate var eventRowsCache = IndexableDictionary<Date, YMEventsRowView>() /// Capacity of eventRowsCache. fileprivate let rowCacheSize = 40 private var maxStartDate: MonthDate? { guard let range = monthRange else { return nil } return max(range.end.add(month: -numberOfLoadedMonths), range.start) } private func dateFrom(monthDate: MonthDate) -> Date { return calendar.date(from: monthDate) } private func monthDate(from date: Date) -> MonthDate { return calendar.monthDate(from: date) } private lazy var startDate = self.monthDate(from: Date()) public var visibleMonths: [MonthDate] { var res: [MonthDate] = [] if let first = collectionView.indexPathsForVisibleItems.first { res.append(monthDate(from: dateAt(first))) } if let last = collectionView.indexPathsForVisibleItems.last { let month = monthDate(from: dateAt(last)) if !res.contains(month) { res.append(month) } } return res } public var visibleDays: DateRange? { guard let first = collectionView.indexPathsForVisibleItems.lazy.sorted().first, let last = collectionView.indexPathsForVisibleItems.lazy.sorted().last else { return nil } return DateRange(start: dateAt(first), end: dateAt(last)) } public var selectAnimation: YMSelectAnimation = .bounce public var deselectAnimation: YMSelectAnimation = .fade private var selectedEventDate: Date? private var selectedEventIndex: Int = 0 private var displayingMonthDate: Date = Date() private var numberOfLoadedMonths: Int { if let range = monthRange { return min(range.start.monthDiff(with: range.end), 9) } return 9 } // MARK: - Initialize override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = .white addSubview(collectionView) } private func createCollectionView() -> UICollectionView { collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.bounces = false collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.allowsMultipleSelection = false collectionView.backgroundView = UIView() collectionView.backgroundView?.layer.insertSublayer(gradientLayer, at: 0) collectionView.ym.register(YMMonthDayCollectionCell.self) collectionView.ym.register(YMMonthBackgroundView.self) collectionView.ym.register(YMMonthWeekView.self) return collectionView } // MARK: - Layout override public func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds gradientLayer.frame = bounds recenterIfNeeded() } } extension YMCalendarView { // MARK: - Utils private func dateAt(_ indexPath: IndexPath) -> Date { var comp = DateComponents() comp.month = indexPath.section comp.day = indexPath.row return calendar.date(byAdding: comp, to: dateFrom(monthDate: startDate))! } private func indexPathForDate(_ date: Date) -> IndexPath? { if let range = monthRange { guard range.contains(monthDate(from: date)) else { return nil } } let comps = calendar.dateComponents([.month, .day], from: dateFrom(monthDate: startDate), to: date) guard let day = comps.day, let month = comps.month else { return nil } return IndexPath(item: day, section: month) } private func startDayAtMonth(in section: Int) -> Date { return dateAt(IndexPath(item: 0, section: section)) } private func column(at indexPath: IndexPath) -> Int { let weekday = calendar.component(.weekday, from: dateAt(indexPath)) return (weekday + 7 - calendar.firstWeekday) % 7 } private func dateRangeOf(rowView: YMEventsRowView) -> DateRange? { guard let start = calendar.date(byAdding: .day, value: rowView.daysRange.location, to: rowView.monthStart), let end = calendar.date(byAdding: .day, value: NSMaxRange(rowView.daysRange), to: rowView.monthStart) else { return nil } return DateRange(start: start, end: end) } public func reload() { clearRowsCacheIn(range: nil) collectionView.reloadData() } } extension YMCalendarView { // MARK: - Public public func registerClass(_ objectClass: ReusableObject.Type, forEventCellReuseIdentifier identifier: String) { reuseQueue.registerClass(objectClass, forObjectWithReuseIdentifier: identifier) } public func dequeueReusableCellWithIdentifier<T: YMEventView>(_ identifier: String, forEventAtIndex index: Int, date: Date) -> T? { guard let cell = reuseQueue.dequeueReusableObjectWithIdentifier(identifier) as? T? else { return nil } if let selectedDate = selectedEventDate, calendar.isDate(selectedDate, inSameDayAs: date) && index == selectedEventIndex { cell?.selected = true } return cell } public func reloadEvents() { eventRowsCache.forEach { $0.value.reload() } } public func reloadEventsAtDate(_ date: Date) { eventRowsCache.first(where: { $0.key == date })?.value.reload() } public func reloadEventsInRange(_ range: DateRange) { eventRowsCache .filter { dateRangeOf(rowView: $0.value)?.intersectsDateRange(range) ?? false }.forEach { $0.value.reload() } } public func reloadEvents(in monthDate: MonthDate) { eventRowsCache .filter { self.monthDate(from: $0.key) == monthDate } .forEach { $0.value.reload() } } public var visibleEventViews: [UIView] { return visibleEventRows.flatMap { $0.viewsInRect($0.convert(bounds, to: self)) } } public func eventViewForEventAtIndex(_ index: Int, date: Date) -> UIView? { for rowView in visibleEventRows { guard let day = calendar.dateComponents([.day], from: rowView.monthStart, to: date).day else { return nil } if NSLocationInRange(day, rowView.daysRange) { return rowView.eventView(at: IndexPath(item: index, section: day)) } } return nil } public func eventCellAtPoint(_ pt: CGPoint, date: inout Date, index: inout Int) -> UIView? { for rowView in visibleEventRows { let ptInRow = rowView.convert(pt, from: self) if let path = rowView.indexPathForCellAtPoint(ptInRow) { var comps = DateComponents() comps.day = path.section date = calendar.date(byAdding: comps, to: rowView.monthStart)! index = path.item return rowView.eventView(at: path) } } return nil } } extension YMCalendarView { // MARK: - Scrolling public func scrollToDate(_ date: Date, animated: Bool) { let month = monthDate(from: date) if let range = monthRange, !range.contains(month) { return } let offset = offsetForMonth(month) if scrollDirection == .vertical { collectionView.setContentOffset(CGPoint(x: 0, y: offset), animated: animated) } else { collectionView.setContentOffset(CGPoint(x: offset, y: 0), animated: animated) } delegate?.calendarViewDidScroll?(self) } private func offsetForMonth(_ monthDate: MonthDate) -> CGFloat { let diff = startDate.monthDiff(with: monthDate) let size = scrollDirection == .vertical ? bounds.height : bounds.width return size * CGFloat(diff) } private func monthFromOffset(_ offset: CGFloat) -> MonthDate { var month = startDate if scrollDirection == .vertical { let height = bounds.height var y = offset > 0 ? height : 0 while y < abs(offset) { month = month.add(month: offset > 0 ? 1 : -1) y += height } } else { let width = bounds.width var x = offset > 0 ? width : 0 while x < abs(offset) { month = month.add(month: offset > 0 ? 1 : -1) x += width } } return month } private func adjustStartDateToCenter(date: MonthDate) -> Int { let offset = (numberOfLoadedMonths - 1) / 2 let start = date.add(month: -offset) var s = start if let range = monthRange, let maxStartDate = maxStartDate { // monthRange.start <= start <= maxStartDate if start < range.start { s = range.start } else if start > maxStartDate { s = maxStartDate } } let diff = startDate.monthDiff(with: s) self.startDate = s return diff } private func recenterIfNeeded() { let offset, content, bounds, boundsMax: CGFloat switch scrollDirection { case .vertical: offset = max(collectionView.contentOffset.y, 0) content = collectionView.contentSize.height bounds = collectionView.bounds.height boundsMax = collectionView.bounds.maxY case .horizontal: offset = max(collectionView.contentOffset.x, 0) content = collectionView.contentSize.width bounds = collectionView.bounds.width boundsMax = collectionView.bounds.maxX } guard content > 0 else { return } if offset < bounds || boundsMax + bounds > content { let oldStart = startDate let centerMonth = monthFromOffset(offset) let monthOffset = adjustStartDateToCenter(date: centerMonth) if monthOffset != 0 { let k = offsetForMonth(oldStart) collectionView.reloadData() var contentOffset = collectionView.contentOffset switch scrollDirection { case .vertical: contentOffset.y = k + offset case .horizontal: contentOffset.x = k + offset } collectionView.contentOffset = contentOffset } } } } extension YMCalendarView { // MARK: - Rows Handling private func removeRowCache(at date: Date) { eventRowsCache.removeValue(forKey: date) } private var visibleEventRows: [YMEventsRowView] { guard let visibleRange = visibleDays else { return [] } return eventRowsCache .filter { visibleRange.contains(date: $0.key) }.map { $0.value } } private func clearRowsCacheIn(range: DateRange?) { if let range = range { eventRowsCache .filter { range.contains(date: $0.key) } .forEach { removeRowCache(at: $0.key) } } else { eventRowsCache.forEach { removeRowCache(at: $0.key) } } } private func eventsRowView(at rowStart: Date) -> YMEventsRowView { var eventsRowView = eventRowsCache.value(forKey: rowStart) if eventsRowView == nil { eventsRowView = YMEventsRowView() let startOfMonth = calendar.startOfMonthForDate(rowStart) let first = calendar.dateComponents([.day], from: startOfMonth, to: rowStart).day if let range = calendar.range(of: .day, in: .weekOfMonth, for: rowStart) { let numDays = range.upperBound - range.lowerBound eventsRowView?.monthStart = startOfMonth eventsRowView?.maxVisibleLines = maxVisibleEvents eventsRowView?.itemHeight = eventViewHeight eventsRowView?.eventsRowDelegate = self eventsRowView?.daysRange = NSRange(location: first!, length: numDays) eventsRowView?.dayWidth = bounds.width / 7 eventsRowView?.reload() } cacheRow(eventsRowView!, forDate: rowStart) } return eventsRowView! } private func cacheRow(_ eventsView: YMEventsRowView, forDate date: Date) { eventRowsCache.updateValue(eventsView, forKey: date) if eventRowsCache.count >= rowCacheSize { if let first = eventRowsCache.first?.0 { removeRowCache(at: first) } } } private func monthRowView(at indexPath: IndexPath) -> YMMonthWeekView { var weekView: YMMonthWeekView! while true { let v = collectionView.ym.dequeue(YMMonthWeekView.self, for: indexPath) if !visibleEventRows.contains(v.eventsView) { weekView = v break } } weekView.eventsView = eventsRowView(at: dateAt(indexPath)) return weekView } } extension YMCalendarView: UICollectionViewDataSource { // MARK: - UICollectionViewDataSource public func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfLoadedMonths } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let startDay = startDayAtMonth(in: section) return calendar.numberOfDaysInMonth(date: startDay) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let appearance = self.appearance ?? self let cell = collectionView.ym.dequeue(YMMonthDayCollectionCell.self, for: indexPath) let date = dateAt(indexPath) let font = appearance.calendarViewAppearance(self, dayLabelFontAtDate: date) cell.day = calendar.day(date) cell.dayLabel.font = font cell.dayLabelAlignment = appearance.dayLabelAlignment(in: self) cell.dayLabelColor = appearance.calendarViewAppearance(self, dayLabelTextColorAtDate: date) cell.dayLabelBackgroundColor = appearance.calendarViewAppearance(self, dayLabelBackgroundColorAtDate: date) cell.dayLabelSelectedColor = appearance.calendarViewAppearance(self, dayLabelSelectedTextColorAtDate: date) cell.dayLabelSelectedBackgroundColor = appearance.calendarViewAppearance(self, dayLabelSelectedBackgroundColorAtDate: date) cell.dayLabelHeight = dayLabelHeight // select cells which already selected dates if selectedIndexes.contains(indexPath) { cell.select(withAnimation: .none) } return cell } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case YMMonthBackgroundView.ym.kind: return backgroundView(at: indexPath) case YMMonthWeekView.ym.kind: return monthRowView(at: indexPath) default: fatalError() } } private func backgroundView(at indexPath: IndexPath) -> UICollectionReusableView { let date = startDayAtMonth(in: indexPath.section) let lastColumn = column(at: IndexPath(item: 0, section: indexPath.section + 1)) let numRows = calendar.numberOfWeeksInMonth(date: date) let view = collectionView.ym.dequeue(YMMonthBackgroundView.self, for: indexPath) view.lastColumn = lastColumn view.numberOfRows = numRows let viewAppearance = appearance ?? self view.horizontalGridColor = viewAppearance.horizontalGridColor(in: self) view.horizontalGridWidth = viewAppearance.horizontalGridWidth(in: self) view.verticalGridColor = viewAppearance.verticalGridColor(in: self) view.verticalGridWidth = viewAppearance.verticalGridWidth(in: self) view.setNeedsDisplay() return view } } extension YMCalendarView: YMEventsRowViewDelegate { // MARK: - YMEventsRowViewDelegate func eventsRowView(_ view: YMEventsRowView, numberOfEventsAt day: Int) -> Int { var comps = DateComponents() comps.day = day guard let date = calendar.date(byAdding: comps, to: view.monthStart), let count = dataSource?.calendarView(self, numberOfEventsAtDate: date) else { return 0 } return count } func eventsRowView(_ view: YMEventsRowView, rangeForEventAtIndexPath indexPath: IndexPath) -> NSRange { var comps = DateComponents() comps.day = indexPath.section guard let date = calendar.date(byAdding: comps, to: view.monthStart), let dateRange = dataSource?.calendarView(self, dateRangeForEventAtIndex: indexPath.item, date: date) else { return NSRange() } let start = max(0, calendar.dateComponents([.day], from: view.monthStart, to: dateRange.start).day!) var end = calendar.dateComponents([.day], from: view.monthStart, to: dateRange.end).day! if dateRange.end.timeIntervalSince(calendar.startOfDay(for: dateRange.end)) >= 0 { end += 1 } end = min(end, NSMaxRange(view.daysRange)) return NSRange(location: start, length: end - start) } func eventsRowView(_ view: YMEventsRowView, cellForEventAtIndexPath indexPath: IndexPath) -> YMEventView { var comps = DateComponents() comps.day = indexPath.section guard let date = calendar.date(byAdding: comps, to: view.monthStart), let eventView = dataSource?.calendarView(self, eventViewForEventAtIndex: indexPath.item, date: date) else { fatalError() } return eventView } func eventsRowView(_ view: YMEventsRowView, didSelectCellAtIndexPath indexPath: IndexPath) { var comps = DateComponents() comps.day = indexPath.section guard let date = calendar.date(byAdding: comps, to: view.monthStart) else { return } selectedEventDate = date selectedEventIndex = indexPath.item delegate?.calendarView?(self, didSelectEventAtIndex: indexPath.item, date: date) } } extension YMCalendarView: YMCalendarLayoutDataSource { // MARK: - YMCalendarLayoutDelegate func collectionView(_ collectionView: UICollectionView, layout: YMCalendarLayout, columnAt indexPath: IndexPath) -> Int { return column(at: indexPath) } } extension YMCalendarView: UICollectionViewDelegate { // MARK: - public /// Select cell item from date manually. public func selectDayCell(at date: Date) { // select cells guard let indexPath = indexPathForDate(date) else { return } collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0)) collectionView(collectionView, didSelectItemAt: indexPath) } /// Deselect cell item of selecting indexPath manually. public func deselectDayCells() { // deselect cells collectionView.indexPathsForSelectedItems?.forEach { collectionView.deselectItem(at: $0, animated: false) } } // MARK: - UICollectionViewDelegate private func cellForItem(at indexPath: IndexPath) -> YMMonthDayCollectionCell? { return collectionView.cellForItem(at: indexPath) as? YMMonthDayCollectionCell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if allowsMultipleSelection { if let i = selectedIndexes.index(of: indexPath) { cellForItem(at: indexPath)?.deselect(withAnimation: deselectAnimation) selectedIndexes.remove(at: i) } else { cellForItem(at: indexPath)?.select(withAnimation: selectAnimation) selectedIndexes.append(indexPath) } } else { selectedIndexes.forEach { cellForItem(at: $0)?.deselect(withAnimation: deselectAnimation) } cellForItem(at: indexPath)?.select(withAnimation: selectAnimation) selectedIndexes = [indexPath] } delegate?.calendarView?(self, didSelectDayCellAtDate: dateAt(indexPath)) } // MARK: - UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { recenterIfNeeded() if let indexPath = collectionView.indexPathForItem(at: center) { let date = dateAt(indexPath) let startMonth = calendar.startOfMonthForDate(date) if displayingMonthDate != startMonth { displayingMonthDate = startMonth delegate?.calendarView?(self, didMoveMonthOfStartDate: startMonth) } } delegate?.calendarViewDidScroll?(self) } }
mit
67acf44a8dd678255d227e9b72f7e89a
32.648936
169
0.622945
4.999802
false
false
false
false
tjw/swift
test/DebugInfo/returnlocation.swift
1
6776
// RUN: %target-swift-frontend -g -emit-ir %s -o %t.ll // REQUIRES: objc_interop import Foundation // This file contains linetable testcases for all permutations // of simple/complex/empty return expressions, // cleanups/no cleanups, single / multiple return locations. // RUN: %FileCheck %s --check-prefix=CHECK_NONE < %t.ll // CHECK_NONE: define{{( protected)?}} {{.*}}void {{.*}}none public func none(_ a: inout Int64) { // CHECK_NONE: call void @llvm.dbg{{.*}}, !dbg // CHECK_NONE: store{{.*}}, !dbg // CHECK_NONE: !dbg ![[NONE_INIT:.*]] a -= 2 // CHECK_NONE: ret {{.*}}, !dbg ![[NONE_RET:.*]] // CHECK_NONE: ![[NONE_INIT]] = !DILocation(line: [[@LINE-2]], column: // CHECK_NONE: ![[NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY < %t.ll // CHECK_EMPTY: define {{.*}}empty public func empty(_ a: inout Int64) { if a > 24 { // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET1:.*]] // CHECK-DAG_EMPTY_RET1: ![[EMPTY_RET1]] = !DILocation(line: [[@LINE+1]], column: 6, return } a -= 2 // CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET2:.*]] // CHECK-DAG_EMPTY_RET2: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 3, return // CHECK-DAG_EMPTY: ret {{.*}}, !dbg ![[EMPTY_RET:.*]] // CHECK-DAG_EMPTY: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_EMPTY_NONE < %t.ll // CHECK_EMPTY_NONE: define {{.*}}empty_none public func empty_none(_ a: inout Int64) { if a > 24 { return } a -= 2 // CHECK_EMPTY_NONE: ret {{.*}}, !dbg ![[EMPTY_NONE_RET:.*]] // CHECK_EMPTY_NONE: ![[EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_RET < %t.ll // CHECK_SIMPLE_RET: define {{.*}}simple public func simple(_ a: Int64) -> Int64 { if a > 24 { return 0 } return 1 // CHECK_SIMPLE_RET: ret i{{.*}}, !dbg ![[SIMPLE_RET:.*]] // CHECK_SIMPLE_RET: ![[SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_RET < %t.ll // CHECK_COMPLEX_RET: define {{.*}}complex public func complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return a/2 // CHECK_COMPLEX_RET: ret i{{.*}}, !dbg ![[COMPLEX_RET:.*]] // CHECK_COMPLEX_RET: ![[COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_SIMPLE < %t.ll // CHECK_COMPLEX_SIMPLE: define {{.*}}complex_simple public func complex_simple(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[COMPLEX_SIMPLE_RET:.*]] // CHECK_COMPLEX_SIMPLE: ![[COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_COMPLEX < %t.ll // CHECK_SIMPLE_COMPLEX: define {{.*}}simple_complex public func simple_complex(_ a: Int64) -> Int64 { if a > 24 { return a*a } return 2 // CHECK_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[SIMPLE_COMPLEX_RET:.*]] // CHECK_SIMPLE_COMPLEX: ![[SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // --------------------------------------------------------------------- // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_NONE < %t.ll // CHECK_CLEANUP_NONE: define {{.*}}cleanup_none public func cleanup_none(_ a: inout NSString) { a = "empty" // CHECK_CLEANUP_NONE: ret void, !dbg ![[CLEANUP_NONE_RET:.*]] // CHECK_CLEANUP_NONE: ![[CLEANUP_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY < %t.ll // CHECK_CLEANUP_EMPTY: define {{.*}}cleanup_empty public func cleanup_empty(_ a: inout NSString) { if a.length > 24 { return } a = "empty" return // CHECK_CLEANUP_EMPTY: ret void, !dbg ![[CLEANUP_EMPTY_RET:.*]] // CHECK_CLEANUP_EMPTY: ![[CLEANUP_EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY_NONE < %t.ll // CHECK_CLEANUP_EMPTY_NONE: define {{.*}}cleanup_empty_none public func cleanup_empty_none(_ a: inout NSString) { if a.length > 24 { return } a = "empty" // CHECK_CLEANUP_EMPTY_NONE: ret {{.*}}, !dbg ![[CLEANUP_EMPTY_NONE_RET:.*]] // CHECK_CLEANUP_EMPTY_NONE: ![[CLEANUP_EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_RET < %t.ll // CHECK_CLEANUP_SIMPLE_RET: define {{.*}}cleanup_simple public func cleanup_simple(_ a: NSString) -> Int64 { if a.length > 24 { return 0 } return 1 // CHECK_CLEANUP_SIMPLE_RET: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_RET:.*]] // CHECK_CLEANUP_SIMPLE_RET: ![[CLEANUP_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX < %t.ll // CHECK_CLEANUP_COMPLEX: define {{.*}}cleanup_complex public func cleanup_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return Int64(a.length/2) // CHECK_CLEANUP_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_RET:.*]] // CHECK_CLEANUP_COMPLEX: ![[CLEANUP_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX_SIMPLE < %t.ll // CHECK_CLEANUP_COMPLEX_SIMPLE: define {{.*}}cleanup_complex_simple public func cleanup_complex_simple(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_SIMPLE_RET:.*]] // CHECK_CLEANUP_COMPLEX_SIMPLE: ![[CLEANUP_COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_COMPLEX < %t.ll // CHECK_CLEANUP_SIMPLE_COMPLEX: define {{.*}}cleanup_simple_complex public func cleanup_simple_complex(_ a: NSString) -> Int64 { if a.length > 24 { return Int64(a.length*a.length) } return 2 // CHECK_CLEANUP_SIMPLE_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_SIMPLE_COMPLEX_RET:.*]] // CHECK_CLEANUP_SIMPLE_COMPLEX: ![[CLEANUP_SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1, } // --------------------------------------------------------------------- // RUN: %FileCheck %s --check-prefix=CHECK_INIT < %t.ll // CHECK_INIT: define {{.*}}$S4main6Class1CACSgycfc public class Class1 { public required init?() { print("hello") // CHECK_INIT: call {{.*}}@"$Ss5print_9separator10terminatoryypd_S2StF"{{.*}}, !dbg [[printLoc:![0-9]+]] // CHECK_INIT: br label {{.*}}, !dbg [[retnLoc:![0-9]+]] // CHECK_INIT: [[printLoc]] = !DILocation(line: [[@LINE-4]] // CHECK_INIT: [[retnLoc]] = !DILocation(line: [[@LINE+1]] return nil } }
apache-2.0
ec558a82141d289888268bb2803bd030
33.927835
110
0.599026
3.147236
false
false
false
false
BrantSteven/SinaProject
BSweibo/BSweibo/class/massage/MassageTableViewController.swift
1
3143
// // MassageTableViewController.swift // BSweibo // // Created by 驴徒 on 16/6/30. // Copyright © 2016年 白霜. All rights reserved. // import UIKit class MassageTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !userLogin { visitorView.setUpVisitorView(false, imageName: "visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") } } func initData() { } func createTableView() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c60fec2fb43a6420284f4e95eed52e53
31.357895
157
0.673715
5.318339
false
false
false
false
mhassanpur/tutorial-ios-barcode-scanner
BarcodeScanner/ViewController.swift
1
4873
// // ViewController.swift // BarcodeScanner // // Created by Mujtaba Hassanpur on 10/12/15. // Copyright © 2015 Mujtaba Hassanpur. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var captureSession: AVCaptureSession! var captureDevice: AVCaptureDevice! var captureDeviceInput: AVCaptureDeviceInput! var captureDeviceOutput: AVCaptureMetadataOutput! var capturePreviewLayer: AVCaptureVideoPreviewLayer! var alertController: UIAlertController! func initializeScanner() { captureSession = AVCaptureSession() do { // get the default device and use auto settings captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) try captureDevice.lockForConfiguration() captureDevice.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure captureDevice.whiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance captureDevice.focusMode = AVCaptureFocusMode.ContinuousAutoFocus if captureDevice.hasTorch { captureDevice.torchMode = AVCaptureTorchMode.Auto } captureDevice.unlockForConfiguration() // add the input/output devices captureSession.beginConfiguration() captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice) if captureSession.canAddInput(captureDeviceInput) { captureSession.addInput(captureDeviceInput) } // AVCaptureMetadataOutput is how we can determine captureDeviceOutput = AVCaptureMetadataOutput() captureDeviceOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) if captureSession.canAddOutput(captureDeviceOutput) { captureSession.addOutput(captureDeviceOutput) captureDeviceOutput.metadataObjectTypes = captureDeviceOutput.availableMetadataObjectTypes } captureSession.commitConfiguration() } catch { displayAlert("Error", message: "Unable to set up the capture device.") } capturePreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) capturePreviewLayer.frame = self.view.layer.bounds capturePreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill self.view.layer.addSublayer(capturePreviewLayer) } func startScanner() { if captureSession != nil { captureSession.startRunning() } } func stopScanner() { if captureSession != nil { captureSession.stopRunning() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.initializeScanner() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) startScanner() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) stopScanner() } func displayAlert(title: String, message: String) { alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in self.dismissViewControllerAnimated(true, completion: nil) self.alertController = nil }) alertController.addAction(dismissAction) self.presentViewController(alertController, animated: true, completion: nil) } /* AVCaptureMetadataOutputObjectsDelegate */ func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if alertController != nil { return } if metadataObjects != nil && metadataObjects.count > 0 { if let machineReadableCode = metadataObjects[0] as? AVMetadataMachineReadableCodeObject { // get the barcode string let type = machineReadableCode.type let barcode = machineReadableCode.stringValue // display the barcode in an alert let title = "Barcode" let message = "Type: \(type)\nBarcode: \(barcode)" displayAlert(title, message: message) } } } }
mit
8aa456a3b6cdae81f26e30ac20ba2e91
36.767442
162
0.656609
6.427441
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Style/Styles.swift
1
1715
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import Eureka func applyStyle() { if #available(iOS 11, *) { } else { UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).isTranslucent = false } UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).tintColor = AppGlobalStyle.navigationBarTintColor UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).barTintColor = AppGlobalStyle.barTintColor UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).titleTextAttributes = [ .foregroundColor: UIColor.white, ] UITextField.appearance().tintColor = Colors.blue UIImageView.appearance().tintColor = Colors.lightBlue BrowserNavigationBar.appearance().setBackgroundImage(.filled(with: .white), for: .default) } struct AppGlobalStyle { static let navigationBarTintColor = UIColor.white static let docPickerNavigationBarTintColor = Colors.darkBlue static let barTintColor = Colors.darkBlue } struct StyleLayout { static let sideMargin: CGFloat = 15 static let sideCellMargin: CGFloat = 10 struct TableView { static let heightForHeaderInSection: CGFloat = 30 static let separatorColor = UIColor(hex: "d7d7d7") } struct CollectibleView { static let heightForHeaderInSection: CGFloat = 40 } } struct EditTokenStyleLayout { static let preferedImageSize: CGFloat = 52 static let sideMargin: CGFloat = 15 } struct TransactionStyleLayout { static let stackViewSpacing: CGFloat = 15 static let preferedImageSize: CGFloat = 26 }
gpl-3.0
c7f7425abf4ccd6bac63dfe6412034a2
30.181818
137
0.754519
5.29321
false
false
false
false
lioonline/LioLoopScrollView
LioLoopScrollView/LioLoopScrollView/LioLoopView.swift
1
8388
// // LioLoopView.swift // LioLoopScrollView // // Created by Cocoa Lee on 16/1/12. // Copyright © 2016年 Cocoa Lee. All rights reserved. // import UIKit class LioLoopView: UIView,UIScrollViewDelegate{ /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ let lioScrollView = UIScrollView() var delegate = LioLoopViewDelegate?() var urlsArray = NSMutableArray() var timer = NSTimer() var pageControl = UIPageControl() //记录偏移量 var contentOffsetX = CGFloat(0.0) //方向枚举值 enum SlidingDirection { case fromLeftToRight //视图向右边滑动 case fromRightToLeft //视图向左边滑动 } var direction:(SlidingDirection) = SlidingDirection.fromLeftToRight required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initialize() } override init(frame: CGRect) { super.init(frame: frame) self.initialize() } func initialize() { NSLog("common init") self.lioScrollView.frame = self.bounds self.lioScrollView.pagingEnabled = true self.lioScrollView.delegate = self self.lioScrollView.showsHorizontalScrollIndicator = false self.addSubview(self.lioScrollView) self.resetScrollViewContentOffset() self.lioScrollView.bounces = false self.pageControl.currentPageIndicatorTintColor = UIColor(red: 250/255.0, green: 99/255.0, blue: 175/255.0, alpha: 1) self.timerStart() self.pageControl.frame = CGRectMake(self.frame.width - 100, self.frame.height - 20, 100, 20) self.addSubview(pageControl) } /** 设置View大小 - parameter fram: fram */ func setLioViewFram(fram:CGRect) { self.frame = frame; } /** 设置滚动视图的arrays - parameter viewsArray: viewsArray */ func setLioScrollViewImageWithURLsArray(URLsArray:NSArray) { self.pageControl.numberOfPages = URLsArray.count self.pageControl.currentPage = 0 if URLsArray.count == 0 { print("没有图片传入") return } else if URLsArray.count == 1 { self.urlsArray.addObjectsFromArray(URLsArray as [AnyObject]); timerStop() } else { self.urlsArray.addObjectsFromArray(URLsArray as [AnyObject]) self.urlsArray.insertObject(URLsArray[URLsArray.count-1], atIndex: 0) self.urlsArray.insertObject(URLsArray[0], atIndex: self.urlsArray.count) } if urlsArray.count > 0 { let viewsCount = self.urlsArray.count let contentWidth = self.lioScrollView.frame.width * CGFloat(viewsCount) self.lioScrollView.contentSize = CGSizeMake(contentWidth, self.lioScrollView.frame.height) self.addImageToLioScrollView(self.urlsArray) self.contentOffsetX = self.lioScrollView.contentOffset.x; } else { print("没有添加图片") } } /** 添加图片 - parameter URLsArray: URLsArray */ func addImageToLioScrollView(urlArray:NSArray) { //第一步 把所有图片添加到 ScrollView 上 for index in 0..<urlArray.count { let urlString = urlArray[index] as! (String) let imageButton = UIButton() let url = NSURL(string: urlString) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let image = UIImage(data: NSData(contentsOfURL: url!)!) dispatch_async(dispatch_get_main_queue(), { imageButton.setImage(image, forState: UIControlState.Normal) }) }) self.lioScrollView.backgroundColor = UIColor.grayColor() imageButton.frame = CGRectMake(CGFloat(index) * self.lioScrollView.frame.width, 0, self.lioScrollView.frame.width, self.lioScrollView.frame.height) self.setButtonsTag(imageButton, withIndex: index) imageButton.addTarget(self, action: "imageButtonEvent:", forControlEvents: UIControlEvents.TouchUpInside) self.lioScrollView.addSubview(imageButton) } } func setButtonsTag(imageButton:UIButton,withIndex:NSInteger) ->(){ if withIndex == 0 { imageButton.tag = self.urlsArray.count - 2 } else if withIndex == self.urlsArray.count-1 { imageButton.tag = 1 } else { imageButton.tag = withIndex } } //重置偏移量 func resetScrollViewContentOffset (){ switch self.direction { case SlidingDirection.fromLeftToRight: self.contentOffsetX = self.lioScrollView.frame.width; self.lioScrollView.contentOffset = CGPointMake(self.lioScrollView.frame.width, 0); case SlidingDirection.fromRightToLeft: let count = self.urlsArray.count - 2; self.contentOffsetX = self.lioScrollView.frame.width * CGFloat(count); self.lioScrollView.contentOffset = CGPointMake(self.lioScrollView.frame.width * CGFloat(count), 0); } } func scrollViewDidScroll(scrollView: UIScrollView) { if (scrollView.contentOffset.x - self.contentOffsetX ) > 0 { self.direction = SlidingDirection.fromLeftToRight } else if (scrollView.contentOffset.x - self.contentOffsetX ) < 0{ self.direction = SlidingDirection.fromRightToLeft }else { } self.contentOffsetX = scrollView.contentOffset.x; self.setPageControlWithScrollView(scrollView) } func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.timerStop() let contentOffsetX = scrollView.contentOffset.x switch self.direction { case SlidingDirection.fromLeftToRight: let realLastWidth = scrollView.contentSize.width - scrollView.frame.width ; if contentOffsetX > realLastWidth || contentOffsetX == realLastWidth { self .resetScrollViewContentOffset() } case SlidingDirection.fromRightToLeft: let realLastWidth = CGFloat(0); if contentOffsetX < realLastWidth || contentOffsetX == realLastWidth { self .resetScrollViewContentOffset() } } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.timerStart() } func setPageControlWithScrollView(scrollView:UIScrollView) { var currenIndex = NSInteger(scrollView.contentOffset.x/scrollView.frame.width) if currenIndex == self.urlsArray.count - 1 { currenIndex = 0 } else if currenIndex == 0 { currenIndex = self.urlsArray.count - 2 } self.pageControl.currentPage = NSInteger(currenIndex-1) } func timerStart (){ self.timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "timerEvent", userInfo: nil, repeats: true) } func timerStop () { self.timer.invalidate() } func timerEvent (){ if (self.lioScrollView.contentOffset.x > self.lioScrollView.contentSize.width - self.lioScrollView.frame.width * 2) { self.lioScrollView.contentOffset = CGPointMake(self.lioScrollView.frame.width, 0) } UIView.animateWithDuration(0.25, animations: { () -> Void in self.lioScrollView.contentOffset = CGPointMake(self.lioScrollView.contentOffset.x + self.lioScrollView.frame.width, 0) }) self.setPageControlWithScrollView(self.lioScrollView) } func imageButtonEvent(imageButton:UIButton){ self.delegate?.lioScrollViewClickAtIndex(imageButton.tag) } } protocol LioLoopViewDelegate { /** 代理方法 - parameter index: 从1到图片的总数 */ func lioScrollViewClickAtIndex(index:NSInteger) }
mit
8b98cf453e05628942a5f0d3bb38ded2
31.011673
159
0.619789
4.755491
false
false
false
false
xcodeswift/xcproj
Tests/XcodeProjTests/Workspace/XCWorkspaceDataTests.swift
1
4287
import Foundation import PathKit import XcodeProj import XCTest final class XCWorkspaceDataTests: XCTestCase { var subject: XCWorkspaceData! var fileRef: XCWorkspaceDataFileRef! override func setUp() { super.setUp() fileRef = XCWorkspaceDataFileRef( location: .self("path") ) subject = XCWorkspaceData(children: []) } func test_equal_returnsTheCorrectValue() { let another = XCWorkspaceData(children: []) XCTAssertEqual(subject, another) } } final class XCWorkspaceDataIntegrationTests: XCTestCase { func test_init_returnsTheModelWithTheRightProperties() throws { let path = fixturePath() let got = try XCWorkspaceData(path: path) if case let XCWorkspaceDataElement.file(location: fileRef) = got.children.first! { XCTAssertEqual(fileRef.location, .self("")) } else { XCTAssertTrue(false, "Expected file reference") } } func test_init_throwsIfThePathIsWrong() { do { _ = try XCWorkspace(path: Path("/test")) XCTAssertTrue(false, "Expected to throw an error but it didn't") } catch {} } func test_write() { testWrite( from: fixturePath(), initModel: { try? XCWorkspaceData(path: $0) }, modify: { $0.children.append( .group(.init(location: .self("shakira"), name: "shakira", children: [])) ) return $0 }, assertion: { before, after in XCTAssertEqual(before, after) XCTAssertEqual(after.children.count, 2) switch after.children.last { case let .group(group)?: XCTAssertEqual(group.name, "shakira") XCTAssertEqual(group.children.count, 0) default: XCTAssertTrue(false, "Expected group") } } ) } func test_init_returnsAllChildren() throws { let workspace = try fixtureWorkspace() XCTAssertEqual(workspace.data.children.count, 4) } func test_init_returnsNestedElements() throws { let workspace = try fixtureWorkspace() if case let XCWorkspaceDataElement.group(group) = workspace.data.children.first! { XCTAssertEqual(group.children.count, 2) } else { XCTAssertTrue(false, "Expected group") } } func test_init_returnsAllLocationTypes() throws { let workspace = try fixtureWorkspace() if case let XCWorkspaceDataElement.group(group) = workspace.data.children[0] { if case let XCWorkspaceDataElement.file(fileRef) = group.children[0] { XCTAssertEqual(fileRef.location, .group("../WithoutWorkspace/WithoutWorkspace.xcodeproj")) } else { XCTAssertTrue(false, "Expected fileRef") } if case let XCWorkspaceDataElement.file(fileRef) = group.children[1] { XCTAssertEqual(fileRef.location, .container("iOS/BuildSettings.xcodeproj")) } else { XCTAssertTrue(false, "Expected fileRef") } } else { XCTAssertTrue(false, "Expected group") } if case let XCWorkspaceDataElement.file(fileRef) = workspace.data.children[2] { XCTAssertEqual(fileRef.location, .absolute("/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app")) } else { XCTAssertTrue(false, "Expected fileRef") } if case let XCWorkspaceDataElement.file(fileRef) = workspace.data.children[3] { XCTAssertEqual(fileRef.location, .developer("Applications/Simulator.app")) } else { XCTAssertTrue(false, "Expected fileRef") } } // MARK: - Private private func fixturePath() -> Path { fixturesPath() + "iOS/Project.xcodeproj/project.xcworkspace/contents.xcworkspacedata" } private func fixtureWorkspace() throws -> XCWorkspace { let path = fixturesPath() + "Workspace.xcworkspace" return try XCWorkspace(path: path) } }
mit
41387cf7455452a14dec1cf2a3147a81
34.139344
128
0.587824
4.950346
false
true
false
false
zjjzmw1/speedxSwift
speedxSwift/speedxSwift/Bike/SampleObject.swift
1
691
// // SampleObject.swift // speedxSwift // // Created by speedx on 16/5/13. // Copyright © 2016年 speedx. All rights reserved. // import Foundation import RealmSwift import CoreLocation class SampleObject: Object { dynamic var activityId = "" /// 点的id -------------------- dynamic var sampleId = 0 /// 经度 - 火星的 dynamic var lat = 0.0 /// 维度 - 火星的 dynamic var log = 0.0 /// 速度 ------------------------------- dynamic var speed = 0.0 /// 里程 - 距离第一个点的里程 dynamic var distance = 0.0 /// 时间 - 距离第一个点的时间 从 1 开始 单位是 s dynamic var time = 1 }
mit
349455b151abd442ec0a4683361f36ee
19.133333
50
0.541391
3.393258
false
false
false
false
DianQK/TransitionTreasury
TransitionTreasury/TabBarTransition/UITabBarController+TRTransition.swift
1
1691
// // UITabBarController+TRTransition.swift // TransitionTreasury // // Created by DianQK on 16/1/19. // Copyright © 2016年 TransitionTreasury. All rights reserved. // import UIKit private var transition_key: Void? private var delegate_key: Void? public typealias ViewControllerIndex = Int public extension UITabBarController { var tr_transitionDelegate: TRTabBarTransitionDelegate? { get { return objc_getAssociatedObject(self, &transition_key) as? TRTabBarTransitionDelegate } set { self.delegate = newValue objc_setAssociatedObject(self, &transition_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } weak var tr_delegate: TRTabBarControllerDelegate? { get { if tr_transitionDelegate == nil { debugPrint("Warning: You forget set tr_transitionDelegate.") } return tr_transitionDelegate?.tr_delegate } set { if tr_transitionDelegate == nil { debugPrint("Warning: You forget set tr_transitionDelegate.") } tr_transitionDelegate?.tr_delegate = newValue } } func tr_selected(_ index: ViewControllerIndex, gesture: UIGestureRecognizer, completion: (() -> Void)? = nil) { if let transitionAnimation = tr_transitionDelegate?.transitionAnimation as? TabBarTransitionInteractiveable { transitionAnimation.gestureRecognizer = gesture transitionAnimation.interacting = true transitionAnimation.completion = completion } selectedIndex = index } }
mit
6124402a9a2cdb425843e0c1be0be915
30.259259
117
0.631517
5.193846
false
false
false
false
Gitliming/Demoes
Demoes/Demoes/Extensions/UIView + Extention.swift
1
836
// // UIView + Extention.swift // Demoes // // Created by xpming on 2016/12/1. // Copyright © 2016年 xpming. All rights reserved. // import UIKit extension UIView{ //获取所在控制器 class func getSelfController(_ view:UIView)->UIViewController?{ var next:UIView? = view repeat{ if let nextResponder = next?.next, nextResponder.isKind(of: UIViewController.self){ return (nextResponder as! UIViewController) } next = next?.superview }while next != nil return nil } // spliteLine class func spliteLine(_ margin:CGFloat? = 10) -> UIView{ let line = UIView(frame:CGRect(x: margin!, y: 0, width: screenWidth - 2 * margin!, height: 1/screenScare)) line.backgroundColor = UIColor.lightGray return line } }
apache-2.0
9192c1127879c53c812428df7dd8ddcd
26.3
110
0.617827
3.975728
false
false
false
false
hollyschilling/EssentialElements
EssentialElements/EssentialElements/ItemLists/ViewControllers/ListTableViewController.swift
1
6044
// // ListTableViewController.swift // EssentialElements // // Created by Holly Schilling on 2/25/17. // Copyright © 2017 Better Practice Solutions. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import CoreData open class ListTableViewController<ItemType: NSFetchRequestResult>: UITableViewController, NSFetchedResultsControllerDelegate { open var viewDidLoadHandler: ((_ controller: ListTableViewController<ItemType>) -> Void)? { didSet { if isViewLoaded { viewDidLoadHandler?(self) } } } open var didSelectItemHandler: ((_ controller: ListTableViewController<ItemType>, _ indexPath: IndexPath) -> Void)? open var contents: NSFetchedResultsController<ItemType>? { didSet { contents?.delegate = self updateBadge() tableView?.reloadData() } } open weak var badgingTarget: UIViewController? { didSet { oldValue?.tabBarItem.badgeValue = nil updateBadge() } } //MARK: - Lifecycle open override func viewDidLoad() { super.viewDidLoad() updateBadge() viewDidLoadHandler?(self) } open override func didMove(toParentViewController parent: UIViewController?) { super.didMove(toParentViewController: parent) updateBadge() } //MARK: - Instance Methods open func updateBadge() { guard let badgingTarget = badgingTarget else { return } let count = contents?.fetchedObjects?.count ?? 0 if count > 0 { badgingTarget.tabBarItem.badgeValue = count.description } else { badgingTarget.tabBarItem.badgeValue = nil } } open func configure<ItemViewType: ItemView<ItemType>>(cell: ItemTableViewCell<ItemViewType>, for indexPath: IndexPath) { let itemView: ItemViewType = cell.itemView let item: ItemType? = contents?.object(at: indexPath) itemView.item = item } open func apply(changes: [FetchedResultsChange]) { guard let tableView = tableView else { return } tableView.beginUpdates() for aChange in changes { apply(change: aChange) } tableView.endUpdates() } open func apply(change: FetchedResultsChange) { guard let tableView = tableView else { return } switch change { case .insert(let indexPath): tableView.insertRows(at: [indexPath], with: .automatic) case .delete(let indexPath): tableView.deleteRows(at: [indexPath], with: .automatic) case .move(let oldIndexPath, let newIndexPath): tableView.moveRow(at: oldIndexPath, to: newIndexPath) case .update(let indexPath): tableView.reloadRows(at: [indexPath], with: .automatic) } } //MARK: - UITableView Delegate and DataSource open override func numberOfSections(in tableView: UITableView) -> Int { return contents?.sections?.count ?? 0 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contents?.sections?[section].numberOfObjects ?? 0 } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { didSelectItemHandler?(self, indexPath) } open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = contents?.sections?[section] return sectionInfo?.name } //MARK: - NSFetchedResultsControllerDelegate open func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { guard controller == contents else { return } tableView.beginUpdates() } open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { guard controller == contents else { return } switch type { case .insert: apply(change: .insert(newIndexPath!)) case .delete: apply(change: .delete(indexPath!)) case .update: apply(change: .update(indexPath!)) case .move: apply(change: .move(indexPath!, newIndexPath!)) } } open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { updateBadge() guard controller == contents else { return } tableView.endUpdates() } }
mit
53ec2d458862c7ecd199837ebe4ea495
33.335227
127
0.634288
5.449053
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/MWKDataStore+LegacyMobileview.swift
1
4371
import CocoaLumberjackSwift enum MigrateMobileviewToMobileHTMLIfNecessaryError: Error { case noArticleURL case noArticleCacheController case noLegacyArticleData case noMobileHTML } extension MWKDataStore { // TODO: use this method's completion block when loading articles (in case a mobileview conversion hasn't happened yet for that article's saved data for any reason) func migrateMobileviewToMobileHTMLIfNecessary(article: WMFArticle, completionHandler: @escaping ((Error?) -> Void)) { guard article.isConversionFromMobileViewNeeded == true else { // If conversion was previously attempted don't try again. completionHandler(nil) return } guard let articleURL = article.url else { assertionFailure("Could not get article url") completionHandler(MigrateMobileviewToMobileHTMLIfNecessaryError.noArticleURL) return } let articleCacheController = cacheController.articleCache let articleFolderURL = URL(fileURLWithPath: path(forArticleURL: articleURL)) guard let legacyArticle = LegacyArticle(articleFolderURL: articleFolderURL) else { completionHandler(MigrateMobileviewToMobileHTMLIfNecessaryError.noLegacyArticleData) return } mobileviewConverter.convertMobileviewSavedDataToMobileHTML(articleURL: articleURL, article: legacyArticle) { (result, error) in let removeArticleMobileviewSavedDataFolder = { // Remove old mobileview saved data folder for this article do { try FileManager.default.removeItem(atPath: self.path(forArticleURL: articleURL)) } catch { DDLogError("Could not remove mobileview folder for articleURL: \(articleURL)") } } let handleConversionFailure = { // No need to keep mobileview section html if conversion failed, so ok to remove section data // because we're setting `isDownloaded` next so saved article fetching will re-download from // new mobilehtml endpoint. removeArticleMobileviewSavedDataFolder() // If conversion failed above for any reason set "article.isDownloaded" to false so normal fetching logic picks it up DispatchQueue.main.async { do { article.isDownloaded = false article.isConversionFromMobileViewNeeded = false try self.save() } catch let error { DDLogError("Error updating article: \(error)") } } } guard error == nil, let result = result else { handleConversionFailure() completionHandler(error) return } guard let mobileHTML = result as? String else { handleConversionFailure() completionHandler(MigrateMobileviewToMobileHTMLIfNecessaryError.noMobileHTML) return } articleCacheController.cacheFromMigration(desktopArticleURL: articleURL, content: mobileHTML) { error in // Conversion succeeded so can safely blast old mobileview folder. removeArticleMobileviewSavedDataFolder() DispatchQueue.main.async { do { article.isConversionFromMobileViewNeeded = false try self.save() } catch let error { completionHandler(error) DDLogError("Error updating article: \(error)") return } completionHandler(nil) } } } } func removeAllLegacyArticleData() { let fileURL = URL(fileURLWithPath: basePath) let titlesToRemoveFileURL = fileURL.appendingPathComponent("TitlesToRemove.plist") let sitesFolderURL = fileURL.appendingPathComponent("sites") let fm = FileManager.default try? fm.removeItem(at: titlesToRemoveFileURL) try? fm.removeItem(at: sitesFolderURL) } }
mit
25ae6bb8c2a6f29a37b8536e0c02a776
44.061856
168
0.602151
6.165021
false
false
false
false
BurntCaramel/Lantern
LanternModel/ONOXMLDocument+StringEncoding.swift
1
497
// // ONOXMLDocument+StringEncoding.swift // Hoverlytics // // Created by Patrick Smith on 29/04/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Foundation import Ono extension ONOXMLDocument { func stringEncodingWithFallback(_ fallback: String.Encoding = String.Encoding.utf8) -> String.Encoding { var stringEncoding = self.stringEncoding if stringEncoding == 0 { stringEncoding = fallback.rawValue } return String.Encoding(rawValue: stringEncoding) } }
apache-2.0
8221b7bd8ae7aa141cca195942c52684
22.666667
105
0.752515
3.823077
false
false
false
false
hwsyy/PlainReader
PlainReader/View/ThemeSwitch.swift
5
2932
// // ThemeSwitch.swift // PlainReader // // Created by guo on 11/29/14. // Copyright (c) 2014 guojiubo. All rights reserved. // import UIKit class ThemeSwitch: UIControl { var normalLabel = UILabel(frame: CGRectZero) var selectedLabel = UILabel(frame: CGRectZero) var imageView = UIImageView(image: UIImage(named: "ThemeNight")) override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init(coder: NSCoder) { super.init(coder: coder) self.setup() } func setup() { let border = UIImageView(image: UIImage(named: "ThemeSwitchBorder")) border.center.y = self.bounds.height / 2 self.addSubview(border) self.normalLabel.frame = CGRect(x: 10, y: (self.bounds.height - border.bounds.height) / 2, width: border.bounds.width - 20, height: border.bounds.height) self.normalLabel.font = UIFont.systemFontOfSize(12) self.normalLabel.textColor = UIColor.whiteColor() self.normalLabel.text = "夜间" self.normalLabel.textAlignment = .Right self.addSubview(normalLabel) self.selectedLabel.frame = CGRect(x: 10, y: (self.bounds.height - border.bounds.height) / 2, width: border.bounds.width - 20, height: border.bounds.height) self.selectedLabel.font = UIFont.systemFontOfSize(12) self.selectedLabel.textColor = CW_HEXColor(0x23beff) self.selectedLabel.text = "白天" self.selectedLabel.alpha = 0 self.addSubview(selectedLabel) self.imageView.frame = CGRect(x: 5, y: (CGRectGetHeight(self.bounds) - CGRectGetHeight(self.imageView.bounds)) / 2, width: CGRectGetWidth(self.imageView.bounds), height: CGRectGetHeight(self.imageView.bounds)) self .addSubview(self.imageView) self.addTarget(self, action: "handleTouchDown:", forControlEvents: .TouchDown) } func handleTouchDown(sender: UIControl) { self.selected = !self.selected self.sendActionsForControlEvents(.ValueChanged) } override var selected: Bool { didSet { UIView.animateWithDuration(0.3, animations: { () -> Void in self.normalLabel.alpha = self.selected ? 0 : 1 self.selectedLabel.alpha = self.selected ? 1 : 0 var frame = self.imageView.frame frame.origin.x = self.selected ? ( self.bounds.width - self.imageView.bounds.width - 5) : 5 self.imageView.frame = frame }) UIView.transitionWithView(self.imageView, duration: 0.3, options: .TransitionCrossDissolve, animations: { () -> Void in self.imageView.image = self.selected ? UIImage(named: "ThemeDay") : UIImage(named: "ThemeNight") }, completion: nil) } } }
mit
1a3af370dc90baab52afdf7913ccbd3c
36.012658
217
0.617305
4.325444
false
false
false
false
ruilin/RLMap
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/ViatorCells/ViatorElement.swift
3
2602
final class ViatorElement : UICollectionViewCell { @IBOutlet private weak var more: UIButton! @IBOutlet private weak var image: UIImageView! @IBOutlet private weak var title: UILabel! { didSet { title.font = UIFont.medium14() title.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var duration: UILabel! { didSet { duration.font = UIFont.regular12() duration.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var price: UILabel! { didSet { price.font = UIFont.medium14() price.textColor = UIColor.linkBlue() } } @IBOutlet private var rating: [UIImageView]! private var isLastCell = false { didSet { more.isHidden = !isLastCell image.isHidden = isLastCell title.isHidden = isLastCell duration.isHidden = isLastCell price.isHidden = isLastCell rating.forEach { $0.isHidden = isLastCell } } } override var isHighlighted: Bool { didSet { guard model != nil else { return } UIView.animate(withDuration: kDefaultAnimationDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.alpha = self.isHighlighted ? 0.3 : 1 }, completion: nil) } } @IBAction private func onMore() { onMoreAction?() } var model: ViatorItemModel? { didSet { if let model = model { image.af_setImage(withURL: model.imageURL, imageTransition: .crossDissolve(kDefaultAnimationDuration)) title.text = model.title duration.text = model.duration price.text = model.price rating.forEach { if Double($0.tag) <= model.rating.rounded(.up) { $0.image = #imageLiteral(resourceName: "ic_star_rating_on") } else { $0.image = UIColor.isNightMode() ? #imageLiteral(resourceName: "ic_star_rating_off_dark") : #imageLiteral(resourceName: "ic_star_rating_off_light") } } backgroundColor = UIColor.white() layer.cornerRadius = 6 layer.borderWidth = 1 layer.borderColor = UIColor.blackDividers().cgColor isLastCell = false } else { more.setImage(UIColor.isNightMode() ? #imageLiteral(resourceName: "btn_float_more_dark") : #imageLiteral(resourceName: "btn_float_more_light"), for: .normal) backgroundColor = UIColor.clear layer.borderColor = UIColor.clear.cgColor isLastCell = true } } } var onMoreAction: (() -> Void)? }
apache-2.0
dbcf4eaad509cf086e4cbcebfd9cbf6f
29.611765
165
0.623367
4.455479
false
false
false
false
russbishop/swift
test/IDE/infer_import_as_member.swift
1
4871
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=InferImportAsMember -always-argument-labels -enable-infer-import-as-member > %t.printed.A.txt // RUN: %target-swift-frontend -parse -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules %s -enable-infer-import-as-member -verify // RUN: FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // REQUIRES: objc_interop import InferImportAsMember let mine = IAMStruct1() let _ = mine.getCollisionNonProperty(1) // TODO: more cases, eventually exhaustive, as we start inferring the result we // want // PRINT-LABEL: struct IAMStruct1 { // PRINT-NEXT: var x: Double // PRINT-NEXT: var y: Double // PRINT-NEXT: var z: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double, y y: Double, z z: Double) // PRINT-NEXT: } // PRINT-LABEL: extension IAMStruct1 { // PRINT-NEXT: static var globalVar: Double // // PRINT-LABEL: /// Init // PRINT-NEXT: init(copyIn in: IAMStruct1) // PRINT-NEXT: init(simpleValue value: Double) // PRINT-NEXT: init(redundant redundant: Double) // PRINT-NEXT: init(specialLabel specialLabel: ()) // // PRINT-LABEL: /// Methods // PRINT-NEXT: func invert() -> IAMStruct1 // PRINT-NEXT: mutating func invertInPlace() // PRINT-NEXT: func rotate(radians radians: Double) -> IAMStruct1 // PRINT-NEXT: func selfComesLast(x x: Double) // PRINT-NEXT: func selfComesThird(a a: Double, b b: Float, x x: Double) // // PRINT-LABEL: /// Properties // PRINT-NEXT: var radius: Double { get nonmutating set } // PRINT-NEXT: var altitude: Double // PRINT-NEXT: var magnitude: Double { get } // PRINT-NEXT: var length: Double // // PRINT-LABEL: /// Various instance functions that can't quite be imported as properties. // PRINT-NEXT: func getNonPropertyNumParams() -> Float // PRINT-NEXT: func setNonPropertyNumParams(a a: Float, b b: Float) // PRINT-NEXT: func getNonPropertyType() -> Float // PRINT-NEXT: func setNonPropertyType(x x: Double) // PRINT-NEXT: func getNonPropertyNoSelf() -> Float // PRINT-NEXT: static func setNonPropertyNoSelf(x x: Double, y y: Double) // PRINT-NEXT: func setNonPropertyNoGet(x x: Double) // PRINT-NEXT: func setNonPropertyExternalCollision(x x: Double) // // PRINT-LABEL: /// Various static functions that can't quite be imported as properties. // PRINT-NEXT: static func staticGetNonPropertyNumParams() -> Float // PRINT-NEXT: static func staticSetNonPropertyNumParams(a a: Float, b b: Float) // PRINT-NEXT: static func staticGetNonPropertyNumParamsGetter(d d: Double) // PRINT-NEXT: static func staticGetNonPropertyType() -> Float // PRINT-NEXT: static func staticSetNonPropertyType(x x: Double) // PRINT-NEXT: static func staticGetNonPropertyNoSelf() -> Float // PRINT-NEXT: static func staticSetNonPropertyNoSelf(x x: Double, y y: Double) // PRINT-NEXT: static func staticSetNonPropertyNoGet(x x: Double) // // PRINT-LABEL: /// Static method // PRINT-NEXT: static func staticMethod() -> Double // PRINT-NEXT: static func tlaThreeLetterAcronym() -> Double // // PRINT-LABEL: /// Static computed properties // PRINT-NEXT: static var staticProperty: Double // PRINT-NEXT: static var staticOnlyProperty: Double { get } // // PRINT-LABEL: /// Omit needless words // PRINT-NEXT: static func onwNeedlessTypeArgLabel(_ Double: Double) -> Double // // PRINT-LABEL: /// Fuzzy // PRINT-NEXT: init(fuzzy fuzzy: ()) // PRINT-NEXT: init(fuzzyWithFuzzyName fuzzyWithFuzzyName: ()) // PRINT-NEXT: init(fuzzyName fuzzyName: ()) // // PRINT-NEXT: func getCollisionNonProperty(_ _: Int32) -> Float // // PRINT-NEXT: } // // PRINT-NEXT: func __IAMStruct1IgnoreMe(_ s: IAMStruct1) -> Double // // PRINT-LABEL: /// Mutable // PRINT-NEXT: struct IAMMutableStruct1 { // PRINT-NEXT: init() // PRINT-NEXT: } // PRINT-NEXT: extension IAMMutableStruct1 { // PRINT-NEXT: init(with withIAMStruct1: IAMStruct1) // PRINT-NEXT: init(url url: UnsafePointer<Int8>!) // PRINT-NEXT: func doSomething() // PRINT-NEXT: } // // PRINT-LABEL: struct TDStruct { // PRINT-NEXT: var x: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double) // PRINT-NEXT: } // PRINT-NEXT: extension TDStruct { // PRINT-NEXT: init(float Float: Float) // PRINT-NEXT: } // // PRINT-LABEL: /// Class // PRINT-NEXT: class IAMClass { // PRINT-NEXT: } // PRINT-NEXT: typealias IAMOtherName = IAMClass // PRINT-NEXT: extension IAMClass { // PRINT-NEXT: class var typeID: UInt32 { get } // PRINT-NEXT: init!(i i: Double) // PRINT-NEXT: class func invert(_ iamOtherName: IAMOtherName!) // PRINT-NEXT: }
apache-2.0
8dfa067b1cf83c7498c2a271e1ddfcd9
42.106195
311
0.688154
3.366275
false
false
false
false
BanyaKrylov/Learn-Swift
Skill/Homework 14/Pods/Alamofire/Source/SessionDelegate.swift
4
14634
// // SessionDelegate.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. open class SessionDelegate: NSObject { private let fileManager: FileManager weak var stateProvider: SessionStateProvider? var eventMonitor: EventMonitor? /// Creates an instance from the given `FileManager`. /// /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. /// `.default` by default. public init(fileManager: FileManager = .default) { self.fileManager = fileManager } /// Internal method to find and cast requests while maintaining some integrity checking. /// /// - Parameters: /// - task: The `URLSessionTask` for which to find the associated `Request`. /// - type: The `Request` subclass type to cast any `Request` associate with `task`. func request<R: Request>(for task: URLSessionTask, as type: R.Type) -> R? { guard let provider = stateProvider else { assertionFailure("StateProvider is nil.") return nil } guard let request = provider.request(for: task) as? R else { fatalError("Returned Request is not of expected type: \(R.self).") } return request } } /// Type which provides various `Session` state values. protocol SessionStateProvider: AnyObject { var serverTrustManager: ServerTrustManager? { get } var redirectHandler: RedirectHandler? { get } var cachedResponseHandler: CachedResponseHandler? { get } func request(for task: URLSessionTask) -> Request? func didGatherMetricsForTask(_ task: URLSessionTask) func didCompleteTask(_ task: URLSessionTask) func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? func cancelRequestsForSessionInvalidation(with error: Error?) } // MARK: URLSessionDelegate extension SessionDelegate: URLSessionDelegate { open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) stateProvider?.cancelRequestsForSessionInvalidation(with: error) } } // MARK: URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Result of a `URLAuthenticationChallenge` evaluation. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { eventMonitor?.urlSession(session, task: task, didReceive: challenge) let evaluation: ChallengeEvaluation switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodServerTrust: evaluation = attemptServerTrustAuthentication(with: challenge) case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate: evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) default: evaluation = (.performDefaultHandling, nil, nil) } if let error = evaluation.error { stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) } completionHandler(evaluation.disposition, evaluation.credential) } /// Evaluates the server trust `URLAuthenticationChallenge` received. /// /// - Parameter challenge: The `URLAuthenticationChallenge`. /// /// - Returns: The `ChallengeEvaluation`. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { let host = challenge.protectionSpace.host guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust else { return (.performDefaultHandling, nil, nil) } do { guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { return (.performDefaultHandling, nil, nil) } try evaluator.evaluate(trust, forHost: host) return (.useCredential, URLCredential(trust: trust), nil) } catch { return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) } } /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. /// /// - Parameters: /// - challenge: The `URLAuthenticationChallenge`. /// - task: The `URLSessionTask` which received the challenge. /// /// - Returns: The `ChallengeEvaluation`. func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, belongingTo task: URLSessionTask) -> ChallengeEvaluation { guard challenge.previousFailureCount == 0 else { return (.rejectProtectionSpace, nil, nil) } guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { return (.performDefaultHandling, nil, nil) } return (.useCredential, credential, nil) } open func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { eventMonitor?.urlSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend) stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend) } open func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) guard let request = request(for: task, as: UploadRequest.self) else { assertionFailure("needNewBodyStream did not find UploadRequest.") completionHandler(nil) return } completionHandler(request.inputStream()) } open func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) } else { completionHandler(request) } } open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) stateProvider?.request(for: task)?.didGatherMetrics(metrics) stateProvider?.didGatherMetricsForTask(task) } open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) stateProvider?.didCompleteTask(task) } @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) } } // MARK: URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) guard let request = request(for: dataTask, as: DataRequest.self) else { assertionFailure("dataTask did not find DataRequest.") return } request.didReceive(data: data) } open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) } else { completionHandler(proposedResponse) } } } // MARK: URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes) guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, totalBytesExpectedToWrite: expectedTotalBytes) } open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) guard let request = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } guard let response = request.response else { fatalError("URLSessionDownloadTask finished downloading with no response.") } let (destination, options) = (request.destination)(location, response) eventMonitor?.request(request, didCreateDestinationURL: destination) do { if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { try fileManager.removeItem(at: destination) } if options.contains(.createIntermediateDirectories) { let directory = destination.deletingLastPathComponent() try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) } try fileManager.moveItem(at: location, to: destination) request.didFinishDownloading(using: downloadTask, with: .success(destination)) } catch { request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination))) } } }
apache-2.0
3c26567d05e582d57566241d0d439f3d
43.889571
162
0.66202
6.01727
false
false
false
false
cmds4410/Mention
Pod/Classes/Mention.swift
2
1605
// // Mention.swift // BetterWorks // // Created by Connor Smith on 11/25/14. // Copyright (c) 2014 BetterWorks. https://www.betterworks.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /** * The NSAttributesString attributes used to encode and decode @mentions */ struct MentionAttributes { static let UserId = "MentionUserIdAttribute" static let Name = "MentionNameAttribute" static let Encoded = "MentionEncodedAttribute" } public var MentionCharacter: Character = "@" public var MentionColor = UIColor.blueColor()
mit
a8ee3b397a54fcec843f017fda562fd6
42.378378
74
0.739564
4.268617
false
false
false
false
PiXeL16/MealPlanExchanges
MealPlanExchanges/Model/FoodGroup.swift
1
756
// // FoodGroup.swift // MealPlanExchanges // // Created by Chris Jimenez on 6/2/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import UIKit /** * Represents a food group and the quantity that the food group has */ public struct FoodGroup { public var quantity: Double = 0 public var group: FoodTypes = FoodTypes.Other /** Initializer of the quantity and the group that the quantity is assign - parameter quantity: <#quantity description#> - parameter group: <#group description#> - returns: <#return value description#> */ init(quantity: Double = 0, group: FoodTypes = FoodTypes.Other){ self.quantity = quantity self.group = group } }
mit
1de1aa0ded82efc68117e91b80cab0d8
21.878788
74
0.635762
4.265537
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/NameDrawViewController.swift
1
8883
// // NameDrawViewController.swift // TeacherTools // // Created by Parker Rushton on 11/2/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class NameDrawViewController: UIViewController, AutoStoryboardInitializable { @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var ticketsButton: UIBarButtonItem! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet var drawNameGesture: UITapGestureRecognizer! fileprivate let cellReuseIdentifier = "NameDrawCell" fileprivate let emptyStudentsString = "Tap here to \ndraw a name!" fileprivate let audioHelper = AudioHelper(resource: AudioHelper.AudioResource.drumroll) fileprivate var allStudents = [Student]() fileprivate var selectedStudents = [Student]() fileprivate var animator: UIViewPropertyAnimator! fileprivate var animateNameDraw = true fileprivate var currentStudent: Student? { didSet { handleNewStudent(currentStudent, previousStudent: oldValue) updateCountLabel() } } var core = App.core override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 38 animator = UIViewPropertyAnimator(duration: 1.5, curve: .easeInOut) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) resetNames() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) core.remove(subscriber: self) } @IBAction func resetButtonPressed(_ sender: UIBarButtonItem) { resetNames() } @IBAction func topViewTapped(_ sender: UITapGestureRecognizer) { drawName() } @IBAction func ticketsButtonPressed(_ sender: UIBarButtonItem) { if let currentUser = core.state.currentUser, currentUser.isPro { let studentTicketsVC = StudentTicketsViewController.initializeFromStoryboard().embededInNavigationController studentTicketsVC.modalPresentationStyle = .popover studentTicketsVC.popoverPresentationController?.barButtonItem = sender present(studentTicketsVC, animated: true, completion: nil) } else { let proViewController = ProViewController.initializeFromStoryboard().embededInNavigationController proViewController.modalPresentationStyle = .popover proViewController.popoverPresentationController?.barButtonItem = sender present(proViewController, animated: true, completion: nil) } } } // MARK: - Subscriber extension NameDrawViewController: Subscriber { func update(with state: AppState) { ticketsButton.tintColor = state.isUsingTickets ? .ticketRed : state.theme.textColor.withAlphaComponent(0.5) updateUI(with: state.theme) } func updateUI(with theme: Theme) { let borderImage = theme.borderImage.image.stretchableImage(withLeftCapWidth: 0, topCapHeight: 0) navigationController?.navigationBar.setBackgroundImage(borderImage, for: .default) backgroundImageView.image = theme.mainImage.image topLabel.textColor = theme.textColor countLabel.textColor = theme.textColor topLabel.font = theme.font(withSize: Platform.isPad ? 40 : 35) countLabel.font = theme.font(withSize: Platform.isPad ? 18 : 15) } } extension NameDrawViewController { func studentListWithTickets(students: [Student]) -> [Student] { var updatedStudents = students for student in updatedStudents { guard let index = updatedStudents.index(of: student) else { continue } if student.tickets == 0 { updatedStudents.remove(at: index) } else if student.tickets > 1 { var additionalStudents = student.tickets - 1 while additionalStudents > 0 { let studentCopy = student updatedStudents.append(studentCopy) additionalStudents -= 1 } } } return updatedStudents } func drawName() { guard allStudents.count > 0 else { currentStudent = nil; return } currentStudent = allStudents.removeLast() } func handleNewStudent(_ student: Student?, previousStudent: Student?) { if let newStudent = student { changeTopLabel(animated: animateNameDraw) { self.topLabel.text = newStudent.displayedName } } else { let isStart = currentStudent == nil && selectedStudents.isEmpty topLabel.text = isStart ? emptyStudentsString : allDrawnString() } addPrevious(student: previousStudent) } func changeTopLabel(animated: Bool = true, completion: @escaping () -> Void) { if animated { drawNameGesture.isEnabled = false topLabel.text = "???" animator.addAnimations { self.topLabel.rotate(duration: 0.5, count: 2) self.topLabel.transform = CGAffineTransform(scaleX: 5, y: 5) self.topLabel.transform = CGAffineTransform(scaleX: 1, y: 1) } animator.startAnimation() if let drumrollPlayer = audioHelper { drumrollPlayer.play() } animator.addCompletion { position in self.drawNameGesture.isEnabled = true completion() } } else { completion() } } fileprivate func addPrevious(student: Student?) { if let previousStudent = student { selectedStudents.append(previousStudent) let indexPath = IndexPath(row: 0, section: 0) tableView.beginUpdates() tableView.insertRows(at: [indexPath], with: .top) tableView.endUpdates() } else if allStudents.isEmpty { resetNames() } } fileprivate func updateCountLabel() { let drawnNamesCount = currentStudent == nil ? selectedStudents.count : selectedStudents.count + 1 let totalStudentCount = studentListWithTickets(students: core.state.currentStudents).count countLabel.text = "\(drawnNamesCount)/\(totalStudentCount)" } fileprivate func resetNames() { if currentStudent != nil { currentStudent = nil } allStudents = studentListWithTickets(students: core.state.currentStudents).shuffled() selectedStudents.removeAll() tableView.reloadData() updateCountLabel() topLabel.text = emptyStudentsString AnalyticsHelper.logEvent(.nameDrawUsed) } fileprivate func allDrawnString() -> String { let strings = ["That's all she wrote", "You've drawn them all!", "You're all winners!", "Gold stars all around!", "Way to go!", "Everyone's a winner!", "Well that was fun!", "Let's do this again sometime"] return strings.randomElement()! } fileprivate func presentAnimationAlert() { let alert = UIAlertController(title: "Turn name draw animation:", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Off", style: .default, handler: { _ in self.animateNameDraw = false })) alert.addAction(UIAlertAction(title: "On", style: .default, handler: { _ in self.animateNameDraw = true })) present(alert, animated: true, completion: nil) } } extension NameDrawViewController { override var canBecomeFirstResponder: Bool { return true } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == UIEvent.EventSubtype.motionShake { presentAnimationAlert() } } } extension NameDrawViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selectedStudents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) let studentAtRow = selectedStudents.reversed()[indexPath.row] cell.textLabel?.text = studentAtRow.displayedName cell.textLabel?.font = core.state.theme.font(withSize: Platform.isPad ? 20 : 15) cell.textLabel?.textColor = core.state.theme.textColor cell.backgroundColor = .clear return cell } }
mit
df3ede63de765a28a668ded940106a9a
35.253061
213
0.640847
5.18203
false
false
false
false
malaonline/iOS
mala-ios/Model/Course/CourseChoosingObject.swift
1
3887
// // CourseChoosingObject.swift // mala-ios // // Created by 王新宇 on 2/24/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit // MARK: - 课程购买模型 class CourseChoosingObject: NSObject { // MARK: - Property /// 授课年级 dynamic var grade: GradeModel? { didSet { switchGradePrices() } } /// 上课时间 dynamic var selectedTime: [ClassScheduleDayModel] = [] { didSet { isBeginEditing = true originalPrice = getOriginalPrice() } } /// 上课小时数 dynamic var classPeriod: Int = 2 { didSet { isBeginEditing = true originalPrice = getOriginalPrice() } } /// 优惠券 dynamic var coupon: CouponModel? { didSet { originalPrice = getOriginalPrice() } } /// 全部年级价格阶梯数据 dynamic var grades: [GradeModel]? { didSet { originalPrice = getOriginalPrice() } } /// 当前年级价格阶梯 dynamic var prices: [GradePriceModel]? = [] { didSet { originalPrice = getOriginalPrice() } } /// 原价 dynamic var originalPrice: Int = 0 /// 是否已开始选课标记(未开始选课时,还需支付数额返回0) var isBeginEditing: Bool = false // MARK: - API /// 切换当前价格梯度(与年级相对应) func switchGradePrices() { guard let currentGradeId = grade?.id, let grades = grades else { return } for grade in grades { if grade.id == currentGradeId { prices = grade.prices break }else { println("无与用户所选年级相对应的价格阶梯") } } } /// 根据当前选课条件获取价格, 选课条件不正确时返回0 /// /// - returns: 原价 func getOriginalPrice() -> Int { // 验证[当前年级价格阶梯][上课时间][课时] if prices != nil && prices!.count > 0 && selectedTime.count != 0 && classPeriod >= selectedTime.count*2 { return prices![0].price * classPeriod }else { return 0 } } /// 根据[所选课时][价格梯度]计算优惠后单价 func calculatePrice() -> Int { for priceLevel in (prices ?? []) { if classPeriod >= priceLevel.min_hours && classPeriod <= priceLevel.max_hours { return priceLevel.price } } return 0 } /// 获取最终需支付金额 func getAmount() -> Int? { // 未开始选课时,还需支付数额返回0(例如初始化状态) if !isBeginEditing { return 0 } // 根据价格阶梯计算优惠后价格 var amount = calculatePrice() * classPeriod // 循环其他服务数组,计算折扣、减免 // 暂时注释,目前仅有奖学金折扣 /* for object in MalaServiceObject { switch object.priceHandleType { case .Discount: amount = amount - (object.price ?? 0) break case .Reduce: break } } */ // 计算其他优惠服务 if coupon != nil { amount = amount - (coupon?.amount ?? 0) } // 确保需支付金额不小于零 amount = amount < 0 ? 0 : amount return amount } /// 重置选课模型 func reset() { grade = nil selectedTime.removeAll() classPeriod = 2 coupon = nil grades = nil prices = nil originalPrice = 0 isBeginEditing = false } }
mit
943a5e631b62925daaaaa5dbcb7e3355
22.858156
113
0.490785
3.89803
false
false
false
false
zmeyc/telegram-bot-swift
Sources/TelegramBotSDK/TelegramBot.swift
1
12075
// // TelegramBot.swift // // This source file is part of the Telegram Bot SDK for Swift (unofficial). // // Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See AUTHORS.txt for the list of the project authors // import Foundation import Dispatch import CCurl public class TelegramBot { internal typealias DataTaskCompletion = (_ result: Decodable?, _ error: DataTaskError?)->() public typealias RequestParameters = [String: Encodable?] /// Telegram server URL. public var url = "https://api.telegram.org" /// Unique authentication token obtained from BotFather. public var token: String /// Default request parameters public var defaultParameters = [String: RequestParameters]() /// In case of network errors or server problems, /// do not report the errors and try to reconnect /// automatically. public var autoReconnect: Bool = true /// Offset for long polling. public var nextOffset: Int64? /// Number of updates to fetch by default. public var defaultUpdatesLimit: Int = 100 /// Default getUpdates timeout in seconds. public var defaultUpdatesTimeout: Int = 60 // Should probably be a LinkedList, but it won't be longer than // 100 elements anyway. var unprocessedUpdates: [Update] /// Queue for callbacks in asynchronous versions of requests. public var queue = DispatchQueue.main /// Last error for use with synchronous requests. public var lastError: DataTaskError? /// Logging function. Defaults to `print`. public var logger: (_ text: String) -> () = { print($0) } /// Defines reconnect delay in seconds when requesting updates. Can be overridden. /// /// - Parameter retryCount: Number of reconnect retries associated with `request`. /// - Returns: Seconds to wait before next reconnect attempt. Return `0.0` for instant reconnect. public var reconnectDelay: (_ retryCount: Int) -> Double = { retryCount in switch retryCount { case 0: return 0.0 case 1: return 1.0 case 2: return 2.0 case 3: return 5.0 case 4: return 10.0 case 5: return 20.0 default: break } return 30.0 } /// Equivalent of calling `getMe()` /// /// This function will block until the request is finished. public lazy var user: User = { guard let me = self.getMeSync() else { print("Unable to fetch bot information: \(self.lastError.unwrapOptional)") exit(1) } return me }() /// Equivalent of calling `user.username` and unwrapping it /// /// This function will block until the request is finished. public lazy var username: String = { guard let username = self.user.username else { fatalError("Unable to fetch bot username") } return username }() /// Equivalent of calling `BotName(username: username)` /// /// This function will block until the request is finished. public lazy var name: BotName = BotName(username: self.username) /// Creates an instance of Telegram Bot. /// - Parameter token: A unique authentication token. /// - Parameter fetchBotInfo: If true, issue a blocking `getMe()` call and cache the bot information. Otherwise it will be lazy-loaded when needed. Defaults to true. /// - Parameter session: `NSURLSession` instance, a session with `ephemeralSessionConfiguration` is used by default. public init(token: String, fetchBotInfo: Bool = true) { self.token = token self.unprocessedUpdates = [] if fetchBotInfo { _ = user // Load the lazy user variable } } deinit { //print("Deinit") } /// Returns next update for this bot. /// /// Blocks while fetching updates from the server. /// /// - Parameter mineOnly: Ignore commands not addressed to me, i.e. `/command@another_bot`. /// - Returns: `Update`. `Nil` on error, in which case details /// can be obtained from `lastError` property. public func nextUpdateSync(onlyMine: Bool = true) -> Update? { while let update = nextUpdateSync() { if onlyMine { if let message = update.message, !message.addressed(to: self) { continue } } return update } return nil } /// Waits for specified number of seconds. Message loop won't be blocked. /// /// - Parameter wait: Seconds to wait. public func wait(seconds: Double) { let sem = DispatchSemaphore(value: 0) DispatchQueue.global().asyncAfter(deadline: .now() + seconds) { sem.signal() } RunLoop.current.waitForSemaphore(sem) } /// Initiates a request to the server. Used for implementing /// specific requests (getMe, getStatus etc). internal func startDataTaskForEndpoint<T: Decodable>(_ endpoint: String, resultType: T.Type, completion: @escaping DataTaskCompletion) { startDataTaskForEndpoint(endpoint, parameters: [:], resultType: resultType, completion: completion) } /// Initiates a request to the server. Used for implementing /// specific requests. internal func startDataTaskForEndpoint<T: Decodable>(_ endpoint: String, parameters: [String: Encodable?], resultType: T.Type, completion: @escaping DataTaskCompletion) { let endpointUrl = urlForEndpoint(endpoint) // If parameters contain values of type InputFile, use multipart/form-data for sending them. var hasAttachments = false for value in parameters.values { if value is InputFile { hasAttachments = true break } if value is InputFileOrString { if case InputFileOrString.inputFile = (value as! InputFileOrString) { hasAttachments = true break } } } let contentType: String var requestDataOrNil: Data? if hasAttachments { let boundary = HTTPUtils.generateBoundaryString() contentType = "multipart/form-data; boundary=\(boundary)" requestDataOrNil = HTTPUtils.createMultipartFormDataBody(with: parameters, boundary: boundary) //try! requestDataOrNil!.write(to: URL(fileURLWithPath: "/tmp/dump.bin")) logger("endpoint: \(endpoint), sending parameters as multipart/form-data") } else { contentType = "application/x-www-form-urlencoded" let encoded = HTTPUtils.formUrlencode(parameters) requestDataOrNil = encoded.data(using: .utf8) logger("endpoint: \(endpoint), data: \(encoded)") } requestDataOrNil?.append(0) guard let requestData = requestDataOrNil else { completion(nil, .invalidRequest) return } // -1 for '\0' let byteCount = requestData.count - 1 DispatchQueue.global().async { requestData.withUnsafeBytes { (unsafeRawBufferPointer) -> Void in let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self).baseAddress! self.curlPerformRequest(endpointUrl: endpointUrl, contentType: contentType, resultType: resultType, requestBytes: unsafeBufferPointer, byteCount: byteCount, completion: completion) } } } /// Note: performed on global queue private func curlPerformRequest<T: Decodable>(endpointUrl: URL, contentType: String, resultType: T.Type, requestBytes: UnsafePointer<UInt8>, byteCount: Int, completion: @escaping DataTaskCompletion) { var callbackData = WriteCallbackData() guard let curl = curl_easy_init() else { completion(nil, .libcurlInitError) return } defer { curl_easy_cleanup(curl) } curl_easy_setopt_string(curl, CURLOPT_URL, endpointUrl.absoluteString) //curl_easy_setopt_int(curl, CURLOPT_SAFE_UPLOAD, 1) curl_easy_setopt_int(curl, CURLOPT_POST, 1) curl_easy_setopt_binary(curl, CURLOPT_POSTFIELDS, requestBytes) curl_easy_setopt_int(curl, CURLOPT_POSTFIELDSIZE, Int32(byteCount)) var headers: UnsafeMutablePointer<curl_slist>? = nil headers = curl_slist_append(headers, "Content-Type: \(contentType)") curl_easy_setopt_slist(curl, CURLOPT_HTTPHEADER, headers) defer { curl_slist_free_all(headers) } let writeFunction: curl_write_callback = { (ptr, size, nmemb, userdata) -> Int in let count = size * nmemb if let writeCallbackDataPointer = userdata?.assumingMemoryBound(to: WriteCallbackData.self) { let writeCallbackData = writeCallbackDataPointer.pointee ptr?.withMemoryRebound(to: UInt8.self, capacity: count) { writeCallbackData.data.append(&$0.pointee, count: count) } } return count } curl_easy_setopt_write_function(curl, CURLOPT_WRITEFUNCTION, writeFunction) curl_easy_setopt_pointer(curl, CURLOPT_WRITEDATA, &callbackData) //curl_easy_setopt_int(curl, CURLOPT_VERBOSE, 1) let code = curl_easy_perform(curl) guard code == CURLE_OK else { reportCurlError(code: code, completion: completion) return } //let result = String(data: callbackData.data, encoding: .utf8) //print("CURLcode=\(code.rawValue) result=\(result.unwrapOptional)") guard code != CURLE_ABORTED_BY_CALLBACK else { completion(nil, .libcurlAbortedByCallback) return } var httpCode: Int = 0 guard CURLE_OK == curl_easy_getinfo_long(curl, CURLINFO_RESPONSE_CODE, &httpCode) else { reportCurlError(code: code, completion: completion) return } let data = callbackData.data let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.dateDecodingStrategy = .secondsSince1970 guard let telegramResponse = try? decoder.decode(Response<T>.self, from: data) else { completion(nil, .decodeError(data: data)) return } guard httpCode == 200 else { completion(nil, .invalidStatusCode( statusCode: httpCode, telegramDescription: telegramResponse.description!, telegramErrorCode: telegramResponse.errorCode!, data: data) ) return } guard !data.isEmpty else { completion(nil, .noDataReceived) return } if !telegramResponse.ok { completion(nil, .serverError(data: data)) return } completion(telegramResponse.result!, nil) } private func reportCurlError(code: CURLcode, completion: @escaping DataTaskCompletion) { let failReason = String(cString: curl_easy_strerror(code), encoding: .utf8) ?? "unknown error" //print("Request failed: \(failReason)") completion(nil, .libcurlError(code: code, description: failReason)) } private func urlForEndpoint(_ endpoint: String) -> URL { let tokenUrlencoded = token.urlQueryEncode() let endpointUrlencoded = endpoint.urlQueryEncode() let urlString = "\(url)/bot\(tokenUrlencoded)/\(endpointUrlencoded)" guard let result = URL(string: urlString) else { fatalError("Invalid URL: \(urlString)") } return result } }
apache-2.0
8f3206f83f896a4dc9bd2198015fd276
38.332248
204
0.616977
4.733438
false
false
false
false
pubnub/SwiftConsole
PubNubSwiftConsole/Classes/UI/CollectionView/Cells/PresenceEventCollectionViewCell.swift
1
2923
// // PresenceEventCollectionViewCell.swift // Pods // // Created by Keith Martin on 8/10/16. // // import UIKit import PubNub protocol PresenceEventItem: Item { init(itemType: ItemType, event: PNPresenceEventResult) var eventType: String {get} var occupancy: NSNumber? {get} var timeToken: NSNumber? {get} } extension PresenceEventItem { var title: String { return eventType } } struct PresenceEvent: PresenceEventItem { let itemType: ItemType let eventType: String let occupancy: NSNumber? let timeToken: NSNumber? init(itemType: ItemType, event: PNPresenceEventResult) { self.itemType = itemType self.eventType = event.data.presenceEvent self.occupancy = event.data.presence.occupancy self.timeToken = event.data.presence.timetoken } var reuseIdentifier: String { return PresenceEventCollectionViewCell.reuseIdentifier } } class PresenceEventCollectionViewCell: CollectionViewCell { private let eventTypeLabel: UILabel private let occupancyLabel: UILabel private let timeTokenLabel: UILabel override class var reuseIdentifier: String { return String(self.dynamicType) } override init(frame: CGRect) { eventTypeLabel = UILabel(frame: CGRect(x: 5, y: 0, width: frame.size.width, height: frame.size.height/4)) occupancyLabel = UILabel(frame: CGRect(x: 5, y: 30, width: frame.size.width, height: frame.size.height/4)) timeTokenLabel = UILabel(frame: CGRect(x: 5, y: 60, width: frame.size.width, height: frame.size.height/4)) super.init(frame: frame) contentView.addSubview(eventTypeLabel) contentView.addSubview(occupancyLabel) contentView.addSubview(timeTokenLabel) contentView.layer.borderWidth = 3 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updatePresence(item: PresenceEventItem) { eventTypeLabel.text = "Type: \(item.title)" if let channelOccupancy = item.occupancy { occupancyLabel.hidden = false occupancyLabel.text = "Occupancy: \(channelOccupancy)" } else { occupancyLabel.hidden = true } if let eventTimeToken = item.timeToken { timeTokenLabel.hidden = false timeTokenLabel.text = "Time token: \(eventTimeToken)" } else { timeTokenLabel.hidden = true } setNeedsLayout() } override func updateCell(item: Item) { guard let presenceEventItem = item as? PresenceEventItem else { fatalError("init(coder:) has not been implemented") } updatePresence(presenceEventItem) } class override func size(collectionViewSize: CGSize) -> CGSize { return CGSize(width: collectionViewSize.width, height: 150.0) } }
mit
314aa0ab8e9e6e110cbe594b1aa208ef
30.771739
114
0.663702
4.388889
false
false
false
false
nicopuri/CrossNavigation
Swift/CrossNavigation/Utils/cn_direction.swift
3
1109
// // cn_direction.swift // CrossNavigationDemo // // Created by Nicolas Purita on 11/5/14. // // import UIKit enum CNDirection { case None case Left case Top case Right case Bottom func getOpposite() -> CNDirection { var opposite: CNDirection = .None switch self { case .Left: opposite = .Right case .Right: opposite = .Left case .Top: opposite = .Bottom case .Bottom: opposite = .Top default: opposite = .None } return opposite } func oppositeToDirection(direction: CNDirection) -> Bool { let oppositeDirection = direction.getOpposite() if self == .None || oppositeDirection == .None { return false } return self == oppositeDirection } func isHorizontal() -> Bool { return self == .Left || self == .Right } func isVertical() -> Bool { return self == .Top || self == .Bottom } }
mit
7cbb23a1912c24c2c0b37c2867386f17
18.12069
62
0.496844
4.780172
false
false
false
false
tickCoder/Practise_Swift
Practise_Swift/LanguageGuide.swift
1
6177
// // LanguageGuide.swift // Practise_Swift // // Created by Milk on 2015.11.16.Monday. // Copyright © 2015 tickCoder. All rights reserved. // import Foundation /* Int, Double, Fload, Bool, String Collection Types: Array, Set, Dictionary Tuples:元组,在值组中创建、传递。create and pass around groupings of values.可以使用元组从一个函数中将单一的混合值作为返回值。 Swift引入了可选值类型来处理缺失的值。可选值代表:有一个值为x,或者压根没有这个值。类似于objc的nil,但是它对所有类型有效,而不仅仅是类。可选值不仅比objc的nil指针更安全更高效,而且是很多swift更强大特征的心脏。 Swift是type-safe类型安全的语言,这说明语言帮你明确值的类型。如果你代码要求String了ing,类型安全防止你错误传递Int。同样,它防止你偶然传递给一个可选String给期望的不可选String。类型安全帮助你今早地在开发阶段找到并修正错误。 let声明常量,var声明变量 类型注释:代表welcomMessage of type String var welcomMessage:String var red, green, blue: Double = 0.0 常量和变量名几乎可以用任何字符。不可以包含空格、数学符号、箭头、私有使用(或无效)的unicode字符,or line- and box-drawing。不可以使用数字开头。类型一旦定义不可更改,不可以存储不相符类型值。不可以将常量变为变量。 如果需要使用关键字作为常量和变量名,需要使用(`)环绕,但这仅仅应该在没有其他选择的情况下使用。 let `let` = "let" 可以将已存在的变量值变为另一个兼容的类型。 */ class LanguageGuide { func test () { self.hello(); } func hello() { //var red, green, blue: Double = 0.0 let π = 3.14159 let 你好 = "你好世界" let 🐶🐮 = "dogcow" let `let` = "hello" print("a", "b") // 分隔符,终止符 print("a", "b", separator: ",", terminator: ".") print("\n") print(UInt8.max, UInt16.max, UInt32.max, UInt64.max, separator: ",", terminator: ".") /* 在32bit为Int32,在64bit为Int64; UInt同理 */ var intValue:Int = 3; print("\n") print(Int.max, Int32.max, Int64.max, separator: ",", terminator: ".") print("\n") print(UInt.max, UInt32.max, UInt64.max, separator: ",", terminator: ".") /* Double: 64bit floating,精确度至少15位 Float: 32bit floating,精确度至少6位 */ /* 类型安全与类型推断 let pi=3.1415, Swift在推断浮点数时,总是推断为Double,而不是Float let anotherPi = 3 + 3.1415 ---> Double */ /* Integer可以写做: *十进制,不带前缀 let decimalInteger = 3 *二进制,前缀0b let binaryInteger = 0b1001 *八进制,前缀0o let octalInteger = 0o87 *十六进制,前缀0x let hexadecimalInteger = 0x1A 浮点数可以为 *十进制,无前缀 *十六进制,前缀0x 十进制浮点数可以有一个可选的指数,使用大写或小写的e,“ the base number is multiplied by 10^exp”,如1.25e2,1.25e-2 十六进制浮点数必须又一个质数,使用大写或小写p,“the base number is multiplied by 2^exp”,如0xFp2(60.0),0xFp-2(3.75) */ let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0 /* Numeric literals数字字面值可以包含额外的格式来增强易读性。 intergers和floats都可以是哟功能额外的0来填充,也可以包含下划线来帮助阅读。 */ let paddedDouble = 000123.456 let oneMillioin = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1 /* Int8: -128~+127 UInt8:0~255 */ let twoThousand:UInt16 = 2_000; let one: UInt8 = 1 let twoThuosandAndOne = twoThousand + UInt16(one) print("\n") print(UInt16.max, twoThousand, twoThuosandAndOne, "\n", separator: ",", terminator: ".") /* “Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.” */ /* Type Aliases类型别名:为已知类型定义了一个替代名。 */ typealias AudioSample = UInt16; var maxAmplitudeFound = AudioSample.max; // 布尔值 let orange = true let apple = false // Tuples let http404Error = (404, "Not Found") let (statusCode, statusMessage) = http404Error print(http404Error.0) print(statusCode) print(statusMessage) let (statusCode1, _) = http404Error print(statusCode1) var http200Status = (statusCode:200, description:"ok") print(http200Status.description) http200Status.statusCode = 300; http200Status.description = "300" let responseInfo = (false, 30, "cannot find this file") // Optionals let possibleNumber = "abc" let convertedNumber = Int(possibleNumber) // optional value print(convertedNumber) // nil var serverResponseCode: Int? = 404 serverResponseCode = nil // var serverResponseCode1: Int = 404 // serverResponseCode1 = nil // will be error if not Int? var surveyAnswer: String? // means surveyAnswer is nil /* “Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.” */ } }
mit
2957c33c1d5fdfef7913728781d529d9
30.6
261
0.596079
3.344945
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
1
16583
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension KingfisherWrapper where Base: UIButton { // MARK: Setting Image /// Sets an image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setImage(placeholder, for: state) setTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } var mutatingSelf = self let issuedTaskIdentifier = Source.Identifier.next() setTaskIdentifier(issuedTaskIdentifier, for: state) let task = KingfisherManager.shared.retrieveImage( with: source, options: options, progressBlock: { receivedSize, totalSize in guard issuedTaskIdentifier == self.taskIdentifier(for: state) else { return } progressBlock?(receivedSize, totalSize) }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedTaskIdentifier == self.taskIdentifier(for: state) else { let error = KingfisherError.imageSettingError( reason: .notCurrentSourceTask(result: result.value, error: result.error, source: source)) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil switch result { case .success(let value): self.base.setImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setImage(image, for: state) } completionHandler?(result) } } }) mutatingSelf.imageTask = task return task } /// Sets an image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource.map { Source.network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Downloading Task /// Cancels the image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelImageDownloadTask() { imageTask?.cancel() } // MARK: Setting Background Image /// Sets a background image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setBackgroundImage(placeholder, for: state) setBackgroundTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } var mutatingSelf = self let issuedTaskIdentifier = Source.Identifier.next() setBackgroundTaskIdentifier(issuedTaskIdentifier, for: state) let task = KingfisherManager.shared.retrieveImage( with: source, options: options, progressBlock: { receivedSize, totalSize in guard issuedTaskIdentifier == self.backgroundTaskIdentifier(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedTaskIdentifier == self.backgroundTaskIdentifier(for: state) else { let error = KingfisherError.imageSettingError( reason: .notCurrentSourceTask(result: result.value, error: result.error, source: source)) completionHandler?(.failure(error)) return } mutatingSelf.backgroundImageTask = nil switch result { case .success(let value): self.base.setBackgroundImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setBackgroundImage(image, for: state) } completionHandler?(result) } } }) mutatingSelf.backgroundImageTask = task return task } /// Sets a background image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setBackgroundImage( with: resource.map { .network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Background Downloading Task /// Cancels the background image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: UIButton { public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return (taskIdentifierInfo[NSNumber(value:state.rawValue)] as? Box<Source.Identifier.Value>)?.value } private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { taskIdentifierInfo[NSNumber(value:state.rawValue)] = identifier.map { Box($0) } } private var taskIdentifierInfo: NSMutableDictionary { get { guard let dictionary: NSMutableDictionary = getAssociatedObject(base, &taskIdentifierKey) else { let dic = NSMutableDictionary() var mutatingSelf = self mutatingSelf.taskIdentifierInfo = dic return dic } return dictionary } set { setRetainedAssociatedObject(base, &taskIdentifierKey, newValue) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } private var backgroundTaskIdentifierKey: Void? private var backgroundImageTaskKey: Void? // MARK: Background Properties extension KingfisherWrapper where Base: UIButton { public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return (backgroundTaskIdentifierInfo[NSNumber(value:state.rawValue)] as? Box<Source.Identifier.Value>)?.value } private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { backgroundTaskIdentifierInfo[NSNumber(value:state.rawValue)] = identifier.map { Box($0) } } private var backgroundTaskIdentifierInfo: NSMutableDictionary { get { guard let dictionary: NSMutableDictionary = getAssociatedObject(base, &backgroundTaskIdentifierKey) else { let dic = NSMutableDictionary() var mutatingSelf = self mutatingSelf.backgroundTaskIdentifierInfo = dic return dic } return dictionary } set { setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, newValue) } } private var backgroundImageTask: DownloadTask? { get { return getAssociatedObject(base, &backgroundImageTaskKey) } mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } } } extension KingfisherWrapper where Base: UIButton { /// Gets the image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified image. /// - Returns: Current URL for image. @available(*, obsoleted: 5.0, message: "Use `taskIdentifier` instead to identify a setting task.") public func webURL(for state: UIControl.State) -> URL? { return nil } /// Gets the background image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified background image. /// - Returns: Current URL for image. @available(*, obsoleted: 5.0, message: "Use `backgroundTaskIdentifier` instead to identify a setting task.") public func backgroundWebURL(for state: UIControl.State) -> URL? { return nil } }
mit
b388669d96f07bff9f145ab59fae070e
44.185286
119
0.638606
5.454934
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Util/TripUtils.swift
1
944
// // TripUtils.swift // SASAbus // // Created by Alex Lardschneider on 27/09/2017. // Copyright © 2017 SASA AG. All rights reserved. // import Foundation import Realm import RealmSwift class TripUtils { static func insertTripIfValid(beacon: BusBeacon) -> CloudTrip? { if beacon.origin == beacon.destination && beacon.lastSeen - beacon.startDate.millis() < 600000 { Log.error("Trip \(beacon.id) invalid -> origin == destination => \(beacon.origin) == \(beacon.destination)") return nil } let realm = try! Realm() let trip = realm.objects(Trip.self).filter("tripHash == '\(beacon.tripHash)'").first if trip != nil { // Trip is already in db. // We do not care about this error so do not show an error notification return nil } return UserRealmHelper.insertTrip(beacon: beacon) } }
gpl-3.0
579115ca53977e5ea040f5786ea2a8f4
27.575758
120
0.598091
4.191111
false
false
false
false
Palleas/Rewatch
Rewatch/Domain/DownloadController.swift
1
3587
// // DownloadController.swift // Rewatch // // Created by Romain Pouclet on 2015-11-04. // Copyright © 2015 Perfectly-Cooked. All rights reserved. // import UIKit import ReactiveCocoa import Result import CoreData let DownloadControllerLastSyncKey = "LastSyncKey" func lastSyncDate() -> String? { guard let date = NSUserDefaults.standardUserDefaults().objectForKey(DownloadControllerLastSyncKey) as? NSDate else { return nil } let formatter = NSDateFormatter() formatter.dateStyle = .ShortStyle formatter.timeStyle = .ShortStyle return formatter.stringFromDate(date) } class DownloadController: NSObject { let contentController: ContentController let persistenceController: PersistenceController init(contentController: ContentController, persistenceController: PersistenceController) { self.contentController = contentController self.persistenceController = persistenceController super.init() } /// Download the content needed to run the application /// and returns the number of episodes available for the random func download() -> SignalProducer<Int, ContentError> { let importMoc = persistenceController.spawnManagedObjectContext() let importScheduler = PersistenceScheduler(context: importMoc) // Fetch shows let fetchShows = contentController.fetchShows() // Import shows into local database let importShowsSignal = fetchShows.flatMap(.Merge, transform: { (show) -> SignalProducer<StoredShow, ContentError> in return SignalProducer { observable, disposable in observable.sendNext(StoredShow.showInContext(importMoc, mappedOnShow: show)) observable.sendCompleted() }.startOn(importScheduler) }) // Import episode let importEpisodesSignal = importShowsSignal.flatMap(.Merge) { (storedShow) -> SignalProducer<(StoredShow, StoredEpisode), ContentError> in let fetchEpisodeSignal = self.contentController.fetchEpisodes(Int(storedShow.id)) .flatMap(FlattenStrategy.Merge, transform: { (episode) -> SignalProducer<StoredEpisode, ContentError> in return SignalProducer { observable, disposable in let storedEpisode = StoredEpisode.episodeInContext(importMoc, mappedOnEpisode: episode) storedEpisode.show = storedShow observable.sendNext(storedEpisode) observable.sendCompleted() }.startOn(importScheduler) }) return combineLatest(SignalProducer(value: storedShow), fetchEpisodeSignal) } .collect() let finalCountdownSignalProducer = importEpisodesSignal.flatMap(FlattenStrategy.Latest) { (showsAndEpisodes) -> SignalProducer<Int, ContentError> in return SignalProducer<Int, ContentError> { sink, disposable in try! importMoc.save() sink.sendNext(showsAndEpisodes.count) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(NSDate(), forKey: DownloadControllerLastSyncKey) defaults.synchronize() sink.sendCompleted() } } return finalCountdownSignalProducer } func fetchSeenEpisodeFromShow(id: Int) -> SignalProducer<Episode, ContentError> { return self.contentController.fetchEpisodes(id) } }
mit
d37bcf9bf0796da7d700c00f804e3091
38.406593
156
0.666202
5.55969
false
false
false
false
daltoniam/SwiftHTTP
Source/Request.swift
1
12373
// // Request.swift // SwiftHTTP // // Created by Dalton Cherry on 8/16/15. // Copyright © 2015 vluxe. All rights reserved. // import Foundation extension String { /** A simple extension to the String object to encode it for web request. :returns: Encoded version of of string it was called as. */ var escaped: String? { var set = CharacterSet() set.formUnion(CharacterSet.urlQueryAllowed) set.remove(charactersIn: "[].:/?&=;+!@#$()',*\"") // remove the HTTP ones from the set. return self.addingPercentEncoding(withAllowedCharacters: set) } /** A simple extension to the String object to url encode quotes only. :returns: string with . */ var quoteEscaped: String { return self.replacingOccurrences(of: "\"", with: "%22").replacingOccurrences(of: "'", with: "%27") } } /** The standard HTTP Verbs */ public enum HTTPVerb: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" case PATCH = "PATCH" case OPTIONS = "OPTIONS" case TRACE = "TRACE" case CONNECT = "CONNECT" case UNKNOWN = "UNKNOWN" } /** This is used to create key/value pairs of the parameters */ public struct HTTPPair { var key: String? let storeVal: AnyObject /** Create the object with a possible key and a value */ init(key: String?, value: AnyObject) { self.key = key self.storeVal = value } /** Computed property of the string representation of the storedVal */ var upload: Upload? { return storeVal as? Upload } /** Computed property of the string representation of the storedVal */ var value: String { if storeVal is NSNull { return "" } else if let v = storeVal as? String { return v } else { return storeVal.description ?? "" } } /** Computed property of the string representation of the storedVal escaped for URLs */ var escapedValue: String { let v = value.escaped ?? "" if let k = key { if let escapedKey = k.escaped { return "\(escapedKey)=\(v)" } } return "" } } /** This is super gross, but it is just an edge case, I'm willing to live with it versus trying to handle such an rare need with more code and confusion */ public class HTTPParameterProtocolSettings { public static var sendEmptyArray = false } /** This protocol is used to make the dictionary and array serializable into key/value pairs. */ public protocol HTTPParameterProtocol { func createPairs(_ key: String?) -> [HTTPPair] } /** Support for the Dictionary type as an HTTPParameter. */ extension Dictionary: HTTPParameterProtocol { public func createPairs(_ key: String?) -> [HTTPPair] { var collect = [HTTPPair]() for (k, v) in self { if let nestedKey = k as? String { let useKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey if let subParam = v as? HTTPParameterProtocol { collect.append(contentsOf: subParam.createPairs(useKey)) } else { collect.append(HTTPPair(key: useKey, value: v as AnyObject)) } } } return collect } } /** Support for the Array type as an HTTPParameter. */ extension Array: HTTPParameterProtocol { public func createPairs(_ key: String?) -> [HTTPPair] { var collect = [HTTPPair]() for v in self { let useKey = key != nil ? "\(key!)[]" : key if let subParam = v as? HTTPParameterProtocol { collect.append(contentsOf: subParam.createPairs(useKey)) } else { collect.append(HTTPPair(key: useKey, value: v as AnyObject)) } } if HTTPParameterProtocolSettings.sendEmptyArray && collect.count == 0 { collect.append(HTTPPair(key: key, value: "[]" as AnyObject)) } return collect } } /** Support for the Upload type as an HTTPParameter. */ extension Upload: HTTPParameterProtocol { public func createPairs(_ key: String?) -> Array<HTTPPair> { var collect = Array<HTTPPair>() collect.append(HTTPPair(key: key, value: self)) return collect } } /** Adds convenience methods to URLRequest to make using it with HTTP much simpler. */ extension URLRequest { /** Convenience init to allow init with a string. -parameter urlString: The string representation of a URL to init with. */ public init?(urlString: String, parameters: HTTPParameterProtocol? = nil, headers: [String: String]? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60) { if let url = URL(string: urlString) { self.init(url: url) } else { return nil } if let params = parameters { let _ = appendParameters(params) } if let heads = headers { for (key,value) in heads { addValue(value, forHTTPHeaderField: key) } } } /** Convenience method to avoid having to use strings and allow using an enum */ public var verb: HTTPVerb { set { httpMethod = newValue.rawValue } get { if let verb = httpMethod, let v = HTTPVerb(rawValue: verb) { return v } return .UNKNOWN } } /** Used to update the content type in the HTTP header as needed */ var contentTypeKey: String { return "Content-Type" } /** append the parameters using the standard HTTP Query model. This is parameters in the query string of the url (e.g. ?first=one&second=two for GET, HEAD, DELETE. It uses 'application/x-www-form-urlencoded' for the content type of POST/PUT requests that don't contains files. If it contains a file it uses `multipart/form-data` for the content type. -parameter parameters: The container (array or dictionary) to convert and append to the URL or Body */ public mutating func appendParameters(_ parameters: HTTPParameterProtocol) -> Error? { if isURIParam() { appendParametersAsQueryString(parameters) } else if containsFile(parameters) { return appendParametersAsMultiPartFormData(parameters) } else { appendParametersAsUrlEncoding(parameters) } return nil } /** append the parameters as a HTTP Query string. (e.g. domain.com?first=one&second=two) -parameter parameters: The container (array or dictionary) to convert and append to the URL */ public mutating func appendParametersAsQueryString(_ parameters: HTTPParameterProtocol) { let queryString = parameters.createPairs(nil).map({ (pair) in return pair.escapedValue }).joined(separator: "&") if let u = self.url , queryString.count > 0 { let para = u.query != nil ? "&" : "?" self.url = URL(string: "\(u.absoluteString)\(para)\(queryString)") } } /** append the parameters as a url encoded string. (e.g. in the body of the request as: first=one&second=two) -parameter parameters: The container (array or dictionary) to convert and append to the HTTP body */ public mutating func appendParametersAsUrlEncoding(_ parameters: HTTPParameterProtocol) { if value(forHTTPHeaderField: contentTypeKey) == nil { var contentStr = "application/x-www-form-urlencoded" if let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) { contentStr += "; charset=\(charset)" } setValue(contentStr, forHTTPHeaderField:contentTypeKey) } let queryString = parameters.createPairs(nil).map({ (pair) in return pair.escapedValue }).joined(separator: "&") httpBody = queryString.data(using: .utf8) } /** append the parameters as a multpart form body. This is the type normally used for file uploads. -parameter parameters: The container (array or dictionary) to convert and append to the HTTP body */ public mutating func appendParametersAsMultiPartFormData(_ parameters: HTTPParameterProtocol) -> Error? { let boundary = "Boundary+\(arc4random())\(arc4random())" if value(forHTTPHeaderField: contentTypeKey) == nil { setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField:contentTypeKey) } let mutData = NSMutableData() let multiCRLF = "\r\n" mutData.append("--\(boundary)".data(using: .utf8)!) for pair in parameters.createPairs(nil) { guard let key = pair.key else { continue } //this won't happen, but just to properly unwrap if let upload = pair.upload { let resp = upload.getData() if let error = resp.error { return error } mutData.append("\(multiCRLF)".data(using: .utf8)!) if let data = resp.data { mutData.append(multiFormHeader(key, fileName: upload.fileName, type: upload.mimeType, multiCRLF: multiCRLF).data(using: .utf8)!) mutData.append(data) } else { return HTTPUploadError.noData } } else { mutData.append("\(multiCRLF)".data(using: .utf8)!) let str = "\(multiFormHeader(key, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.value)" mutData.append(str.data(using: .utf8)!) } mutData.append("\(multiCRLF)--\(boundary)".data(using: .utf8)!) } mutData.append("--\(multiCRLF)".data(using: .utf8)!) httpBody = mutData as Data return nil } /** Helper method to create the multipart form data */ func multiFormHeader(_ name: String, fileName: String?, type: String?, multiCRLF: String) -> String { var str = "Content-Disposition: form-data; name=\"\(name.quoteEscaped)\"" if let n = fileName { str += "; filename=\"\(n.quoteEscaped)\"" } str += multiCRLF if let t = type { str += "Content-Type: \(t)\(multiCRLF)" } str += multiCRLF return str } /** send the parameters as a body of JSON -parameter parameters: The container (array or dictionary) to convert and append to the URL or Body */ public mutating func appendParametersAsJSON(_ parameters: HTTPParameterProtocol) -> Error? { if isURIParam() { appendParametersAsQueryString(parameters) } else { do { httpBody = try JSONSerialization.data(withJSONObject: parameters as AnyObject, options: JSONSerialization.WritingOptions()) } catch let error { return error } var contentStr = "application/json" if let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) { contentStr += "; charset=\(charset)" } setValue(contentStr, forHTTPHeaderField: contentTypeKey) } return nil } /** Check if the request requires the parameters to be appended to the URL */ public func isURIParam() -> Bool { if verb == .GET || verb == .HEAD || verb == .DELETE { return true } return false } /** check if the parameters contain a file object within them -parameter parameters: The parameters to search through for an upload object */ public func containsFile(_ parameters: HTTPParameterProtocol) -> Bool { for pair in parameters.createPairs(nil) { if let _ = pair.upload { return true } } return false } }
apache-2.0
f57d280ac3acfc0f28b6d72db68f19a4
33.271468
212
0.594811
4.688139
false
false
false
false
carolwdc/CustomPopviewAnmation
CustomPopviewAnimation/CustomPopViewManager.swift
1
4767
// // PopViewManager.swift // NTESLocalActivities-Swift // // Created by Carol on 16/6/3. // Copyright © 2016年 NetEase. All rights reserved. // import Foundation protocol PopViewAnimation { func showPopview(popView: UIView,overlayView: UIView) func dismissView(popView: UIView,overlayView: UIView, completion:()->()) } class CustomPopViewManager: NSObject { var popView: UIView? var overlayView: UIView? var popAnimation: PopViewAnimation? private static let sharedInstance = CustomPopViewManager() class var sharedManager: CustomPopViewManager { return sharedInstance } /** 显示popview的实现方法 - parameter popView: 外部传入的popView,不能为nil - parameter viewController: 需要显示popView的controller,不能为nil - parameter animation: 动画效果 - parameter backgroundClickable: 背景是否可以点击 */ func cm_presentPopView(popView: UIView,viewController: UIViewController, animation:PopViewAnimation?,backgroundClickable:Bool) { presentPopView(popView,viewController:viewController,animation:animation,backgroundClickable:backgroundClickable) } func dismissPopView() { dismissPopViewWithAnimation(self.popAnimation) } /** popView消失动画 - parameter animation: 动画类型 */ func dismissPopViewWithAnimation(animation: PopViewAnimation?) { if animation != nil { animation!.dismissView(self.popView!, overlayView: self.overlayView!, completion: { self.overlayView?.removeFromSuperview() self.popView?.removeFromSuperview() self.popView = nil self.overlayView = nil }) }else { self.overlayView?.removeFromSuperview() self.popView?.removeFromSuperview() self.popView = nil self.overlayView = nil } } /** 显示popview的实现方法 - parameter popView: 外部传入的popView,不能为nil - parameter viewController: 需要显示popView的controller,不能为nil - parameter animation: 动画效果 - parameter backgroundClickable: 背景是否可以点击 */ private func presentPopView(popView: UIView,viewController: UIViewController, animation:PopViewAnimation?,backgroundClickable:Bool) { if let overlayView = overlayView { if overlayView.subviews.contains(popView) { return } if overlayView.subviews.count > 1 { dismissPopViewWithAnimation(nil) } } self.popView = popView self.popAnimation = animation let sourceView = topView(viewController) popView.autoresizingMask = [UIViewAutoresizing.FlexibleTopMargin,UIViewAutoresizing.FlexibleLeftMargin,UIViewAutoresizing.FlexibleBottomMargin,UIViewAutoresizing.FlexibleRightMargin] popView.tag = 888; popView.layer.shadowPath = UIBezierPath(rect: popView.bounds).CGPath; popView.layer.masksToBounds = false; popView.layer.shadowOffset = CGSizeMake(5, 5); popView.layer.shadowRadius = 5; popView.layer.shadowOpacity = 0.5; popView.layer.shouldRasterize = true; popView.layer.rasterizationScale = UIScreen.mainScreen().scale; if self.overlayView == nil { self.overlayView = UIView(frame: sourceView.bounds) overlayView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth,UIViewAutoresizing.FlexibleHeight] overlayView!.tag = 999 overlayView?.backgroundColor = UIColor(white: 0.4, alpha: 0.8) } self.overlayView!.addSubview(popView) sourceView.addSubview(self.overlayView!) self.overlayView!.alpha = 1.0 popView.center = self.overlayView!.center if animation != nil { animation!.showPopview(popView, overlayView: self.overlayView!) } if backgroundClickable { let tap = UITapGestureRecognizer(target: self, action: #selector(CustomPopViewManager.dismissPopView)) overlayView?.addGestureRecognizer(tap) } } /** 获取最底层控制器的view,用来获取overlayview的大小 - parameter vc: 当前vc - returns: 获取最底层控制器的view */ private func topView(vc:UIViewController)->UIView { var recentVC = vc while recentVC.parentViewController != nil { recentVC = recentVC.parentViewController! } return recentVC.view } }
mit
83eab6879400f2f2430eb16bce7d315a
33.431818
190
0.644146
5.20504
false
false
false
false